openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
12 lines • 17 kB
JavaScript
import{s as formatErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{d as redactToolPayloadText}from"./redact-BT59pdZ_.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{a as withGitProcessOperation}from"./spawn-diagnostics-C-LTFiNq.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{t as truncateUtf8Prefix}from"./utf8-truncate-B8GdsL7T.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{i as resolveCommandEnv}from"./exec-spawn-DNCbDcyJ.mjs";import{t as runCommandBuffered}from"./exec-c5tqm8tb.mjs";import{t as createCommandError}from"./command-error-B187dN8z.mjs";import{r as githubRepositoryUrl}from"./github-host-BIyVIYLv.mjs";import{n as appendGitConfig,r as gitMaintenanceEnvironment}from"./git-maintenance-env-CIA5le3f.mjs";import{i as withGitNetworkRetry,r as retryableGitNetworkOperation}from"./git-network-retry-Dmgh4hDr.mjs";import{l as gitNullConfigPath,u as gitReadOnlyEnvironment}from"./git-exec-BRQo7oSy.mjs";import{t as withGitObjectStoreTransport}from"./git-object-store-transport-CP8klqLL.mjs";import{t as GitHubPublicationApiError}from"./github-publication-failure-CZb5rwTV.mjs";import{i as parseGitHubPublicationBaseRef,n as githubPublicationUnsafeConfigArgs}from"./github-publication-base-BoRNavWF.mjs";import path from"node:path";import fs from"node:fs/promises";import os from"node:os";
//!src/gateway/github-publication-command-env.ts
function publicationCommandEnv(e,t={}){return{...e[0]===`git`?gitReadOnlyEnvironment(e.slice(1),t):t,GIT_NO_REPLACE_OBJECTS:`1`,...appendGitConfig(gitMaintenanceEnvironment(),[[`core.hooksPath`,os.devNull]])}}function createGitHubPublicationReadEnvironment(e){let t;return()=>t??=resolveCommandEnv({argv:[`gh`],env:publicationCommandEnv([`gh`],e)})}
//!src/gateway/github-publication-git-error.ts
function createGitHubPublicationGitError(e,t,n,r){const i=[createCommandError(`Git ${t}`,{...n,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0),error:void 0},{timeoutMs:r}).message,n.error?formatErrorMessage(n.error,{includeCode:true}):``,n.stderr.toString(`utf8`)].filter(Boolean).join(`: `);const a=truncateUtf8Prefix(redactToolPayloadText(sanitizeForLog(i.replace(/[\r\n\t]+/gu,` `)).replace(/\b[a-z][a-z\d+.-]*:\/\/\S+/giu,`[redacted URL]`)).trim(),1024);const o=t===`commit fetch`&&n.termination===`timeout`?` Do not repeat the same full-history fetch. Open the PR in its base project's workspace so Git can reuse project history. For a standalone inspection, use a separate depth-limited clone; do not shallow the shared project store.`:``;return/* @__PURE__ */ new Error(`${e} ${a}${o}`)}
//!src/gateway/github-publication-git-transport.ts
const DEFAULT_COMMAND_TIMEOUT_MS=6e4;function githubPublicationApiArgs(e,t=`GET`,n=`github.com`){return[`gh`,`api`,`--hostname`,n,`--method`,t,e,...t===`GET`?[]:[`--input`,`-`]]}async function runPublicationCommand(e,t={}){return await withGitProcessOperation(t.operation??`publication`,()=>withGitNetworkRetry(e[0]===`git`?retryableGitNetworkOperation(e.slice(1)):void 0,{timeoutMs:t.timeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,beforeRun:t.beforeRun},n=>runCommandBuffered(e,{...t.cwd?{cwd:t.cwd}:{},...t.prepareEnv?{preparedEnv:t.prepareEnv()}:{env:publicationCommandEnv(e,t.env)},...t.input!==void 0?{input:typeof t.input===`function`?t.input():t.input}:{},timeoutMs:n,noOutputTimeoutMs:t.noOutputTimeoutMs,discardOutput:t.discardOutput,maxOutputBytes:t.maxOutputBytes??262144})))}async function requirePublicationCommand(e,t={}){const n=await runPublicationCommand(e,t);if(n.code!==0||n.error){if(e[0]===`gh`)throw new GitHubPublicationApiError(n,t.timeoutMs??DEFAULT_COMMAND_TIMEOUT_MS);throw createCommandError(e[0]??`command`,{...n,stdout:Buffer.alloc(0)},{timeoutMs:t.timeoutMs??DEFAULT_COMMAND_TIMEOUT_MS})}return n.stdout.toString(`utf8`).trim()}function createGitHubPublicationCommandRunner(e,t=`publication`){const step=async t=>{e?.();const n=await t();e?.();return n};const guarded=n=>async(r,i={})=>{const a=await n(r,{...i,operation:t,beforeRun:e});e?.();return a};return{step,run:guarded(runPublicationCommand),require:guarded(requirePublicationCommand)}}async function readGitHubPublicationBaseSha(e,t,n,r,i){const a=await e([`gh`,`api`,`--hostname`,r,`repos/${t}/git/ref/heads/${n}`,`--jq`,`{ref: .ref, sha: .object.sha}`],{env:i});if(a.code!==0)throw new Error(`GitHub publication workspace base branch could not be verified.`);return parseGitHubPublicationBaseRef(a.stdout.toString(`utf8`),n)}async function requireGitHubPublicationCommit(e,t,n,r,i,a,o,s={}){const c=`remote.${githubRepositoryUrl(t,r)}.promisor`;const fetch=async(s,l=[n])=>{const command=async(t,n,r=a,i)=>{const c=await e(n,{cwd:t,env:r,input:i});if(c.error&&hasCommandProcessCleanupError(c.error))throw c.error;if(c.code!==0||c.error)throw createGitHubPublicationGitError(o,s?`content fetch`:`commit fetch`,c,DEFAULT_COMMAND_TIMEOUT_MS);return c.stdout.toString(`utf8`).trim()};const acquire=(e,a)=>command(e,[...GITHUB_CREDENTIAL_ARGS,`-c`,`core.hooksPath=${os.devNull}`,`-c`,`core.fsmonitor=false`,...e===i?[]:[`-c`,`core.alternateRefsCommand=true`],...s?[`-c`,`fetch.negotiationAlgorithm=noop`]:[],`fetch`,`--no-auto-maintenance`,`--no-tags`,`--no-write-fetch-head`,`--recurse-submodules=no`,...l.map(e=>`--negotiation-tip=${e}`),`--filter=blob:none`,...s?[`--quiet`,`--stdin`]:[],`--`,githubRepositoryUrl(t,r),...s?[]:[`${n}:refs/openclaw/fetched/${n}`]],a,s?`${s.join(`
`)}\n`:void 0);const u=l.length>0?await command(i,[`git`,`config`,`--type=bool`,`--default=false`,`--get`,c]):`false`;if(u!==`true`&&!s)await acquire(i,a);else{if(s&&u!==`true`)await command(i,[`git`,`config`,c,`true`]);const e={...a,GIT_DIR:void 0,GIT_COMMON_DIR:void 0,GIT_WORK_TREE:void 0};await withGitObjectStoreTransport(i,(t,n)=>command(t,[`git`,...n],e),(t,n)=>acquire(t,{...e,GIT_OBJECT_DIRECTORY:n}))}if(!s&&u===`true`)await command(i,[`git`,`update-ref`,`refs/openclaw/fetched/${n}`,n])};if(!s.commitPresent){const t=await e([`git`,`-c`,`core.commitGraph=false`,`cat-file`,`--batch-check=%(objectname) %(objecttype)`],{cwd:i,env:a,input:[n,`refs/remotes/origin/HEAD`,...s.baseBranch?[`refs/remotes/origin/${s.baseBranch}`]:[]].map(e=>`${e}^{commit}\n`).join(``)});const[r,...o]=t.stdout.toString(`utf8`).trim().split(`
`).map(e=>e.endsWith(` commit`)?e.slice(0,-7):``);if(t.code!==0||!r)await fetch(void 0,o.filter(Boolean))}if(!s.contents)return;const missingObjects=async(t=`content inventory`)=>{const r=await e([`git`,`rev-list`,`--objects`,`--missing=print`,`--no-object-names`,`--max-count=1`,n],{cwd:i,env:{...a,GIT_NO_LAZY_FETCH:`1`},maxOutputBytes:TREE_LISTING_MAX_OUTPUT_BYTES});if(r.code!==0||r.error)throw createGitHubPublicationGitError(o,t,r,DEFAULT_COMMAND_TIMEOUT_MS);return r.stdout.toString(`utf8`).split(`
`).filter(e=>e.startsWith(`?`)).map(e=>e.slice(1))};let l=await missingObjects();for(let e=0;l.length&&e<2;e++){await fetch(l);l=await missingObjects(`content verification`)}if(l.length)throw new Error(`${o} Git content verification failed: required objects are still missing after fetching.`)}const TREE_LISTING_MAX_OUTPUT_BYTES=67108864;async function assertSafeGitPublicationWorkspace(e,t){const n={GIT_CONFIG_GLOBAL:gitNullConfigPath(),GIT_CONFIG_SYSTEM:gitNullConfigPath()};const[r,i]=await Promise.all([t(githubPublicationUnsafeConfigArgs(`--local`),{cwd:e,env:n}),t([`git`,`config`,`--local`,`--includes`,`--bool`,`--get`,`extensions.worktreeConfig`],{cwd:e,env:n})]);const a=i.stdout.toString(`utf8`).trim();const o=i.code===0&&(a===`true`||a===`false`)||i.code===1&&i.stdout.length===0;if(r.code!==1||r.stdout.length>0||!o)throw new Error(`GitHub publication workspace has unsupported Git transport configuration.`);const s=a===`true`?await t(githubPublicationUnsafeConfigArgs(`--worktree`),{cwd:e,env:n}):void 0;if(s&&(s.code!==1||s.stdout.length>0))throw new Error(`GitHub publication workspace has unsupported Git transport configuration.`);const[c,l]=await Promise.all([t([`git`,`for-each-ref`,`--count=1`,`--format=%(refname)`,`refs/replace`],{cwd:e}),t([`git`,`rev-parse`,`--git-path`,`info/grafts`],{cwd:e})]);if(c.code!==0||c.stdout.length>0||l.code!==0)throw new Error(`GitHub publication workspace has unsupported Git replacement metadata.`);const u=await readOptionalAttributeFile(path.resolve(e,l.stdout.toString(`utf8`).trim()));if(u&&u.length>0)throw new Error(`GitHub publication workspace has unsupported Git replacement metadata.`)}function assertNoGitFilterAttributes(e){for(const t of e.toString(`latin1`).split(/\r?\n/u)){const e=t.trimStart().split(/[\t ]+/u);if(!e[0]||e[0].startsWith(`#`))continue;if(e.slice(1).some(e=>/^(?:-|!)?filter(?:=|$)/u.test(e)))throw new Error(`GitHub publication workspace uses an unsupported Git clean filter.`)}}async function readOptionalAttributeFile(e){try{return await fs.readFile(e)}catch(e){if(hasErrnoCode(e,`ENOENT`))return;throw e}}async function readGitHubPublicationTree(e,t,n){const r=await n([`git`,`ls-tree`,`-r`,`-z`,`--full-tree`,t],{cwd:e,maxOutputBytes:TREE_LISTING_MAX_OUTPUT_BYTES});if(r.code!==0)throw new Error(`GitHub publication workspace tree could not be verified.`);return r.stdout}async function assertGitHubPublicationIndexHasNoFilters(e,t){const n=await runPublicationCommand([`git`,`-c`,`core.fsmonitor=false`,`ls-files`,`--cached`,`--format=%(objectname)`,`--`,`:(top,icase,glob)**/.gitattributes`],{cwd:e,env:{GIT_INDEX_FILE:t,GIT_LITERAL_PATHSPECS:`0`},maxOutputBytes:TREE_LISTING_MAX_OUTPUT_BYTES});if(n.code!==0)throw new Error(`GitHub publication workspace attributes could not be verified.`);const r=new Set(n.stdout.toString(`utf8`).trim().split(`
`).filter(Boolean));if(r.size>1024)throw new Error(`GitHub publication workspace has too many Git attribute files.`);for(const t of r){const n=await runPublicationCommand([`git`,`cat-file`,`blob`,t],{cwd:e});if(n.code!==0)throw new Error(`GitHub publication workspace attributes could not be verified.`);assertNoGitFilterAttributes(n.stdout)}const i=await runPublicationCommand([`git`,`rev-parse`,`--git-path`,`info/attributes`],{cwd:e});if(i.code!==0)throw new Error(`GitHub publication workspace attributes could not be verified.`);const a=await Promise.all([`GIT_ATTR_GLOBAL`,`GIT_ATTR_SYSTEM`].map(async t=>await runPublicationCommand([`git`,`var`,t],{cwd:e})));if(a.some(e=>e.code!==0))throw new Error(`GitHub publication workspace attributes could not be verified.`);const o=[path.resolve(e,i.stdout.toString(`utf8`).trim()),...a.flatMap(e=>e.stdout.length>0?[e.stdout.toString(`utf8`).trim()]:[])];for(const e of o){const t=await readOptionalAttributeFile(e);if(t)assertNoGitFilterAttributes(t)}}async function captureGitHubPublicationWorkspaceSnapshot(e){const t=await runPublicationCommand([`git`,`rev-parse`,`--verify`,`--quiet`,`MERGE_HEAD`],{cwd:e.cwd,beforeRun:e.assertCurrent});e.assertCurrent?.();if(t.code===0)throw new Error(`Workspace base integration is pending. Use github_publish refresh_base, resolve its reported conflicts, then repeat refresh_base with conflictsResolved and the returned baseCommit before tests, Auto Review, and publication.`);if(t.code!==1)throw new Error(`Workspace base integration state could not be verified; retry refresh_base.`);const n=captureOpenClawStateWorkerContext();const{withSettledLocalWorkspacePath:r}=await import(`./local-workspace-projection-0RUCjJww.mjs`);return await r(e,async t=>{const r=await t?.canonicalPaths?.();const i={...e,assertCurrent:()=>{n.admission.assertCurrent();e.assertCurrent?.();t?.assertCurrent()}};const[{readLiveRegistryWorktreeByPath:a},{withManagedWorktreeGit:o},{getRuntimeConfig:s}]=await Promise.all([import(`./registry-read-C2RVyLjC.mjs`),import(`./checkout-policy-JOnyopwt.mjs`),import(`./config/config.js`)]);const c=await a(n,e.cwd);i.assertCurrent();return c?await o({record:c,env:process.env,getConfig:s,beforeRun:i.assertCurrent},e=>captureSettledGitHubPublicationWorkspaceSnapshot(i,e.sourceOnly?e:void 0,r)):await captureSettledGitHubPublicationWorkspaceSnapshot(i,void 0,r)})}async function captureSettledGitHubPublicationWorkspaceSnapshot(e,t,n){const{step:r,require:i}=createGitHubPublicationCommandRunner(e.assertCurrent);const git=(n,a,o)=>t?r(()=>t.require(e.cwd,n,{env:a,input:o,beforeRun:e.assertCurrent})):i([`git`,`-c`,`core.hooksPath=${os.devNull}`,`-c`,`core.fsmonitor=false`,...n],{cwd:e.cwd,env:a,input:o});await r(()=>assertSafeGitPublicationWorkspace(e.cwd,runPublicationCommand));const a=await i([`git`,`rev-parse`,`--verify`,`HEAD^{commit}`],{cwd:e.cwd});const o=path.resolve(e.cwd,await git([`rev-parse`,`--git-path`,`index`]));const s=await fs.mkdtemp(path.join(os.tmpdir(),`openclaw-github-snapshot-`));try{const i={GIT_ATTR_NOSYSTEM:`1`,GIT_CONFIG_GLOBAL:gitNullConfigPath(),GIT_CONFIG_SYSTEM:gitNullConfigPath(),GIT_INDEX_FILE:path.join(s,`index`)};const c=await r(()=>fs.stat(o,{bigint:true}));await r(()=>fs.copyFile(o,i.GIT_INDEX_FILE));const l=Number(c.mtimeNs/1000000000n);await r(()=>fs.utimes(i.GIT_INDEX_FILE,l,l));const u=await git([`write-tree`],i);try{const n=[`-c`,`core.attributesFile=${os.devNull}`,`add`,`-A`,`--verbose`];const a={cwd:e.cwd,env:i,timeoutMs:6e5,noOutputTimeoutMs:18e4,discardOutput:{stdout:true},beforeRun:e.assertCurrent};const o=await r(()=>t?t.worker.buffered(e.cwd,n,a):runPublicationCommand([`git`,`-c`,`core.fsmonitor=false`,...n],a));if(o.code!==0||o.error)throw createCommandError(`git add`,o,a)}catch(e){throw new Error(`GitHub publication snapshot staging failed before submission: ${formatErrorMessage(e,{includeCode:true})}. The source index is unchanged; inspect Git locks, disk space and host load, then retry publication.`,{cause:e})}let d=await git([`write-tree`],i);if(n){const t=await r(()=>readGitHubPublicationTree(e.cwd,d,runPublicationCommand));const a=[];let o=0;for(let e=t.indexOf(0);e!==-1;e=t.indexOf(0,o)){const r=t.indexOf(9,o)+1;const i=t.toString(`utf8`,r,e);if(!n.has(i)||i.includes(`�`)&&!Buffer.from(i).equals(t.subarray(r,e)))a.push(t.subarray(r,e+1));o=e+1}if(a.length){await git([`update-index`,`--force-remove`,`-z`,`--stdin`],i,Buffer.concat(a));d=await git([`write-tree`],i)}}await r(()=>assertGitHubPublicationIndexHasNoFilters(e.cwd,i.GIT_INDEX_FILE));return{sourceHeadCommit:a,sourceIndexTree:u,workspaceTree:d}}finally{await fs.rm(s,{recursive:true,force:true})}}const GITHUB_CREDENTIAL_ARGS=[`git`,`-c`,`credential.helper=`,`-c`,`credential.helper=!gh auth git-credential`];async function readGitHubPublicationCoauthorTrailers(e){return(await e.command([`git`,`-c`,`trailer.separators=:`,`-c`,`trailer.co-authored-by.key=Co-authored-by`,`show`,`-s`,`--format=%(trailers:key=Co-authored-by,only,unfold)`,e.headCommit],{cwd:e.cwd})).split(/\r?\n/u)}function appendGitHubPublicationMessage(e,t){const n=[...new Set(t)].join(`
`);return n?`${e.trimEnd()}\n\n${n}`:e.trimEnd()}function hasGitHubPublicationMessageFooter(e,t,n){const r=e.replace(/[\r\n]+$/u,``).split(/\r?\n/u);const i=r.lastIndexOf(``);if(i<1||r.at(-1)!==n)return false;const a=r.slice(i+1,-1);const o=new Set(t);return a.length===o.size&&[...o].every(e=>a.includes(e))}async function assertGitHubPublicationBranchRef(e,t){const n=await t([`git`,`symbolic-ref`,`--quiet`,`refs/heads/${e}`]);if(n===0)throw new Error(`GitHub publication workspace branch ref became symbolic.`);if(n!==1)throw new Error(`GitHub publication workspace branch ref could not be verified.`)}function githubPublicationPushArgs(e,t,n,r){return[...GITHUB_CREDENTIAL_ARGS,`-c`,`core.hooksPath=${os.devNull}`,`push`,`--porcelain`,`--force-with-lease=refs/heads/${n}:${r}`,`--no-follow-tags`,`--recurse-submodules=no`,`--`,e,`${t}:refs/heads/${n}`]}function githubPublicationRemoteHeadArgs(e,t){return[...GITHUB_CREDENTIAL_ARGS,`ls-remote`,`--refs`,e,`refs/heads/${t}`]}function githubPublicationUpdateRefArgs(e,t,n){return[`git`,`-c`,`core.hooksPath=${os.devNull}`,`-c`,`core.fsmonitor=false`,`update-ref`,`refs/heads/${e}`,t,n]}function gitHubPublicationObjectSha(e){if(!isRecord(e)||typeof e.sha!==`string`||!/^[a-f0-9]{40}$/u.test(e.sha))throw new Error(`GitHub returned an invalid Git object identity.`);return e.sha}export{requireGitHubPublicationCommit as _,captureGitHubPublicationWorkspaceSnapshot as a,createGitHubPublicationReadEnvironment as b,gitHubPublicationObjectSha as c,githubPublicationRemoteHeadArgs as d,githubPublicationUpdateRefArgs as f,readGitHubPublicationTree as g,readGitHubPublicationCoauthorTrailers as h,assertSafeGitPublicationWorkspace as i,githubPublicationApiArgs as l,readGitHubPublicationBaseSha as m,appendGitHubPublicationMessage as n,captureSettledGitHubPublicationWorkspaceSnapshot as o,hasGitHubPublicationMessageFooter as p,assertGitHubPublicationBranchRef as r,createGitHubPublicationCommandRunner as s,TREE_LISTING_MAX_OUTPUT_BYTES as t,githubPublicationPushArgs as u,requirePublicationCommand as v,runPublicationCommand as y};