Skip to content

@chamvi/github ​

The GitHub channel (webhook deliveries in, issue comments out) and GitHub tools for chamvi agents. The public API of packages/github/src/index.ts.

bash
npm install @chamvi/github @chamvi/http @chamvi/core ai --save

@chamvi/core, @chamvi/http and ai are peer dependencies. See GitHub App for setup and behaviour.

createGithubApp ​

ts
function createGithubApp(options: GithubAppOptions): IGithubApp;

const DEFAULT_GITHUB_API_URL: 'https://api.github.com';
const INSTALLATION_CACHE_TTL_MS: 600_000;

Throws InvalidAgentDefinitionError for an empty appId, a key that is no RSA private key, an empty webhook secret, an installationId that is no positive integer, a baseUrl that is no absolute https URL without query (empty means https://api.github.com) and a slug that is not the App's lower-case slug (^[a-z0-9]+(-[a-z0-9]+)*$, as in the App's URL; a miscased one would silently disable the self guard).

ts
/*
 * Copyright (c) 2026.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import type { ToolSet } from 'ai';
import type { IClock } from '@chamvi/core';
import type { PaginatedOctokit } from './helpers/index.ts';

export type GithubAppOptions = {
    appId: string | number;
    /** PEM (PKCS#1 or PKCS#8); literal "\n" sequences become newlines. */
    privateKey: string;
    /** Several during a secret rotation; a delivery verifies under any. */
    webhookSecret: string | readonly string[];
    /** For runs not started by a delivery (cron, http, mcp) and comments on their behalf. */
    installationId?: number;
    /** The App's slug; skips `GET /app` for the bot login. */
    slug?: string;
    /** Default DEFAULT_GITHUB_API_URL ('https://api.github.com'). */
    baseUrl?: string;
    clock?: IClock;
    fetch?: typeof globalThis.fetch;
    /** Opt in to file proposals, limited to these repositories and repository-relative globs. */
    proposals?: GithubProposalsOptions;
};

/** The allowlist for `github_propose_change`; `.github/**` is always forbidden. */
export type GithubProposalsOptions = {
    repos: Record<string, { paths: readonly string[] }>;
};

/** An Octokit (`@octokit/core` with `paginate`). */
export type GithubOctokit = InstanceType<typeof PaginatedOctokit>;

/** GitHub App permissions of a token, e.g. `{ contents: 'write', workflows: 'write' }`. */
export type GithubPermissions = Record<string, 'read' | 'write'>;

/** A short-lived token of one repository (`IGithubApp.repositoryToken`). */
export type GithubRepositoryToken = {
    token: string;
    expiresAt: Date;
};

/** The App's bot as a git commit identity. */
export type GithubBotIdentity = {
    /** `<slug>[bot]`. */
    name: string;
    /** `<bot user id>+<slug>[bot]@users.noreply.github.com`, which GitHub links to the bot. */
    email: string;
};

/** An installation of the App (`IGithubApp.installations()`). */
export type GithubInstallation = {
    id: number;
    /** The account login, e.g. `tada5hi` or an org. */
    account: string;
    /** `User` or `Organization`. */
    accountType: string;
    repositorySelection: 'all' | 'selected';
    permissions: GithubPermissions;
    /** Whether the account suspended the App (`suspended_at` set): its token exchange answers 403. */
    suspended: boolean;
};

/** A merge method of `github_merge_pull_request`. */
export type GithubMergeMethod = 'merge' | 'squash' | 'rebase';

/** Options of `IGithubApp.writeTools()`. */
export type GithubWriteToolsOptions = {
    /** The merge method when a call names none (default DEFAULT_MERGE_METHOD, `squash`). */
    mergeMethod?: GithubMergeMethod;
};

export interface IGithubApp {
    readonly appId: string;
    readonly installationId?: number;
    /** An Octokit authenticated as the installation (cached token). */
    octokit(installationId: number): Promise<GithubOctokit>;
    /** `<slug>[bot]`, from `slug` or one `GET /app`; cached, single-flight. */
    botLogin(): Promise<string>;
    /**
     * The bot as a commit identity (`GET /users/<login>` for its user id,
     * once; a failure is not cached), e.g. the workspace manager's `author`.
     */
    botIdentity(): Promise<GithubBotIdentity>;
    /**
     * A token limited to one repository and `permissions` (the deferred
     * scoped token of plan 014): the App's installation on the repository
     * (`GET /repos/{owner}/{repo}/installation`), then an exchange with
     * `repositories: [repo]`. Cached per repository and permissions until 5
     * minutes before it expires, concurrent callers share one exchange, a
     * failure is not cached. Undefined when the App is not installed there.
     */
    repositoryToken(target: { owner: string; repo: string }, options: { permissions: GithubPermissions }): Promise<GithubRepositoryToken | undefined>;
    /**
     * The App's installation on the repository (App JWT `GET
     * /repos/{owner}/{repo}/installation`), cached per lower-cased
     * `owner/repo` for INSTALLATION_CACHE_TTL_MS on the clock; concurrent
     * callers share one lookup. Undefined (not cached) when the App is not
     * installed there; a failure is a `github_request` ChamviError and not
     * cached.
     */
    installationFor(target: { owner: string; repo: string }): Promise<number | undefined>;
    /**
     * The whole installation `installationFor()` looked up (account,
     * permissions), from the same cache; undefined where the App is not
     * installed.
     */
    repositoryInstallation(target: { owner: string; repo: string }): Promise<GithubInstallation | undefined>;
    /** Every installation of the App (`GET /app/installations`, paginated), not cached. */
    installations(): Promise<GithubInstallation[]>;
    /** `sha256=<hex>` of the raw body under any webhook secret, compared in constant time. */
    verifySignature(body: Uint8Array, signature: string | null): boolean;
    /**
     * The read-only tools (`github_get_issue`, `github_search_issues`,
     * `github_list_pull_requests`, ...), each acting as the installation of
     * the repository it names.
     */
    readTools(): ToolSet;
    /**
     * The write tools (`github_add_labels`, `github_create_comment`,
     * `github_close_issue`, `github_create_issue`,
     * `github_create_pull_request`, `github_merge_pull_request`), effect
     * tools applied at most once per run. An unknown `mergeMethod` is an
     * InvalidAgentDefinitionError.
     */
    writeTools(options?: GithubWriteToolsOptions): ToolSet;
}

/** An `IGithubApp` whose real App arrives later (`createDeferredGithubApp()`). */
export interface IDeferredGithubApp extends IGithubApp {
    /** Whether `bind` was called. */
    readonly configured: boolean;
    /** The App every call goes to from now on; replaces an earlier one. */
    bind(app: IGithubApp): void;
}

export type DeferredGithubAppOptions = ({
    /** The connection named by the not-configured errors. */
    connection: string;
} | {
    /** An agent no GitHub connection serves: the errors name it, never a connection. */
    agent: string;
}) & {
    /** Validated now, so the write tools can carry the proposal tool before the App exists. */
    proposals?: GithubProposalsOptions;
};

installationFor({ owner, repo }) answers the App's installation on a repository (App JWT, cached per lower-cased owner/repo for INSTALLATION_CACHE_TTL_MS on the clock, concurrent callers sharing one lookup; undefined, not cached, where the App is not installed); repositoryInstallation({ owner, repo }) answers the whole installation of that lookup (GithubInstallation, permissions included) from the same cache; installations() lists every installation (GET /app/installations, not cached). writeTools({ mergeMethod }) throws InvalidAgentDefinitionError for a method outside MERGE_METHODS.

ts
const GITHUB_REQUEST_ERROR_CODE: 'github_request';
const REPO_PATTERN: string; // '^([\\w.-]*[\\w-][\\w.-]*)/([\\w.-]*[\\w-][\\w.-]*)$'

GITHUB_REQUEST_ERROR_CODE is the code of every failed GitHub request (the tools' errors and the channel's send failures); REPO_PATTERN is the owner/name rule the tools apply (GitHub's name characters, each segment with one that is not a dot, so . and .. never fold the URL into another API path). Build a RegExp from it.

githubChannel ​

ts
function githubChannel(options: GithubChannelOptions): GithubChannel; // IChannel with in and out, plus on() and to() bound to its name

const GITHUB_CHANNEL_NAME: 'github';
const GITHUB_CHANNEL_TIMEOUT_MS: 30_000;
const COMMENT_BODY_MAX_LENGTH: 60_000;
ts
/** What `approvalUrl` gets: ids only, never a token. */
export type GithubApprovalRef = {
    runId: string;
    approvalId: string;
    agent: string;
};

export type GithubChannelOptions = {
    app: IGithubApp;
    /** The channel name; default `'github'`. A second instance needs its own. */
    name?: string;
    /** Persistent-comment coordination: the engine's lock service (`engine.lockService`), shared across replicas. */
    locks: Pick<ILockService, 'acquire' | 'release'>;
    /** Logins mentioned at the top of every comment (without `@`). */
    mention?: string | readonly string[];
    /**
     * A link to the approval in the chamvi UI, e.g.
     * `https://<app>/ui/approvals?run=<runId>&approval=<approvalId>`, where the
     * signed-in owner answers it; it carries no token.
     */
    approvalUrl?: (ref: GithubApprovalRef) => string;
    /** Bound of one comment send; default `GITHUB_CHANNEL_TIMEOUT_MS` (30 s). */
    timeoutMs?: number;
    /** Bytes a delivery may have (413 above); default 1 MiB. */
    bodyLimit?: number;
    /**
     * Receives each agent a delivery could not be dispatched to (a throwing
     * filter or key function, a refused key, a failed dispatch); the delivery
     * is then answered 500. Default `console.error('[chamvi]', error)`.
     */
    onError?: (error: unknown) => void;
    clock?: IClock;
};

/** The GitHub channel: deliveries `in`, issue and pull request comments `out`, with `on()` and `to()` bound to its name. */
export type GithubChannel = IChannel<ChannelRequest, Response> & GithubSubscriber;

Every option is checked when githubChannel() is called (InvalidAgentDefinitionError). Register the channel on the engine and list it in createHttpApp({ channels }), which serves its in at POST /channels/<name> (the deliveries: signature, self guard, one run per matching agent, 202 with a GithubWebhookResult). Its out(message, address) comments on the issue or pull request address names (owner/repo#n, else a ValidationError), deduplicated by the marker effectMarker(message.key). An approval with options lists them fenced as - <id>: <label> under Options (choose one): (or Options (choose one or more):), the body is cut by that block's length, and the link line reads Choose and approve or deny: <link>. See GitHub App for both directions.

Send emit({ body, slot: 'status' }) or approve({ title, slot: 'status' }) to create/update one persistent comment per GitHub App, repository, issue/PR, channel, agent and named slot. slot must be a non-empty, well-formed Unicode string without NUL characters; omitting it appends an ordinary comment. A channel and agent can mix ordinary comments and multiple slots. Approval slots survive notification retries and recovery. locks: Pick<LockService, 'acquire' | 'release'> (required) coordinates slot lookup and write: pass engine.lockService; githubModule() supplies the app's lock service. A busy slot is waited for with backoff within timeoutMs, then fails with github_request for retry; the lock release runs in the background (failures to onError) and never fails a delivered comment. Persistent lookup has no time cutoff and pages every comment (no durable comment id cache), so very long threads can outlast timeoutMs; it requires the stable marker and App bot identity, and PATCH errors never create a replacement in the same attempt. See persistent status comments for replica and ordering limits.

ts
/*
 * Copyright (c) 2026.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

/** The `202` answer to a delivery: the run each matching agent got (deduplicated on a redelivery). */
export type GithubWebhookResult = {
    delivery: string;
    runs: Array<{
        agent: string;
        runId: string;
        deduplicated: boolean;
    }>;
};

github.on, github.to ​

ts
const github: GithubSubscriber; // github.on(events, options?), github.to({ repo, number }) for the channel named 'github'

github.on() throws InvalidAgentDefinitionError without events or for an event that is not name or name.action (lower case letters, digits and underscores, e.g. projects_v2_item.created), and for a selfEvents entry of that shape naming issue_comment, issues or pull_request_review_comment (the bot's own comment would start the agent again). A bot-sent delivery starts each agent's first matching subscription whose selfEvents name it; a bare pull_request there also takes the labeled, closed and synchronize deliveries the agent's own tools and pushes cause, so name the actions (pull_request.opened). A delivery the App's bot sent reaches only subscriptions whose selfEvents name its event. github.to({ repo, number }) returns the address <owner>/<repo>#<number>.

ts
/*
 * Copyright (c) 2026.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import type { ChannelSubscription } from '@chamvi/core';

/** The parts of a GitHub webhook body chamvi reads; the rest passes through. */
export type GithubPayload = {
    action?: string;
    installation?: { id: number };
    repository?: {
        id?: number;
        full_name: string;
        [key: string]: unknown
    };
    sender?: {
        login: string;
        type: string;
        [key: string]: unknown
    };
    issue?: { number: number; [key: string]: unknown };
    pull_request?: { number: number; [key: string]: unknown };
    [key: string]: unknown;
};

/** The envelope payload of a run the GitHub channel started. */
export type GithubEvent = {
    /** X-GitHub-Event, e.g. 'issues'; not covered by the signature, so never a key on its own. */
    name: string;
    action?: string;
    /** X-GitHub-Delivery; not covered by the signature. */
    delivery: string;
    installationId?: number;
    payload: GithubPayload;
};

export type GithubSubscriptionOptions = {
    /** Shared-store execution cap within the agent; omitted or false adds no cap. */
    concurrencyMaxRuns?: number | false;
    /** Default `github:<events joined by ','>`. */
    id?: string;
    /** Runs after the event match; a delivery it refuses starts no run of this subscription. */
    filter?: (event: GithubEvent) => boolean;
    /**
     * Default: the delivery id (applied by the channel). The signature does not
     * cover that header, so a replayed body under a new id is a new run;
     * derive the key from the content on an exposed endpoint.
     */
    idempotencyKey?: (event: GithubEvent) => string | undefined;
    /**
     * Default: `<full_name>#<issue|pull_request number>` (a check suite or
     * check run: its one pull request of the repository), else `<full_name>`.
     */
    concurrencyKey?: (event: GithubEvent) => string | undefined;
    /**
     * Events (`name` or `name.action`) the App's own bot may start this
     * subscription with, e.g. `['pull_request.opened',
     * 'pull_request.synchronize', 'check_suite.completed']` for the pull
     * requests the agent opens or pushes to. Every other delivery the bot
     * sent dispatches nothing (the loop guard). A bare `pull_request` also
     * takes the `labeled`, `closed`, ... the agent's own tools cause, so it
     * starts again after each of its writes: name the actions. The agent's
     * first subscription matching the event whose `selfEvents` name it is
     * the one started.
     * `issue_comment`, `issues` and `pull_request_review_comment` are
     * refused (InvalidAgentDefinitionError): the bot's own comment would
     * start the agent again.
     */
    selfEvents?: readonly string[];
};

/** An issue or pull request, for `github.to()`. */
export type GithubTarget = {
    /** `owner/name`. */
    repo: string;
    /** The issue or pull request number. */
    number: number;
};

/** Makes GitHub subscriptions and addresses for one channel name. */
export type GithubSubscriber = {
    /**
     * A subscription to deliveries of `events`: `'issues'` (every action) or
     * `'issues.opened'`, one or several.
     */
    on(events: string | readonly string[], options?: GithubSubscriptionOptions): ChannelSubscription<GithubEvent>;
    /** The address of an issue or pull request, `<owner>/<repo>#<number>`. */
    to(target: GithubTarget): string;
};

Tools ​

ts
const DEFAULT_MERGE_METHOD: 'squash';
const MERGE_METHODS: readonly ['merge', 'squash', 'rebase'];
const MERGE_STATES: readonly ['clean', 'unstable', 'has_hooks'];

gh.readTools() (github_get_issue, github_search_issues, github_list_labels, github_get_pull_request, github_get_file, github_get_latest_release, github_list_releases, github_compare, github_list_repositories, github_list_issues, github_list_pull_requests, github_get_pull_request_checks, github_get_push_target) and gh.writeTools(options?) (github_add_labels, github_create_comment, github_close_issue, github_create_issue, github_create_pull_request, github_merge_pull_request) return plain AI SDK ToolSets. Each tool acts as the installation of the repository it names: the delivery's for a run of the GitHub channel on that repository, else installationFor(), else the delivery's or installationId (a public repository the App is not installed on stays readable); without any a github_request tool error. github_merge_pull_request refuses with ToolDeniedError, before the merge request, a closed pull request, a head that moved from sha, a draft, a mergeability not computed yet, a mergeable_state outside MERGE_STATES any required check that is not green or has not reported, required checks it cannot read (a 403 or 404 on the branch or its rules, required.known false), a head without any check yet and any check still running; a failing check that is not required does not stop it. The results are these shapes.

ts
/*
 * Copyright (c) 2026.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import type { GithubMergeMethod } from '../app/types.ts';

/** The input of a tool on a repository. */
export type RepoInput = { repo: string };

/** `github_propose_change`: replacement content for one allowlisted file. */
export type GithubProposeChangeInput = RepoInput & {
    path: string;
    content: string;
    reason: string;
};

/** The input of a tool on an issue or pull request. */
export type NumberInput = RepoInput & { number: number };

/** A parsed repository (`parseRepo`), the target an installation is resolved for. */
export type RepoTarget = { owner: string; repo: string };

/** `github_get_issue`. */
export type GithubIssue = {
    number: number;
    title: string;
    body: string | null;
    state: string;
    labels: string[];
    author: string | null;
    url: string;
    createdAt: string;
    comments: number;
    isPullRequest: boolean;
};

/** `github_search_issues`. */
export type GithubIssueSearch = {
    total: number;
    items: Array<{
        repo: string;
        number: number;
        title: string;
        state: string;
        url: string;
    }>;
};

/** One entry of `github_list_labels`. */
export type GithubLabel = {
    name: string;
    description: string | null;
};

/** `github_get_pull_request`; `base` and `head` are branch names. */
export type GithubPullRequest = {
    number: number;
    title: string;
    body: string | null;
    state: string;
    draft: boolean;
    merged: boolean;
    base: string;
    head: string;
    author: string | null;
    url: string;
    changedFiles: number;
    headSha: string;
    /** `owner/name` of the head repository; null when the fork was deleted. */
    headRepo: string | null;
    /** The head lives in another repository than the base (or was deleted). */
    fork: boolean;
    /** The author's account type, e.g. `Bot` or `User`. */
    authorType: string | null;
    labels: string[];
    /** null while GitHub is still computing it. */
    mergeable: boolean | null;
    /** GitHub's `mergeable_state` (`clean`, `unstable`, `dirty`, `blocked`, `behind`, `draft`, `has_hooks`, `unknown`). */
    mergeableState: string;
    maintainerCanModify: boolean;
    mergeCommitSha: string | null;
};

/** `github_get_file` for a file: UTF-8 text, cut at FILE_MAX_CHARS characters. */
export type GithubFile = {
    path: string;
    size: number;
    content: string;
    truncated: boolean;
};

/** `github_get_file` for a directory. */
export type GithubDirectory = {
    path: string;
    entries: Array<{
        name: string;
        type: string;
        path: string;
    }>;
};

/** `github_get_latest_release`; `{ none: true }` when the repository has no release. */
export type GithubRelease = {
    tag: string;
    name: string | null;
    publishedAt: string | null;
    url: string;
    body: string | null;
} | { none: true };

/** One release of `github_list_releases`. */
export type GithubReleaseNote = {
    tag: string;
    name: string | null;
    publishedAt: string | null;
    url: string;
    prerelease: boolean;
    /** Cut at RELEASE_BODY_MAX_CHARS characters. */
    body: string | null;
    bodyTruncated: boolean;
};

/** `github_list_releases`: oldest first; `truncated` when more matched than RELEASES_MAX or the pages read did not reach `from`. */
export type GithubReleaseList = {
    releases: GithubReleaseNote[];
    truncated: boolean;
    /** The scan stopped before the last page (not exhaustive) with nothing in range: a later page may hold a release. */
    incomplete: boolean;
};

/** `github_compare`: commits oldest first, both lists capped. */
export type GithubComparison = {
    status: string;
    aheadBy: number;
    behindBy: number;
    totalCommits: number;
    url: string;
    commits: Array<{
        sha: string;
        /** The first line, cut at 300 characters. */
        message: string;
        author: string | null;
        date: string | null;
    }>;
    files: Array<{
        path: string;
        status: string;
        additions: number;
        deletions: number;
    }>;
    /** True when commits were cut or the files reached GitHub's cap of 300 (more may exist). */
    truncated: boolean;
};

/** `github_create_comment`: the posted (or found) comment. */
export type GithubComment = {
    id: number;
    url: string;
};

/** `github_add_labels`: every label the issue carries afterwards. */
export type GithubIssueLabels = {
    labels: string[];
};

/** `github_close_issue`. */
export type GithubClosedIssue = {
    number: number;
    state: 'closed';
    stateReason: string | null;
};

/** One repository of `github_list_repositories`: `repo` is `owner/name`, `account` the installation's account. */
export type GithubRepository = {
    repo: string;
    installationId: number;
    account: string;
    private: boolean;
    archived: boolean;
    fork: boolean;
    defaultBranch: string;
    url: string;
};

/** `github_list_repositories`, sorted by `repo`; `truncated` when REPOSITORIES_MAX cut it. */
export type GithubRepositoryList = {
    repositories: GithubRepository[];
    truncated: boolean;
};

/** One open issue of `github_list_issues`. */
export type GithubIssueSummary = {
    number: number;
    title: string;
    author: string | null;
    labels: string[];
    comments: number;
    createdAt: string;
    updatedAt: string;
    url: string;
};

/** `github_list_issues`, newest updated first; `truncated` when more remained. */
export type GithubIssueList = {
    issues: GithubIssueSummary[];
    truncated: boolean;
};

/** One open pull request of `github_list_pull_requests`. */
export type GithubPullRequestSummary = {
    number: number;
    title: string;
    author: string | null;
    authorType: string | null;
    draft: boolean;
    base: string;
    head: string;
    headSha: string;
    headRepo: string | null;
    fork: boolean;
    labels: string[];
    createdAt: string;
    updatedAt: string;
    url: string;
};

/** `github_list_pull_requests`; `truncated` when more remained. */
export type GithubPullRequestList = {
    pullRequests: GithubPullRequestSummary[];
    truncated: boolean;
};

/** `github_get_push_target`: whether the App can push fix commits onto a pull request's branch. */
export type GithubPushTarget = {
    number: number;
    headRepo: string | null;
    headBranch: string;
    headSha: string;
    fork: boolean;
    /** The App's installation on the head repository, null when not installed. */
    installationId: number | null;
    contents: 'read' | 'write' | null;
    workflows: 'read' | 'write' | null;
    maintainerCanModify: boolean;
    /** headRepo set, installed, contents write. A fork the App is not installed on is never pushable (App tokens cannot use maintainer edits). */
    canPush: boolean;
    /** Why `canPush` is false, else null. */
    reason: string | null;
};

/** How a check reads: green, red, or not finished. */
export type GithubCheckOutcome = 'success' | 'failure' | 'pending';

/** One check run or commit status of a pull request's head. */
export type GithubCheck = {
    name: string;
    kind: 'check_run' | 'status';
    /** check run: queued | in_progress | completed | waiting | requested | pending; status: its state. */
    status: string;
    conclusion: string | null;
    outcome: GithubCheckOutcome;
    required: boolean;
    url: string | null;
};

/** `none` while no check reported at all (a push seconds ago): never read as green. */
export type GithubChecksState = 'success' | 'failure' | 'pending' | 'none';

/** `github_get_pull_request_checks`. */
export type GithubPullRequestChecks = {
    number: number;
    headSha: string;
    base: string;
    state: GithubChecksState;
    pending: number;
    failing: number;
    checks: GithubCheck[];
    required: {
        /** false when branch protection or the rulesets could not be read (403, 404): required checks may exist that are not listed. */
        known: boolean;
        contexts: string[];
        /** Required contexts with no report yet; counted as pending. */
        missing: string[];
    };
    truncated: boolean;
};

/** `github_create_issue`. */
export type GithubCreatedIssue = {
    number: number;
    url: string;
};

/** `github_create_pull_request`; `head` as `owner:branch`. */
export type GithubCreatedPullRequest = {
    number: number;
    url: string;
    base: string;
    head: string;
};

/** `github_merge_pull_request`: `sha` is the merge commit. */
export type GithubMergeResult = {
    number: number;
    sha: string;
    method: GithubMergeMethod;
    /** It was merged at the given head before this call (a redone step). */
    alreadyMerged: boolean;
};

Opt-in file proposals ​

createGithubApp({ ..., proposals: { repos: { 'acme/agents': { paths: ['agents/**', 'skills/**'] } } } }) enables github_propose_change in app.writeTools(). Without proposals, app.writeTools() does not include it. GithubAppOptions.proposals uses GithubProposalsOptions; configuration is validated and copied at app construction.

The input is GithubProposeChangeInput: { repo, path, content, reason }. It returns { number, url, base, head } after creating or updating one stable branch and open PR for the agent/path, based on the repository's default branch. Every repository/path must match the configured allowlist; unsafe/ambiguous paths, .github/**, .husky/**, CODEOWNERS and .gitmodules (in any folder) and paths holding Unicode format characters (category Cf, e.g. bidi overrides and zero-width characters, which would also reach the PR title) are always refused before GitHub requests, also as allowlist globs. There is no general file-write tool, automatic merge or local config hot reload. Review and merge through the existing PR flow; normal folder reload picks up merged configuration.

This is an outbound effect tool, subject to untrusted-run approval. The initial branch is chamvi/<agent>/<path-slug>-<path-hash>, and the effect key <runId>:propose:<repo>:<path>:<sha256 of content>:<model step> permits one proposal per run, path, content and model step: a corrected content for the same path in one run (approved again by the outbound gate) is applied as a new commit, never answered with the first proposal's record. Proposal PRs are found per branch (head=<owner>:<branch>, one request per generation), so a repository's total PR count does not matter. Later runs reuse its open PR. After closure or merge, new proposals use a fresh -g-<previous-pr-number> branch from the current default branch. Content already matching that base produces a no-change validation error, not an empty PR. Paginated commit ancestry reconciles lost effects without reverting newer content, including closed/merged PRs whose branches were deleted. Preserve proposal commits and PR ownership markers for recovery.

Pinned Git-tree reads reject symlinks, submodules and non-directory parents; regular-file executable mode is preserved. Diffs use observed base/head SHAs, include rename sources, and reject missing/truncated data and the 300-file comparison cap. Commits have the observed head as their sole parent and refs advance without force. Proposal-branch movement detected before or after PR publication fails closed, but can leave an already published PR to review. Base movement is checked before publication only, so a busy default branch never reports an applied proposal as failed.

Exclusive tool ownership of proposal branches is required. Serialize runs for the same agent/repository/path; external writes, force resets and deletion of active branches are unsupported. Checks cover an observed head, not an immutable branch. Ref updates and PR publication are not atomic, and no check guarantees future PR contents after its final observation. Review the current head before merging. GitHub App permissions must allow contents and pull-request writes. See the package README's tools section for details.

Proposal reconciliation scans each historical PR independently and returns immediately on a matching run marker. A missing marker at GitHub's 250-commit PR cap fails closed. New updates stop at 249 commits: close or merge the proposal to allow a fresh generation. Already-capped historical PRs may require manual recovery. Unpublished branches are checked back to the pinned comparison's merge base, so independent base advancement does not invalidate proposal ownership.

Content trust ​

The GitHub channel opts into untrusted ingress, and GitHub reads return untrusted content. Creating issues, pull requests and file proposals, merging, and commenting on another issue/PR are outbound. A comment on the source issue/PR is exempt. Adding only labels that already exist in the target repository is also exempt; introducing a new label name, or failing to resolve the repository's label vocabulary, remains outbound. Closing an issue is not classified outbound. Adding labels still taints the run: GitHub returns all labels on the issue, including externally controlled existing names. These destination/finite-label exemptions do not sanitize message content or replace authorization. See Tools and Approvals.

Git credentials ​

ts
function githubAppCredentials(app: IGithubApp, options?: GithubAppCredentialsOptions): IGithubGitCredentials;

const DEFAULT_GITHUB_GIT_HOST: 'github.com';
const GITHUB_TOKEN_USERNAME: 'x-access-token';

The workspace manager's credentials source for the App (typed structurally against @chamvi/sandbox's IGitCredentials, which this package does not depend on): for a request of its host (default github.com) and an owner/name path it answers app.repositoryToken() as x-access-token, with contents: read for read and contents: write plus options.permissions for write; nothing for another host, the host itself or a repository the App is not installed on, so the next source (or an anonymous call) follows. Throws InvalidAgentDefinitionError for an app without repositoryToken, permissions that are not read or write and a host that is no host name. app.repositoryToken({ owner, repo }, { permissions }) finds the installation (GET /repos/{owner}/{repo}/installation, a 404 answers undefined) and exchanges a token with repositories: [repo], cached per installation, repository and permissions until 5 minutes before it expires (one exchange for concurrent callers, failures not cached); app.botIdentity() is { name: '<slug>[bot]', email: '<user id>+<slug>[bot]@users.noreply.github.com' } (one public GET /users/<login>), for the manager's author.

ts
/*
 * Copyright (c) 2026.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import type { GithubPermissions } from '../app/types.ts';

/**
 * What a git credential source is asked (structurally the
 * `GitCredentialRequest` of `@chamvi/sandbox`, which this package does not
 * depend on).
 */
export type GithubGitCredentialRequest = {
    url: string;
    /** Lower case, with the port when the URL names one. */
    host: string;
    /** `owner/name`; empty for the host itself. */
    path: string;
    access: 'read' | 'write';
    runId: string;
    signal?: AbortSignal;
};

/** Structurally `@chamvi/sandbox`'s `GitCredential`. */
export type GithubGitCredential = {
    username: string;
    password: string;
    expiresAt?: Date;
};

/** Structurally `@chamvi/sandbox`'s `IGitCredentials`: pass it as the workspace manager's `credentials`. */
export interface IGithubGitCredentials {
    get(input: GithubGitCredentialRequest): Promise<GithubGitCredential | undefined>;
}

export type GithubAppCredentialsOptions = {
    /**
     * Added to write tokens (`contents: write` always), e.g.
     * `{ workflows: 'write' }` to push changes under `.github/workflows`.
     */
    permissions?: GithubPermissions;
    /** The git host the App serves; default `github.com` (a GitHub Enterprise Server host otherwise). */
    host?: string;
};

Context ​

ts
function provideGithubContext(provider: IContextProvider, app: IGithubApp): void; // engine.provide under the key 'github'
function injectGithubContext(ctx: ToolContext): IGithubApp;                    // else ContextNotProvidedError

With a hand-built engine call provideGithubContext(engine, gh) after new Engine(): one App for every agent. The githubModule() instances instead provide a per-agent resolver once per engine, and injectGithubContext(ctx) picks the App by the run's agent. Inject in a tools factory (tools: (ctx) => injectGithubContext(ctx).readTools()), in a tool's execute or in an effect hook; see Context. One provide per engine: a second one throws InvalidAgentDefinitionError.

Module ​

ts
// @chamvi/github/module, needs @chamvi/app
function githubModule(options?: GithubModuleOptions): GithubModule; // id `chamvi:github:<name>` (default name `github`), .app: IGithubApp

Reads GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY, GITHUB_WEBHOOK_SECRET (comma-separated), GITHUB_INSTALLATION_ID, GITHUB_APP_SLUG and GITHUB_API_URL (GITHUB_<NAME>_* for a module with name) from options.env ?? process.env, then the connection store in setup, unless options.app is given; explicit options win. A partial env fails at startup naming the missing variable, nothing set starts idle (tools report not configured, webhooks answer 503). agents restricts a module to those agents; a targeted module contributes git credentials only with credentials set, and they serve any agent's clone. The module without agents is the fallback, and injectGithubContext(ctx) picks by the run's agent. setup contributes githubChannel() (options.channel, the approval link from PUBLIC_URL unless channel.approvalUrl is given, the app's clock) to the app's channels, which the http module serves at /channels/<name>, and githubAppCredentials(app, options.credentials) to AppToken.GIT_CREDENTIALS, which sandboxModule() asks after its own sources (credentials: false contributes none); the first module's engineCreated hook provides the per-agent resolver over every module's .app. @chamvi/app is an optional peer: the main entry never imports it. See Apps & Modules.

ts
/*
 * Copyright (c) 2026.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import type { Env } from '@chamvi/app';
import type { DeclaredConnection, IEngine } from '@chamvi/core';
import type { GithubAppOptions, IGithubApp } from '../app/types.ts';
import type { GithubChannelOptions } from '../channel/types.ts';
import type { GithubAppCredentialsOptions } from '../credentials/types.ts';

/** `githubChannel()` options; `approvalUrl` defaults to the UI link from `PUBLIC_URL`, `clock` is the app's. */
export type GithubModuleChannelOptions = Omit<GithubChannelOptions, 'app' | 'clock' | 'locks'> & {
    /** Default the app's lock service (`AppToken.LOCK_SERVICE`). */
    locks?: GithubChannelOptions['locks'];
};

export type GithubModuleOptions = Partial<GithubAppOptions> & {
    /**
     * The instance's name (agent-name rule), default `github`: its stored
     * connection, the default channel name and the env prefix
     * (`GITHUB_<NAME>_*`; the default instance keeps `GITHUB_*`).
     */
    name?: string;
    /**
     * The agents this module serves. Without it the module is the fallback
     * for every agent no other module targets; at most one module may omit it.
     */
    agents?: readonly string[];
    /** Used as is; no env is read then, the connection is listed but not editable. */
    app?: IGithubApp;
    /** Default `process.env`, read when the factory is called; format errors throw there, a missing value in `setup`. */
    env?: Env;
    /** The channel's options; named comment slots use the app's lock service by default. */
    channel?: GithubModuleChannelOptions;
    /**
     * The App's git credentials (`githubAppCredentials()`), contributed to
     * `AppToken.GIT_CREDENTIALS` for `sandboxModule()`'s workspaces once
     * configured; `false` contributes none. Default on for the fallback
     * module; a module with `agents` contributes only when this is set.
     */
    credentials?: false | GithubAppCredentialsOptions;
};

/** The createGithubApp options env and the store can set; one variable and form field each. */
export type GithubEnvOption = 'appId' | 'privateKey' | 'webhookSecret' | 'installationId' | 'slug' | 'baseUrl';

/** One module's part in the shared collection. */
export type GithubInstance = {
    name: string;
    app: IGithubApp;
    channelName: string;
    agents?: readonly string[];
    /** Set once the instance's connection is resolved. */
    connection?: DeclaredConnection;
};

/** The GitHub modules of one app; `provided` guards the resolver per engine. */
export type GithubInstances = {
    list: GithubInstance[];
    provided: WeakSet<IEngine>;
};