UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10 lines • 24.8 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{o as captureExecRequestOwners}from"./exec-request-context-BB4c5QQi.mjs";import{St as resolveReplyRunForCurrentSessionId}from"./session-controller.state-BIDbpLPn.mjs";import{f as withGatewayToolCallerIdentity,o as getGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{n as jsonResult}from"./tool-results-BkLNMSCi.mjs";import{r as bindAgentToolListingScope}from"./agent-tool-metadata-D7ctyGhj.mjs";import"./common-DIgvX97L.mjs";import{_ as SessionGitHubPublishParamsSchema,a as GitHubPublicationEditSchema,c as GitHubPullRequestInspectSchema,i as GitHubPublicationActionSchema,o as GitHubPublicationEvidenceSchema,r as GitHubBaseRefreshSchema,s as GitHubPublicationTitleSchema}from"./session-github-publication-BWfce2xy.mjs";import{n as stringEnum}from"./string-enum-BHQI27hJ.mjs";import{t as findSessionControllerOperationByRunId}from"./session-controller.queries-CBzzV0sx.mjs";import{a as waitForGatewayDispatch}from"./server-in-process-dispatch-D586Y7B_.mjs";import{n as callAgentToolGatewayRequest,r as callInProcessGatewayTool}from"./in-process-gateway-vrnZpIbq.mjs";import{n as getAgentToolAssistantTurnId}from"./tool-execution-context-Rg9KhMAw.mjs";import{n as canRefreshGitHubPublicationBase,r as canUploadGitHubPublicationEvidence,t as canPrepareGitHubPullRequest}from"./github-publication-M73uvQ_4.mjs";import{Type}from"typebox"; //!src/agents/tools/github-publish-tool.ts const publicationOperatorActions=GitHubPublicationActionSchema.properties.action.anyOf.map(e=>e.const);const publicationWorkspaceActions=[`publish`,`readiness`,`inspect_pr`,`prepare_pr`,`refresh_base`,`edit`,`ready`,`request_review`,`upload_evidence`];const githubPublishToolDefinition={name:`github_publish`,parameters:Type.Object({publishingSessionKey:GitHubPublicationActionSchema.properties.publishingSessionKey,...GitHubBaseRefreshSchema.properties,...GitHubPublicationEditSchema.properties,evidence:Type.Optional(GitHubPublicationEvidenceSchema),action:Type.Optional(stringEnum(publicationWorkspaceActions)),title:Type.Optional(GitHubPublicationTitleSchema),body:GitHubPublicationEditSchema.properties.body,draft:Type.Optional(Type.Boolean()),workspacePath:SessionGitHubPublishParamsSchema.properties.workspacePath},{additionalProperties:false})};function describeGitHubPublishTool(e,t,n,r){return`readiness: strictly observe the selected publishing session and optional existing requestId without credentials, refresh, source adoption, publication or recovery. Reports separate read policy, custody, bounded target support and shared receipt facts; write authority, authentication, exact remote destination, CI and mergeability remain unknown. Pending or unconfirmed effects retain their original requestId: observe that request, never resubmit it. Accepts only action, publishingSessionKey and requestId. It does not check for running background exec, unfinished children, open terminals or another active run, which refuse workspace publication. inspect_pr: supply pullRequestUrl to read an existing PR. Guests verify authorship through their linked GitHub account; a current full-write maintainer may inspect another person's PR through the shared publisher. Accepts copied PR tab, query and comment links. Returns the canonical PR URL, author, state, base/head repositories, branches and observed commits. It does not prepare a workspace, bind the PR, publish changes or grant later authority. This is not a credential preflight for the managed publisher: bot-authored PRs need not belong to your linked account. Guests need verified current account access for private repositories. ${e?`Publish workspace changes or edit authorized PR metadata through Gateway-held credentials. - publish (default when action is omitted): publish accepted workspace changes as an open PR by default; draft: true creates a draft. title/body and draft are used only when creating a PR. Updating an existing PR preserves its state. requested/publishing means accepted, not finished: retain requestId, finish the turn and await its result here; do not submit another publication to recover it. The receipt does not resume the agent. If authorized review, CI or landing remains, continue that work before ending the turn, or use automations to schedule a continuation when it offers add and the current caller is authorized (at + agentTurn + sessionTarget "session:<this session key from Runtime>"). While that scheduled continuation waits, use automations next_check to rearm its existing job, not add another job. If a scheduled continuation is unavailable, explain the remaining work; a receipt does not complete it. With workspacePath, status started is not success: the result, possibly a refusal, resumes this session as the next turn. Running background exec, unfinished children, open terminals or another active run refuse preparation; finish or kill them first. Each checkout publishes to one PR; publishing it again updates that PR. - edit: read current metadata with {action: "edit"}. To edit an explicitly identified PR without preparing its source, also supply pullRequestUrl on every read and edit; the Gateway verifies your linked authorship or current maintainer authority and repository access. This explicit target takes precedence over the session PR and accepts no requestId. Read first, omitting expectedHeadCommit, title/body and expectedTitle/expectedBody. To change either field, send the read's top-level headCommit as expectedHeadCommit (not publication.headCommit), requestId when a publication receipt is returned, and its new value with the observed expectedTitle/expectedBody. Keep attribution, marker and footer unchanged in the full body. Omitted fields stay unchanged. Edit never synchronizes, stages, commits or pushes files or changes PR state. After an uncertain response, read again with action edit and the same pullRequestUrl when explicitly selected, without write preconditions, before retrying. - ready: mark the current session's own draft, or an explicitly identified pullRequestUrl, ready for review, using the expectedHeadCommit and any publication requestId observed with edit. After an uncertain response, read with edit before retrying. This does not merge the PR. - request_review: after an explicit re-review request, read the PR with edit, then send expectedHeadCommit and any publication requestId to post only "@clawsweeper re-review". For an explicitly identified PR, supply the same pullRequestUrl on the read and request_review, without requestId; current linked authorship or maintainer authority is verified without importing source. No comment text, focus or child target is accepted. Posting is not review acceptance or completion. If the response is uncertain, read existing PR comments before any new request; never retry blindly. ${t?`- prepare_pr: when the user asks to continue their own existing PR or a current full-write maintainer assists in this conversation, supply pullRequestUrl. Maintainer assistance does not require being the conversation creator or PR author and never grants later guest turns additional authority. Intent may be established before the URL arrives; inspect_pr is optional. An ordinary unbound conversation yields and resumes here with a new owned PR workspace. Earlier files remain in their original source and earlier message links stay read-only. Background work, children or terminals cause a no-effect busy refusal; finish or observe them and retry. Initial preparation in an already managed workspace requires clean source without dirty, untracked, staged, or unpublished work; otherwise preparation preserves it and refuses. For a PR this conversation published, including one the managed publisher authored, preparation instead merges another writer's newer head into the saved work. A clean workspace receives exactly the PR head files. Already managed workspaces keep their directory, sandbox scope and guest Git history. Preparation associates the original PR without publishing. Repeating a completed same-head preparation preserves edits without resetting files. ${n?`An explicit refresh reconciles the PR's current destination and review comparison while preserving local edits and history; a destination change alone does not merge it into the PR head. Use inspect_pr for current branch and commit facts when needed. Reconcile recoverable changes from the user's intent; ask a focused question only when the intended work is materially ambiguous. Do not ask the user to undo a destination change. An explicit refresh of the bound PR integrates its newer head while preserving later guest work. Files with both staged and unstaged changes must have their staged changes committed first; refresh preserves them and refuses. Resolve returned conflictPaths, then repeat with conflictsResolved: true and expectedHeadCommit set to the returned headCommit. `:``}Interrupted preparation finishes the same accepted head; if headChanged is true, repeat to integrate the newer remote head. Tests and Auto Review use the returned exact review base. After preparation, omit action to append accepted changes to the original PR through the shared publisher, preserving its branch history, author and draft state. A remote head change refuses publication and preserves local work until the newer head is integrated; do not create a replacement PR. Existing edit, ready${r?`, upload_evidence`:``} and request_review actions use the original bound PR before any new push. Read with edit first: an imported target returns pullRequest instead of a publication receipt; send expectedHeadCommit without requestId.\n`:``}${r?`- upload_evidence: upload one inspected image/video from this conversation's sandbox workspace to its existing GitHub.com PR repository. First read the PR with edit; send its expectedHeadCommit, any publication requestId, and evidence {path: workspace-relative path, sha256: inspected lowercase SHA-256, sizeBytes: inspected byte count, at most 10 MB}. Supports PNG, JPEG, GIF, WebP, MP4, MOV and WebM. Only the inspected bytes are sent. Use the returned uploaded URL with edit to associate it in the PR body, then verify reviewer access; uploaded does not prove public access. An unconfirmed result may have created an attachment: never repeat the upload blindly. No host credentials, other mounts, remote URLs, repository or PR selectors are accepted. `:``}${n?`- refresh_base: integrate the current target base of this workspace's prepared or published PR into its local managed sandbox before tests and Auto Review; without a PR, use the selected repository base. Finish any pending prepare_pr first. Base refresh preserves the accepted PR head and never imports another writer's newer PR head; use prepare_pr for that source update. Commit distinct staged changes before refreshing a file with unstaged edits. Resolve returned conflicts, then acknowledge with conflictsResolved: true and the returned baseCommit, including unchanged binary choices. Tests and Auto Review use the returned exact review base (mode local). Refresh stages source but preserves guest HEAD/branches/commits and never publishes. `:``}Edit, request_review, inspect, ready, merge and close accept an optional verified pullRequestUrl, never with a publishing session or source ref.`:`This conversation cannot publish its own workspace. It can act on an explicitly selected publishing child's PR.`} inspect, ready, merge and close act on this session's published or bound PR, a delegated child's publishingSessionKey, or an explicit pullRequestUrl (without requestId or publishingSessionKey). For an explicit landing request from a person with full operator write access, use inspect, then ready and merge after review and required checks; pass the same pullRequestUrl on every call for a PR this session did not publish. For an explicit closure request, use close to close the PR without merging or deleting saved work. ready, merge and close require the inspected expectedHeadCommit and any publication requestId; merge also requires mergeMethod. For delegated work, explicitly select its publishingSessionKey from this conversation's children; never guess a PR. Actions return the observed GitHub state and never enable auto-merge. Inspect after an uncertain response before retrying. Inspect, merge, close and child selection require full operator write access. These actions also support a bound original PR: use its observed expectedHeadCommit without requestId when no publication receipt is returned. Actions do not change session sandboxing.`}function describeGitHubPublishToolPreview(e){const t=isRecord(e)?e.properties:void 0;const n=isRecord(t)?t.action:void 0;if(!isRecord(n)||!Array.isArray(n.enum))throw new Error(`GitHub tool preview requires a declared action enum.`);return`GitHub actions in this preview: ${n.enum.filter(e=>typeof e===`string`).join(`, `)}. Some actions depend on the prepared runtime; previewing them grants no execution authority.`}const githubPublishParameterSchemas=/* @__PURE__ */ new Map;const githubPublicationObservationParameters=Type.Object({action:stringEnum([`readiness`]),publishingSessionKey:GitHubPublicationActionSchema.properties.publishingSessionKey,requestId:GitHubPublicationActionSchema.properties.requestId},{additionalProperties:false});function resolveGitHubPublishParameters(e){const{publicationAvailable:t,refreshBaseAvailable:n,evidenceAvailable:r,workspaceActions:i}=e;const a=[t,e.prepareAvailable,n,r,e.workspacePreparationAvailable].join(`:`);let o=githubPublishParameterSchemas.get(a);if(!o){o=t?Type.Object({...GitHubPublicationActionSchema.properties,...n?GitHubBaseRefreshSchema.properties:{},...GitHubPublicationEditSchema.properties,...r?{evidence:Type.Optional(GitHubPublicationEvidenceSchema)}:{},action:Type.Optional(stringEnum([.../* @__PURE__ */ new Set([...i,...publicationOperatorActions])])),title:Type.Optional(GitHubPublicationTitleSchema),body:GitHubPublicationEditSchema.properties.body,draft:Type.Optional(Type.Boolean()),...e.workspacePreparationAvailable?{workspacePath:SessionGitHubPublishParamsSchema.properties.workspacePath}:{}},{additionalProperties:false}):Type.Object({...GitHubPublicationActionSchema.properties,pullRequestUrl:Type.Optional(GitHubPullRequestInspectSchema.properties.pullRequestUrl),action:stringEnum([`readiness`,`inspect_pr`,...publicationOperatorActions])},{additionalProperties:false});githubPublishParameterSchemas.set(a,o)}return o}function createGitHubPublishTool(e={}){const t=e.publicationAvailable!==false;const n=!e.observationOnly&&t;const r=!e.sandbox;const i=e.preview||canPrepareGitHubPullRequest(e.sandbox);const a=!e.observationOnly&&i;const o=a&&e.sandbox?.workspaceSource!==`managed-worktree`;const s=e.preview||canRefreshGitHubPublicationBase(e.sandbox);const c=e.preview||canUploadGitHubPublicationEvidence(e.sandbox);const l=publicationWorkspaceActions.filter(e=>(e!==`prepare_pr`||a)&&(e!==`refresh_base`||s)&&(e!==`upload_evidence`||c));let u=e.runId?findSessionControllerOperationByRunId(e.runId):void 0;if(e.runId===void 0&&e.sessionId){const t=resolveReplyRunForCurrentSessionId(e.sessionId);u=t.kind===`one`?t.operation:void 0}const d=captureExecRequestOwners(e);const f={label:e.observationOnly?`GitHub Publication Readiness`:`GitHub Publish`,name:githubPublishToolDefinition.name,...i&&e.sandbox?.workspaceSource!==`managed-worktree`||t&&r?{async:false,catalogMode:`direct-only`}:{},description:e.observationOnly?`Observe publication readiness and existing receipts without credentials, refresh, publication, or recovery. Send action readiness and retain the original requestId for accepted or uncertain work; never resubmit it. This listing offers no authenticated GitHub actions; configuration or tool refresh re-evaluates them. For current identity status or setup, ask the operator to check GitHub in Settings → Agents → Tools. Readiness does not establish write authority, authentication, CI, or mergeability.`:e.preview?`Work with GitHub pull requests through the Gateway.`:describeGitHubPublishTool(n,a,s,c)+(n&&r?` For a local task checkout, supply workspacePath after committing its changes. Publication uses a separate task checkout and returns here without changing this conversation's workspace.`:``),parameters:e.observationOnly?githubPublicationObservationParameters:resolveGitHubPublishParameters({publicationAvailable:n,prepareAvailable:a,refreshBaseAvailable:s,evidenceAvailable:c,workspacePreparationAvailable:r,workspaceActions:l}),execute:async(t,i,s)=>{if(e.preview)throw new Error(`GitHub tool previews cannot execute actions.`);const c=i;const l=c.action??`publish`;if(e.observationOnly&&l!==`readiness`)throw new Error(`Only publication readiness and existing receipt observation are available.`);if(c.workspacePath!==void 0&&(l!==`publish`||!r))throw new Error(l===`publish`?`workspacePath is only available for local host publication.`:`workspacePath is accepted only with action publish. Send only the fields ${l} needs; omit optional fields instead of filling them with placeholders.`);const f=getGatewayToolCallerIdentity();if(!f?.sessionKey)throw new Error(`GitHub publication requires the current Gateway session.`);const callGateway=(...e)=>waitForGatewayDispatch(e[0],callInProcessGatewayTool(...e),e[2]?.timeoutMs??6e5,s);if(l===`readiness`){const e=Object.keys(c).filter(e=>![`action`,`publishingSessionKey`,`requestId`].includes(e));if(e.length)throw new Error(`readiness accepts only publishingSessionKey and an existing requestId; remove ${e.join(`, `)}.`);const t=await callGateway(`sessions.github.readiness`,{sessionKey:c.publishingSessionKey??f.sessionKey,...c.publishingSessionKey?{}:{agentId:f.agentId},...c.requestId?{requestId:c.requestId}:{}});return jsonResult(t.custody.kind===`unbound_workspace`&&!c.publishingSessionKey&&n&&r?{...t,next:`No checkout is bound yet. Commit the work, then publish with workspacePath set to the checkout. Running background exec, unfinished children, open terminals or another active run refuse preparation; finish or kill them first.`}:t)}const handoff=async(t,n,r)=>{const{handoffSessionTool:i}=await import(`./session-tool-handoff-BA8bIf9h.mjs`);return i({name:t,sessionId:e.sessionId,runId:e.runId,operation:u,requestOwners:d,onYield:e.onYield,signal:s,...n===`sessions.github.action`?{retainRequester:true}:{},fenceSuccessors:true,run:({assertCurrent:t,signal:i})=>withGatewayToolCallerIdentity({agentId:f.agentId,sessionKey:f.sessionKey,workspaceBaseRefreshSandbox:e.sandbox??void 0,workspacePrAdoptionSessionId:e.sessionId,workspacePublicationRunId:e.runId,...n===`sessions.github.publish`&&(e.inheritedToolAllowlist||e.inheritedToolDenylist||e.sessionPermissionPolicy)?{workspacePublicationPolicy:{allow:[...e.inheritedToolAllowlist??[]],deny:[...e.inheritedToolDenylist??[]],permissionMode:e.sessionPermissionPolicy?.mode}}:{}},()=>callAgentToolGatewayRequest({method:n,params:r,sessionMutationCommitGuard:t,signal:i,timeoutMs:null})),formatResult:e=>n===`sessions.github.publish`?JSON.stringify(e):JSON.stringify({status:e.status,url:e.url,headCommit:e.headCommit,headChanged:e.headChanged,review:e.review,...e.ok===false?{ok:false,error:typeof e.error===`string`?truncateUtf16Safe(e.error,1600):t+` failed.`}:{}})})};if(c.draft!==void 0&&c.action&&c.action!==`publish`)throw new Error(`draft only selects the state when publishing a new PR.`);if(c.action===`prepare_pr`){if(!n||!c.pullRequestUrl||Object.keys(c).some(e=>![`action`,`pullRequestUrl`,`conflictsResolved`,`expectedHeadCommit`].includes(e)))throw new Error(`prepare_pr accepts this PR's URL and its returned conflict acknowledgement for the current workspace.`);const t={sessionKey:f.sessionKey,action:`prepare_pr`,pullRequestUrl:c.pullRequestUrl,...c.conflictsResolved!==void 0?{conflictsResolved:c.conflictsResolved}:{},...c.expectedHeadCommit?{expectedHeadCommit:c.expectedHeadCommit}:{}};if(o&&e.sandbox)return handoff(`PR preparation`,`sessions.github.action`,t);return jsonResult(await withGatewayToolCallerIdentity({...f,workspaceBaseRefreshSandbox:e.sandbox??void 0},()=>callGateway(`sessions.github.action`,t,{timeoutMs:6e5})))}if(c.action===`inspect_pr`){const e=Object.keys(c).filter(e=>![`action`,`pullRequestUrl`].includes(e));if(!c.pullRequestUrl||e.length)throw new Error(`inspect_pr accepts only the pullRequestUrl to inspect, without publication or workspace fields${e.length?`; remove ${e.join(`, `)}`:``}.`);return jsonResult(await callGateway(`sessions.github.action`,{sessionKey:f.sessionKey,action:`inspect_pr`,pullRequestUrl:c.pullRequestUrl}))}if(c.pullRequestUrl!==void 0&&![`edit`,`request_review`,...publicationOperatorActions].includes(l))throw new Error(`Use inspect_pr${a?` or prepare_pr`:``}, edit, request_review, inspect, ready, merge or close for a pullRequestUrl.`);if(c.action===`request_review`){if(!n||Object.keys(c).some(e=>![`action`,`pullRequestUrl`,`requestId`,`expectedHeadCommit`].includes(e)))throw new Error(`request_review only posts the fixed ClawSweeper command on an authorized PR.`);return jsonResult(await callGateway(`sessions.github.action`,{sessionKey:f.sessionKey,action:`request_review`,...c.pullRequestUrl!==void 0?{pullRequestUrl:c.pullRequestUrl}:{},requestId:c.requestId,expectedHeadCommit:c.expectedHeadCommit}))}if(c.action===`upload_evidence`){if(!c.evidence||c.publishingSessionKey!==void 0||c.mergeMethod!==void 0||c.conflictsResolved!==void 0||c.baseCommit!==void 0||c.title!==void 0||c.body!==void 0||c.expectedTitle!==void 0||c.expectedBody!==void 0)throw new Error(`upload_evidence accepts only this session's observed PR and inspected workspace media.`);return jsonResult(await withGatewayToolCallerIdentity({...f,workspaceEvidenceSandbox:e.sandbox??void 0},()=>callGateway(`sessions.github.action`,{sessionKey:f.sessionKey,action:`upload_evidence`,requestId:c.requestId,expectedHeadCommit:c.expectedHeadCommit,evidence:c.evidence},{timeoutMs:18e4})))}if(c.evidence!==void 0)throw new Error(`Use upload_evidence for inspected media; other actions do not upload files.`);if(c.action===`edit`){if(!n||c.publishingSessionKey!==void 0||c.mergeMethod!==void 0||c.conflictsResolved!==void 0||c.baseCommit!==void 0)throw new Error(`edit accepts the current session PR or a verified PR URL, with metadata fields only.`);return jsonResult(await callGateway(`sessions.github.action`,{sessionKey:f.sessionKey,action:`edit`,...c.pullRequestUrl!==void 0?{pullRequestUrl:c.pullRequestUrl}:{},...c.requestId!==void 0?{requestId:c.requestId}:{},...c.expectedHeadCommit!==void 0?{expectedHeadCommit:c.expectedHeadCommit}:{},...c.title!==void 0?{title:c.title}:{},...c.body!==void 0?{body:c.body}:{},...c.expectedTitle!==void 0?{expectedTitle:c.expectedTitle}:{},...c.expectedBody!==void 0?{expectedBody:c.expectedBody}:{}}))}if(c.expectedTitle!==void 0||c.expectedBody!==void 0)throw new Error(`Use action edit for PR metadata preconditions; publish changes source.`);if(l===`refresh_base`){if(c.publishingSessionKey||c.requestId||c.expectedHeadCommit||c.mergeMethod||c.title!==void 0||c.body!==void 0)throw new Error(`refresh_base only prepares the current workspace; it accepts no publication target or PR action fields.`);return jsonResult(await withGatewayToolCallerIdentity({...f,workspaceBaseRefreshSandbox:e.sandbox??void 0},()=>callGateway(`sessions.github.action`,{sessionKey:f.sessionKey,action:`refresh_base`,...c.conflictsResolved!==void 0?{conflictsResolved:c.conflictsResolved}:{},...c.baseCommit?{baseCommit:c.baseCommit}:{}})))}if(l!==`publish`)return jsonResult(await callGateway(`sessions.github.action`,{sessionKey:f.sessionKey,action:l,...c.pullRequestUrl!==void 0?{pullRequestUrl:c.pullRequestUrl}:{},...c.publishingSessionKey?{publishingSessionKey:c.publishingSessionKey}:{},...c.requestId?{requestId:c.requestId}:{},...c.expectedHeadCommit?{expectedHeadCommit:c.expectedHeadCommit}:{},...c.mergeMethod?{mergeMethod:c.mergeMethod}:{}}));if(!n)throw new Error(`This session cannot publish its workspace; select a publishing child and an explicit PR action.`);const p=getAgentToolAssistantTurnId();const m={sessionKey:f.sessionKey,idempotencyKey:p?`${p}:${t}`:t,...c.title?{title:c.title}:{},...c.body!==void 0?{body:c.body}:{},...c.draft!==void 0?{draft:c.draft}:{},...c.workspacePath!==void 0?{workspacePath:c.workspacePath}:{}};if(c.workspacePath!==void 0)return handoff(`GitHub publication`,`sessions.github.publish`,m);const h=await callGateway(`sessions.github.publish`,m);return jsonResult(h)}};bindAgentToolListingScope(f,[t,i,s,c,r].join(`:`));return f}export{describeGitHubPublishToolPreview as n,githubPublishToolDefinition as r,createGitHubPublishTool as t};