dsh-git-scm 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["firstLine","excerpt"],"sources":["../src/host/git.ts","../src/host/types.ts","../src/host/commit-message.ts","../src/index.ts"],"sourcesContent":["/**\n * Git command layer of the source-control plugin.\n *\n * Pure Node ESM: this module knows Git's argument grammar and machine-readable\n * output formats and nothing about Cordis, Sessions, or HTTP. Every invocation\n * goes through the `exec` seam its caller supplies, so the caller owns process\n * policy (executable resolution, confinement, cancellation, output caps) while\n * this module owns what is asked and how the answer is read.\n *\n * Reading is lazy by design: the repository snapshot carries identity, branches,\n * stashes, and tags, while a branch's commits and a commit's files are read only\n * when the panel expands that node.\n *\n * Parsing follows Git's own stable formats: `status --porcelain=v2 -z`,\n * `for-each-ref`, and `log --pretty=format:` with NUL separators. Human prose is\n * never parsed.\n */\n\nimport { readFile, stat, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, normalize } from 'node:path'\nimport type { Exec, ExecOptions, ExecResult, GitLimits } from './types.ts'\n\n/** Environment every Git call must run with: no inherited repository selectors, no prompts, no lazy fetches. */\nexport const GIT_ENV: Readonly<Record<string, string | undefined>> = Object.freeze({\n ...Object.fromEntries([\n 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',\n 'GIT_CEILING_DIRECTORIES', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE',\n 'GIT_REPLACE_REF_BASE', 'GIT_ATTR_SOURCE',\n ].map(key => [key, undefined] as const)),\n GIT_TERMINAL_PROMPT: '0',\n GIT_OPTIONAL_LOCKS: '0',\n GIT_NO_LAZY_FETCH: '1',\n LC_ALL: 'C',\n})\n\n/** Stable failure codes this layer raises; the Host route relays them onto the wire. */\nexport type GitErrorCode =\n | 'NOT_A_REPO'\n | 'INVALID'\n | 'GIT_FAILED'\n | 'TIMEOUT'\n | 'SPAWN_FAILED'\n | 'TOO_LARGE'\n | 'CANCELLED'\n\n/** A structured Git failure the Host route reports with its `code`. */\nexport class GitError extends Error {\n /** Stable code such as `NOT_A_REPO`, `INVALID`, or `GIT_FAILED`. */\n readonly code: GitErrorCode\n\n /** Raw output excerpt, when one exists. */\n readonly detail: string | null\n\n /**\n * @param code - stable code such as `NOT_A_REPO`, `INVALID`, or `GIT_FAILED`.\n * @param message - readable reason, usually Git's first diagnostic line.\n * @param detail - raw output excerpt.\n */\n constructor(code: GitErrorCode, message: string, detail: string | null = null) {\n super(message)\n this.name = 'GitError'\n this.code = code\n this.detail = detail\n }\n}\n\n/** Status letters `status --porcelain=v2` reports for one side of a change. */\nexport type ChangeStatus =\n | 'modified'\n | 'added'\n | 'deleted'\n | 'renamed'\n | 'copied'\n | 'typechange'\n | 'untracked'\n | 'conflicted'\n\n/** One side of a working-tree change as the wire contract reports it. */\nexport interface FileEntry {\n /** Repository-relative path. */\n path: string\n /** Previous path of a rename or copy, else null. */\n origPath: string | null\n /** Human-readable status, e.g. `modified`. */\n status: ChangeStatus\n /** Raw porcelain letter, e.g. `M`. */\n code: string\n /** Whether this entry is the index side of the change. */\n staged: boolean\n}\n\n/** The four change lists of one working tree. */\nexport interface Changes {\n /** Changes recorded in the index. */\n staged: FileEntry[]\n /** Changes in the working tree, against the index. */\n unstaged: FileEntry[]\n /** Files Git does not track yet. */\n untracked: FileEntry[]\n /** Unmerged paths of a pending merge, rebase, or cherry-pick. */\n conflicted: FileEntry[]\n}\n\n/** Change lists plus the total count the cap applies to. */\nexport interface ChangesSummary extends Changes {\n /** Number of entries across all four lists, capped by `maxFiles`. */\n total: number\n}\n\n/** One configured remote. */\nexport interface Remote {\n /** Remote name such as `origin`. */\n name: string\n /** Fetch URL. */\n url: string\n}\n\n/** The checked-out commit, as the repository block reports it. */\nexport interface CommitHead {\n /** Full commit hash. */\n hash: string\n /** Abbreviated commit hash. */\n short: string\n /** Subject line. */\n subject: string\n /** Author name. */\n author: string\n /** Author timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n /** Raw commit message body, so amending starts from the previous message. */\n message: string\n}\n\n/** Operation the checkout is in the middle of, or null when it is clean. */\nexport type PendingOperation = 'cherry-pick' | 'revert' | 'merge' | 'rebase'\n\n/** Ahead/behind counts between HEAD and its upstream. */\nexport interface AheadBehind {\n /** Local commits the upstream does not have, or null without an upstream. */\n ahead: number | null\n /** Upstream commits HEAD does not have, or null without an upstream. */\n behind: number | null\n}\n\n/** Repository identity block shared by `summary` and `status`. */\nexport interface Repo {\n /** Absolute work-tree root. */\n root: string\n /** Base name of the work-tree root. */\n name: string\n /** Checked-out branch, or null when HEAD is detached. */\n branch: string | null\n /** Whether HEAD is detached. */\n detached: boolean\n /** Whether the repository has no commit yet. */\n unborn: boolean\n /** Upstream branch such as `origin/main`, or null. */\n upstream: string | null\n /** Local commits not pushed, or null without an upstream. */\n ahead: number | null\n /** Remote commits not pulled, or null without an upstream. */\n behind: number | null\n /** Configured remotes. */\n remotes: Remote[]\n /** Checked-out commit, or null while unborn. */\n head: CommitHead | null\n /** mtime of `FETCH_HEAD` in Unix epoch milliseconds, or null. */\n lastFetchAt: number | null\n /** Whether the checkout is a linked worktree of a shared Git directory. */\n isWorktree: boolean\n /** In-progress cherry-pick, revert, merge, or rebase, or null. */\n pending: PendingOperation | null\n /** Total working-tree changes, capped by `maxFiles`. */\n totalChanges: number\n}\n\n/** One local or remote branch. */\nexport interface Branch {\n /** Short branch name; remote entries are prefixed with the remote name. */\n name: string\n /** Whether the branch is local or remote-tracking. */\n kind: 'local' | 'remote'\n /** Whether this is the checked-out branch. */\n current: boolean\n /** Configured upstream branch, or null. */\n upstream: string | null\n /** Local commits the upstream does not have, or null. */\n ahead: number | null\n /** Upstream commits the branch does not have, or null. */\n behind: number | null\n /** Abbreviated tip hash. */\n hash: string\n /** Subject of the tip commit. */\n subject: string\n /** Committer timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n /** Remote name for a remote branch, else null. */\n remote: string | null\n}\n\n/** Local and remote branch lists. */\nexport interface Branches {\n /** Local branches, the current one first. */\n local: Branch[]\n /** Remote-tracking branches, symbolic `…/HEAD` entries excluded. */\n remote: Branch[]\n}\n\n/** One stash entry. */\nexport interface Stash {\n /** Stack index, newest first. */\n index: number\n /** Stash message. */\n message: string\n}\n\n/** One tag. */\nexport interface Tag {\n /** Short tag name. */\n name: string\n /** Creation timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n}\n\n/** The repository snapshot `gitSummary` answers. */\nexport interface Summary {\n /** Repository identity. */\n repo: Repo\n /** Working-tree changes. */\n changes: Changes\n /** Local and remote branches. */\n branches: Branches\n /** Stash stack. */\n stashes: Stash[]\n /** Tags. */\n tags: Tag[]\n}\n\n/** The light snapshot `gitStatus` answers. */\nexport interface StatusSnapshot {\n /** Repository identity. */\n repo: Repo\n /** Working-tree changes. */\n changes: Changes\n}\n\n/** One unified patch. */\nexport interface Diff {\n /** Repository-relative path the patch is addressed by. */\n path: string\n /** Whether the patch reads the index instead of the working tree. */\n staged: boolean\n /** Raw unified patch text, trimmed at `maxDiffBytes`. */\n text: string\n /** Whether the change was detected as binary. */\n binary: boolean\n /** Whether the patch was trimmed at `maxDiffBytes`. */\n tooLarge: boolean\n /** Added line count. */\n added: number\n /** Deleted line count. */\n deleted: number\n}\n\n/** One commit of a commit page. */\nexport interface Commit {\n /** Full commit hash. */\n hash: string\n /** Abbreviated commit hash. */\n short: string\n /** Subject line. */\n subject: string\n /** Author name. */\n author: string\n /** Author timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n /** Parent count; a merge commit has more than one. */\n parents: number\n /** Names HEAD and the remote refs point at through this commit. */\n refs: string[]\n}\n\n/** One page of a commit walk. */\nexport interface CommitPage {\n /** Resolved commit the walk started from. */\n ref: string\n /** Commits of this page, newest first. */\n commits: Commit[]\n /** Whether further commits exist after this page. */\n more: boolean\n}\n\n/** One page of one file's history. */\nexport interface FileHistoryPage {\n /** Repository-relative path the history follows. */\n path: string\n /** Commits of this page, newest first. */\n commits: Commit[]\n /** Whether further commits exist after this page. */\n more: boolean\n}\n\n/** One file a commit changed, with its line counts. */\nexport interface CommitFile extends FileEntry {\n /** Added lines, or null for a binary file. */\n additions: number | null\n /** Deleted lines, or null for a binary file. */\n deletions: number | null\n}\n\n/** The changed files of one commit. */\nexport interface CommitFiles {\n /** Full hash of the resolved commit. */\n hash: string\n /** Changed files against the commit's first parent. */\n files: CommitFile[]\n /** Added lines across the reported files. */\n additions: number\n /** Deleted lines across the reported files. */\n deletions: number\n /** Whether the file list hit `maxFiles`. */\n truncated: boolean\n}\n\n/** One remote reference a fetch moved. */\nexport interface RefChange {\n /** Short remote ref name. */\n ref: string\n /** Tip before the fetch, or null when the ref is new. */\n from: string | null\n /** Tip after the fetch, or null when the ref disappeared. */\n to: string | null\n}\n\n/** Result of one mutation Git operation. */\nexport interface ActionResult {\n /** Operator-readable summary. */\n message: string\n /** Raw output excerpt, when one exists. */\n detail: string | null\n /** Fetch only: whether remote references moved. */\n updated?: boolean\n /** Fetch only: the remote references that moved. */\n changed?: RefChange[]\n /** `pullBranch` only: commits the fast-forward brought in. */\n commits?: number\n}\n\n/** Line counts of one changed file. */\nexport interface LineCount {\n /** Added lines, or null for a binary file. */\n additions: number | null\n /** Deleted lines, or null for a binary file. */\n deletions: number | null\n}\n\n/** Request of one repository snapshot read. */\nexport interface GitSummaryRequest {\n /** The caller's process seam. */\n exec: Exec\n /** Directory inside the checkout. */\n cwd: string\n /** Overrides for the layer's default limits. */\n limits?: Partial<GitLimits> | undefined\n}\n\n/** Request of one working-tree patch read. */\nexport interface GitDiffRequest extends GitSummaryRequest {\n /** Repository-relative path to diff. */\n path: string\n /** Read the index instead of the working tree. */\n staged?: boolean | undefined\n /** Synthesize the patch of an untracked file. */\n untracked?: boolean | undefined\n}\n\n/** Request of one branch page read. */\nexport interface GitCommitsRequest extends GitSummaryRequest {\n /** Ref or commit to walk. */\n ref: string\n /** Commits to skip. */\n skip?: number | undefined\n /** Page size; the layer caps it at 200. */\n limit?: number | undefined\n}\n\n/** Request of one file history page read. */\nexport interface GitFileHistoryRequest extends GitSummaryRequest {\n /** Repository-relative path whose history is read. */\n path: string\n /** Commits to skip. */\n skip?: number | undefined\n /** Page size; the layer caps it at 200. */\n limit?: number | undefined\n}\n\n/** Request of one commit's changed files read. */\nexport interface GitCommitFilesRequest extends GitSummaryRequest {\n /** Commit hash or abbreviation. */\n hash: string\n}\n\n/** Request of one file patch inside a commit. */\nexport interface GitCommitDiffRequest extends GitSummaryRequest {\n /** Commit hash or abbreviation. */\n hash: string\n /** Repository-relative path to diff. */\n path: string\n}\n\n/** Request of one stash patch read. */\nexport interface GitStashDiffRequest extends GitSummaryRequest {\n /** Stash stack index. */\n index: unknown\n}\n\n/** Request of one mutation operation. */\nexport interface GitActionRequest {\n /** The caller's process seam. */\n exec: Exec\n /** Directory inside the checkout. */\n cwd: string\n /** Operation name from {@link OPERATIONS}. */\n operation: string\n /** Operation-specific parameters, validated per operation. */\n params?: Readonly<Record<string, unknown>> | undefined\n}\n\n/** Falls back to these bounds when the caller omits a limit. */\nconst DEFAULT_LIMITS: GitLimits = Object.freeze({\n maxBranches: 500,\n maxCommits: 40,\n maxTags: 30,\n maxFiles: 3000,\n maxDiffBytes: 400 * 1024,\n})\n\n/** Names of {@link DEFAULT_LIMITS}, so an override map is read without string indexing. */\nconst LIMIT_KEYS = ['maxBranches', 'maxCommits', 'maxTags', 'maxFiles', 'maxDiffBytes'] as const\n\n/** Deadline for operations that talk to a remote: large fetches take minutes. */\nexport const NETWORK_TIMEOUT_MS = 300_000\n\n/** Deadline for one GitHub CLI probe that only reads the account. */\nconst GITHUB_PROBE_TIMEOUT_MS = 15_000\n\n/** Status letters `status --porcelain=v2` reports for one side of a change. */\nconst STATUS_OF_CODE: Readonly<Record<string, ChangeStatus>> = Object.freeze({\n M: 'modified',\n A: 'added',\n D: 'deleted',\n R: 'renamed',\n C: 'copied',\n T: 'typechange',\n U: 'conflicted',\n})\n\n/** Merge the caller's limits onto the defaults, ignoring invalid entries. */\nfunction resolveLimits(limits: Partial<GitLimits> = {}): GitLimits {\n const resolved = { ...DEFAULT_LIMITS }\n for (const key of LIMIT_KEYS) {\n const value = limits[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) resolved[key] = value\n }\n return resolved\n}\n\n/** Build the argv this layer hands the seam: program name first, then the subcommand. */\nfunction argvOf(args: readonly string[]): string[] {\n return ['git', ...args]\n}\n\n/** The first non-empty line of Git output. */\nfunction firstLine(text: unknown): string {\n return String(text ?? '').split(/\\r?\\n/).map(line => line.trim()).find(line => line.length > 0) ?? 'no diagnostic'\n}\n\n/** At most `limit` characters of raw output, for a failure report. */\nfunction excerpt(text: unknown, limit = 2000): string | null {\n if (typeof text !== 'string' || text.length === 0) return null\n return text.length <= limit ? text : `${text.slice(0, limit)}…`\n}\n\n/** Whether an error is the layer's own structured failure. */\nfunction isGitError(error: unknown): error is GitError {\n return error instanceof GitError\n}\n\n/** Read the `code`, `message`, and `detail` fields a rejection from the `exec` seam may carry. */\nfunction failureFieldsOf(error: unknown): { code?: unknown; message?: unknown; detail?: unknown } {\n if (typeof error !== 'object' || error === null) return {}\n return error as { code?: unknown; message?: unknown; detail?: unknown }\n}\n\n/** Normalize a rejection from the `exec` seam into a structured failure. */\nfunction failureOf(error: unknown, operation: string): GitError {\n if (isGitError(error)) return error\n const fields = failureFieldsOf(error)\n const code = typeof fields.code === 'string' && fields.code.length > 0 ? fields.code : 'GIT_FAILED'\n const message = typeof fields.message === 'string' && fields.message.length > 0\n ? fields.message\n : `git ${operation} failed`\n const detail = typeof fields.detail === 'string' ? fields.detail : null\n // The seam relays its own provider codes verbatim; the Host route admits only\n // codes it knows, so the cast documents that relay rather than narrowing it here.\n return new GitError(code as GitErrorCode, message, detail)\n}\n\n/**\n * Run one Git invocation that must succeed.\n * @param exec - the caller's seam.\n * @param args - subcommand arguments, without the program name.\n * @param operation - name used in failure messages.\n * @param options - `allowedExitCodes`, `timeoutMs`, and other exec options.\n * @returns the output.\n */\nasync function run(exec: Exec, args: readonly string[], operation: string, options: ExecOptions = {}): Promise<ExecResult> {\n try {\n return await exec(argvOf(args), options)\n } catch (error) {\n throw failureOf(error, operation)\n }\n}\n\n/** Whether a directory is inside a Git work tree, without throwing for the ordinary negative answer. */\nasync function repositoryRoot(exec: Exec, _cwd: string): Promise<string | null> {\n let result: ExecResult\n try {\n result = await exec(argvOf(['rev-parse', '--show-toplevel']), { allowedExitCodes: [0, 128] })\n } catch (error) {\n throw failureOf(error, 'rev-parse')\n }\n if (result.exitCode === 0) {\n const root = firstLine(result.stdout)\n if (root.length === 0) throw new GitError('GIT_FAILED', 'git rev-parse printed no work tree root')\n return root\n }\n if (/not a git repository|must be run in a work tree/i.test(result.stderr)) return null\n throw new GitError('GIT_FAILED', `git rev-parse failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n}\n\n/** Resolve the canonical Git directories of a checkout: shared and per-worktree. */\nasync function gitDirectories(exec: Exec, _cwd: string): Promise<{ commonDir: string; gitDir: string }> {\n const [common, own] = await Promise.all([\n run(exec, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'rev-parse'),\n run(exec, ['rev-parse', '--path-format=absolute', '--git-dir'], 'rev-parse'),\n ])\n return { commonDir: firstLine(common.stdout), gitDir: firstLine(own.stdout) }\n}\n\n/** Read the mtime of `FETCH_HEAD`, the only durable record of the last fetch. */\nasync function lastFetchAt(commonDir: string): Promise<number | null> {\n try {\n const info = await stat(join(commonDir, 'FETCH_HEAD'))\n return Math.round(info.mtimeMs)\n } catch {\n return null\n }\n}\n\n/** Name the operation the checkout is in the middle of, or null when it is clean. */\nasync function pendingOperation(gitDir: string): Promise<PendingOperation | null> {\n const marks: ReadonlyArray<readonly [PendingOperation, string]> = [\n ['cherry-pick', 'CHERRY_PICK_HEAD'],\n ['revert', 'REVERT_HEAD'],\n ['merge', 'MERGE_HEAD'],\n ['rebase', 'rebase-merge'],\n ['rebase', 'rebase-apply'],\n ]\n for (const [kind, mark] of marks) {\n try {\n await stat(join(gitDir, mark))\n return kind\n } catch {\n // Not in progress; the next marker is the only candidate.\n }\n }\n return null\n}\n\n/** The checked-out branch, or null when HEAD is detached. */\nasync function currentBranch(exec: Exec): Promise<string | null> {\n const result = await exec(argvOf(['symbolic-ref', '--quiet', '--short', 'HEAD']), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) return null\n const name = firstLine(result.stdout)\n return name.length === 0 ? null : name\n}\n\n/** HEAD facts: whether a commit exists and, if so, its identity. */\nasync function headCommit(exec: Exec): Promise<{ unborn: boolean; head: CommitHead | null }> {\n const head = await exec(argvOf(['rev-parse', '--verify', '--quiet', 'HEAD']), { allowedExitCodes: [0, 1, 128] })\n if (head.exitCode !== 0) return { unborn: true, head: null }\n const log = await run(exec, ['log', '-1', '--date=unix', '--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%B'], 'log')\n const [hash, short, subject, author, date, body] = log.stdout.split('\\u0000')\n return {\n unborn: false,\n head: {\n hash: hash ?? '',\n short: short ?? '',\n subject: subject ?? '',\n author: author ?? '',\n date: parseDate(date),\n // The raw body, so amending starts from the previous message.\n message: (body ?? '').trim(),\n },\n }\n}\n\n/** Upstream branch name of HEAD, or null when none is configured. */\nasync function upstreamBranch(exec: Exec): Promise<string | null> {\n const result = await exec(argvOf(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) return null\n const name = firstLine(result.stdout)\n return name.length === 0 ? null : name\n}\n\n/** Ahead/behind counts between HEAD and its upstream, or nulls without an upstream. */\nasync function aheadBehind(exec: Exec, upstream: string | null): Promise<AheadBehind> {\n if (upstream === null) return { ahead: null, behind: null }\n const result = await exec(argvOf(['rev-list', '--left-right', '--count', `HEAD...${upstream}`]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) return { ahead: null, behind: null }\n const [aheadText, behindText] = firstLine(result.stdout).split(/\\s+/)\n return { ahead: parseCount(aheadText), behind: parseCount(behindText) }\n}\n\n/** One line of `status --porcelain=v2 -z` as one side of a change. */\nfunction changeEntry(path: string, code: string, origPath: string | null): FileEntry {\n return {\n path,\n origPath: origPath ?? null,\n status: STATUS_OF_CODE[code] ?? 'modified',\n code,\n staged: false,\n }\n}\n\n/**\n * Parse `git status --porcelain=v2 -z` into the four change lists.\n * @param output - raw NUL-separated records.\n * @param maxFiles - cap applied across all four lists.\n * @returns the lists.\n */\nfunction parseStatus(output: string, maxFiles: number): ChangesSummary {\n const changes: ChangesSummary = { staged: [], unstaged: [], untracked: [], conflicted: [], total: 0 }\n if (typeof output !== 'string' || output.length === 0) return changes\n const records = output.split('\\u0000')\n let total = 0\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index]!\n if (record.length === 0) continue\n const kind = record.charAt(0)\n if (kind === '1') {\n // `1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>`\n const parts = record.split(' ')\n if (parts.length < 9) continue\n const code = parts[1]!\n const path = parts.slice(8).join(' ')\n const [x, y] = [code.charAt(0), code.charAt(1)]\n if (x !== '.') { changes.staged.push(changeEntry(path, x, null)); total += 1 }\n if (y !== '.') { changes.unstaged.push(changeEntry(path, y, null)); total += 1 }\n } else if (kind === '2') {\n // `2 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <X><score> <path>` then the original path record.\n const parts = record.split(' ')\n if (parts.length < 10) continue\n const code = parts[1]!\n const path = parts.slice(9).join(' ')\n const origPath = records[index + 1] ?? null\n index += 1\n const [x, y] = [code.charAt(0), code.charAt(1)]\n if (x !== '.') { changes.staged.push(changeEntry(path, x, origPath)); total += 1 }\n if (y !== '.') { changes.unstaged.push(changeEntry(path, y, origPath)); total += 1 }\n } else if (kind === 'u') {\n // `u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>`\n const parts = record.split(' ')\n if (parts.length < 11) continue\n const path = parts.slice(10).join(' ')\n changes.conflicted.push({ path, origPath: null, status: 'conflicted', code: 'U', staged: false })\n total += 1\n } else if (kind === '?') {\n const path = record.slice(2)\n changes.untracked.push({ path, origPath: null, status: 'untracked', code: '?', staged: false })\n total += 1\n }\n if (total >= maxFiles) break\n }\n changes.total = total\n return changes\n}\n\n/** Read the working-tree changes of a repository. */\nasync function readChanges(exec: Exec, limits: GitLimits): Promise<ChangesSummary> {\n const status = await run(exec, ['status', '--porcelain=v2', '-z', '--untracked-files=normal'], 'status')\n return parseStatus(status.stdout, limits.maxFiles)\n}\n\n/** Parse one `for-each-ref` record into a branch entry. */\nfunction branchOf(fields: string[]): Branch | null {\n const [refname, short, head, upstream, track, hash, date] = fields\n // The subject is the last field and may itself contain the separator.\n const subject = fields.slice(7).join('\\t')\n if (refname === undefined || short === undefined) return null\n const kind = refname.startsWith('refs/heads/') ? 'local' : refname.startsWith('refs/remotes/') ? 'remote' : null\n if (kind === null) return null\n if (kind === 'remote' && short.endsWith('/HEAD')) return null\n const parsedTrack = parseTrack(track ?? '')\n return {\n name: short,\n kind,\n current: head === '*',\n upstream: upstream === undefined || upstream.length === 0 ? null : upstream,\n ahead: parsedTrack.ahead,\n behind: parsedTrack.behind,\n hash: hash ?? '',\n subject: subject ?? '',\n date: parseDate(date),\n remote: kind === 'remote' ? short.split('/')[0]! : null,\n }\n}\n\n/** Parse `%(upstream:track)` such as `[ahead 2, behind 1]` or `[gone]`. */\nfunction parseTrack(text: string): AheadBehind {\n const aheadMatch = /ahead (\\d+)/.exec(text)\n const behindMatch = /behind (\\d+)/.exec(text)\n return {\n ahead: aheadMatch === null ? null : Number(aheadMatch[1]),\n behind: behindMatch === null ? null : Number(behindMatch[1]),\n }\n}\n\n/** List local and remote branches, newest commit first but with the current branch first. */\nasync function readBranches(exec: Exec, limits: GitLimits): Promise<Branches> {\n // `for-each-ref` has no hex-escape syntax, so its fields are tab-separated.\n const format = ['%(refname)', '%(refname:short)', '%(HEAD)', '%(upstream:short)', '%(upstream:track)', '%(objectname:short)', '%(committerdate:unix)', '%(contents:subject)'].join('\\t')\n const result = await run(exec, [\n 'for-each-ref', '--sort=-committerdate', `--format=${format}`, 'refs/heads', 'refs/remotes',\n ], 'for-each-ref')\n const local: Branch[] = []\n const remote: Branch[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const branch = branchOf(line.split('\\t'))\n if (branch === null) continue\n if (branch.kind === 'local') local.push(branch)\n else remote.push(branch)\n }\n const ordered = [...local.filter(branch => branch.current), ...local.filter(branch => !branch.current)]\n return {\n local: ordered.slice(0, limits.maxBranches),\n remote: remote.slice(0, limits.maxBranches),\n }\n}\n\n/** Stashed work, newest first. */\nasync function readStashes(exec: Exec): Promise<Stash[]> {\n const result = await run(exec, ['stash', 'list', '--format=%gd%x00%gs'], 'stash list')\n const stashes: Stash[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [ref, message] = line.split('\\u0000')\n const match = /^stash@\\{(\\d+)\\}$/.exec(ref ?? '')\n if (match === null) continue\n stashes.push({ index: Number(match[1]), message: message ?? '' })\n }\n return stashes\n}\n\n/** Tags, newest first. */\nasync function readTags(exec: Exec, limits: GitLimits): Promise<Tag[]> {\n if (limits.maxTags === 0) return []\n const result = await run(exec, [\n 'for-each-ref', '--sort=-creatordate', '--format=%(refname:short)\\t%(creatordate:unix)', 'refs/tags',\n ], 'for-each-ref')\n const tags: Tag[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [name, date] = line.split('\\t')\n if (name === undefined || name.length === 0) continue\n tags.push({ name, date: parseDate(date) })\n if (tags.length >= limits.maxTags) break\n }\n return tags\n}\n\n/** Current remote-tracking tips, keyed by short ref name. */\nasync function readRemoteTips(exec: Exec): Promise<Map<string, string>> {\n const result = await run(exec, ['for-each-ref', '--format=%(refname:short)%09%(objectname)', 'refs/remotes'], 'for-each-ref')\n const tips = new Map<string, string>()\n for (const line of result.stdout.split('\\n')) {\n const [ref, hash] = line.split('\\t')\n if (ref !== undefined && hash !== undefined && ref.length > 0) tips.set(ref, hash)\n }\n return tips\n}\n\n/** Configured remotes with their fetch URLs. */\nasync function readRemotes(exec: Exec): Promise<Remote[]> {\n const result = await run(exec, ['remote', '-v'], 'remote')\n const seen = new Map<string, string>()\n for (const line of result.stdout.split('\\n')) {\n const match = /^(\\S+)\\t(\\S*) \\(fetch\\)$/.exec(line)\n if (match === null) continue\n const name = match[1]!\n const url = match[2]!\n if (!seen.has(name)) seen.set(name, url)\n }\n return [...seen.entries()].map(([name, url]) => ({ name, url }))\n}\n\n/** Parse a Git `--date=unix` timestamp into milliseconds, or null. */\nfunction parseDate(text: unknown): number | null {\n const seconds = Number(text)\n return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null\n}\n\n/** Parse one count line from `rev-list --count`, or null. */\nfunction parseCount(text: unknown): number | null {\n const value = Number(text)\n return Number.isFinite(value) && value >= 0 ? value : null\n}\n\n/**\n * The repository identity block shared by `summary` and `status`.\n * @param options - the seam, the checkout root, and the limits.\n * @returns the `repo` and `changes` objects of the wire contract.\n */\nasync function readRepo({ exec, root, limits }: { exec: Exec; root: string; limits: GitLimits }): Promise<StatusSnapshot> {\n const { commonDir, gitDir } = await gitDirectories(exec, root)\n const [branch, head, upstream, remotes, fetched, pending, changes] = await Promise.all([\n currentBranch(exec),\n headCommit(exec),\n upstreamBranch(exec),\n readRemotes(exec),\n lastFetchAt(commonDir),\n pendingOperation(gitDir),\n readChanges(exec, limits),\n ])\n const counts = await aheadBehind(exec, upstream)\n return {\n repo: {\n root,\n name: root.split(/[\\\\/]/).filter(part => part.length > 0).pop() ?? root,\n branch,\n detached: branch === null && head.unborn === false,\n unborn: head.unborn,\n upstream,\n ahead: counts.ahead,\n behind: counts.behind,\n remotes,\n head: head.head,\n lastFetchAt: fetched,\n isWorktree: commonDir !== gitDir,\n pending,\n totalChanges: changes.total,\n },\n changes: {\n staged: changes.staged,\n unstaged: changes.unstaged,\n untracked: changes.untracked,\n conflicted: changes.conflicted,\n },\n }\n}\n\n/**\n * Read the repository identity, branches, stashes, and tags in one call.\n * @param request - `exec`, `cwd`, and `limits`.\n * @returns the `Summary` of the wire contract.\n * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitSummary({ exec, cwd, limits = {} }: GitSummaryRequest): Promise<Summary> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const [{ repo, changes }, branches, stashes, tags] = await Promise.all([\n readRepo({ exec, root, limits: bounds }),\n readBranches(exec, bounds),\n readStashes(exec),\n readTags(exec, bounds),\n ])\n return { repo, changes, branches, stashes, tags }\n}\n\n/**\n * Read the repository identity and working-tree changes only, for polling.\n * @param request - `exec`, `cwd`, and `limits`.\n * @returns the light snapshot.\n * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitStatus({ exec, cwd, limits = {} }: GitSummaryRequest): Promise<StatusSnapshot> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n return await readRepo({ exec, root, limits: bounds })\n}\n\n/** One changed path a commit-message request describes. */\nexport interface CommitMessageFile {\n /** Change status word such as `modified` or `untracked`. */\n readonly status: string\n /** Repository-relative path. */\n readonly path: string\n}\n\n/** The change summary and patch a commit-message request reads. */\nexport interface CommitMessageContext {\n /** Whether the patch describes staged changes (the next commit). */\n readonly staged: boolean\n /** Changed paths across the staged or working-tree lists. */\n readonly files: readonly CommitMessageFile[]\n /** Unified patch, truncated to the read limit. */\n readonly diff: string\n /** Whether the patch was truncated. */\n readonly truncated: boolean\n /** Recent commit subjects, newest first, for style reference. */\n readonly recent: readonly string[]\n /** Whether most recent commits use a Conventional Commits type prefix. */\n readonly recentConventional: boolean\n /** Whether most recent commits carry a body. */\n readonly recentHasBody: boolean\n}\n\n/** Largest patch handed to the model. */\nconst COMMIT_MESSAGE_DIFF_BYTES = 48 * 1024\n\n/** Recent commit subjects read for style. */\nconst COMMIT_MESSAGE_RECENT = 8\n\n/** Conventional Commits subject prefix, used to observe the repository style. */\nconst CONVENTIONAL_SUBJECT = /^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\\([^)]+\\))?!?:\\s+/\n\n/** Record and field separators that keep multi-line bodies apart in one log call. */\nconst LOG_RECORD = '\\x1e'\nconst LOG_FIELD = '\\x1f'\n\n/**\n * Read the changes a commit message should describe. Staged changes win; a\n * checkout with none staged is described by its working tree instead.\n * @param request - the `exec` seam, a directory inside the checkout, and limits.\n * @returns the scope, changed paths, patch, truncation flag, and recent subjects.\n * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommitMessageContext({ exec, cwd, limits = {} }: GitSummaryRequest): Promise<CommitMessageContext> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const { changes } = await readRepo({ exec, root, limits: bounds })\n const stagedFiles = changes.staged.map(changeFile)\n const worktreeFiles = [...changes.unstaged, ...changes.untracked, ...changes.conflicted].map(changeFile)\n const staged = stagedFiles.length > 0\n const files = staged ? stagedFiles : worktreeFiles\n const args = staged\n ? ['diff', '--cached', '--no-color', '--no-ext-diff', '-M', '--unified=3']\n : ['diff', '--no-color', '--no-ext-diff', '-M', '--unified=3']\n const patch = files.length === 0 ? '' : (await run(exec, args, 'diff')).stdout\n const history = await exec(\n argvOf(['log', `-${COMMIT_MESSAGE_RECENT}`, `--format=%s${LOG_FIELD}%b${LOG_RECORD}`]),\n { allowedExitCodes: [0, 128] },\n )\n const commits = history.exitCode === 0\n ? history.stdout.split(LOG_RECORD)\n .map(record => record.replace(/^\\r?\\n/, ''))\n .filter(record => record.trim().length > 0)\n .map((record) => {\n const [subject = '', body = ''] = record.split(LOG_FIELD)\n return { subject: subject.trim(), body: body.trim() }\n })\n : []\n const recent = commits.map(commit => commit.subject).filter(subject => subject.length > 0)\n const half = Math.ceil(commits.length / 2)\n const recentConventional = half > 0 && commits.filter(commit => CONVENTIONAL_SUBJECT.test(commit.subject)).length >= half\n const recentHasBody = half > 0 && commits.filter(commit => commit.body.length > 0).length >= half\n const truncated = Buffer.byteLength(patch, 'utf8') > COMMIT_MESSAGE_DIFF_BYTES\n return {\n staged, files,\n diff: truncated ? `${Buffer.from(patch, 'utf8').subarray(0, COMMIT_MESSAGE_DIFF_BYTES).toString('utf8')}\\n… (diff truncated)` : patch,\n truncated,\n recent,\n recentConventional,\n recentHasBody,\n }\n}\n\n/** Project one change-list entry onto the prompt's file view. */\nfunction changeFile(entry: { readonly status: string; readonly path: string }): CommitMessageFile {\n return { status: entry.status, path: entry.path }\n}\n\n/** Reject a path that would escape the repository or confuse Git's argument parser. */\nfunction checkedPath(path: unknown): string {\n if (typeof path !== 'string' || path.length === 0) throw new GitError('INVALID', 'a file path is required')\n if (path.includes('\\u0000')) throw new GitError('INVALID', 'a path must not contain a NUL byte')\n if (isAbsolute(path)) throw new GitError('INVALID', 'a path must be relative to the repository root')\n const normalized = normalize(path).split('\\\\').join('/')\n if (normalized === '..' || normalized.startsWith('../')) throw new GitError('INVALID', 'a path must stay inside the repository')\n return normalized\n}\n\n/** Reject a ref argument the client asks to walk. */\nfunction checkedRef(ref: unknown): string {\n if (typeof ref !== 'string' || ref.length === 0) throw new GitError('INVALID', 'a ref is required')\n if (ref.startsWith('-') || /\\s/.test(ref) || ref.includes('\\u0000')) {\n throw new GitError('INVALID', `\"${ref}\" is not a valid ref`)\n }\n return ref\n}\n\n/** One Git config value, or null when unset. */\nasync function configValue(exec: Exec, key: string): Promise<string | null> {\n const result = await exec(argvOf(['config', '--get', key]), { allowedExitCodes: [0, 1] })\n return result.exitCode === 0 ? result.stdout.trim() : null\n}\n\n/** Reject anything that is not a commit identity. */\nfunction checkedHash(hash: unknown): string {\n if (typeof hash !== 'string' || !/^[0-9a-f]{4,64}$/i.test(hash)) {\n throw new GitError('INVALID', 'a commit hash is required')\n }\n return hash.toLowerCase()\n}\n\n/** Resolve a ref or abbreviation to a full commit hash. */\nasync function resolveCommit(exec: Exec, ref: string): Promise<string> {\n const result = await exec(argvOf(['rev-parse', '--verify', '--quiet', `${checkedRef(ref)}^{commit}`]), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) throw new GitError('INVALID', `\"${ref}\" does not name a commit`)\n return firstLine(result.stdout)\n}\n\n/** The first parent of a commit, or null for a root commit. */\nasync function firstParent(exec: Exec, commit: string): Promise<string | null> {\n const result = await exec(argvOf(['rev-parse', '--verify', '--quiet', `${commit}^`]), { allowedExitCodes: [0, 1, 128] })\n return result.exitCode === 0 ? firstLine(result.stdout) : null\n}\n\n/** Count added and deleted lines in a unified diff. */\nfunction countDiffLines(text: string): { added: number; deleted: number } {\n let added = 0\n let deleted = 0\n for (const line of text.split('\\n')) {\n if (line.startsWith('+++') || line.startsWith('---')) continue\n if (line.startsWith('+')) added += 1\n else if (line.startsWith('-')) deleted += 1\n }\n return { added, deleted }\n}\n\n/** Build the wire `Diff` from raw patch text. */\nfunction diffOf({ path, staged, text, maxDiffBytes }: {\n path: string\n staged: boolean\n text: string\n maxDiffBytes: number\n}): Diff {\n const tooLarge = text.length > maxDiffBytes\n const body = tooLarge ? text.slice(0, maxDiffBytes) : text\n const binary = /^Binary files .* differ$/m.test(body)\n const counts = binary ? { added: 0, deleted: 0 } : countDiffLines(body)\n return { path, staged, text: body, binary, tooLarge, added: counts.added, deleted: counts.deleted }\n}\n\n/** Render a synthetic unified diff for an untracked file. */\nasync function untrackedDiff(root: string, path: string, maxDiffBytes: number): Promise<Diff> {\n const absolute = join(root, path)\n let buffer: Buffer\n try {\n buffer = await readFile(absolute)\n } catch {\n throw new GitError('GIT_FAILED', `${path} could not be read`)\n }\n const binary = buffer.subarray(0, 8000).includes(0)\n if (binary) {\n return { path, staged: false, text: `Binary file ${path} is untracked\\n`, binary: true, tooLarge: false, added: 0, deleted: 0 }\n }\n const text = buffer.toString('utf8')\n const lines = text.split('\\n')\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()\n const tooLarge = buffer.byteLength > maxDiffBytes || text.length > maxDiffBytes\n const shown = tooLarge ? lines.slice(0, Math.max(0, Math.floor(maxDiffBytes / 40))) : lines\n const header = [\n `diff --git a/${path} b/${path}`,\n 'new file mode 100644',\n '--- /dev/null',\n `+++ b/${path}`,\n `@@ -0,0 +1,${lines.length} @@`,\n ]\n return {\n path,\n staged: false,\n text: [...header, ...shown.map(line => `+${line}`)].join('\\n'),\n binary: false,\n tooLarge,\n added: lines.length,\n deleted: 0,\n }\n}\n\n/**\n * Read one working-tree file's unified diff.\n * @param request - `exec`, `cwd`, `limits`, `path`, `staged`, and `untracked`.\n * @returns the `Diff` of the wire contract.\n * @throws {GitError} `INVALID` for an unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitDiff({ exec, cwd, limits = {}, path, staged = false, untracked = false }: GitDiffRequest): Promise<Diff> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const checked = checkedPath(path)\n if (untracked) return await untrackedDiff(root, checked, bounds.maxDiffBytes)\n const args = ['diff', '--no-color', '--no-ext-diff', '-U3']\n if (staged) args.push('--cached')\n args.push('--', checked)\n const result = await run(exec, args, 'diff')\n return diffOf({ path: checked, staged, text: result.stdout, maxDiffBytes: bounds.maxDiffBytes })\n}\n\n/**\n * Read one branch's or ref's commits, newest first.\n * @param request - `exec`, `cwd`, `limits`, `ref`, `skip`, and `limit`.\n * @returns the page of commits.\n * @throws {GitError} `INVALID` for an unknown ref, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommits({ exec, cwd, limits = {}, ref, skip = 0, limit }: GitCommitsRequest): Promise<CommitPage> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const commit = await resolveCommit(exec, ref)\n const take = typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 200) : bounds.maxCommits\n const offset = typeof skip === 'number' && Number.isSafeInteger(skip) && skip > 0 ? skip : 0\n // The resolved commit is the walk's starting point: without it Git would log\n // HEAD, which is a different branch whenever the checked-out branch differs.\n const result = await exec(argvOf([\n 'log', `-n${take + 1}`, `--skip=${offset}`, '--date=unix', '--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%P%x00%D', commit,\n ]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) throw new GitError('GIT_FAILED', `git log failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n const commits: Commit[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [hash, short, subject, author, date, parents, refs] = line.split('\\u0000')\n commits.push({\n hash: hash ?? '',\n short: short ?? '',\n subject: subject ?? '',\n author: author ?? '',\n date: parseDate(date),\n parents: (parents ?? '').split(' ').filter(Boolean).length,\n refs: (refs ?? '').split(', ').map(entry => entry.trim()).filter(entry => entry.length > 0),\n })\n }\n return { ref: commit, commits: commits.slice(0, take), more: commits.length > take }\n}\n\n/**\n * Read the commit history of one file, newest first, following renames.\n * @param request - `exec`, `cwd`, `limits`, `path`, `skip`, and `limit`.\n * @returns the page of commits.\n * @throws {GitError} `INVALID` for an unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitFileHistory({ exec, cwd, limits = {}, path, skip = 0, limit }: GitFileHistoryRequest): Promise<FileHistoryPage> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const checked = checkedPath(path)\n const take = typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 200) : bounds.maxCommits\n const offset = typeof skip === 'number' && Number.isSafeInteger(skip) && skip > 0 ? skip : 0\n const result = await exec(argvOf([\n 'log', `-n${take + 1}`, `--skip=${offset}`, '--follow', '--date=unix',\n '--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%P%x00%D', '--', checked,\n ]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) {\n throw new GitError('GIT_FAILED', `git log failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n }\n const commits: Commit[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [hash, short, subject, author, date, parents, refs] = line.split('\\u0000')\n commits.push({\n hash: hash ?? '',\n short: short ?? '',\n subject: subject ?? '',\n author: author ?? '',\n date: parseDate(date),\n parents: (parents ?? '').split(' ').filter(Boolean).length,\n refs: (refs ?? '').split(', ').map(entry => entry.trim()).filter(entry => entry.length > 0),\n })\n }\n return { path: checked, commits: commits.slice(0, take), more: commits.length > take }\n}\n\n/** Parse `--numstat -z` output into path → line counts. */\nfunction parseNumstat(output: string): Map<string, LineCount> {\n const counts = new Map<string, LineCount>()\n const fields = output.split('\\u0000')\n for (let index = 0; index < fields.length; index += 1) {\n const record = fields[index]!\n if (record.length === 0) continue\n const firstTab = record.indexOf('\\t')\n const secondTab = record.indexOf('\\t', firstTab + 1)\n if (firstTab < 0 || secondTab < 0) continue\n const additions = record.slice(0, firstTab)\n const deletions = record.slice(firstTab + 1, secondTab)\n const rest = record.slice(secondTab + 1)\n // A rename emits an empty path, then the old path and the new path as records.\n const path = rest.length > 0 ? rest : fields[index + 2] ?? ''\n if (rest.length === 0) index += 2\n counts.set(path, {\n additions: additions === '-' ? null : Number(additions),\n deletions: deletions === '-' ? null : Number(deletions),\n })\n }\n return counts\n}\n\n/**\n * Read the files one commit changed, against its first parent.\n * @param request - `exec`, `cwd`, `limits`, and `hash`.\n * @returns the changed files with their line counts.\n * @throws {GitError} `INVALID` for an unknown commit, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommitFiles({ exec, cwd, limits = {}, hash }: GitCommitFilesRequest): Promise<CommitFiles> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const commit = await resolveCommit(exec, checkedHash(hash))\n const parent = await firstParent(exec, commit)\n const [names, numstat] = await Promise.all([\n parent === null\n ? run(exec, ['diff-tree', '--root', '-r', '--no-commit-id', '--name-status', commit], 'diff-tree')\n : run(exec, ['diff', '--name-status', '-M', parent, commit], 'diff'),\n parent === null\n ? run(exec, ['diff-tree', '--root', '-r', '--no-commit-id', '--numstat', '-z', '-M', commit], 'diff-tree')\n : run(exec, ['diff', '--numstat', '-z', '-M', parent, commit], 'diff'),\n ])\n const counts = parseNumstat(numstat.stdout)\n const files: CommitFile[] = []\n let additions = 0\n let deletions = 0\n for (const line of names.stdout.split('\\n')) {\n if (line.length === 0) continue\n const fields = line.split('\\t')\n const code = (fields[0] ?? 'M').charAt(0)\n const renamed = code === 'R' || code === 'C'\n const path = renamed ? (fields[2] ?? '') : (fields[1] ?? '')\n if (path.length === 0) continue\n const stat = counts.get(path) ?? { additions: 0, deletions: 0 }\n additions += stat.additions ?? 0\n deletions += stat.deletions ?? 0\n files.push({\n path,\n origPath: renamed ? (fields[1] ?? null) : null,\n status: STATUS_OF_CODE[code] ?? 'modified',\n code,\n staged: false,\n additions: stat.additions,\n deletions: stat.deletions,\n })\n if (files.length >= bounds.maxFiles) break\n }\n return { hash: commit, files, additions, deletions, truncated: files.length >= bounds.maxFiles }\n}\n\n/**\n * Read one file's diff inside a commit.\n * @param request - `exec`, `cwd`, `limits`, `hash`, and `path`.\n * @returns the `Diff` of the wire contract.\n * @throws {GitError} `INVALID` for an unknown commit or unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommitDiff({ exec, cwd, limits = {}, hash, path }: GitCommitDiffRequest): Promise<Diff> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const commit = await resolveCommit(exec, checkedHash(hash))\n const checked = checkedPath(path)\n const parent = await firstParent(exec, commit)\n const args = parent === null\n ? ['show', '--no-color', '--no-ext-diff', '--format=', '-U3', commit, '--', checked]\n : ['diff', '--no-color', '--no-ext-diff', '-U3', parent, commit, '--', checked]\n const result = await run(exec, args, 'diff')\n return diffOf({ path: checked, staged: false, text: result.stdout, maxDiffBytes: bounds.maxDiffBytes })\n}\n\n/**\n * Read one stash entry's patch.\n * @param request - `exec`, `cwd`, `limits`, and `index`.\n * @returns the `Diff` of the wire contract, addressed as `stash@{index}`.\n * @throws {GitError} `INVALID` for a missing index, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitStashDiff({ exec, cwd, limits = {}, index }: GitStashDiffRequest): Promise<Diff> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const stash = checkedStashIndex(index)\n const ref = `stash@{${stash}}`\n const result = await exec(argvOf(['stash', 'show', '-p', '--no-color', ref]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) throw new GitError('GIT_FAILED', `git stash show failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n return diffOf({ path: ref, staged: false, text: result.stdout, maxDiffBytes: bounds.maxDiffBytes })\n}\n\n/** Validate a stash index from the client. */\nfunction checkedStashIndex(index: unknown): number {\n if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) {\n throw new GitError('INVALID', 'a stash index is required')\n }\n return index\n}\n\n/** Validate a local branch name with Git's own rule. */\nasync function checkBranchName(exec: Exec, name: unknown): Promise<string> {\n if (typeof name !== 'string' || name.trim().length === 0) throw new GitError('INVALID', 'a branch name is required')\n const result = await exec(argvOf(['check-ref-format', '--branch', name]), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) throw new GitError('INVALID', `\"${name}\" is not a valid branch name`)\n return name\n}\n\n/** Validate a tag name with Git's own rule. */\nasync function checkTagName(exec: Exec, name: unknown): Promise<string> {\n if (typeof name !== 'string' || name.trim().length === 0) throw new GitError('INVALID', 'a tag name is required')\n const result = await exec(argvOf(['check-ref-format', `refs/tags/${name}`]), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) throw new GitError('INVALID', `\"${name}\" is not a valid tag name`)\n return name\n}\n\n/** Whether a local branch exists. */\nasync function localBranchExists(exec: Exec, name: string): Promise<boolean> {\n const result = await exec(argvOf(['show-ref', '--verify', '--quiet', `refs/heads/${name}`]), { allowedExitCodes: [0, 1, 128] })\n return result.exitCode === 0\n}\n\n/** Whether the repository has no commit yet. */\nasync function isUnborn(exec: Exec): Promise<boolean> {\n const result = await exec(argvOf(['rev-parse', '--verify', '--quiet', 'HEAD']), { allowedExitCodes: [0, 1, 128] })\n return result.exitCode !== 0\n}\n\n/** Read the checked-out branch name, for operations that need one. */\nasync function requireBranch(exec: Exec): Promise<string> {\n const branch = await currentBranch(exec)\n if (branch === null) throw new GitError('INVALID', 'the repository has no checked-out branch')\n return branch\n}\n\n/** Configured remote names, in the order `git remote` prints them. */\nasync function remoteNames(exec: Exec): Promise<string[]> {\n const result = await run(exec, ['remote'], 'remote')\n return result.stdout.split(/\\r?\\n/).map(line => line.trim()).filter(line => line.length > 0)\n}\n\n/** The remote a publish should target: `origin` when configured, else the only one, else the first. */\nasync function defaultRemote(exec: Exec): Promise<string | null> {\n const names = await remoteNames(exec)\n if (names.length === 0) return null\n return names.includes('origin') ? 'origin' : names[0]!\n}\n\n/** A configured remote name, for commands that address one. */\nfunction checkedRemoteName(name: unknown): string {\n const value = typeof name === 'string' ? name.trim() : ''\n if (value.length === 0) throw new GitError('INVALID', 'a remote name is required')\n if (value.startsWith('-') || /[\\s\\0-\\x1f\\x7f]/.test(value)) throw new GitError('INVALID', `\"${value}\" is not a valid remote name`)\n return value\n}\n\n/** A remote URL handed to `git remote add`. */\nfunction checkedRemoteUrl(url: unknown): string {\n const value = typeof url === 'string' ? url.trim() : ''\n if (value.length === 0) throw new GitError('INVALID', 'a remote URL is required')\n if (value.startsWith('-') || /[\\0-\\x1f\\x7f]/.test(value)) throw new GitError('INVALID', `\"${value}\" is not a valid remote URL`)\n return value\n}\n\n/** A GitHub repository name or `owner/name`, as `gh repo create` accepts it. */\nfunction checkedGithubRepository(name: unknown): string {\n const value = typeof name === 'string' ? name.trim() : ''\n if (value.length === 0) throw new GitError('INVALID', 'a GitHub repository name is required')\n if (!/^[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)?$/.test(value)) {\n throw new GitError('INVALID', `\"${value}\" is not a valid GitHub repository name`)\n }\n return value\n}\n\n/** Initialize a new repository in the Session directory. */\nasync function initRepository(exec: Exec, cwd: string): Promise<ActionResult> {\n const existing = await repositoryRoot(exec, cwd)\n if (existing !== null) throw new GitError('INVALID', 'the directory is already inside a Git work tree')\n return await mutate(exec, ['init', '-b', 'main'], 'init')\n}\n\n/** Run one mutating operation and report it. */\nasync function mutate(exec: Exec, args: readonly string[], operation: string, options: ExecOptions = {}): Promise<ActionResult> {\n const result = await run(exec, args, operation, options)\n return { message: `git ${operation} completed`, detail: excerpt(result.stdout) }\n}\n\n/** Names of the operations the checkout can be in the middle of, and their abort command. */\nconst ABORTABLE: Readonly<Record<string, readonly string[]>> = Object.freeze({\n 'cherry-pick': ['cherry-pick', '--abort'],\n revert: ['revert', '--abort'],\n rebase: ['rebase', '--abort'],\n merge: ['merge', '--abort'],\n})\n\n/**\n * Append one repository-relative path to `.gitignore`.\n * @param root - repository root.\n * @param path - relative path to ignore.\n * @returns the operation result.\n */\nasync function addToIgnoreFile(root: string, path: string): Promise<ActionResult> {\n const file = join(root, '.gitignore')\n let current = ''\n try {\n current = await readFile(file, 'utf8')\n } catch {\n // A missing .gitignore is created below.\n }\n const pattern = path.startsWith('#') || path.startsWith('!') ? `\\\\${path}` : path\n const lines = current.split(/\\r?\\n/).map(line => line.trim())\n if (lines.includes(pattern)) return { message: 'already ignored', detail: null }\n const prefix = current.length === 0 || current.endsWith('\\n') ? current : `${current}\\n`\n await writeFile(file, `${prefix}${pattern}\\n`, 'utf8')\n return { message: `added ${pattern} to .gitignore`, detail: null }\n}\n\n/** Whether the platform can reveal a path in its file manager. */\nfunction revealCommand(absolute: string): string[] {\n if (process.platform === 'darwin') return ['open', '-R', absolute]\n if (process.platform === 'win32') return ['explorer.exe', `/select,${absolute}`]\n return ['xdg-open', dirname(absolute)]\n}\n\n/** What the panel needs before offering to publish a repository on GitHub. */\nexport interface GithubInfo {\n /** Whether the GitHub CLI is installed, signed in, and can read the account. */\n readonly available: boolean\n /** Authenticated account login, or null. */\n readonly login: string | null\n /** Why publishing is unavailable, or null. */\n readonly reason: string | null\n}\n\n/**\n * Read the GitHub account the CLI would publish under.\n * @param request - the `exec` seam bound to the repository.\n * @returns availability, login, and a refusal reason.\n */\nexport async function gitGithubInfo({ exec }: { exec: Exec }): Promise<GithubInfo> {\n const unavailable = (reason: string): GithubInfo => ({ available: false, login: null, reason })\n try {\n await exec(['gh', '--version'], { allowedExitCodes: [0], timeoutMs: GITHUB_PROBE_TIMEOUT_MS })\n } catch {\n return unavailable('gh is not installed')\n }\n const status = await exec(['gh', 'auth', 'status'], { allowedExitCodes: [0, 1], timeoutMs: GITHUB_PROBE_TIMEOUT_MS })\n if (status.exitCode !== 0) return unavailable('gh is not signed in')\n const account = await exec(['gh', 'api', 'user', '--jq', '.login'], { allowedExitCodes: [0, 1], timeoutMs: GITHUB_PROBE_TIMEOUT_MS })\n const login = (account.stdout.split(/\\r?\\n/).map(line => line.trim()).find(line => line.length > 0)) ?? ''\n if (account.exitCode !== 0 || login.length === 0) return unavailable('the GitHub account could not be read')\n return { available: true, login, reason: null }\n}\n\n/**\n * Run one Git operation.\n * @param request - `exec`, `cwd`, `operation`, and `params`.\n * @returns the operation result.\n * @throws {GitError} `INVALID` for malformed parameters, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitAction({ exec, cwd, operation, params = {} }: GitActionRequest): Promise<ActionResult> {\n // Creating the repository is the one operation that runs before a work tree exists.\n if (operation === 'initRepository') return await initRepository(exec, cwd)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const paths = Array.isArray(params.paths) ? params.paths.map(checkedPath) : []\n const requirePaths = (): string[] => {\n if (paths.length === 0) throw new GitError('INVALID', 'at least one path is required')\n return paths\n }\n const network: ExecOptions = { timeoutMs: NETWORK_TIMEOUT_MS }\n switch (operation) {\n case 'stage':\n return await mutate(exec, ['add', '-A', '--', ...requirePaths()], 'add')\n case 'unstage': {\n const target = requirePaths()\n if (await isUnborn(exec)) return await mutate(exec, ['reset', '-q', '--', ...target], 'reset')\n return await mutate(exec, ['restore', '--staged', '--', ...target], 'restore')\n }\n case 'discard': {\n const target = requirePaths()\n if (params.untracked === true) return await mutate(exec, ['clean', '-fdq', '--', ...target], 'clean')\n return await mutate(exec, ['restore', '--worktree', '--', ...target], 'restore')\n }\n case 'stageAll':\n return await mutate(exec, ['add', '-A'], 'add')\n case 'unstageAll':\n return await mutate(exec, ['reset', '-q'], 'reset')\n case 'commit': {\n const message = typeof params.message === 'string' ? params.message.trim() : ''\n if (message.length === 0) throw new GitError('INVALID', 'a commit message is required')\n const args = ['commit', '-m', message]\n if (params.amend === true) args.push('--amend')\n if (params.signoff === true) args.push('--signoff')\n return await mutate(exec, args, 'commit')\n }\n case 'undoCommit': {\n const head = await exec(argvOf(['rev-parse', '--verify', '--quiet', 'HEAD^']), { allowedExitCodes: [0, 1, 128] })\n if (head.exitCode !== 0) throw new GitError('INVALID', 'there is no commit to undo')\n return await mutate(exec, ['reset', '--soft', 'HEAD^'], 'reset')\n }\n case 'fetch': {\n const args = ['fetch', '--prune']\n if (params.all !== false) args.push('--all')\n const before = await readRemoteTips(exec)\n const result = await mutate(exec, args, 'fetch', network)\n const after = await readRemoteTips(exec)\n const changed: RefChange[] = []\n for (const [ref, hash] of after) {\n const previous = before.get(ref)\n if (previous !== hash) changed.push({ ref, from: previous ?? null, to: hash })\n }\n for (const [ref, hash] of before) {\n if (!after.has(ref)) changed.push({ ref, from: hash, to: null })\n }\n // `updated` lets the panel distinguish \"fetched, nothing new\" from\n // \"fetched, references moved\" without a second scan.\n return { ...result, updated: changed.length > 0, changed }\n }\n case 'pullBranch': {\n const name = checkedRef(typeof params.name === 'string' ? params.name.trim() : '')\n const remote = await configValue(exec, `branch.${name}.remote`)\n const merge = await configValue(exec, `branch.${name}.merge`)\n if (remote === null || merge === null || remote.length === 0 || remote === '.') {\n throw new GitError('INVALID', `branch \"${name}\" has no upstream branch`)\n }\n const remoteBranch = merge.startsWith('refs/heads/') ? merge.slice('refs/heads/'.length) : merge\n const upstreamRef = `${remote}/${remoteBranch}`\n await mutate(exec, ['fetch', '--prune', remote], 'fetch', network)\n const upstream = await exec(argvOf(['rev-parse', '--verify', '--quiet', `${upstreamRef}^{commit}`]), { allowedExitCodes: [0, 1] })\n if (upstream.exitCode !== 0) throw new GitError('INVALID', `upstream \"${upstreamRef}\" is missing`)\n const remoteTip = firstLine(upstream.stdout)\n const local = await exec(argvOf(['rev-parse', '--verify', '--quiet', `refs/heads/${name}^{commit}`]), { allowedExitCodes: [0, 1] })\n if (local.exitCode !== 0) throw new GitError('INVALID', `branch \"${name}\" is missing`)\n const localTip = firstLine(local.stdout)\n const counted = await exec(argvOf(['rev-list', '--count', `${localTip}..${remoteTip}`]), { allowedExitCodes: [0, 1] })\n const commits = Number.parseInt(firstLine(counted.stdout), 10) || 0\n if (localTip === remoteTip || commits === 0) {\n return { message: `branch \"${name}\" is already up to date`, detail: null, commits: 0 }\n }\n const current = await exec(argvOf(['symbolic-ref', '--quiet', '--short', 'HEAD']), { allowedExitCodes: [0, 1] })\n if (current.exitCode === 0 && current.stdout.trim() === name) {\n await mutate(exec, ['merge', '--ff-only', remoteTip], 'merge')\n } else {\n const ancestor = await exec(argvOf(['merge-base', '--is-ancestor', localTip, remoteTip]), { allowedExitCodes: [0, 1] })\n if (ancestor.exitCode !== 0) throw new GitError('INVALID', `branch \"${name}\" cannot fast-forward`)\n await mutate(exec, ['update-ref', `refs/heads/${name}`, remoteTip, localTip], 'update-ref')\n }\n return { message: `pulled ${name}`, detail: null, commits }\n }\n case 'pull': {\n const args = ['pull', '--no-edit']\n if (params.rebase === true) args.push('--rebase')\n if (params.ffOnly === true) args.push('--ff-only')\n return await mutate(exec, args, 'pull', network)\n }\n case 'publish': {\n const branch = await requireBranch(exec)\n const url = typeof params.url === 'string' ? params.url.trim() : ''\n const requested = params.remote === undefined ? undefined : checkedRemoteName(params.remote)\n let remote: string | null\n if (url.length > 0) {\n remote = requested ?? 'origin'\n if ((await remoteNames(exec)).includes(remote)) throw new GitError('INVALID', `remote \"${remote}\" already exists`)\n await mutate(exec, ['remote', 'add', remote, checkedRemoteUrl(url)], 'remote add')\n } else {\n remote = requested ?? await defaultRemote(exec)\n }\n if (remote === null) throw new GitError('INVALID', 'the repository has no remote to publish to')\n return await mutate(exec, ['push', '--set-upstream', remote, branch], 'push', network)\n }\n case 'publishGithub': {\n const branch = await requireBranch(exec)\n const name = checkedGithubRepository(params.name)\n const visibility = params.private === true ? '--private' : params.public === true ? '--public' : null\n if (visibility === null) throw new GitError('INVALID', 'choose a public or private GitHub repository')\n if ((await remoteNames(exec)).length > 0) throw new GitError('INVALID', 'the repository already has a remote')\n try {\n await exec(['gh', 'repo', 'create', name, visibility, '--source', root, '--remote', 'origin'], {\n timeoutMs: NETWORK_TIMEOUT_MS,\n })\n } catch (error) {\n throw failureOf(error, 'GitHub repository')\n }\n return await mutate(exec, ['push', '--set-upstream', 'origin', branch], 'push', network)\n }\n case 'push': {\n const args = ['push']\n if (params.forceWithLease === true) args.push('--force-with-lease')\n if (params.tags === true) args.push('--tags')\n if (params.setUpstream === true) {\n const branch = await requireBranch(exec)\n const remote = params.remote === undefined ? await defaultRemote(exec) : checkedRemoteName(params.remote)\n if (remote === null) throw new GitError('INVALID', 'the repository has no remote to publish to')\n args.push('--set-upstream', remote, branch)\n }\n return await mutate(exec, args, 'push', network)\n }\n case 'checkoutBranch': {\n const name = typeof params.name === 'string' ? params.name : ''\n if (name.length === 0) throw new GitError('INVALID', 'a branch name is required')\n if (params.kind === 'remote') {\n const local = name.split('/').slice(1).join('/')\n if (local.length === 0) throw new GitError('INVALID', `\"${name}\" is not a remote branch`)\n await checkBranchName(exec, local)\n if (await localBranchExists(exec, local)) return await mutate(exec, ['switch', local], 'switch')\n return await mutate(exec, ['switch', '-c', local, '--track', name], 'switch')\n }\n await checkBranchName(exec, name)\n return await mutate(exec, ['switch', name], 'switch')\n }\n case 'checkoutCommit': {\n const commit = await resolveCommit(exec, checkedHash(params.hash))\n return await mutate(exec, ['switch', '--detach', commit], 'switch')\n }\n case 'createBranch': {\n const name = await checkBranchName(exec, typeof params.name === 'string' ? params.name.trim() : '')\n const args = ['switch', '-c', name]\n if (typeof params.from === 'string' && params.from.length > 0) {\n args.push(await resolveCommit(exec, checkedRef(params.from)))\n }\n return await mutate(exec, args, 'switch')\n }\n case 'renameBranch': {\n const from = await checkBranchName(exec, typeof params.from === 'string' ? params.from : '')\n const to = await checkBranchName(exec, typeof params.to === 'string' ? params.to.trim() : '')\n return await mutate(exec, ['branch', '-m', from, to], 'branch')\n }\n case 'deleteBranch': {\n const name = await checkBranchName(exec, typeof params.name === 'string' ? params.name : '')\n return await mutate(exec, ['branch', params.force === true ? '-D' : '-d', name], 'branch')\n }\n case 'deleteRemoteBranch': {\n const name = typeof params.name === 'string' ? params.name : ''\n if (name.length === 0) throw new GitError('INVALID', 'a remote branch name is required')\n const slash = name.indexOf('/')\n if (slash <= 0 || slash === name.length - 1) throw new GitError('INVALID', `\"${name}\" is not a remote branch`)\n const remote = name.slice(0, slash)\n const branch = name.slice(slash + 1)\n return await mutate(exec, ['push', remote, '--delete', branch], 'push', network)\n }\n case 'cherryPick': {\n const commit = await resolveCommit(exec, checkedHash(params.hash))\n const args = ['cherry-pick']\n if (params.noCommit === true) args.push('--no-commit')\n const parents = (await run(exec, ['rev-list', '--parents', '-n1', commit], 'rev-list')).stdout.trim().split(' ').filter(Boolean).length - 1\n if (parents > 1) args.push('-m', '1')\n args.push(commit)\n return await mutate(exec, args, 'cherry-pick')\n }\n case 'revert': {\n const commit = await resolveCommit(exec, checkedHash(params.hash))\n const args = ['revert', '--no-edit']\n const parents = (await run(exec, ['rev-list', '--parents', '-n1', commit], 'rev-list')).stdout.trim().split(' ').filter(Boolean).length - 1\n if (parents > 1) args.push('-m', '1')\n args.push(commit)\n return await mutate(exec, args, 'revert')\n }\n case 'abortOperation': {\n const kind = params.kind\n const command = typeof kind === 'string' ? ABORTABLE[kind] : undefined\n if (command === undefined) throw new GitError('INVALID', `\"${String(kind)}\" is not an abortable operation`)\n return await mutate(exec, command, command.join(' '))\n }\n case 'stashSave': {\n const args = ['stash', 'push']\n if (params.includeUntracked === true) args.push('-u')\n if (params.staged === true) args.push('--staged')\n const message = typeof params.message === 'string' ? params.message.trim() : ''\n if (message.length > 0) args.push('-m', message)\n if (paths.length > 0) args.push('--', ...paths)\n return await mutate(exec, args, 'stash push')\n }\n case 'stashApply':\n case 'stashPop':\n case 'stashDrop': {\n const index = checkedStashIndex(params.index)\n const verb = operation === 'stashApply' ? 'apply' : operation === 'stashPop' ? 'pop' : 'drop'\n return await mutate(exec, ['stash', verb, `stash@{${index}}`], `stash ${verb}`)\n }\n case 'stashClear':\n return await mutate(exec, ['stash', 'clear'], 'stash clear')\n case 'tagCreate': {\n const name = await checkTagName(exec, typeof params.name === 'string' ? params.name.trim() : '')\n const message = typeof params.message === 'string' ? params.message.trim() : ''\n const args = message.length > 0 ? ['tag', '-a', '-m', message, name] : ['tag', name]\n if (typeof params.at === 'string' && params.at.length > 0) args.push(await resolveCommit(exec, checkedRef(params.at)))\n return await mutate(exec, args, 'tag')\n }\n case 'tagDelete': {\n const name = await checkTagName(exec, typeof params.name === 'string' ? params.name : '')\n return await mutate(exec, ['tag', '-d', name], 'tag')\n }\n case 'addToIgnore':\n return await addToIgnoreFile(root, requirePaths()[0]!)\n case 'reveal': {\n const target = requirePaths()[0]!\n const command = revealCommand(join(root, target))\n try {\n await exec(command, { allowedExitCodes: [0, 1] })\n } catch (error) {\n throw failureOf(error, 'reveal')\n }\n return { message: 'revealed in the file manager', detail: null }\n }\n default:\n throw new GitError('INVALID', `unknown operation \"${operation}\"`)\n }\n}\n\n/** Every operation name this layer accepts, for the caller's request validation. */\nexport const OPERATIONS = Object.freeze([\n 'stage', 'unstage', 'discard', 'stageAll', 'unstageAll', 'commit', 'undoCommit',\n 'fetch', 'pull', 'pullBranch', 'publish', 'publishGithub', 'push', 'checkoutBranch', 'checkoutCommit', 'createBranch', 'renameBranch',\n 'deleteBranch', 'deleteRemoteBranch', 'cherryPick', 'revert', 'abortOperation',\n 'stashSave', 'stashApply', 'stashPop', 'stashDrop', 'stashClear',\n 'tagCreate', 'tagDelete', 'addToIgnore', 'reveal', 'initRepository',\n])\n","/**\n * Shared contracts of the Host half: the process seam the Git layer runs\n * through, the failure shape the JSON route reports, and the read limits the\n * caller applies to one snapshot.\n */\n\n/** Stable failure codes the browser half already knows how to phrase. */\nexport type WireCode =\n | 'NOT_A_REPO'\n | 'INVALID'\n | 'INVALID_REQUEST'\n | 'NO_SESSION'\n | 'NO_WORKSPACE'\n | 'GIT_FAILED'\n | 'TIMEOUT'\n | 'TOO_LARGE'\n | 'SPAWN_FAILED'\n | 'CANCELLED'\n | 'BUSY'\n | 'NETWORK'\n | 'FORBIDDEN'\n | 'INTERNAL'\n\n/** Every name in {@link WireCode}, for admitting a caught failure onto the wire. */\nconst WIRE_CODE_NAMES = [\n 'NOT_A_REPO', 'INVALID', 'INVALID_REQUEST', 'NO_SESSION', 'NO_WORKSPACE', 'GIT_FAILED',\n 'TIMEOUT', 'TOO_LARGE', 'SPAWN_FAILED', 'CANCELLED', 'BUSY', 'NETWORK', 'FORBIDDEN', 'INTERNAL',\n] as const satisfies readonly WireCode[]\n\n/** Set form of {@link WIRE_CODE_NAMES} used to recognize an already-coded failure. */\nexport const WIRE_CODES: ReadonlySet<string> = new Set(WIRE_CODE_NAMES)\n\n/** Failure body of a rejected request, as it goes onto the wire. */\nexport interface WireError {\n /** Stable wire code, e.g. `NOT_A_REPO`. */\n readonly code: WireCode\n /** Operator-readable reason. */\n readonly message: string\n /** Raw Git output excerpt, when one exists. */\n readonly detail: string | null\n}\n\n/** A caught failure that already carries a wire code the page understands. */\nexport interface WireFailureLike {\n readonly code: WireCode\n readonly message: string\n readonly detail?: unknown\n}\n\n/** A rejected request as the route reports it, before it becomes an HTTP body. */\nexport class RequestError extends Error {\n /** Stable wire code such as `NOT_A_REPO`. */\n readonly code: WireCode\n\n /** Raw Git output excerpt, when one exists. */\n readonly detail: string | null\n\n /**\n * @param code - stable wire code such as `NOT_A_REPO`.\n * @param message - operator-readable reason.\n * @param detail - raw Git output excerpt, when one exists.\n */\n constructor(code: WireCode, message: string, detail: string | null = null) {\n super(message)\n this.name = 'RequestError'\n this.code = code\n this.detail = detail\n }\n}\n\n/** Complete output of one program the `exec` seam ran to an allowed exit code. */\nexport interface ExecResult {\n /** Captured standard output. */\n readonly stdout: string\n /** Captured standard error. */\n readonly stderr: string\n /** Exit code; always one of the requested allowed codes. */\n readonly exitCode: number\n}\n\n/** Per-invocation options the Git layer hands the `exec` seam. */\nexport interface ExecOptions {\n /** Exit codes that resolve instead of rejecting; defaults to `[0]`. */\n readonly allowedExitCodes?: readonly number[] | undefined\n /** One-off Git configuration values, passed as `-c key=value`. */\n readonly config?: Readonly<Record<string, string>> | undefined\n /** Bytes written to the child's stdin, then closed. */\n readonly input?: string | undefined\n /** Deadline for this command, including executable lookup. */\n readonly timeoutMs?: number | undefined\n}\n\n/**\n * Run one program for one Session directory.\n *\n * Resolves for an allowed exit code and rejects otherwise; a rejection carries\n * the Git layer's code (`GIT_FAILED`, `TIMEOUT`, `SPAWN_FAILED`, `TOO_LARGE`, …).\n */\nexport type Exec = (argv: string[], options?: ExecOptions) => Promise<ExecResult>\n\n/** Limits one Git snapshot applies; omitted entries fall back to the Git layer's own bounds. */\nexport interface GitLimits {\n /** Maximum branches in each branch list. */\n maxBranches: number\n /** Maximum commits in one page. */\n maxCommits: number\n /** Maximum tags. */\n maxTags: number\n /** Maximum changed files across all change lists. */\n maxFiles: number\n /** Maximum characters of one returned diff. */\n maxDiffBytes: number\n}\n","/**\n * Commit-message generation for the source-control panel: prompt construction,\n * output cleanup, and the one-shot model call the Host entry supplies.\n *\n * The module holds no LLM client of its own: the Host passes a `generate`\n * seam backed by the app's own model runtime, so this package keeps no\n * runtime dependency on any `@deepseek-ai/*` package.\n */\nimport type { CommitMessageContext } from './git.ts'\nimport { RequestError } from './types.ts'\n\n/** How the model should treat the drafted message. */\nexport type CommitMessageMode = 'generate' | 'improve'\n\n/** Message shape the caller asked for; `auto` leaves it to the model and repository style. */\nexport type CommitMessageStyle = 'auto' | 'conventional' | 'single' | 'detailed'\n\n/** Every accepted style, for validating an untrusted request field. */\nexport const COMMIT_MESSAGE_STYLES: readonly CommitMessageStyle[] = Object.freeze(['auto', 'conventional', 'single', 'detailed'])\n\n/** One prompt handed to the model. */\nexport interface CommitMessagePrompt {\n /** Instructions and output contract. */\n readonly system: string\n /** Change context and, for an improvement, the draft. */\n readonly user: string\n}\n\n/** Dispatch one prompt to a model and resolve its text. */\nexport type CommitMessageGenerator = (prompt: CommitMessagePrompt) => Promise<string>\n\n/** One commit-message generation request. */\nexport interface CommitMessageRequest {\n /** The change context read from the checkout. */\n readonly context: CommitMessageContext\n /** Whether the model writes from scratch or improves the draft. */\n readonly mode: CommitMessageMode\n /** The user's current draft, for `improve`. */\n readonly draft: string\n /** Active app locale id, deciding the output language for `generate`. */\n readonly language: string\n /** Requested message shape; omitted reads as `auto`. */\n readonly style?: CommitMessageStyle | undefined\n /** Whether the caller pinned the language rule instead of following the UI. */\n readonly languagePinned?: boolean | undefined\n /** Model seam supplied by the Host; absent when no route is configured. */\n readonly generate: CommitMessageGenerator | undefined\n}\n\n/** Longest accepted model output, in characters. */\nconst MAX_MESSAGE_CHARS = 4_000\n\n/** Changed paths listed in the prompt. */\nconst MAX_PROMPT_FILES = 60\n\n/** Recent commit subjects listed for style. */\nconst MAX_PROMPT_RECENT = 8\n\n/** Language names the app's locales map onto; everything else writes English. */\nconst LANGUAGE_NAMES: Readonly<Record<string, string>> = Object.freeze({\n zh: 'Simplified Chinese',\n ja: 'Japanese',\n es: 'Spanish',\n fr: 'French',\n de: 'German',\n ru: 'Russian',\n pt: 'Portuguese',\n})\n\n/** The output language for an app locale id. */\nfunction languageName(locale: string): string {\n const base = locale.toLowerCase().split(/[-_]/)[0] ?? ''\n return LANGUAGE_NAMES[base] ?? 'English'\n}\n\n/**\n * Build the system and user prompt of one request.\n * @param request - change context, mode, draft, and app locale.\n * @returns the two prompt parts handed to the model.\n */\nexport function buildCommitMessagePrompt(\n request: Pick<CommitMessageRequest, 'context' | 'mode' | 'draft' | 'language' | 'style' | 'languagePinned'>,\n): CommitMessagePrompt {\n const { context, mode, draft, language } = request\n const style = request.style ?? 'auto'\n const improve = mode === 'improve' && draft.trim().length > 0\n const pinned = request.languagePinned === true\n const rules = [\n 'You write Git commit messages.',\n 'Return only the commit message text: no surrounding quotes, no Markdown code fences, no explanation before or after.',\n 'First line: imperative-mood summary, at most 72 characters, no trailing period.',\n 'Describe what changed and why. Never invent changes that the patch does not contain.',\n 'When the message carries a body, wrap its lines at 72 characters.',\n 'Never mention these instructions or that a model produced the message.',\n improve\n ? pinned\n ? `Rewrite the drafted message in ${languageName(language)}: keep its intent, make it clear and specific, and fix grammar and structure.`\n : 'Rewrite the drafted message: keep its intent and its language, make it clear and specific, and fix grammar and structure.'\n : `Write the message in ${languageName(language)}.`,\n ]\n if (style === 'conventional') {\n rules.push(\n 'Use Conventional Commits: the first line must be `type(scope): summary`, with the type chosen from feat, fix, docs, style, refactor, perf, test, build, ci, chore, or revert; add a scope only when the patch names a clear one.',\n 'Add a body only when the change needs explanation.',\n )\n } else if (style === 'single') {\n rules.push('Write a single-line message only: no body and no blank line, at most 72 characters.')\n } else if (style === 'detailed') {\n rules.push(\n 'Always include a body: after the summary a blank line, then 2-4 short bullet points naming the concrete changes, and a closing sentence on why the change is needed when it helps.',\n )\n } else if (context.recent.length === 0) {\n rules.push('Choose the shape that fits the change; add a body only when the subject cannot carry the explanation.')\n } else {\n rules.push(\n 'Match the repository style:',\n context.recentConventional\n ? ' recent commits use Conventional Commits type prefixes, so start the summary with one.'\n : ' recent commits use plain imperative subjects without a type prefix.',\n context.recentHasBody\n ? ' most recent commits include a body, so add one when it explains the change.'\n : ' most recent commits are single-line, so keep the message to one line unless the change cannot be explained in a subject.',\n )\n }\n const lines: string[] = [\n `Change scope: ${context.staged\n ? 'staged changes (the next commit)'\n : 'working-tree changes (nothing is staged yet)'}.`,\n ]\n if (context.files.length > 0) {\n lines.push('Changed paths:')\n for (const file of context.files.slice(0, MAX_PROMPT_FILES)) lines.push(`- ${file.status}: ${file.path}`)\n if (context.files.length > MAX_PROMPT_FILES) {\n lines.push(`- … and ${String(context.files.length - MAX_PROMPT_FILES)} more paths`)\n }\n } else {\n lines.push('Changed paths: none.')\n }\n if (context.recent.length > 0) {\n lines.push('Recent commit subjects (style reference):')\n for (const subject of context.recent.slice(0, MAX_PROMPT_RECENT)) lines.push(`- ${subject}`)\n }\n if (context.diff.length > 0) {\n lines.push('Patch:', '```diff', context.diff, '```')\n }\n if (improve) lines.push('Draft to improve:', '```text', draft.slice(0, MAX_MESSAGE_CHARS), '```')\n return { system: rules.join('\\n'), user: lines.join('\\n') }\n}\n\n/** A wrapped emphasis marker the model sometimes puts around the subject. */\nconst BOUNDARY_QUOTES = /^[\"'`]|[\"'`]$/g\n\n/**\n * Normalize one model answer into a commit message.\n * @param text - raw model output.\n * @returns the cleaned message, possibly empty.\n */\nexport function cleanCommitMessage(text: string): string {\n let value = String(text ?? '').replace(/\\r\\n/g, '\\n').trim()\n const fenced = /^```[a-zA-Z]*\\n([\\s\\S]*?)\\n```$/.exec(value)\n if (fenced !== null) value = (fenced[1] ?? '').trim()\n value = value.replace(/^(?:commit message|message)\\s*:\\s*/i, '')\n if (value.length > 1) {\n const first = value[0]\n const last = value[value.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\") || (first === '`' && last === '`')) {\n value = value.slice(1, -1)\n }\n }\n value = value.replace(BOUNDARY_QUOTES, '')\n value = value\n .split('\\n')\n .map(line => line.trimEnd())\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n return value.slice(0, MAX_MESSAGE_CHARS)\n}\n\n/**\n * Generate or improve one commit message.\n * @param request - change context, mode, draft, language, and the model seam.\n * @returns the cleaned message.\n * @throws {RequestError} `INVALID` for an empty change set or a missing model\n * route, `INTERNAL` when the model call fails or returns nothing usable.\n */\nexport async function generateCommitMessage(request: CommitMessageRequest): Promise<{ message: string }> {\n if (request.mode === 'generate' && request.draft.trim().length === 0\n && request.context.files.length === 0 && request.context.diff.length === 0) {\n throw new RequestError('INVALID', 'there are no changes to describe')\n }\n if (request.generate === undefined) {\n throw new RequestError('INVALID', 'no model is configured to write commit messages')\n }\n let raw: string\n try {\n raw = await request.generate(buildCommitMessagePrompt(request))\n } catch (error) {\n throw new RequestError('INTERNAL', `the commit message could not be generated: ${error instanceof Error ? error.message : String(error)}`)\n }\n const message = cleanCommitMessage(raw)\n if (message.length === 0) throw new RequestError('INTERNAL', 'the model returned an empty commit message')\n return { message }\n}\n","/**\n * Host half of the Git source-control plugin: one JSON route that answers Git\n * facts and Git operations for a Session's checkout.\n *\n * The browser half cannot call generated Remotes, so this plugin carries its own\n * HTTP route on the shared web server. A request names a Session, never a path:\n * the route resolves the Session's effective working directory through the\n * `workingDirectory` service and runs Git there, so a page cannot reach a\n * directory the open Session does not already belong to.\n *\n * Every Git invocation goes through `ctx.subprocess` (`resolveExecutable` plus a\n * collected spawn), so the process seam, cancellation, output caps, and teardown\n * stay with the provider. The route itself is a raw Node handler because Git\n * operations must be POSTs; resource routes answer GET and HEAD only.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport type {} from '@deepseek-ai/dsh-session'\nimport type {} from '@deepseek-ai/dsh-subprocess'\nimport type {} from '@deepseek-ai/dsh-working-directory'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess'\nimport {\n GIT_ENV, OPERATIONS, gitAction, gitCommitDiff, gitCommitFiles, gitCommitMessageContext, gitCommits, gitDiff, gitFileHistory, gitGithubInfo, gitStashDiff, gitStatus, gitSummary,\n} from './host/git.ts'\nimport { RequestError, WIRE_CODES } from './host/types.ts'\nimport { generateCommitMessage } from './host/commit-message.ts'\nimport type { CommitMessageGenerator, CommitMessagePrompt } from './host/commit-message.ts'\nimport type { Exec, GitLimits, WireFailureLike } from './host/types.ts'\n\n/** Exact route path; the handler answers this path and everything below it. */\nconst ROUTE = '/api/dsh-git-scm'\n\n/** Default executable when the request names none (every request but `reveal`). */\nconst GIT_COMMAND = 'git'\n\n/** Flags before every Git subcommand: no index refresh writes, hooks, or fsmonitor. */\nconst GIT_PREFIX = Object.freeze(['--no-optional-locks', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false'])\n\n/** Deadline for one local Git command, including executable lookup. */\nconst GIT_TIMEOUT_MS = 30_000\n\n/** Deadline for a command that talks to a remote; the Git layer raises it per operation. */\nconst REQUEST_TIMEOUT_MS = 420_000\n\n/** Deadline for one commit-message model request. */\nconst COMMIT_MESSAGE_TIMEOUT_MS = 90_000\n\n/** Output tokens reserved for one commit-message request, thinking included. */\nconst COMMIT_MESSAGE_MAX_TOKENS = 2_048\n\n/** Characters of model output accepted before assembly stops. */\nconst COMMIT_MESSAGE_MAX_OUTPUT_CHARS = 8_192\n\n/** Auxiliary-purpose tag recorded for the model request. */\nconst COMMIT_MESSAGE_PURPOSE = 'git-commit-message'\n\n/** Grace period the provider grants a terminating process. */\nconst GRACE_MS = 2_000\n\n/** Captured bytes per output stream. */\nconst MAX_OUTPUT_BYTES = 8 * 1024 * 1024\n\n/** Characters of a returned diff. */\nconst MAX_DIFF_BYTES = 400 * 1024\n\n/** Accepted request body size. */\nconst MAX_BODY_BYTES = 256 * 1024\n\n/** How many requests one Session may have in flight. */\nconst MAX_INFLIGHT_PER_SESSION = 4\n\n/** List caps that keep one panel render bounded on a large repository. */\nconst LIMITS: Readonly<GitLimits & { maxOutputBytes: number }> = Object.freeze({\n maxBranches: 500,\n maxCommits: 40,\n maxTags: 30,\n maxFiles: 3000,\n maxDiffBytes: MAX_DIFF_BYTES,\n maxOutputBytes: MAX_OUTPUT_BYTES,\n})\n\n/** Services this plugin needs; `webServer` binds the route, `sessions` resolves the checkout. */\nexport const inject = ['subprocess', 'sessions', 'webServer']\n\n/** Whether a decoded JSON value is a plain object. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** Whether a caught failure already carries a wire code the page understands. */\nfunction isWireFailure(value: unknown): value is WireFailureLike {\n return isRecord(value)\n && typeof value.code === 'string' && WIRE_CODES.has(value.code)\n && typeof value.message === 'string'\n}\n\n/** Format an unknown thrown value for an operator message. */\nfunction messageOf(error: unknown): string {\n if (error instanceof Error) return error.message\n return String(error)\n}\n\n/** Read the raw `detail` field a caught failure may carry. */\nfunction detailOf(error: unknown): unknown {\n return isRecord(error) ? error.detail : undefined\n}\n\n/**\n * Mount the Git route for the calling profile.\n * @param ctx - Host Cordis context carrying the injected services.\n */\nexport function apply(ctx: Context): void {\n /** Sessions whose requests are in flight, so one page cannot stack unbounded Git work. */\n const active = new Map<string, number>()\n\n /**\n * Run one program for one Session directory.\n * @param options - the Session directory and the request cancellation.\n * @returns the `exec` seam `host/git.ts` expects.\n */\n function createExec({ cwd, signal }: { cwd: string; signal: AbortSignal }): Exec {\n return async function exec(argv, options = {}) {\n const allowedExitCodes = options.allowedExitCodes ?? [0]\n const [program, ...args] = argv\n const controller = new AbortController()\n const onAbort = (): void => { controller.abort(signal.reason) }\n signal.addEventListener('abort', onAbort, { once: true })\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort(new Error('git command timed out'))\n }, options.timeoutMs ?? GIT_TIMEOUT_MS)\n timer.unref?.()\n const callSignal = controller.signal\n try {\n const executable = await ctx.subprocess.resolveExecutable(program ?? GIT_COMMAND, undefined, callSignal)\n const isGit = program === GIT_COMMAND\n const overrides = Object.entries(options.config ?? {})\n const command = [\n executable,\n ...isGit ? GIT_PREFIX : [],\n ...isGit ? overrides.flatMap(([key, value]) => ['-c', `${key}=${value}`]) : [],\n ...args,\n ]\n let child: SubprocessHandle\n try {\n child = ctx.subprocess.spawn({\n argv: command,\n cwd,\n ...isGit ? { env: { ...GIT_ENV } } : {},\n graceMs: GRACE_MS,\n signal: callSignal,\n stdio: {\n stdin: options.input === undefined ? 'ignore' : { data: options.input },\n stdout: { maxBytes: MAX_OUTPUT_BYTES },\n stderr: { maxBytes: MAX_OUTPUT_BYTES },\n },\n })\n } catch (error) {\n throw new RequestError('SPAWN_FAILED', `${program} could not start: ${messageOf(error)}`)\n }\n try {\n const outcome = await child.done\n if (timedOut) throw new RequestError('TIMEOUT', `${program} ${args[0] ?? ''} timed out`)\n if (callSignal.aborted) throw new RequestError('CANCELLED', 'the Git request was cancelled')\n const stdout = child.collected.stdout?.readFrom(0)\n const stderr = child.collected.stderr?.readFrom(0)\n if (stdout?.lossy === true || stderr?.lossy === true) {\n throw new RequestError('TOO_LARGE', `${program} ${args[0] ?? ''} printed more than the output limit`)\n }\n const out = stdout?.text ?? ''\n const err = stderr?.text ?? ''\n if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) {\n throw new RequestError(\n 'GIT_FAILED',\n `${program} ${args[0] ?? ''} failed (${outcome.signal ?? outcome.exitCode}): ${firstLine(err)}`,\n excerpt(err),\n )\n }\n return { stdout: out, stderr: err, exitCode: outcome.exitCode }\n } finally {\n child.terminate()\n await child.waitForExit().catch(() => undefined)\n }\n } catch (error) {\n if (error instanceof RequestError) throw error\n if (timedOut) throw new RequestError('TIMEOUT', `${program} ${args[0] ?? ''} timed out`)\n if (callSignal.aborted) throw new RequestError('CANCELLED', 'the Git request was cancelled')\n throw new RequestError('SPAWN_FAILED', `${program} ${args[0] ?? ''} could not run: ${messageOf(error)}`)\n } finally {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n /**\n * Resolve the checkout directory a request belongs to.\n * @param sessionId - Session identity supplied by the page.\n * @returns the Session's absolute working directory.\n */\n function directoryOf(sessionId: unknown): string {\n if (typeof sessionId !== 'string' || sessionId.length === 0) {\n throw new RequestError('INVALID_REQUEST', 'sessionId must be a non-empty string')\n }\n // Session ids are branded strings; the non-empty check above is the admission.\n const session = ctx.sessions.get(sessionId as SessionId)\n if (session === undefined) throw new RequestError('NO_SESSION', 'the Session is not loaded in this process')\n const workingDirectory = ctx.get('workingDirectory')\n const directory: string | undefined = workingDirectory === undefined ? session.header.cwd : workingDirectory.get(session)\n if (directory === undefined || directory === '') {\n throw new RequestError('NO_WORKSPACE', 'the Session has no working directory')\n }\n return directory\n }\n\n /**\n * Build the model call a commit-message request runs, when the app provides\n * both an adapter and a default route. The panel keeps working without it.\n * @param sessionId - Session whose request routing the model call joins.\n * @param signal - cancellation of the whole HTTP request.\n * @returns the model seam, or undefined when no route is configured.\n */\n function createCommitMessageGenerator(sessionId: string, signal: AbortSignal): CommitMessageGenerator | undefined {\n const llm = (ctx as unknown as { get(name: string): unknown }).get('llm') as {\n stream?: (options: Record<string, unknown>) => AsyncIterable<unknown>\n resolveModelInfo?: (provider: string, model: string, signal?: AbortSignal) => Promise<unknown>\n } | undefined\n const defaults = (ctx as unknown as { get(name: string): unknown }).get('agentDefaultModel') as\n { currentSelection?: () => Record<string, unknown> } | undefined\n const selection = defaults?.currentSelection?.()\n if (llm === undefined || typeof llm.stream !== 'function') return undefined\n if (selection === undefined\n || typeof selection.provider !== 'string' || selection.provider.length === 0\n || typeof selection.model !== 'string' || selection.model.length === 0) return undefined\n const provider = selection.provider\n const model = selection.model\n // A one-shot auxiliary call should think as little as the route allows.\n const auxiliaryEffort = async (): Promise<string | undefined> => {\n try {\n const info = await llm.resolveModelInfo?.(provider, model, signal) as\n { reasoning?: { efforts?: Array<{ id?: unknown }> } } | undefined\n const efforts = (info?.reasoning?.efforts ?? [])\n .map(effort => typeof effort?.id === 'string' ? effort.id : undefined)\n .filter((id): id is string => id !== undefined)\n if (efforts.length === 0) return undefined\n return efforts.includes('off') ? 'off' : efforts[0]\n } catch {\n // A route that cannot describe itself keeps the configured effort.\n return typeof selection.reasoningEffort === 'string' ? selection.reasoningEffort : undefined\n }\n }\n return async (prompt: CommitMessagePrompt): Promise<string> => {\n const reasoningEffort = await auxiliaryEffort()\n const stream = llm.stream!({\n provider,\n model,\n ...reasoningEffort === undefined ? {} : { reasoningEffort },\n system: prompt.system,\n messages: [{ role: 'user', content: [{ type: 'text', text: prompt.user }] }],\n temperature: 0.2,\n maxTokens: COMMIT_MESSAGE_MAX_TOKENS,\n sessionId,\n purpose: COMMIT_MESSAGE_PURPOSE,\n signal,\n })\n let text = ''\n let reason: unknown\n let stopped = false\n for await (const chunk of stream) {\n const typed = chunk as { type?: unknown; text?: unknown; reason?: unknown }\n if (typed.type === 'text-delta' && typeof typed.text === 'string') {\n text += typed.text\n if (text.length >= COMMIT_MESSAGE_MAX_OUTPUT_CHARS) {\n stopped = true\n break\n }\n } else if (typed.type === 'finish') reason = typed.reason\n }\n if (!stopped) {\n const finish = reason as { kind?: unknown; failure?: { message?: unknown } } | undefined\n const failure = typeof finish?.failure?.message === 'string' ? finish.failure.message : undefined\n if (finish?.kind === 'error') throw new Error(`the model request failed${failure === undefined ? '' : `: ${failure}`}`)\n if (finish?.kind === 'aborted') throw new Error('the model request was aborted')\n if (finish?.kind === 'max-tokens' && text.trim().length > 0) return text\n if (finish?.kind !== 'stop') {\n throw new Error(`the model did not finish normally${typeof finish?.kind === 'string' ? ` (${finish.kind})` : ''}`)\n }\n }\n return text\n }\n }\n\n /**\n * Answer one decoded request with Git data.\n * @param body - the decoded body `{ sessionId, action, params }`.\n * @param signal - cancellation of the whole request.\n * @returns the action's JSON result.\n */\n async function dispatch(body: unknown, signal: AbortSignal): Promise<unknown> {\n if (body === null || typeof body !== 'object') {\n throw new RequestError('INVALID_REQUEST', 'the request body must be a JSON object')\n }\n const request = body as Record<string, unknown>\n const rawSessionId = request.sessionId\n const cwd = directoryOf(rawSessionId)\n // `directoryOf` admitted the addressed Session id as a non-empty string.\n const sessionId = rawSessionId as string\n const action = request.action\n if (typeof action !== 'string') throw new RequestError('INVALID_REQUEST', 'action must be a string')\n const params = request.params ?? {}\n if (params === null || typeof params !== 'object' || Array.isArray(params)) {\n throw new RequestError('INVALID_REQUEST', 'params must be a JSON object')\n }\n const fields = params as Record<string, unknown>\n const inflight = active.get(sessionId) ?? 0\n if (inflight >= MAX_INFLIGHT_PER_SESSION) {\n throw new RequestError('BUSY', 'too many Git requests are already running for this Session')\n }\n active.set(sessionId, inflight + 1)\n try {\n const exec = createExec({ cwd, signal })\n switch (action) {\n case 'summary': return await gitSummary({ exec, cwd, limits: LIMITS })\n case 'github': return await gitGithubInfo({ exec })\n case 'commitMessage': {\n const mode = fields.mode === 'improve' ? 'improve' as const : 'generate' as const\n const draft = typeof fields.draft === 'string' ? fields.draft : ''\n const language = typeof fields.language === 'string' && fields.language.length > 0 ? fields.language : 'en'\n const style = fields.style === 'conventional' || fields.style === 'single' || fields.style === 'detailed'\n ? fields.style\n : 'auto'\n const languagePinned = fields.languagePinned === true\n const context = await gitCommitMessageContext({ exec, cwd, limits: LIMITS })\n const deadline = AbortSignal.any([signal, AbortSignal.timeout(COMMIT_MESSAGE_TIMEOUT_MS)])\n try {\n return await generateCommitMessage({\n context, mode, draft, language, style, languagePinned,\n generate: createCommitMessageGenerator(sessionId, deadline),\n })\n } catch (error) {\n const expired = deadline.aborted && deadline.reason instanceof Error && deadline.reason.name === 'TimeoutError'\n if (expired) throw new RequestError('TIMEOUT', 'the commit message request timed out')\n throw error\n }\n }\n case 'status': return await gitStatus({ exec, cwd, limits: LIMITS })\n case 'commits': return await gitCommits({\n exec,\n cwd,\n limits: LIMITS,\n ref: requiredString(fields.ref, 'params.ref'),\n skip: optionalCount(fields.skip),\n limit: optionalCount(fields.limit),\n })\n case 'commitFiles': return await gitCommitFiles({\n exec,\n cwd,\n limits: LIMITS,\n hash: requiredString(fields.hash, 'params.hash'),\n })\n case 'commitDiff': return await gitCommitDiff({\n exec,\n cwd,\n limits: LIMITS,\n hash: requiredString(fields.hash, 'params.hash'),\n path: requiredString(fields.path, 'params.path'),\n })\n case 'stashDiff': return await gitStashDiff({ exec, cwd, limits: LIMITS, index: fields.index })\n case 'fileHistory': return await gitFileHistory({\n exec,\n cwd,\n limits: LIMITS,\n path: requiredString(fields.path, 'params.path'),\n skip: optionalCount(fields.skip),\n limit: optionalCount(fields.limit),\n })\n case 'diff': return await gitDiff({\n exec,\n cwd,\n limits: LIMITS,\n path: requiredString(fields.path, 'params.path'),\n staged: fields.staged === true,\n untracked: fields.untracked === true,\n })\n case 'action': {\n const operation = requiredString(fields.operation, 'params.operation')\n if (!OPERATIONS.includes(operation)) {\n throw new RequestError('INVALID_REQUEST', `unknown operation \"${operation}\"`)\n }\n return await gitAction({ exec, cwd, operation, params: fields })\n }\n default:\n throw new RequestError('INVALID_REQUEST', `unknown action \"${action}\"`)\n }\n } finally {\n const remaining = (active.get(sessionId) ?? 1) - 1\n if (remaining <= 0) active.delete(sessionId)\n else active.set(sessionId, remaining)\n }\n }\n\n /**\n * Answer one HTTP exchange; only same-origin JSON POSTs from the app page are admitted.\n * @param req - the request.\n * @param res - the response.\n * @returns settles after the response is written.\n */\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n if (req.method !== 'POST') {\n res.writeHead(405, { allow: 'POST' })\n res.end()\n return\n }\n // A cross-site page could otherwise drive Git through the open desktop app.\n const origin = req.headers.origin\n if (origin !== undefined && !sameHost(origin, req.headers.host)) {\n writeJson(res, 403, { ok: false, error: { code: 'FORBIDDEN', message: 'requests must come from the app origin' } })\n try { req.resume() } catch { /* the request body is intentionally not read */ }\n return\n }\n if (typeof req.headers['content-type'] !== 'string' || !req.headers['content-type'].startsWith('application/json')) {\n writeJson(res, 415, { ok: false, error: { code: 'INVALID_REQUEST', message: 'content-type must be application/json' } })\n try { req.resume() } catch { /* the request body is intentionally not read */ }\n return\n }\n const controller = new AbortController()\n res.on('close', () => { if (!res.writableEnded) controller.abort(new Error('response closed')) })\n req.on('aborted', () => { controller.abort(new Error('request aborted')) })\n req.on('error', () => { controller.abort(new Error('request failed')) })\n const timeout = setTimeout(() => { controller.abort(new Error('request timed out')) }, REQUEST_TIMEOUT_MS)\n timeout.unref?.()\n try {\n const body = await readJson(req, MAX_BODY_BYTES)\n const data = await dispatch(body, controller.signal)\n writeJson(res, 200, { ok: true, data })\n } catch (error) {\n const failure = isWireFailure(error)\n ? new RequestError(error.code, messageOf(error), excerpt(detailOf(error)))\n : new RequestError('INTERNAL', messageOf(error), excerpt(detailOf(error)))\n if (failure.code === 'INTERNAL') ctx.logger?.warn?.(error instanceof Error ? error : new Error(String(error)))\n if (res.headersSent) {\n res.destroy()\n return\n }\n writeJson(res, 200, { ok: false, error: { code: failure.code, message: failure.message, detail: failure.detail } })\n } finally {\n clearTimeout(timeout)\n }\n }\n\n ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, handler: (req, res) => handle(req, res) }), 'dsh-git-scm: route')\n}\n\n/** Read one required string field of a request's params. */\nfunction requiredString(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new RequestError('INVALID_REQUEST', `${field} must be a non-empty string`)\n }\n return value\n}\n\n/** Read an optional non-negative integer field of a request's params. */\nfunction optionalCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Whether a browser Origin names the same host as the request.\n * @param origin - the Origin header value.\n * @param host - the Host header value.\n * @returns whether the request is same-origin.\n */\nfunction sameHost(origin: string, host: string | undefined): boolean {\n if (typeof host !== 'string') return false\n try {\n return new URL(origin).host === host\n } catch {\n return false\n }\n}\n\n/**\n * Read a bounded JSON body.\n * @param req - the request.\n * @param limit - largest accepted body in bytes.\n * @returns the decoded body.\n */\nasync function readJson(req: IncomingMessage, limit: number): Promise<unknown> {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n size += chunk.length\n if (size > limit) throw new RequestError('INVALID_REQUEST', 'the request body is too large')\n chunks.push(chunk)\n }\n const text = Buffer.concat(chunks).toString('utf8')\n if (text.trim().length === 0) return {}\n try {\n return JSON.parse(text)\n } catch {\n throw new RequestError('INVALID_REQUEST', 'the request body is not valid JSON')\n }\n}\n\n/**\n * Write one JSON response.\n * @param res - the response.\n * @param status - HTTP status.\n * @param body - JSON-serializable body.\n */\nfunction writeJson(res: ServerResponse, status: number, body: unknown): void {\n const text = JSON.stringify(body)\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': Buffer.byteLength(text),\n 'cache-control': 'no-store',\n })\n res.end(text)\n}\n\n/**\n * The first non-empty line of Git's output, for a one-line diagnostic.\n * @param text - raw output.\n * @returns the first meaningful line.\n */\nfunction firstLine(text: unknown): string {\n return String(text ?? '').split(/\\r?\\n/).map(line => line.trim()).find(line => line.length > 0) ?? 'no diagnostic'\n}\n\n/**\n * Bound raw output attached to a failure report.\n * @param text - raw output or detail.\n * @returns at most 2000 characters, or null.\n */\nfunction excerpt(text: unknown): string | null {\n if (typeof text !== 'string' || text.length === 0) return null\n return text.length <= 2000 ? text : `${text.slice(0, 2000)}…`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,UAAwD,OAAO,OAAO;CACjF,GAAG,OAAO,YAAY;EACpB;EAAW;EAAiB;EAAkB;EAAkB;EAChE;EAAoC;EAAc;EAAyB;EAC3E;EAA2B;EAAc;EAAoB;EAC7D;EAAwB;CAC1B,CAAC,CAAC,KAAI,QAAO,CAAC,KAAK,KAAA,CAAS,CAAU,CAAC;CACvC,qBAAqB;CACrB,oBAAoB;CACpB,mBAAmB;CACnB,QAAQ;AACV,CAAC;;AAaD,IAAa,WAAb,cAA8B,MAAM;;CAElC;;CAGA;;;;;;CAOA,YAAY,MAAoB,SAAiB,SAAwB,MAAM;EAC7E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;AA6WA,IAAM,iBAA4B,OAAO,OAAO;CAC9C,aAAa;CACb,YAAY;CACZ,SAAS;CACT,UAAU;CACV,cAAc;AAChB,CAAC;;AAGD,IAAM,aAAa;CAAC;CAAe;CAAc;CAAW;CAAY;AAAc;;AAGtF,IAAa,qBAAqB;;AAGlC,IAAM,0BAA0B;;AAGhC,IAAM,iBAAyD,OAAO,OAAO;CAC3E,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL,CAAC;;AAGD,SAAS,cAAc,SAA6B,CAAC,GAAc;CACjE,MAAM,WAAW,EAAE,GAAG,eAAe;CACrC,KAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,QAAQ,OAAO;EACrB,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,GAAG,SAAS,OAAO;CACzF;CACA,OAAO;AACT;;AAGA,SAAS,OAAO,MAAmC;CACjD,OAAO,CAAC,OAAO,GAAG,IAAI;AACxB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EACF,OAAO,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS;CAClC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,eAAe,SAAS,KAAsB,OAAiC;CAC7E,MAAM,SAAmB,CAAC;CAC1B,IAAI,OAAO;CACX,WAAW,MAAM,SAAS,KAAK;EAC7B,QAAQ,MAAM;EACd,IAAI,OAAO,OAAO,MAAM,IAAI,aAAa,mBAAmB,+BAA+B;EAC3F,OAAO,KAAK,KAAK;CACnB;CACA,MAAM,OAAO,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM;CAClD,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG,OAAO,CAAC;CACtC,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,MAAM,IAAI,aAAa,mBAAmB,oCAAoC;CAChF;AACF;;;;;;;AAQA,SAAS,UAAU,KAAqB,QAAgB,MAAqB;CAC3E,MAAM,OAAO,KAAK,UAAU,IAAI;CAChC,IAAI,UAAU,QAAQ;EACpB,gBAAgB;EAChB,kBAAkB,OAAO,WAAW,IAAI;EACxC,iBAAiB;CACnB,CAAC;CACD,IAAI,IAAI,IAAI;AACd;;;;;;AAOA,SAAS,UAAU,MAAuB;CACxC,OAAO,OAAO,QAAQ,EAAE,CAAC,CAAC,MAAM,OAAO,CAAC,CAAC,KAAI,SAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,MAAK,SAAQ,KAAK,SAAS,CAAC,KAAK;AACrG;;;;;;AAOA,SAAS,QAAQ,MAA8B;CAC7C,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG,OAAO;CAC1D,OAAO,KAAK,UAAU,MAAO,OAAO,GAAG,KAAK,MAAM,GAAG,GAAI,EAAE;AAC7D"}
1
+ {"version":3,"file":"index.js","names":["firstLine","excerpt"],"sources":["../src/host/git.ts","../src/host/types.ts","../src/host/commit-message.ts","../src/index.ts"],"sourcesContent":["/**\n * Git command layer of the source-control plugin.\n *\n * Pure Node ESM: this module knows Git's argument grammar and machine-readable\n * output formats and nothing about Cordis, Sessions, or HTTP. Every invocation\n * goes through the `exec` seam its caller supplies, so the caller owns process\n * policy (executable resolution, confinement, cancellation, output caps) while\n * this module owns what is asked and how the answer is read.\n *\n * Reading is lazy by design: the repository snapshot carries identity, branches,\n * stashes, and tags, while a branch's commits and a commit's files are read only\n * when the panel expands that node.\n *\n * Parsing follows Git's own stable formats: `status --porcelain=v2 -z`,\n * `for-each-ref`, and `log --pretty=format:` with NUL separators. Human prose is\n * never parsed.\n */\n\nimport { readFile, stat, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, normalize } from 'node:path'\nimport type { Exec, ExecOptions, ExecResult, GitLimits } from './types.ts'\n\n/** Environment every Git call must run with: no inherited repository selectors, no prompts, no lazy fetches. */\nexport const GIT_ENV: Readonly<Record<string, string | undefined>> = Object.freeze({\n ...Object.fromEntries([\n 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',\n 'GIT_CEILING_DIRECTORIES', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE',\n 'GIT_REPLACE_REF_BASE', 'GIT_ATTR_SOURCE',\n ].map(key => [key, undefined] as const)),\n GIT_TERMINAL_PROMPT: '0',\n GIT_OPTIONAL_LOCKS: '0',\n GIT_NO_LAZY_FETCH: '1',\n LC_ALL: 'C',\n})\n\n/** Stable failure codes this layer raises; the Host route relays them onto the wire. */\nexport type GitErrorCode =\n | 'NOT_A_REPO'\n | 'INVALID'\n | 'GIT_FAILED'\n | 'TIMEOUT'\n | 'SPAWN_FAILED'\n | 'TOO_LARGE'\n | 'CANCELLED'\n\n/** A structured Git failure the Host route reports with its `code`. */\nexport class GitError extends Error {\n /** Stable code such as `NOT_A_REPO`, `INVALID`, or `GIT_FAILED`. */\n readonly code: GitErrorCode\n\n /** Raw output excerpt, when one exists. */\n readonly detail: string | null\n\n /**\n * @param code - stable code such as `NOT_A_REPO`, `INVALID`, or `GIT_FAILED`.\n * @param message - readable reason, usually Git's first diagnostic line.\n * @param detail - raw output excerpt.\n */\n constructor(code: GitErrorCode, message: string, detail: string | null = null) {\n super(message)\n this.name = 'GitError'\n this.code = code\n this.detail = detail\n }\n}\n\n/** Status letters `status --porcelain=v2` reports for one side of a change. */\nexport type ChangeStatus =\n | 'modified'\n | 'added'\n | 'deleted'\n | 'renamed'\n | 'copied'\n | 'typechange'\n | 'untracked'\n | 'conflicted'\n\n/** One side of a working-tree change as the wire contract reports it. */\nexport interface FileEntry {\n /** Repository-relative path. */\n path: string\n /** Previous path of a rename or copy, else null. */\n origPath: string | null\n /** Human-readable status, e.g. `modified`. */\n status: ChangeStatus\n /** Raw porcelain letter, e.g. `M`. */\n code: string\n /** Whether this entry is the index side of the change. */\n staged: boolean\n}\n\n/** The four change lists of one working tree. */\nexport interface Changes {\n /** Changes recorded in the index. */\n staged: FileEntry[]\n /** Changes in the working tree, against the index. */\n unstaged: FileEntry[]\n /** Files Git does not track yet. */\n untracked: FileEntry[]\n /** Unmerged paths of a pending merge, rebase, or cherry-pick. */\n conflicted: FileEntry[]\n}\n\n/** Change lists plus the total count the cap applies to. */\nexport interface ChangesSummary extends Changes {\n /** Number of entries across all four lists, capped by `maxFiles`. */\n total: number\n}\n\n/** One configured remote. */\nexport interface Remote {\n /** Remote name such as `origin`. */\n name: string\n /** Fetch URL. */\n url: string\n}\n\n/** The checked-out commit, as the repository block reports it. */\nexport interface CommitHead {\n /** Full commit hash. */\n hash: string\n /** Abbreviated commit hash. */\n short: string\n /** Subject line. */\n subject: string\n /** Author name. */\n author: string\n /** Author timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n /** Raw commit message body, so amending starts from the previous message. */\n message: string\n}\n\n/** Operation the checkout is in the middle of, or null when it is clean. */\nexport type PendingOperation = 'cherry-pick' | 'revert' | 'merge' | 'rebase'\n\n/** Ahead/behind counts between HEAD and its upstream. */\nexport interface AheadBehind {\n /** Local commits the upstream does not have, or null without an upstream. */\n ahead: number | null\n /** Upstream commits HEAD does not have, or null without an upstream. */\n behind: number | null\n}\n\n/** Repository identity block shared by `summary` and `status`. */\nexport interface Repo {\n /** Absolute work-tree root. */\n root: string\n /** Base name of the work-tree root. */\n name: string\n /** Checked-out branch, or null when HEAD is detached. */\n branch: string | null\n /** Whether HEAD is detached. */\n detached: boolean\n /** Whether the repository has no commit yet. */\n unborn: boolean\n /** Upstream branch such as `origin/main`, or null. */\n upstream: string | null\n /** Local commits not pushed, or null without an upstream. */\n ahead: number | null\n /** Remote commits not pulled, or null without an upstream. */\n behind: number | null\n /** Configured remotes. */\n remotes: Remote[]\n /** Checked-out commit, or null while unborn. */\n head: CommitHead | null\n /** mtime of `FETCH_HEAD` in Unix epoch milliseconds, or null. */\n lastFetchAt: number | null\n /** Whether the checkout is a linked worktree of a shared Git directory. */\n isWorktree: boolean\n /** In-progress cherry-pick, revert, merge, or rebase, or null. */\n pending: PendingOperation | null\n /** Total working-tree changes, capped by `maxFiles`. */\n totalChanges: number\n}\n\n/** One local or remote branch. */\nexport interface Branch {\n /** Short branch name; remote entries are prefixed with the remote name. */\n name: string\n /** Whether the branch is local or remote-tracking. */\n kind: 'local' | 'remote'\n /** Whether this is the checked-out branch. */\n current: boolean\n /** Configured upstream branch, or null. */\n upstream: string | null\n /** Local commits the upstream does not have, or null. */\n ahead: number | null\n /** Upstream commits the branch does not have, or null. */\n behind: number | null\n /** Abbreviated tip hash. */\n hash: string\n /** Subject of the tip commit. */\n subject: string\n /** Committer timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n /** Remote name for a remote branch, else null. */\n remote: string | null\n}\n\n/** Local and remote branch lists. */\nexport interface Branches {\n /** Local branches, the current one first. */\n local: Branch[]\n /** Remote-tracking branches, symbolic `…/HEAD` entries excluded. */\n remote: Branch[]\n}\n\n/** One stash entry. */\nexport interface Stash {\n /** Stack index, newest first. */\n index: number\n /** Stash message. */\n message: string\n}\n\n/** One tag. */\nexport interface Tag {\n /** Short tag name. */\n name: string\n /** Creation timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n}\n\n/** The repository snapshot `gitSummary` answers. */\nexport interface Summary {\n /** Repository identity. */\n repo: Repo\n /** Working-tree changes. */\n changes: Changes\n /** Local and remote branches. */\n branches: Branches\n /** Stash stack. */\n stashes: Stash[]\n /** Tags. */\n tags: Tag[]\n}\n\n/** The light snapshot `gitStatus` answers. */\nexport interface StatusSnapshot {\n /** Repository identity. */\n repo: Repo\n /** Working-tree changes. */\n changes: Changes\n}\n\n/** One unified patch. */\nexport interface Diff {\n /** Repository-relative path the patch is addressed by. */\n path: string\n /** Whether the patch reads the index instead of the working tree. */\n staged: boolean\n /** Raw unified patch text, trimmed at `maxDiffBytes`. */\n text: string\n /** Whether the change was detected as binary. */\n binary: boolean\n /** Whether the patch was trimmed at `maxDiffBytes`. */\n tooLarge: boolean\n /** Added line count. */\n added: number\n /** Deleted line count. */\n deleted: number\n}\n\n/** One commit of a commit page. */\nexport interface Commit {\n /** Full commit hash. */\n hash: string\n /** Abbreviated commit hash. */\n short: string\n /** Subject line. */\n subject: string\n /** Author name. */\n author: string\n /** Author timestamp in Unix epoch milliseconds, or null. */\n date: number | null\n /** Parent count; a merge commit has more than one. */\n parents: number\n /** Names HEAD and the remote refs point at through this commit. */\n refs: string[]\n}\n\n/** One page of a commit walk. */\nexport interface CommitPage {\n /** Resolved commit the walk started from. */\n ref: string\n /** Commits of this page, newest first. */\n commits: Commit[]\n /** Whether further commits exist after this page. */\n more: boolean\n}\n\n/** One page of one file's history. */\nexport interface FileHistoryPage {\n /** Repository-relative path the history follows. */\n path: string\n /** Commits of this page, newest first. */\n commits: Commit[]\n /** Whether further commits exist after this page. */\n more: boolean\n}\n\n/** One file a commit changed, with its line counts. */\nexport interface CommitFile extends FileEntry {\n /** Added lines, or null for a binary file. */\n additions: number | null\n /** Deleted lines, or null for a binary file. */\n deletions: number | null\n}\n\n/** The changed files of one commit. */\nexport interface CommitFiles {\n /** Full hash of the resolved commit. */\n hash: string\n /** Changed files against the commit's first parent. */\n files: CommitFile[]\n /** Added lines across the reported files. */\n additions: number\n /** Deleted lines across the reported files. */\n deletions: number\n /** Whether the file list hit `maxFiles`. */\n truncated: boolean\n}\n\n/** One remote reference a fetch moved. */\nexport interface RefChange {\n /** Short remote ref name. */\n ref: string\n /** Tip before the fetch, or null when the ref is new. */\n from: string | null\n /** Tip after the fetch, or null when the ref disappeared. */\n to: string | null\n}\n\n/** Result of one mutation Git operation. */\nexport interface ActionResult {\n /** Operator-readable summary. */\n message: string\n /** Raw output excerpt, when one exists. */\n detail: string | null\n /** Fetch only: whether remote references moved. */\n updated?: boolean\n /** Fetch only: the remote references that moved. */\n changed?: RefChange[]\n /** `pullBranch` only: commits the fast-forward brought in. */\n commits?: number\n}\n\n/** Line counts of one changed file. */\nexport interface LineCount {\n /** Added lines, or null for a binary file. */\n additions: number | null\n /** Deleted lines, or null for a binary file. */\n deletions: number | null\n}\n\n/** Request of one repository snapshot read. */\nexport interface GitSummaryRequest {\n /** The caller's process seam. */\n exec: Exec\n /** Directory inside the checkout. */\n cwd: string\n /** Overrides for the layer's default limits. */\n limits?: Partial<GitLimits> | undefined\n}\n\n/** Request of one working-tree patch read. */\nexport interface GitDiffRequest extends GitSummaryRequest {\n /** Repository-relative path to diff. */\n path: string\n /** Read the index instead of the working tree. */\n staged?: boolean | undefined\n /** Synthesize the patch of an untracked file. */\n untracked?: boolean | undefined\n}\n\n/** Request of one branch page read. */\nexport interface GitCommitsRequest extends GitSummaryRequest {\n /** Ref or commit to walk. */\n ref: string\n /** Commits to skip. */\n skip?: number | undefined\n /** Page size; the layer caps it at 200. */\n limit?: number | undefined\n}\n\n/** Request of one file history page read. */\nexport interface GitFileHistoryRequest extends GitSummaryRequest {\n /** Repository-relative path whose history is read. */\n path: string\n /** Commits to skip. */\n skip?: number | undefined\n /** Page size; the layer caps it at 200. */\n limit?: number | undefined\n}\n\n/** Request of one commit's changed files read. */\nexport interface GitCommitFilesRequest extends GitSummaryRequest {\n /** Commit hash or abbreviation. */\n hash: string\n}\n\n/** Request of one file patch inside a commit. */\nexport interface GitCommitDiffRequest extends GitSummaryRequest {\n /** Commit hash or abbreviation. */\n hash: string\n /** Repository-relative path to diff. */\n path: string\n}\n\n/** Request of one stash patch read. */\nexport interface GitStashDiffRequest extends GitSummaryRequest {\n /** Stash stack index. */\n index: unknown\n}\n\n/** Request of one mutation operation. */\nexport interface GitActionRequest {\n /** The caller's process seam. */\n exec: Exec\n /** Directory inside the checkout. */\n cwd: string\n /** Operation name from {@link OPERATIONS}. */\n operation: string\n /** Operation-specific parameters, validated per operation. */\n params?: Readonly<Record<string, unknown>> | undefined\n}\n\n/** Falls back to these bounds when the caller omits a limit. */\nconst DEFAULT_LIMITS: GitLimits = Object.freeze({\n maxBranches: 500,\n maxCommits: 40,\n maxTags: 30,\n maxFiles: 3000,\n maxDiffBytes: 400 * 1024,\n})\n\n/** Names of {@link DEFAULT_LIMITS}, so an override map is read without string indexing. */\nconst LIMIT_KEYS = ['maxBranches', 'maxCommits', 'maxTags', 'maxFiles', 'maxDiffBytes'] as const\n\n/** Deadline for operations that talk to a remote: large fetches take minutes. */\nexport const NETWORK_TIMEOUT_MS = 300_000\n\n/** Deadline for one GitHub CLI probe that only reads the account. */\nconst GITHUB_PROBE_TIMEOUT_MS = 15_000\n\n/** Status letters `status --porcelain=v2` reports for one side of a change. */\nconst STATUS_OF_CODE: Readonly<Record<string, ChangeStatus>> = Object.freeze({\n M: 'modified',\n A: 'added',\n D: 'deleted',\n R: 'renamed',\n C: 'copied',\n T: 'typechange',\n U: 'conflicted',\n})\n\n/** Merge the caller's limits onto the defaults, ignoring invalid entries. */\nfunction resolveLimits(limits: Partial<GitLimits> = {}): GitLimits {\n const resolved = { ...DEFAULT_LIMITS }\n for (const key of LIMIT_KEYS) {\n const value = limits[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) resolved[key] = value\n }\n return resolved\n}\n\n/** Build the argv this layer hands the seam: program name first, then the subcommand. */\nfunction argvOf(args: readonly string[]): string[] {\n return ['git', ...args]\n}\n\n/** The first non-empty line of Git output. */\nfunction firstLine(text: unknown): string {\n return String(text ?? '').split(/\\r?\\n/).map(line => line.trim()).find(line => line.length > 0) ?? 'no diagnostic'\n}\n\n/** At most `limit` characters of raw output, for a failure report. */\nfunction excerpt(text: unknown, limit = 2000): string | null {\n if (typeof text !== 'string' || text.length === 0) return null\n return text.length <= limit ? text : `${text.slice(0, limit)}…`\n}\n\n/** Whether an error is the layer's own structured failure. */\nfunction isGitError(error: unknown): error is GitError {\n return error instanceof GitError\n}\n\n/** Read the `code`, `message`, and `detail` fields a rejection from the `exec` seam may carry. */\nfunction failureFieldsOf(error: unknown): { code?: unknown; message?: unknown; detail?: unknown } {\n if (typeof error !== 'object' || error === null) return {}\n return error as { code?: unknown; message?: unknown; detail?: unknown }\n}\n\n/** Normalize a rejection from the `exec` seam into a structured failure. */\nfunction failureOf(error: unknown, operation: string): GitError {\n if (isGitError(error)) return error\n const fields = failureFieldsOf(error)\n const code = typeof fields.code === 'string' && fields.code.length > 0 ? fields.code : 'GIT_FAILED'\n const message = typeof fields.message === 'string' && fields.message.length > 0\n ? fields.message\n : `git ${operation} failed`\n const detail = typeof fields.detail === 'string' ? fields.detail : null\n // The seam relays its own provider codes verbatim; the Host route admits only\n // codes it knows, so the cast documents that relay rather than narrowing it here.\n return new GitError(code as GitErrorCode, message, detail)\n}\n\n/**\n * Run one Git invocation that must succeed.\n * @param exec - the caller's seam.\n * @param args - subcommand arguments, without the program name.\n * @param operation - name used in failure messages.\n * @param options - `allowedExitCodes`, `timeoutMs`, and other exec options.\n * @returns the output.\n */\nasync function run(exec: Exec, args: readonly string[], operation: string, options: ExecOptions = {}): Promise<ExecResult> {\n try {\n return await exec(argvOf(args), options)\n } catch (error) {\n throw failureOf(error, operation)\n }\n}\n\n/** Whether a directory is inside a Git work tree, without throwing for the ordinary negative answer. */\nasync function repositoryRoot(exec: Exec, _cwd: string): Promise<string | null> {\n let result: ExecResult\n try {\n result = await exec(argvOf(['rev-parse', '--show-toplevel']), { allowedExitCodes: [0, 128] })\n } catch (error) {\n throw failureOf(error, 'rev-parse')\n }\n if (result.exitCode === 0) {\n const root = firstLine(result.stdout)\n if (root.length === 0) throw new GitError('GIT_FAILED', 'git rev-parse printed no work tree root')\n return root\n }\n if (/not a git repository|must be run in a work tree/i.test(result.stderr)) return null\n throw new GitError('GIT_FAILED', `git rev-parse failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n}\n\n/** Resolve the canonical Git directories of a checkout: shared and per-worktree. */\nasync function gitDirectories(exec: Exec, _cwd: string): Promise<{ commonDir: string; gitDir: string }> {\n const [common, own] = await Promise.all([\n run(exec, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'rev-parse'),\n run(exec, ['rev-parse', '--path-format=absolute', '--git-dir'], 'rev-parse'),\n ])\n return { commonDir: firstLine(common.stdout), gitDir: firstLine(own.stdout) }\n}\n\n/** Read the mtime of `FETCH_HEAD`, the only durable record of the last fetch. */\nasync function lastFetchAt(commonDir: string): Promise<number | null> {\n try {\n const info = await stat(join(commonDir, 'FETCH_HEAD'))\n return Math.round(info.mtimeMs)\n } catch {\n return null\n }\n}\n\n/** Name the operation the checkout is in the middle of, or null when it is clean. */\nasync function pendingOperation(gitDir: string): Promise<PendingOperation | null> {\n const marks: ReadonlyArray<readonly [PendingOperation, string]> = [\n ['cherry-pick', 'CHERRY_PICK_HEAD'],\n ['revert', 'REVERT_HEAD'],\n ['merge', 'MERGE_HEAD'],\n ['rebase', 'rebase-merge'],\n ['rebase', 'rebase-apply'],\n ]\n for (const [kind, mark] of marks) {\n try {\n await stat(join(gitDir, mark))\n return kind\n } catch {\n // Not in progress; the next marker is the only candidate.\n }\n }\n return null\n}\n\n/** The checked-out branch, or null when HEAD is detached. */\nasync function currentBranch(exec: Exec): Promise<string | null> {\n const result = await exec(argvOf(['symbolic-ref', '--quiet', '--short', 'HEAD']), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) return null\n const name = firstLine(result.stdout)\n return name.length === 0 ? null : name\n}\n\n/** HEAD facts: whether a commit exists and, if so, its identity. */\nasync function headCommit(exec: Exec): Promise<{ unborn: boolean; head: CommitHead | null }> {\n const head = await exec(argvOf(['rev-parse', '--verify', '--quiet', 'HEAD']), { allowedExitCodes: [0, 1, 128] })\n if (head.exitCode !== 0) return { unborn: true, head: null }\n const log = await run(exec, ['log', '-1', '--date=unix', '--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%B'], 'log')\n const [hash, short, subject, author, date, body] = log.stdout.split('\\u0000')\n return {\n unborn: false,\n head: {\n hash: hash ?? '',\n short: short ?? '',\n subject: subject ?? '',\n author: author ?? '',\n date: parseDate(date),\n // The raw body, so amending starts from the previous message.\n message: (body ?? '').trim(),\n },\n }\n}\n\n/** Upstream branch name of HEAD, or null when none is configured. */\nasync function upstreamBranch(exec: Exec): Promise<string | null> {\n const result = await exec(argvOf(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) return null\n const name = firstLine(result.stdout)\n return name.length === 0 ? null : name\n}\n\n/** Ahead/behind counts between HEAD and its upstream, or nulls without an upstream. */\nasync function aheadBehind(exec: Exec, upstream: string | null): Promise<AheadBehind> {\n if (upstream === null) return { ahead: null, behind: null }\n const result = await exec(argvOf(['rev-list', '--left-right', '--count', `HEAD...${upstream}`]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) return { ahead: null, behind: null }\n const [aheadText, behindText] = firstLine(result.stdout).split(/\\s+/)\n return { ahead: parseCount(aheadText), behind: parseCount(behindText) }\n}\n\n/** One line of `status --porcelain=v2 -z` as one side of a change. */\nfunction changeEntry(path: string, code: string, origPath: string | null): FileEntry {\n return {\n path,\n origPath: origPath ?? null,\n status: STATUS_OF_CODE[code] ?? 'modified',\n code,\n staged: false,\n }\n}\n\n/**\n * Parse `git status --porcelain=v2 -z` into the four change lists.\n * @param output - raw NUL-separated records.\n * @param maxFiles - cap applied across all four lists.\n * @returns the lists.\n */\nfunction parseStatus(output: string, maxFiles: number): ChangesSummary {\n const changes: ChangesSummary = { staged: [], unstaged: [], untracked: [], conflicted: [], total: 0 }\n if (typeof output !== 'string' || output.length === 0) return changes\n const records = output.split('\\u0000')\n let total = 0\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index]!\n if (record.length === 0) continue\n const kind = record.charAt(0)\n if (kind === '1') {\n // `1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>`\n const parts = record.split(' ')\n if (parts.length < 9) continue\n const code = parts[1]!\n const path = parts.slice(8).join(' ')\n const [x, y] = [code.charAt(0), code.charAt(1)]\n if (x !== '.') { changes.staged.push(changeEntry(path, x, null)); total += 1 }\n if (y !== '.') { changes.unstaged.push(changeEntry(path, y, null)); total += 1 }\n } else if (kind === '2') {\n // `2 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <X><score> <path>` then the original path record.\n const parts = record.split(' ')\n if (parts.length < 10) continue\n const code = parts[1]!\n const path = parts.slice(9).join(' ')\n const origPath = records[index + 1] ?? null\n index += 1\n const [x, y] = [code.charAt(0), code.charAt(1)]\n if (x !== '.') { changes.staged.push(changeEntry(path, x, origPath)); total += 1 }\n if (y !== '.') { changes.unstaged.push(changeEntry(path, y, origPath)); total += 1 }\n } else if (kind === 'u') {\n // `u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>`\n const parts = record.split(' ')\n if (parts.length < 11) continue\n const path = parts.slice(10).join(' ')\n changes.conflicted.push({ path, origPath: null, status: 'conflicted', code: 'U', staged: false })\n total += 1\n } else if (kind === '?') {\n const path = record.slice(2)\n changes.untracked.push({ path, origPath: null, status: 'untracked', code: '?', staged: false })\n total += 1\n }\n if (total >= maxFiles) break\n }\n changes.total = total\n return changes\n}\n\n/** Read the working-tree changes of a repository. */\nasync function readChanges(exec: Exec, limits: GitLimits): Promise<ChangesSummary> {\n const status = await run(exec, ['status', '--porcelain=v2', '-z', '--untracked-files=all'], 'status')\n return parseStatus(status.stdout, limits.maxFiles)\n}\n\n/** Parse one `for-each-ref` record into a branch entry. */\nfunction branchOf(fields: string[]): Branch | null {\n const [refname, short, head, upstream, track, hash, date] = fields\n // The subject is the last field and may itself contain the separator.\n const subject = fields.slice(7).join('\\t')\n if (refname === undefined || short === undefined) return null\n const kind = refname.startsWith('refs/heads/') ? 'local' : refname.startsWith('refs/remotes/') ? 'remote' : null\n if (kind === null) return null\n if (kind === 'remote' && short.endsWith('/HEAD')) return null\n const parsedTrack = parseTrack(track ?? '')\n return {\n name: short,\n kind,\n current: head === '*',\n upstream: upstream === undefined || upstream.length === 0 ? null : upstream,\n ahead: parsedTrack.ahead,\n behind: parsedTrack.behind,\n hash: hash ?? '',\n subject: subject ?? '',\n date: parseDate(date),\n remote: kind === 'remote' ? short.split('/')[0]! : null,\n }\n}\n\n/** Parse `%(upstream:track)` such as `[ahead 2, behind 1]` or `[gone]`. */\nfunction parseTrack(text: string): AheadBehind {\n const aheadMatch = /ahead (\\d+)/.exec(text)\n const behindMatch = /behind (\\d+)/.exec(text)\n return {\n ahead: aheadMatch === null ? null : Number(aheadMatch[1]),\n behind: behindMatch === null ? null : Number(behindMatch[1]),\n }\n}\n\n/** List local and remote branches, newest commit first but with the current branch first. */\nasync function readBranches(exec: Exec, limits: GitLimits): Promise<Branches> {\n // `for-each-ref` has no hex-escape syntax, so its fields are tab-separated.\n const format = ['%(refname)', '%(refname:short)', '%(HEAD)', '%(upstream:short)', '%(upstream:track)', '%(objectname:short)', '%(committerdate:unix)', '%(contents:subject)'].join('\\t')\n const result = await run(exec, [\n 'for-each-ref', '--sort=-committerdate', `--format=${format}`, 'refs/heads', 'refs/remotes',\n ], 'for-each-ref')\n const local: Branch[] = []\n const remote: Branch[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const branch = branchOf(line.split('\\t'))\n if (branch === null) continue\n if (branch.kind === 'local') local.push(branch)\n else remote.push(branch)\n }\n const ordered = [...local.filter(branch => branch.current), ...local.filter(branch => !branch.current)]\n return {\n local: ordered.slice(0, limits.maxBranches),\n remote: remote.slice(0, limits.maxBranches),\n }\n}\n\n/** Stashed work, newest first. */\nasync function readStashes(exec: Exec): Promise<Stash[]> {\n const result = await run(exec, ['stash', 'list', '--format=%gd%x00%gs'], 'stash list')\n const stashes: Stash[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [ref, message] = line.split('\\u0000')\n const match = /^stash@\\{(\\d+)\\}$/.exec(ref ?? '')\n if (match === null) continue\n stashes.push({ index: Number(match[1]), message: message ?? '' })\n }\n return stashes\n}\n\n/** Tags, newest first. */\nasync function readTags(exec: Exec, limits: GitLimits): Promise<Tag[]> {\n if (limits.maxTags === 0) return []\n const result = await run(exec, [\n 'for-each-ref', '--sort=-creatordate', '--format=%(refname:short)\\t%(creatordate:unix)', 'refs/tags',\n ], 'for-each-ref')\n const tags: Tag[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [name, date] = line.split('\\t')\n if (name === undefined || name.length === 0) continue\n tags.push({ name, date: parseDate(date) })\n if (tags.length >= limits.maxTags) break\n }\n return tags\n}\n\n/** Current remote-tracking tips, keyed by short ref name. */\nasync function readRemoteTips(exec: Exec): Promise<Map<string, string>> {\n const result = await run(exec, ['for-each-ref', '--format=%(refname:short)%09%(objectname)', 'refs/remotes'], 'for-each-ref')\n const tips = new Map<string, string>()\n for (const line of result.stdout.split('\\n')) {\n const [ref, hash] = line.split('\\t')\n if (ref !== undefined && hash !== undefined && ref.length > 0) tips.set(ref, hash)\n }\n return tips\n}\n\n/** Configured remotes with their fetch URLs. */\nasync function readRemotes(exec: Exec): Promise<Remote[]> {\n const result = await run(exec, ['remote', '-v'], 'remote')\n const seen = new Map<string, string>()\n for (const line of result.stdout.split('\\n')) {\n const match = /^(\\S+)\\t(\\S*) \\(fetch\\)$/.exec(line)\n if (match === null) continue\n const name = match[1]!\n const url = match[2]!\n if (!seen.has(name)) seen.set(name, url)\n }\n return [...seen.entries()].map(([name, url]) => ({ name, url }))\n}\n\n/** Parse a Git `--date=unix` timestamp into milliseconds, or null. */\nfunction parseDate(text: unknown): number | null {\n const seconds = Number(text)\n return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null\n}\n\n/** Parse one count line from `rev-list --count`, or null. */\nfunction parseCount(text: unknown): number | null {\n const value = Number(text)\n return Number.isFinite(value) && value >= 0 ? value : null\n}\n\n/**\n * The repository identity block shared by `summary` and `status`.\n * @param options - the seam, the checkout root, and the limits.\n * @returns the `repo` and `changes` objects of the wire contract.\n */\nasync function readRepo({ exec, root, limits }: { exec: Exec; root: string; limits: GitLimits }): Promise<StatusSnapshot> {\n const { commonDir, gitDir } = await gitDirectories(exec, root)\n const [branch, head, upstream, remotes, fetched, pending, changes] = await Promise.all([\n currentBranch(exec),\n headCommit(exec),\n upstreamBranch(exec),\n readRemotes(exec),\n lastFetchAt(commonDir),\n pendingOperation(gitDir),\n readChanges(exec, limits),\n ])\n const counts = await aheadBehind(exec, upstream)\n return {\n repo: {\n root,\n name: root.split(/[\\\\/]/).filter(part => part.length > 0).pop() ?? root,\n branch,\n detached: branch === null && head.unborn === false,\n unborn: head.unborn,\n upstream,\n ahead: counts.ahead,\n behind: counts.behind,\n remotes,\n head: head.head,\n lastFetchAt: fetched,\n isWorktree: commonDir !== gitDir,\n pending,\n totalChanges: changes.total,\n },\n changes: {\n staged: changes.staged,\n unstaged: changes.unstaged,\n untracked: changes.untracked,\n conflicted: changes.conflicted,\n },\n }\n}\n\n/**\n * Read the repository identity, branches, stashes, and tags in one call.\n * @param request - `exec`, `cwd`, and `limits`.\n * @returns the `Summary` of the wire contract.\n * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitSummary({ exec, cwd, limits = {} }: GitSummaryRequest): Promise<Summary> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const [{ repo, changes }, branches, stashes, tags] = await Promise.all([\n readRepo({ exec, root, limits: bounds }),\n readBranches(exec, bounds),\n readStashes(exec),\n readTags(exec, bounds),\n ])\n return { repo, changes, branches, stashes, tags }\n}\n\n/**\n * Read the repository identity and working-tree changes only, for polling.\n * @param request - `exec`, `cwd`, and `limits`.\n * @returns the light snapshot.\n * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitStatus({ exec, cwd, limits = {} }: GitSummaryRequest): Promise<StatusSnapshot> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n return await readRepo({ exec, root, limits: bounds })\n}\n\n/** One changed path a commit-message request describes. */\nexport interface CommitMessageFile {\n /** Change status word such as `modified` or `untracked`. */\n readonly status: string\n /** Repository-relative path. */\n readonly path: string\n}\n\n/** The change summary and patch a commit-message request reads. */\nexport interface CommitMessageContext {\n /** Whether the patch describes staged changes (the next commit). */\n readonly staged: boolean\n /** Changed paths across the staged or working-tree lists. */\n readonly files: readonly CommitMessageFile[]\n /** Unified patch, truncated to the read limit. */\n readonly diff: string\n /** Whether the patch was truncated. */\n readonly truncated: boolean\n /** Recent commit subjects, newest first, for style reference. */\n readonly recent: readonly string[]\n /** Whether most recent commits use a Conventional Commits type prefix. */\n readonly recentConventional: boolean\n /** Whether most recent commits carry a body. */\n readonly recentHasBody: boolean\n}\n\n/** Largest patch handed to the model. */\nconst COMMIT_MESSAGE_DIFF_BYTES = 48 * 1024\n\n/** Recent commit subjects read for style. */\nconst COMMIT_MESSAGE_RECENT = 8\n\n/** Conventional Commits subject prefix, used to observe the repository style. */\nconst CONVENTIONAL_SUBJECT = /^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\\([^)]+\\))?!?:\\s+/\n\n/** Record and field separators that keep multi-line bodies apart in one log call. */\nconst LOG_RECORD = '\\x1e'\nconst LOG_FIELD = '\\x1f'\n\n/**\n * Read the changes a commit message should describe. Staged changes win; a\n * checkout with none staged is described by its working tree instead.\n * @param request - the `exec` seam, a directory inside the checkout, and limits.\n * @returns the scope, changed paths, patch, truncation flag, and recent subjects.\n * @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommitMessageContext({ exec, cwd, limits = {} }: GitSummaryRequest): Promise<CommitMessageContext> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const { changes } = await readRepo({ exec, root, limits: bounds })\n const stagedFiles = changes.staged.map(changeFile)\n const worktreeFiles = [...changes.unstaged, ...changes.untracked, ...changes.conflicted].map(changeFile)\n const staged = stagedFiles.length > 0\n const files = staged ? stagedFiles : worktreeFiles\n const args = staged\n ? ['diff', '--cached', '--no-color', '--no-ext-diff', '-M', '--unified=3']\n : ['diff', '--no-color', '--no-ext-diff', '-M', '--unified=3']\n const patch = files.length === 0 ? '' : (await run(exec, args, 'diff')).stdout\n const history = await exec(\n argvOf(['log', `-${COMMIT_MESSAGE_RECENT}`, `--format=%s${LOG_FIELD}%b${LOG_RECORD}`]),\n { allowedExitCodes: [0, 128] },\n )\n const commits = history.exitCode === 0\n ? history.stdout.split(LOG_RECORD)\n .map(record => record.replace(/^\\r?\\n/, ''))\n .filter(record => record.trim().length > 0)\n .map((record) => {\n const [subject = '', body = ''] = record.split(LOG_FIELD)\n return { subject: subject.trim(), body: body.trim() }\n })\n : []\n const recent = commits.map(commit => commit.subject).filter(subject => subject.length > 0)\n const half = Math.ceil(commits.length / 2)\n const recentConventional = half > 0 && commits.filter(commit => CONVENTIONAL_SUBJECT.test(commit.subject)).length >= half\n const recentHasBody = half > 0 && commits.filter(commit => commit.body.length > 0).length >= half\n const truncated = Buffer.byteLength(patch, 'utf8') > COMMIT_MESSAGE_DIFF_BYTES\n return {\n staged, files,\n diff: truncated ? `${Buffer.from(patch, 'utf8').subarray(0, COMMIT_MESSAGE_DIFF_BYTES).toString('utf8')}\\n… (diff truncated)` : patch,\n truncated,\n recent,\n recentConventional,\n recentHasBody,\n }\n}\n\n/** Project one change-list entry onto the prompt's file view. */\nfunction changeFile(entry: { readonly status: string; readonly path: string }): CommitMessageFile {\n return { status: entry.status, path: entry.path }\n}\n\n/** Reject a path that would escape the repository or confuse Git's argument parser. */\nfunction checkedPath(path: unknown): string {\n if (typeof path !== 'string' || path.length === 0) throw new GitError('INVALID', 'a file path is required')\n if (path.includes('\\u0000')) throw new GitError('INVALID', 'a path must not contain a NUL byte')\n if (isAbsolute(path)) throw new GitError('INVALID', 'a path must be relative to the repository root')\n const normalized = normalize(path).split('\\\\').join('/')\n if (normalized === '..' || normalized.startsWith('../')) throw new GitError('INVALID', 'a path must stay inside the repository')\n return normalized\n}\n\n/** Reject a ref argument the client asks to walk. */\nfunction checkedRef(ref: unknown): string {\n if (typeof ref !== 'string' || ref.length === 0) throw new GitError('INVALID', 'a ref is required')\n if (ref.startsWith('-') || /\\s/.test(ref) || ref.includes('\\u0000')) {\n throw new GitError('INVALID', `\"${ref}\" is not a valid ref`)\n }\n return ref\n}\n\n/** One Git config value, or null when unset. */\nasync function configValue(exec: Exec, key: string): Promise<string | null> {\n const result = await exec(argvOf(['config', '--get', key]), { allowedExitCodes: [0, 1] })\n return result.exitCode === 0 ? result.stdout.trim() : null\n}\n\n/** Reject anything that is not a commit identity. */\nfunction checkedHash(hash: unknown): string {\n if (typeof hash !== 'string' || !/^[0-9a-f]{4,64}$/i.test(hash)) {\n throw new GitError('INVALID', 'a commit hash is required')\n }\n return hash.toLowerCase()\n}\n\n/** Resolve a ref or abbreviation to a full commit hash. */\nasync function resolveCommit(exec: Exec, ref: string): Promise<string> {\n const result = await exec(argvOf(['rev-parse', '--verify', '--quiet', `${checkedRef(ref)}^{commit}`]), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) throw new GitError('INVALID', `\"${ref}\" does not name a commit`)\n return firstLine(result.stdout)\n}\n\n/** The first parent of a commit, or null for a root commit. */\nasync function firstParent(exec: Exec, commit: string): Promise<string | null> {\n const result = await exec(argvOf(['rev-parse', '--verify', '--quiet', `${commit}^`]), { allowedExitCodes: [0, 1, 128] })\n return result.exitCode === 0 ? firstLine(result.stdout) : null\n}\n\n/** Count added and deleted lines in a unified diff. */\nfunction countDiffLines(text: string): { added: number; deleted: number } {\n let added = 0\n let deleted = 0\n for (const line of text.split('\\n')) {\n if (line.startsWith('+++') || line.startsWith('---')) continue\n if (line.startsWith('+')) added += 1\n else if (line.startsWith('-')) deleted += 1\n }\n return { added, deleted }\n}\n\n/** Build the wire `Diff` from raw patch text. */\nfunction diffOf({ path, staged, text, maxDiffBytes }: {\n path: string\n staged: boolean\n text: string\n maxDiffBytes: number\n}): Diff {\n const tooLarge = text.length > maxDiffBytes\n const body = tooLarge ? text.slice(0, maxDiffBytes) : text\n const binary = /^Binary files .* differ$/m.test(body)\n const counts = binary ? { added: 0, deleted: 0 } : countDiffLines(body)\n return { path, staged, text: body, binary, tooLarge, added: counts.added, deleted: counts.deleted }\n}\n\n/** Render a synthetic unified diff for an untracked file. */\nasync function untrackedDiff(root: string, path: string, maxDiffBytes: number): Promise<Diff> {\n const absolute = join(root, path)\n let buffer: Buffer\n try {\n buffer = await readFile(absolute)\n } catch {\n throw new GitError('GIT_FAILED', `${path} could not be read`)\n }\n const binary = buffer.subarray(0, 8000).includes(0)\n if (binary) {\n return { path, staged: false, text: `Binary file ${path} is untracked\\n`, binary: true, tooLarge: false, added: 0, deleted: 0 }\n }\n const text = buffer.toString('utf8')\n const lines = text.split('\\n')\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()\n const tooLarge = buffer.byteLength > maxDiffBytes || text.length > maxDiffBytes\n const shown = tooLarge ? lines.slice(0, Math.max(0, Math.floor(maxDiffBytes / 40))) : lines\n const header = [\n `diff --git a/${path} b/${path}`,\n 'new file mode 100644',\n '--- /dev/null',\n `+++ b/${path}`,\n `@@ -0,0 +1,${lines.length} @@`,\n ]\n return {\n path,\n staged: false,\n text: [...header, ...shown.map(line => `+${line}`)].join('\\n'),\n binary: false,\n tooLarge,\n added: lines.length,\n deleted: 0,\n }\n}\n\n/**\n * Read one working-tree file's unified diff.\n * @param request - `exec`, `cwd`, `limits`, `path`, `staged`, and `untracked`.\n * @returns the `Diff` of the wire contract.\n * @throws {GitError} `INVALID` for an unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitDiff({ exec, cwd, limits = {}, path, staged = false, untracked = false }: GitDiffRequest): Promise<Diff> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const checked = checkedPath(path)\n if (untracked) return await untrackedDiff(root, checked, bounds.maxDiffBytes)\n const args = ['diff', '--no-color', '--no-ext-diff', '-U3']\n if (staged) args.push('--cached')\n args.push('--', checked)\n const result = await run(exec, args, 'diff')\n return diffOf({ path: checked, staged, text: result.stdout, maxDiffBytes: bounds.maxDiffBytes })\n}\n\n/**\n * Read one branch's or ref's commits, newest first.\n * @param request - `exec`, `cwd`, `limits`, `ref`, `skip`, and `limit`.\n * @returns the page of commits.\n * @throws {GitError} `INVALID` for an unknown ref, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommits({ exec, cwd, limits = {}, ref, skip = 0, limit }: GitCommitsRequest): Promise<CommitPage> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const commit = await resolveCommit(exec, ref)\n const take = typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 200) : bounds.maxCommits\n const offset = typeof skip === 'number' && Number.isSafeInteger(skip) && skip > 0 ? skip : 0\n // The resolved commit is the walk's starting point: without it Git would log\n // HEAD, which is a different branch whenever the checked-out branch differs.\n const result = await exec(argvOf([\n 'log', `-n${take + 1}`, `--skip=${offset}`, '--date=unix', '--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%P%x00%D', commit,\n ]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) throw new GitError('GIT_FAILED', `git log failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n const commits: Commit[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [hash, short, subject, author, date, parents, refs] = line.split('\\u0000')\n commits.push({\n hash: hash ?? '',\n short: short ?? '',\n subject: subject ?? '',\n author: author ?? '',\n date: parseDate(date),\n parents: (parents ?? '').split(' ').filter(Boolean).length,\n refs: (refs ?? '').split(', ').map(entry => entry.trim()).filter(entry => entry.length > 0),\n })\n }\n return { ref: commit, commits: commits.slice(0, take), more: commits.length > take }\n}\n\n/**\n * Read the commit history of one file, newest first, following renames.\n * @param request - `exec`, `cwd`, `limits`, `path`, `skip`, and `limit`.\n * @returns the page of commits.\n * @throws {GitError} `INVALID` for an unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitFileHistory({ exec, cwd, limits = {}, path, skip = 0, limit }: GitFileHistoryRequest): Promise<FileHistoryPage> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const checked = checkedPath(path)\n const take = typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 200) : bounds.maxCommits\n const offset = typeof skip === 'number' && Number.isSafeInteger(skip) && skip > 0 ? skip : 0\n const result = await exec(argvOf([\n 'log', `-n${take + 1}`, `--skip=${offset}`, '--follow', '--date=unix',\n '--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%P%x00%D', '--', checked,\n ]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) {\n throw new GitError('GIT_FAILED', `git log failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n }\n const commits: Commit[] = []\n for (const line of result.stdout.split('\\n')) {\n if (line.length === 0) continue\n const [hash, short, subject, author, date, parents, refs] = line.split('\\u0000')\n commits.push({\n hash: hash ?? '',\n short: short ?? '',\n subject: subject ?? '',\n author: author ?? '',\n date: parseDate(date),\n parents: (parents ?? '').split(' ').filter(Boolean).length,\n refs: (refs ?? '').split(', ').map(entry => entry.trim()).filter(entry => entry.length > 0),\n })\n }\n return { path: checked, commits: commits.slice(0, take), more: commits.length > take }\n}\n\n/** Parse `--numstat -z` output into path → line counts. */\nfunction parseNumstat(output: string): Map<string, LineCount> {\n const counts = new Map<string, LineCount>()\n const fields = output.split('\\u0000')\n for (let index = 0; index < fields.length; index += 1) {\n const record = fields[index]!\n if (record.length === 0) continue\n const firstTab = record.indexOf('\\t')\n const secondTab = record.indexOf('\\t', firstTab + 1)\n if (firstTab < 0 || secondTab < 0) continue\n const additions = record.slice(0, firstTab)\n const deletions = record.slice(firstTab + 1, secondTab)\n const rest = record.slice(secondTab + 1)\n // A rename emits an empty path, then the old path and the new path as records.\n const path = rest.length > 0 ? rest : fields[index + 2] ?? ''\n if (rest.length === 0) index += 2\n counts.set(path, {\n additions: additions === '-' ? null : Number(additions),\n deletions: deletions === '-' ? null : Number(deletions),\n })\n }\n return counts\n}\n\n/**\n * Read the files one commit changed, against its first parent.\n * @param request - `exec`, `cwd`, `limits`, and `hash`.\n * @returns the changed files with their line counts.\n * @throws {GitError} `INVALID` for an unknown commit, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommitFiles({ exec, cwd, limits = {}, hash }: GitCommitFilesRequest): Promise<CommitFiles> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const commit = await resolveCommit(exec, checkedHash(hash))\n const parent = await firstParent(exec, commit)\n const [names, numstat] = await Promise.all([\n parent === null\n ? run(exec, ['diff-tree', '--root', '-r', '--no-commit-id', '--name-status', commit], 'diff-tree')\n : run(exec, ['diff', '--name-status', '-M', parent, commit], 'diff'),\n parent === null\n ? run(exec, ['diff-tree', '--root', '-r', '--no-commit-id', '--numstat', '-z', '-M', commit], 'diff-tree')\n : run(exec, ['diff', '--numstat', '-z', '-M', parent, commit], 'diff'),\n ])\n const counts = parseNumstat(numstat.stdout)\n const files: CommitFile[] = []\n let additions = 0\n let deletions = 0\n for (const line of names.stdout.split('\\n')) {\n if (line.length === 0) continue\n const fields = line.split('\\t')\n const code = (fields[0] ?? 'M').charAt(0)\n const renamed = code === 'R' || code === 'C'\n const path = renamed ? (fields[2] ?? '') : (fields[1] ?? '')\n if (path.length === 0) continue\n const stat = counts.get(path) ?? { additions: 0, deletions: 0 }\n additions += stat.additions ?? 0\n deletions += stat.deletions ?? 0\n files.push({\n path,\n origPath: renamed ? (fields[1] ?? null) : null,\n status: STATUS_OF_CODE[code] ?? 'modified',\n code,\n staged: false,\n additions: stat.additions,\n deletions: stat.deletions,\n })\n if (files.length >= bounds.maxFiles) break\n }\n return { hash: commit, files, additions, deletions, truncated: files.length >= bounds.maxFiles }\n}\n\n/**\n * Read one file's diff inside a commit.\n * @param request - `exec`, `cwd`, `limits`, `hash`, and `path`.\n * @returns the `Diff` of the wire contract.\n * @throws {GitError} `INVALID` for an unknown commit or unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitCommitDiff({ exec, cwd, limits = {}, hash, path }: GitCommitDiffRequest): Promise<Diff> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const commit = await resolveCommit(exec, checkedHash(hash))\n const checked = checkedPath(path)\n const parent = await firstParent(exec, commit)\n const args = parent === null\n ? ['show', '--no-color', '--no-ext-diff', '--format=', '-U3', commit, '--', checked]\n : ['diff', '--no-color', '--no-ext-diff', '-U3', parent, commit, '--', checked]\n const result = await run(exec, args, 'diff')\n return diffOf({ path: checked, staged: false, text: result.stdout, maxDiffBytes: bounds.maxDiffBytes })\n}\n\n/**\n * Read one stash entry's patch.\n * @param request - `exec`, `cwd`, `limits`, and `index`.\n * @returns the `Diff` of the wire contract, addressed as `stash@{index}`.\n * @throws {GitError} `INVALID` for a missing index, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitStashDiff({ exec, cwd, limits = {}, index }: GitStashDiffRequest): Promise<Diff> {\n const bounds = resolveLimits(limits)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const stash = checkedStashIndex(index)\n const ref = `stash@{${stash}}`\n const result = await exec(argvOf(['stash', 'show', '-p', '--no-color', ref]), { allowedExitCodes: [0, 128] })\n if (result.exitCode !== 0) throw new GitError('GIT_FAILED', `git stash show failed: ${firstLine(result.stderr)}`, excerpt(result.stderr))\n return diffOf({ path: ref, staged: false, text: result.stdout, maxDiffBytes: bounds.maxDiffBytes })\n}\n\n/** Validate a stash index from the client. */\nfunction checkedStashIndex(index: unknown): number {\n if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) {\n throw new GitError('INVALID', 'a stash index is required')\n }\n return index\n}\n\n/** Validate a local branch name with Git's own rule. */\nasync function checkBranchName(exec: Exec, name: unknown): Promise<string> {\n if (typeof name !== 'string' || name.trim().length === 0) throw new GitError('INVALID', 'a branch name is required')\n const result = await exec(argvOf(['check-ref-format', '--branch', name]), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) throw new GitError('INVALID', `\"${name}\" is not a valid branch name`)\n return name\n}\n\n/** Validate a tag name with Git's own rule. */\nasync function checkTagName(exec: Exec, name: unknown): Promise<string> {\n if (typeof name !== 'string' || name.trim().length === 0) throw new GitError('INVALID', 'a tag name is required')\n const result = await exec(argvOf(['check-ref-format', `refs/tags/${name}`]), { allowedExitCodes: [0, 1, 128] })\n if (result.exitCode !== 0) throw new GitError('INVALID', `\"${name}\" is not a valid tag name`)\n return name\n}\n\n/** Whether a local branch exists. */\nasync function localBranchExists(exec: Exec, name: string): Promise<boolean> {\n const result = await exec(argvOf(['show-ref', '--verify', '--quiet', `refs/heads/${name}`]), { allowedExitCodes: [0, 1, 128] })\n return result.exitCode === 0\n}\n\n/** Whether the repository has no commit yet. */\nasync function isUnborn(exec: Exec): Promise<boolean> {\n const result = await exec(argvOf(['rev-parse', '--verify', '--quiet', 'HEAD']), { allowedExitCodes: [0, 1, 128] })\n return result.exitCode !== 0\n}\n\n/** Read the checked-out branch name, for operations that need one. */\nasync function requireBranch(exec: Exec): Promise<string> {\n const branch = await currentBranch(exec)\n if (branch === null) throw new GitError('INVALID', 'the repository has no checked-out branch')\n return branch\n}\n\n/** Configured remote names, in the order `git remote` prints them. */\nasync function remoteNames(exec: Exec): Promise<string[]> {\n const result = await run(exec, ['remote'], 'remote')\n return result.stdout.split(/\\r?\\n/).map(line => line.trim()).filter(line => line.length > 0)\n}\n\n/** The remote a publish should target: `origin` when configured, else the only one, else the first. */\nasync function defaultRemote(exec: Exec): Promise<string | null> {\n const names = await remoteNames(exec)\n if (names.length === 0) return null\n return names.includes('origin') ? 'origin' : names[0]!\n}\n\n/** A configured remote name, for commands that address one. */\nfunction checkedRemoteName(name: unknown): string {\n const value = typeof name === 'string' ? name.trim() : ''\n if (value.length === 0) throw new GitError('INVALID', 'a remote name is required')\n if (value.startsWith('-') || /[\\s\\0-\\x1f\\x7f]/.test(value)) throw new GitError('INVALID', `\"${value}\" is not a valid remote name`)\n return value\n}\n\n/** A remote URL handed to `git remote add`. */\nfunction checkedRemoteUrl(url: unknown): string {\n const value = typeof url === 'string' ? url.trim() : ''\n if (value.length === 0) throw new GitError('INVALID', 'a remote URL is required')\n if (value.startsWith('-') || /[\\0-\\x1f\\x7f]/.test(value)) throw new GitError('INVALID', `\"${value}\" is not a valid remote URL`)\n return value\n}\n\n/** A GitHub repository name or `owner/name`, as `gh repo create` accepts it. */\nfunction checkedGithubRepository(name: unknown): string {\n const value = typeof name === 'string' ? name.trim() : ''\n if (value.length === 0) throw new GitError('INVALID', 'a GitHub repository name is required')\n if (!/^[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)?$/.test(value)) {\n throw new GitError('INVALID', `\"${value}\" is not a valid GitHub repository name`)\n }\n return value\n}\n\n/** Initialize a new repository in the Session directory. */\nasync function initRepository(exec: Exec, cwd: string): Promise<ActionResult> {\n const existing = await repositoryRoot(exec, cwd)\n if (existing !== null) throw new GitError('INVALID', 'the directory is already inside a Git work tree')\n return await mutate(exec, ['init', '-b', 'main'], 'init')\n}\n\n/** Run one mutating operation and report it. */\nasync function mutate(exec: Exec, args: readonly string[], operation: string, options: ExecOptions = {}): Promise<ActionResult> {\n const result = await run(exec, args, operation, options)\n return { message: `git ${operation} completed`, detail: excerpt(result.stdout) }\n}\n\n/** Names of the operations the checkout can be in the middle of, and their abort command. */\nconst ABORTABLE: Readonly<Record<string, readonly string[]>> = Object.freeze({\n 'cherry-pick': ['cherry-pick', '--abort'],\n revert: ['revert', '--abort'],\n rebase: ['rebase', '--abort'],\n merge: ['merge', '--abort'],\n})\n\n/**\n * Append one repository-relative path to `.gitignore`.\n * @param root - repository root.\n * @param path - relative path to ignore.\n * @returns the operation result.\n */\nasync function addToIgnoreFile(root: string, path: string): Promise<ActionResult> {\n const file = join(root, '.gitignore')\n let current = ''\n try {\n current = await readFile(file, 'utf8')\n } catch {\n // A missing .gitignore is created below.\n }\n const pattern = path.startsWith('#') || path.startsWith('!') ? `\\\\${path}` : path\n const lines = current.split(/\\r?\\n/).map(line => line.trim())\n if (lines.includes(pattern)) return { message: 'already ignored', detail: null }\n const prefix = current.length === 0 || current.endsWith('\\n') ? current : `${current}\\n`\n await writeFile(file, `${prefix}${pattern}\\n`, 'utf8')\n return { message: `added ${pattern} to .gitignore`, detail: null }\n}\n\n/** Whether the platform can reveal a path in its file manager. */\nfunction revealCommand(absolute: string): string[] {\n if (process.platform === 'darwin') return ['open', '-R', absolute]\n if (process.platform === 'win32') return ['explorer.exe', `/select,${absolute}`]\n return ['xdg-open', dirname(absolute)]\n}\n\n/** What the panel needs before offering to publish a repository on GitHub. */\nexport interface GithubInfo {\n /** Whether the GitHub CLI is installed, signed in, and can read the account. */\n readonly available: boolean\n /** Authenticated account login, or null. */\n readonly login: string | null\n /** Why publishing is unavailable, or null. */\n readonly reason: string | null\n}\n\n/**\n * Read the GitHub account the CLI would publish under.\n * @param request - the `exec` seam bound to the repository.\n * @returns availability, login, and a refusal reason.\n */\nexport async function gitGithubInfo({ exec }: { exec: Exec }): Promise<GithubInfo> {\n const unavailable = (reason: string): GithubInfo => ({ available: false, login: null, reason })\n try {\n await exec(['gh', '--version'], { allowedExitCodes: [0], timeoutMs: GITHUB_PROBE_TIMEOUT_MS })\n } catch {\n return unavailable('gh is not installed')\n }\n const status = await exec(['gh', 'auth', 'status'], { allowedExitCodes: [0, 1], timeoutMs: GITHUB_PROBE_TIMEOUT_MS })\n if (status.exitCode !== 0) return unavailable('gh is not signed in')\n const account = await exec(['gh', 'api', 'user', '--jq', '.login'], { allowedExitCodes: [0, 1], timeoutMs: GITHUB_PROBE_TIMEOUT_MS })\n const login = (account.stdout.split(/\\r?\\n/).map(line => line.trim()).find(line => line.length > 0)) ?? ''\n if (account.exitCode !== 0 || login.length === 0) return unavailable('the GitHub account could not be read')\n return { available: true, login, reason: null }\n}\n\n/**\n * Run one Git operation.\n * @param request - `exec`, `cwd`, `operation`, and `params`.\n * @returns the operation result.\n * @throws {GitError} `INVALID` for malformed parameters, `NOT_A_REPO` outside a work tree, or a structured Git failure.\n */\nexport async function gitAction({ exec, cwd, operation, params = {} }: GitActionRequest): Promise<ActionResult> {\n // Creating the repository is the one operation that runs before a work tree exists.\n if (operation === 'initRepository') return await initRepository(exec, cwd)\n const root = await repositoryRoot(exec, cwd)\n if (root === null) throw new GitError('NOT_A_REPO', `${cwd} is not inside a Git work tree`)\n const paths = Array.isArray(params.paths) ? params.paths.map(checkedPath) : []\n const requirePaths = (): string[] => {\n if (paths.length === 0) throw new GitError('INVALID', 'at least one path is required')\n return paths\n }\n const network: ExecOptions = { timeoutMs: NETWORK_TIMEOUT_MS }\n switch (operation) {\n case 'stage':\n return await mutate(exec, ['add', '-A', '--', ...requirePaths()], 'add')\n case 'unstage': {\n const target = requirePaths()\n if (await isUnborn(exec)) return await mutate(exec, ['reset', '-q', '--', ...target], 'reset')\n return await mutate(exec, ['restore', '--staged', '--', ...target], 'restore')\n }\n case 'discard': {\n const target = requirePaths()\n if (params.untracked === true) return await mutate(exec, ['clean', '-fdq', '--', ...target], 'clean')\n return await mutate(exec, ['restore', '--worktree', '--', ...target], 'restore')\n }\n case 'stageAll':\n return await mutate(exec, ['add', '-A'], 'add')\n case 'unstageAll':\n return await mutate(exec, ['reset', '-q'], 'reset')\n case 'commit': {\n const message = typeof params.message === 'string' ? params.message.trim() : ''\n if (message.length === 0) throw new GitError('INVALID', 'a commit message is required')\n const args = ['commit', '-m', message]\n if (params.amend === true) args.push('--amend')\n if (params.signoff === true) args.push('--signoff')\n return await mutate(exec, args, 'commit')\n }\n case 'undoCommit': {\n const head = await exec(argvOf(['rev-parse', '--verify', '--quiet', 'HEAD^']), { allowedExitCodes: [0, 1, 128] })\n if (head.exitCode !== 0) throw new GitError('INVALID', 'there is no commit to undo')\n return await mutate(exec, ['reset', '--soft', 'HEAD^'], 'reset')\n }\n case 'fetch': {\n const args = ['fetch', '--prune']\n if (params.all !== false) args.push('--all')\n const before = await readRemoteTips(exec)\n const result = await mutate(exec, args, 'fetch', network)\n const after = await readRemoteTips(exec)\n const changed: RefChange[] = []\n for (const [ref, hash] of after) {\n const previous = before.get(ref)\n if (previous !== hash) changed.push({ ref, from: previous ?? null, to: hash })\n }\n for (const [ref, hash] of before) {\n if (!after.has(ref)) changed.push({ ref, from: hash, to: null })\n }\n // `updated` lets the panel distinguish \"fetched, nothing new\" from\n // \"fetched, references moved\" without a second scan.\n return { ...result, updated: changed.length > 0, changed }\n }\n case 'pullBranch': {\n const name = checkedRef(typeof params.name === 'string' ? params.name.trim() : '')\n const remote = await configValue(exec, `branch.${name}.remote`)\n const merge = await configValue(exec, `branch.${name}.merge`)\n if (remote === null || merge === null || remote.length === 0 || remote === '.') {\n throw new GitError('INVALID', `branch \"${name}\" has no upstream branch`)\n }\n const remoteBranch = merge.startsWith('refs/heads/') ? merge.slice('refs/heads/'.length) : merge\n const upstreamRef = `${remote}/${remoteBranch}`\n await mutate(exec, ['fetch', '--prune', remote], 'fetch', network)\n const upstream = await exec(argvOf(['rev-parse', '--verify', '--quiet', `${upstreamRef}^{commit}`]), { allowedExitCodes: [0, 1] })\n if (upstream.exitCode !== 0) throw new GitError('INVALID', `upstream \"${upstreamRef}\" is missing`)\n const remoteTip = firstLine(upstream.stdout)\n const local = await exec(argvOf(['rev-parse', '--verify', '--quiet', `refs/heads/${name}^{commit}`]), { allowedExitCodes: [0, 1] })\n if (local.exitCode !== 0) throw new GitError('INVALID', `branch \"${name}\" is missing`)\n const localTip = firstLine(local.stdout)\n const counted = await exec(argvOf(['rev-list', '--count', `${localTip}..${remoteTip}`]), { allowedExitCodes: [0, 1] })\n const commits = Number.parseInt(firstLine(counted.stdout), 10) || 0\n if (localTip === remoteTip || commits === 0) {\n return { message: `branch \"${name}\" is already up to date`, detail: null, commits: 0 }\n }\n const current = await exec(argvOf(['symbolic-ref', '--quiet', '--short', 'HEAD']), { allowedExitCodes: [0, 1] })\n if (current.exitCode === 0 && current.stdout.trim() === name) {\n await mutate(exec, ['merge', '--ff-only', remoteTip], 'merge')\n } else {\n const ancestor = await exec(argvOf(['merge-base', '--is-ancestor', localTip, remoteTip]), { allowedExitCodes: [0, 1] })\n if (ancestor.exitCode !== 0) throw new GitError('INVALID', `branch \"${name}\" cannot fast-forward`)\n await mutate(exec, ['update-ref', `refs/heads/${name}`, remoteTip, localTip], 'update-ref')\n }\n return { message: `pulled ${name}`, detail: null, commits }\n }\n case 'pull': {\n const args = ['pull', '--no-edit']\n if (params.rebase === true) args.push('--rebase')\n if (params.ffOnly === true) args.push('--ff-only')\n return await mutate(exec, args, 'pull', network)\n }\n case 'publish': {\n const branch = await requireBranch(exec)\n const url = typeof params.url === 'string' ? params.url.trim() : ''\n const requested = params.remote === undefined ? undefined : checkedRemoteName(params.remote)\n let remote: string | null\n if (url.length > 0) {\n remote = requested ?? 'origin'\n if ((await remoteNames(exec)).includes(remote)) throw new GitError('INVALID', `remote \"${remote}\" already exists`)\n await mutate(exec, ['remote', 'add', remote, checkedRemoteUrl(url)], 'remote add')\n } else {\n remote = requested ?? await defaultRemote(exec)\n }\n if (remote === null) throw new GitError('INVALID', 'the repository has no remote to publish to')\n return await mutate(exec, ['push', '--set-upstream', remote, branch], 'push', network)\n }\n case 'publishGithub': {\n const branch = await requireBranch(exec)\n const name = checkedGithubRepository(params.name)\n const visibility = params.private === true ? '--private' : params.public === true ? '--public' : null\n if (visibility === null) throw new GitError('INVALID', 'choose a public or private GitHub repository')\n if ((await remoteNames(exec)).length > 0) throw new GitError('INVALID', 'the repository already has a remote')\n try {\n await exec(['gh', 'repo', 'create', name, visibility, '--source', root, '--remote', 'origin'], {\n timeoutMs: NETWORK_TIMEOUT_MS,\n })\n } catch (error) {\n throw failureOf(error, 'GitHub repository')\n }\n return await mutate(exec, ['push', '--set-upstream', 'origin', branch], 'push', network)\n }\n case 'push': {\n const args = ['push']\n if (params.forceWithLease === true) args.push('--force-with-lease')\n if (params.tags === true) args.push('--tags')\n if (params.setUpstream === true) {\n const branch = await requireBranch(exec)\n const remote = params.remote === undefined ? await defaultRemote(exec) : checkedRemoteName(params.remote)\n if (remote === null) throw new GitError('INVALID', 'the repository has no remote to publish to')\n args.push('--set-upstream', remote, branch)\n }\n return await mutate(exec, args, 'push', network)\n }\n case 'checkoutBranch': {\n const name = typeof params.name === 'string' ? params.name : ''\n if (name.length === 0) throw new GitError('INVALID', 'a branch name is required')\n if (params.kind === 'remote') {\n const local = name.split('/').slice(1).join('/')\n if (local.length === 0) throw new GitError('INVALID', `\"${name}\" is not a remote branch`)\n await checkBranchName(exec, local)\n if (await localBranchExists(exec, local)) return await mutate(exec, ['switch', local], 'switch')\n return await mutate(exec, ['switch', '-c', local, '--track', name], 'switch')\n }\n await checkBranchName(exec, name)\n return await mutate(exec, ['switch', name], 'switch')\n }\n case 'checkoutCommit': {\n const commit = await resolveCommit(exec, checkedHash(params.hash))\n return await mutate(exec, ['switch', '--detach', commit], 'switch')\n }\n case 'createBranch': {\n const name = await checkBranchName(exec, typeof params.name === 'string' ? params.name.trim() : '')\n const args = ['switch', '-c', name]\n if (typeof params.from === 'string' && params.from.length > 0) {\n args.push(await resolveCommit(exec, checkedRef(params.from)))\n }\n return await mutate(exec, args, 'switch')\n }\n case 'renameBranch': {\n const from = await checkBranchName(exec, typeof params.from === 'string' ? params.from : '')\n const to = await checkBranchName(exec, typeof params.to === 'string' ? params.to.trim() : '')\n return await mutate(exec, ['branch', '-m', from, to], 'branch')\n }\n case 'deleteBranch': {\n const name = await checkBranchName(exec, typeof params.name === 'string' ? params.name : '')\n return await mutate(exec, ['branch', params.force === true ? '-D' : '-d', name], 'branch')\n }\n case 'deleteRemoteBranch': {\n const name = typeof params.name === 'string' ? params.name : ''\n if (name.length === 0) throw new GitError('INVALID', 'a remote branch name is required')\n const slash = name.indexOf('/')\n if (slash <= 0 || slash === name.length - 1) throw new GitError('INVALID', `\"${name}\" is not a remote branch`)\n const remote = name.slice(0, slash)\n const branch = name.slice(slash + 1)\n return await mutate(exec, ['push', remote, '--delete', branch], 'push', network)\n }\n case 'cherryPick': {\n const commit = await resolveCommit(exec, checkedHash(params.hash))\n const args = ['cherry-pick']\n if (params.noCommit === true) args.push('--no-commit')\n const parents = (await run(exec, ['rev-list', '--parents', '-n1', commit], 'rev-list')).stdout.trim().split(' ').filter(Boolean).length - 1\n if (parents > 1) args.push('-m', '1')\n args.push(commit)\n return await mutate(exec, args, 'cherry-pick')\n }\n case 'revert': {\n const commit = await resolveCommit(exec, checkedHash(params.hash))\n const args = ['revert', '--no-edit']\n const parents = (await run(exec, ['rev-list', '--parents', '-n1', commit], 'rev-list')).stdout.trim().split(' ').filter(Boolean).length - 1\n if (parents > 1) args.push('-m', '1')\n args.push(commit)\n return await mutate(exec, args, 'revert')\n }\n case 'abortOperation': {\n const kind = params.kind\n const command = typeof kind === 'string' ? ABORTABLE[kind] : undefined\n if (command === undefined) throw new GitError('INVALID', `\"${String(kind)}\" is not an abortable operation`)\n return await mutate(exec, command, command.join(' '))\n }\n case 'stashSave': {\n const args = ['stash', 'push']\n if (params.includeUntracked === true) args.push('-u')\n if (params.staged === true) args.push('--staged')\n const message = typeof params.message === 'string' ? params.message.trim() : ''\n if (message.length > 0) args.push('-m', message)\n if (paths.length > 0) args.push('--', ...paths)\n return await mutate(exec, args, 'stash push')\n }\n case 'stashApply':\n case 'stashPop':\n case 'stashDrop': {\n const index = checkedStashIndex(params.index)\n const verb = operation === 'stashApply' ? 'apply' : operation === 'stashPop' ? 'pop' : 'drop'\n return await mutate(exec, ['stash', verb, `stash@{${index}}`], `stash ${verb}`)\n }\n case 'stashClear':\n return await mutate(exec, ['stash', 'clear'], 'stash clear')\n case 'tagCreate': {\n const name = await checkTagName(exec, typeof params.name === 'string' ? params.name.trim() : '')\n const message = typeof params.message === 'string' ? params.message.trim() : ''\n const args = message.length > 0 ? ['tag', '-a', '-m', message, name] : ['tag', name]\n if (typeof params.at === 'string' && params.at.length > 0) args.push(await resolveCommit(exec, checkedRef(params.at)))\n return await mutate(exec, args, 'tag')\n }\n case 'tagDelete': {\n const name = await checkTagName(exec, typeof params.name === 'string' ? params.name : '')\n return await mutate(exec, ['tag', '-d', name], 'tag')\n }\n case 'addToIgnore':\n return await addToIgnoreFile(root, requirePaths()[0]!)\n case 'reveal': {\n const target = requirePaths()[0]!\n const command = revealCommand(join(root, target))\n try {\n await exec(command, { allowedExitCodes: [0, 1] })\n } catch (error) {\n throw failureOf(error, 'reveal')\n }\n return { message: 'revealed in the file manager', detail: null }\n }\n default:\n throw new GitError('INVALID', `unknown operation \"${operation}\"`)\n }\n}\n\n/** Every operation name this layer accepts, for the caller's request validation. */\nexport const OPERATIONS = Object.freeze([\n 'stage', 'unstage', 'discard', 'stageAll', 'unstageAll', 'commit', 'undoCommit',\n 'fetch', 'pull', 'pullBranch', 'publish', 'publishGithub', 'push', 'checkoutBranch', 'checkoutCommit', 'createBranch', 'renameBranch',\n 'deleteBranch', 'deleteRemoteBranch', 'cherryPick', 'revert', 'abortOperation',\n 'stashSave', 'stashApply', 'stashPop', 'stashDrop', 'stashClear',\n 'tagCreate', 'tagDelete', 'addToIgnore', 'reveal', 'initRepository',\n])\n","/**\n * Shared contracts of the Host half: the process seam the Git layer runs\n * through, the failure shape the JSON route reports, and the read limits the\n * caller applies to one snapshot.\n */\n\n/** Stable failure codes the browser half already knows how to phrase. */\nexport type WireCode =\n | 'NOT_A_REPO'\n | 'INVALID'\n | 'INVALID_REQUEST'\n | 'NO_SESSION'\n | 'NO_WORKSPACE'\n | 'GIT_FAILED'\n | 'TIMEOUT'\n | 'TOO_LARGE'\n | 'SPAWN_FAILED'\n | 'CANCELLED'\n | 'BUSY'\n | 'NETWORK'\n | 'FORBIDDEN'\n | 'INTERNAL'\n\n/** Every name in {@link WireCode}, for admitting a caught failure onto the wire. */\nconst WIRE_CODE_NAMES = [\n 'NOT_A_REPO', 'INVALID', 'INVALID_REQUEST', 'NO_SESSION', 'NO_WORKSPACE', 'GIT_FAILED',\n 'TIMEOUT', 'TOO_LARGE', 'SPAWN_FAILED', 'CANCELLED', 'BUSY', 'NETWORK', 'FORBIDDEN', 'INTERNAL',\n] as const satisfies readonly WireCode[]\n\n/** Set form of {@link WIRE_CODE_NAMES} used to recognize an already-coded failure. */\nexport const WIRE_CODES: ReadonlySet<string> = new Set(WIRE_CODE_NAMES)\n\n/** Failure body of a rejected request, as it goes onto the wire. */\nexport interface WireError {\n /** Stable wire code, e.g. `NOT_A_REPO`. */\n readonly code: WireCode\n /** Operator-readable reason. */\n readonly message: string\n /** Raw Git output excerpt, when one exists. */\n readonly detail: string | null\n}\n\n/** A caught failure that already carries a wire code the page understands. */\nexport interface WireFailureLike {\n readonly code: WireCode\n readonly message: string\n readonly detail?: unknown\n}\n\n/** A rejected request as the route reports it, before it becomes an HTTP body. */\nexport class RequestError extends Error {\n /** Stable wire code such as `NOT_A_REPO`. */\n readonly code: WireCode\n\n /** Raw Git output excerpt, when one exists. */\n readonly detail: string | null\n\n /**\n * @param code - stable wire code such as `NOT_A_REPO`.\n * @param message - operator-readable reason.\n * @param detail - raw Git output excerpt, when one exists.\n */\n constructor(code: WireCode, message: string, detail: string | null = null) {\n super(message)\n this.name = 'RequestError'\n this.code = code\n this.detail = detail\n }\n}\n\n/** Complete output of one program the `exec` seam ran to an allowed exit code. */\nexport interface ExecResult {\n /** Captured standard output. */\n readonly stdout: string\n /** Captured standard error. */\n readonly stderr: string\n /** Exit code; always one of the requested allowed codes. */\n readonly exitCode: number\n}\n\n/** Per-invocation options the Git layer hands the `exec` seam. */\nexport interface ExecOptions {\n /** Exit codes that resolve instead of rejecting; defaults to `[0]`. */\n readonly allowedExitCodes?: readonly number[] | undefined\n /** One-off Git configuration values, passed as `-c key=value`. */\n readonly config?: Readonly<Record<string, string>> | undefined\n /** Bytes written to the child's stdin, then closed. */\n readonly input?: string | undefined\n /** Deadline for this command, including executable lookup. */\n readonly timeoutMs?: number | undefined\n}\n\n/**\n * Run one program for one Session directory.\n *\n * Resolves for an allowed exit code and rejects otherwise; a rejection carries\n * the Git layer's code (`GIT_FAILED`, `TIMEOUT`, `SPAWN_FAILED`, `TOO_LARGE`, …).\n */\nexport type Exec = (argv: string[], options?: ExecOptions) => Promise<ExecResult>\n\n/** Limits one Git snapshot applies; omitted entries fall back to the Git layer's own bounds. */\nexport interface GitLimits {\n /** Maximum branches in each branch list. */\n maxBranches: number\n /** Maximum commits in one page. */\n maxCommits: number\n /** Maximum tags. */\n maxTags: number\n /** Maximum changed files across all change lists. */\n maxFiles: number\n /** Maximum characters of one returned diff. */\n maxDiffBytes: number\n}\n","/**\n * Commit-message generation for the source-control panel: prompt construction,\n * output cleanup, and the one-shot model call the Host entry supplies.\n *\n * The module holds no LLM client of its own: the Host passes a `generate`\n * seam backed by the app's own model runtime, so this package keeps no\n * runtime dependency on any `@deepseek-ai/*` package.\n */\nimport type { CommitMessageContext } from './git.ts'\nimport { RequestError } from './types.ts'\n\n/** How the model should treat the drafted message. */\nexport type CommitMessageMode = 'generate' | 'improve'\n\n/** Message shape the caller asked for; `auto` leaves it to the model and repository style. */\nexport type CommitMessageStyle = 'auto' | 'conventional' | 'single' | 'detailed'\n\n/** Every accepted style, for validating an untrusted request field. */\nexport const COMMIT_MESSAGE_STYLES: readonly CommitMessageStyle[] = Object.freeze(['auto', 'conventional', 'single', 'detailed'])\n\n/** One prompt handed to the model. */\nexport interface CommitMessagePrompt {\n /** Instructions and output contract. */\n readonly system: string\n /** Change context and, for an improvement, the draft. */\n readonly user: string\n}\n\n/** Dispatch one prompt to a model and resolve its text. */\nexport type CommitMessageGenerator = (prompt: CommitMessagePrompt) => Promise<string>\n\n/** One commit-message generation request. */\nexport interface CommitMessageRequest {\n /** The change context read from the checkout. */\n readonly context: CommitMessageContext\n /** Whether the model writes from scratch or improves the draft. */\n readonly mode: CommitMessageMode\n /** The user's current draft, for `improve`. */\n readonly draft: string\n /** Active app locale id, deciding the output language for `generate`. */\n readonly language: string\n /** Requested message shape; omitted reads as `auto`. */\n readonly style?: CommitMessageStyle | undefined\n /** Whether the caller pinned the language rule instead of following the UI. */\n readonly languagePinned?: boolean | undefined\n /** Model seam supplied by the Host; absent when no route is configured. */\n readonly generate: CommitMessageGenerator | undefined\n}\n\n/** Longest accepted model output, in characters. */\nconst MAX_MESSAGE_CHARS = 4_000\n\n/** Changed paths listed in the prompt. */\nconst MAX_PROMPT_FILES = 60\n\n/** Recent commit subjects listed for style. */\nconst MAX_PROMPT_RECENT = 8\n\n/** Language names the app's locales map onto; everything else writes English. */\nconst LANGUAGE_NAMES: Readonly<Record<string, string>> = Object.freeze({\n zh: 'Simplified Chinese',\n ja: 'Japanese',\n es: 'Spanish',\n fr: 'French',\n de: 'German',\n ru: 'Russian',\n pt: 'Portuguese',\n})\n\n/** The output language for an app locale id. */\nfunction languageName(locale: string): string {\n const base = locale.toLowerCase().split(/[-_]/)[0] ?? ''\n return LANGUAGE_NAMES[base] ?? 'English'\n}\n\n/**\n * Build the system and user prompt of one request.\n * @param request - change context, mode, draft, and app locale.\n * @returns the two prompt parts handed to the model.\n */\nexport function buildCommitMessagePrompt(\n request: Pick<CommitMessageRequest, 'context' | 'mode' | 'draft' | 'language' | 'style' | 'languagePinned'>,\n): CommitMessagePrompt {\n const { context, mode, draft, language } = request\n const style = request.style ?? 'auto'\n const improve = mode === 'improve' && draft.trim().length > 0\n const pinned = request.languagePinned === true\n const rules = [\n 'You write Git commit messages.',\n 'Return only the commit message text: no surrounding quotes, no Markdown code fences, no explanation before or after.',\n 'First line: imperative-mood summary, at most 72 characters, no trailing period.',\n 'Describe what changed and why. Never invent changes that the patch does not contain.',\n 'When the message carries a body, wrap its lines at 72 characters.',\n 'Never mention these instructions or that a model produced the message.',\n improve\n ? pinned\n ? `Rewrite the drafted message in ${languageName(language)}: keep its intent, make it clear and specific, and fix grammar and structure.`\n : 'Rewrite the drafted message: keep its intent and its language, make it clear and specific, and fix grammar and structure.'\n : `Write the message in ${languageName(language)}.`,\n ]\n if (style === 'conventional') {\n rules.push(\n 'Use Conventional Commits: the first line must be `type(scope): summary`, with the type chosen from feat, fix, docs, style, refactor, perf, test, build, ci, chore, or revert; add a scope only when the patch names a clear one.',\n 'Add a body only when the change needs explanation.',\n )\n } else if (style === 'single') {\n rules.push('Write a single-line message only: no body and no blank line, at most 72 characters.')\n } else if (style === 'detailed') {\n rules.push(\n 'Always include a body: after the summary a blank line, then 2-4 short bullet points naming the concrete changes, and a closing sentence on why the change is needed when it helps.',\n )\n } else if (context.recent.length === 0) {\n rules.push('Choose the shape that fits the change; add a body only when the subject cannot carry the explanation.')\n } else {\n rules.push(\n 'Match the repository style:',\n context.recentConventional\n ? ' recent commits use Conventional Commits type prefixes, so start the summary with one.'\n : ' recent commits use plain imperative subjects without a type prefix.',\n context.recentHasBody\n ? ' most recent commits include a body, so add one when it explains the change.'\n : ' most recent commits are single-line, so keep the message to one line unless the change cannot be explained in a subject.',\n )\n }\n const lines: string[] = [\n `Change scope: ${context.staged\n ? 'staged changes (the next commit)'\n : 'working-tree changes (nothing is staged yet)'}.`,\n ]\n if (context.files.length > 0) {\n lines.push('Changed paths:')\n for (const file of context.files.slice(0, MAX_PROMPT_FILES)) lines.push(`- ${file.status}: ${file.path}`)\n if (context.files.length > MAX_PROMPT_FILES) {\n lines.push(`- … and ${String(context.files.length - MAX_PROMPT_FILES)} more paths`)\n }\n } else {\n lines.push('Changed paths: none.')\n }\n if (context.recent.length > 0) {\n lines.push('Recent commit subjects (style reference):')\n for (const subject of context.recent.slice(0, MAX_PROMPT_RECENT)) lines.push(`- ${subject}`)\n }\n if (context.diff.length > 0) {\n lines.push('Patch:', '```diff', context.diff, '```')\n }\n if (improve) lines.push('Draft to improve:', '```text', draft.slice(0, MAX_MESSAGE_CHARS), '```')\n return { system: rules.join('\\n'), user: lines.join('\\n') }\n}\n\n/** A wrapped emphasis marker the model sometimes puts around the subject. */\nconst BOUNDARY_QUOTES = /^[\"'`]|[\"'`]$/g\n\n/**\n * Normalize one model answer into a commit message.\n * @param text - raw model output.\n * @returns the cleaned message, possibly empty.\n */\nexport function cleanCommitMessage(text: string): string {\n let value = String(text ?? '').replace(/\\r\\n/g, '\\n').trim()\n const fenced = /^```[a-zA-Z]*\\n([\\s\\S]*?)\\n```$/.exec(value)\n if (fenced !== null) value = (fenced[1] ?? '').trim()\n value = value.replace(/^(?:commit message|message)\\s*:\\s*/i, '')\n if (value.length > 1) {\n const first = value[0]\n const last = value[value.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\") || (first === '`' && last === '`')) {\n value = value.slice(1, -1)\n }\n }\n value = value.replace(BOUNDARY_QUOTES, '')\n value = value\n .split('\\n')\n .map(line => line.trimEnd())\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n return value.slice(0, MAX_MESSAGE_CHARS)\n}\n\n/**\n * Generate or improve one commit message.\n * @param request - change context, mode, draft, language, and the model seam.\n * @returns the cleaned message.\n * @throws {RequestError} `INVALID` for an empty change set or a missing model\n * route, `INTERNAL` when the model call fails or returns nothing usable.\n */\nexport async function generateCommitMessage(request: CommitMessageRequest): Promise<{ message: string }> {\n if (request.mode === 'generate' && request.draft.trim().length === 0\n && request.context.files.length === 0 && request.context.diff.length === 0) {\n throw new RequestError('INVALID', 'there are no changes to describe')\n }\n if (request.generate === undefined) {\n throw new RequestError('INVALID', 'no model is configured to write commit messages')\n }\n let raw: string\n try {\n raw = await request.generate(buildCommitMessagePrompt(request))\n } catch (error) {\n throw new RequestError('INTERNAL', `the commit message could not be generated: ${error instanceof Error ? error.message : String(error)}`)\n }\n const message = cleanCommitMessage(raw)\n if (message.length === 0) throw new RequestError('INTERNAL', 'the model returned an empty commit message')\n return { message }\n}\n","/**\n * Host half of the Git source-control plugin: one JSON route that answers Git\n * facts and Git operations for a Session's checkout.\n *\n * The browser half cannot call generated Remotes, so this plugin carries its own\n * HTTP route on the shared web server. A request names a Session, never a path:\n * the route resolves the Session's effective working directory through the\n * `workingDirectory` service and runs Git there, so a page cannot reach a\n * directory the open Session does not already belong to.\n *\n * Every Git invocation goes through `ctx.subprocess` (`resolveExecutable` plus a\n * collected spawn), so the process seam, cancellation, output caps, and teardown\n * stay with the provider. The route itself is a raw Node handler because Git\n * operations must be POSTs; resource routes answer GET and HEAD only.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport type {} from '@deepseek-ai/dsh-session'\nimport type {} from '@deepseek-ai/dsh-subprocess'\nimport type {} from '@deepseek-ai/dsh-working-directory'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess'\nimport {\n GIT_ENV, OPERATIONS, gitAction, gitCommitDiff, gitCommitFiles, gitCommitMessageContext, gitCommits, gitDiff, gitFileHistory, gitGithubInfo, gitStashDiff, gitStatus, gitSummary,\n} from './host/git.ts'\nimport { RequestError, WIRE_CODES } from './host/types.ts'\nimport { generateCommitMessage } from './host/commit-message.ts'\nimport type { CommitMessageGenerator, CommitMessagePrompt } from './host/commit-message.ts'\nimport type { Exec, GitLimits, WireFailureLike } from './host/types.ts'\n\n/** Exact route path; the handler answers this path and everything below it. */\nconst ROUTE = '/api/dsh-git-scm'\n\n/** Default executable when the request names none (every request but `reveal`). */\nconst GIT_COMMAND = 'git'\n\n/** Flags before every Git subcommand: no index refresh writes, hooks, or fsmonitor. */\nconst GIT_PREFIX = Object.freeze(['--no-optional-locks', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false'])\n\n/** Deadline for one local Git command, including executable lookup. */\nconst GIT_TIMEOUT_MS = 30_000\n\n/** Deadline for a command that talks to a remote; the Git layer raises it per operation. */\nconst REQUEST_TIMEOUT_MS = 420_000\n\n/** Deadline for one commit-message model request. */\nconst COMMIT_MESSAGE_TIMEOUT_MS = 90_000\n\n/** Output tokens reserved for one commit-message request, thinking included. */\nconst COMMIT_MESSAGE_MAX_TOKENS = 2_048\n\n/** Characters of model output accepted before assembly stops. */\nconst COMMIT_MESSAGE_MAX_OUTPUT_CHARS = 8_192\n\n/** Auxiliary-purpose tag recorded for the model request. */\nconst COMMIT_MESSAGE_PURPOSE = 'git-commit-message'\n\n/** Grace period the provider grants a terminating process. */\nconst GRACE_MS = 2_000\n\n/** Captured bytes per output stream. */\nconst MAX_OUTPUT_BYTES = 8 * 1024 * 1024\n\n/** Characters of a returned diff. */\nconst MAX_DIFF_BYTES = 400 * 1024\n\n/** Accepted request body size. */\nconst MAX_BODY_BYTES = 256 * 1024\n\n/** How many requests one Session may have in flight. */\nconst MAX_INFLIGHT_PER_SESSION = 4\n\n/** List caps that keep one panel render bounded on a large repository. */\nconst LIMITS: Readonly<GitLimits & { maxOutputBytes: number }> = Object.freeze({\n maxBranches: 500,\n maxCommits: 40,\n maxTags: 30,\n maxFiles: 3000,\n maxDiffBytes: MAX_DIFF_BYTES,\n maxOutputBytes: MAX_OUTPUT_BYTES,\n})\n\n/** Services this plugin needs; `webServer` binds the route, `sessions` resolves the checkout. */\nexport const inject = ['subprocess', 'sessions', 'webServer']\n\n/** Whether a decoded JSON value is a plain object. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** Whether a caught failure already carries a wire code the page understands. */\nfunction isWireFailure(value: unknown): value is WireFailureLike {\n return isRecord(value)\n && typeof value.code === 'string' && WIRE_CODES.has(value.code)\n && typeof value.message === 'string'\n}\n\n/** Format an unknown thrown value for an operator message. */\nfunction messageOf(error: unknown): string {\n if (error instanceof Error) return error.message\n return String(error)\n}\n\n/** Read the raw `detail` field a caught failure may carry. */\nfunction detailOf(error: unknown): unknown {\n return isRecord(error) ? error.detail : undefined\n}\n\n/**\n * Mount the Git route for the calling profile.\n * @param ctx - Host Cordis context carrying the injected services.\n */\nexport function apply(ctx: Context): void {\n /** Sessions whose requests are in flight, so one page cannot stack unbounded Git work. */\n const active = new Map<string, number>()\n\n /**\n * Run one program for one Session directory.\n * @param options - the Session directory and the request cancellation.\n * @returns the `exec` seam `host/git.ts` expects.\n */\n function createExec({ cwd, signal }: { cwd: string; signal: AbortSignal }): Exec {\n return async function exec(argv, options = {}) {\n const allowedExitCodes = options.allowedExitCodes ?? [0]\n const [program, ...args] = argv\n const controller = new AbortController()\n const onAbort = (): void => { controller.abort(signal.reason) }\n signal.addEventListener('abort', onAbort, { once: true })\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort(new Error('git command timed out'))\n }, options.timeoutMs ?? GIT_TIMEOUT_MS)\n timer.unref?.()\n const callSignal = controller.signal\n try {\n const executable = await ctx.subprocess.resolveExecutable(program ?? GIT_COMMAND, undefined, callSignal)\n const isGit = program === GIT_COMMAND\n const overrides = Object.entries(options.config ?? {})\n const command = [\n executable,\n ...isGit ? GIT_PREFIX : [],\n ...isGit ? overrides.flatMap(([key, value]) => ['-c', `${key}=${value}`]) : [],\n ...args,\n ]\n let child: SubprocessHandle\n try {\n child = ctx.subprocess.spawn({\n argv: command,\n cwd,\n ...isGit ? { env: { ...GIT_ENV } } : {},\n graceMs: GRACE_MS,\n signal: callSignal,\n stdio: {\n stdin: options.input === undefined ? 'ignore' : { data: options.input },\n stdout: { maxBytes: MAX_OUTPUT_BYTES },\n stderr: { maxBytes: MAX_OUTPUT_BYTES },\n },\n })\n } catch (error) {\n throw new RequestError('SPAWN_FAILED', `${program} could not start: ${messageOf(error)}`)\n }\n try {\n const outcome = await child.done\n if (timedOut) throw new RequestError('TIMEOUT', `${program} ${args[0] ?? ''} timed out`)\n if (callSignal.aborted) throw new RequestError('CANCELLED', 'the Git request was cancelled')\n const stdout = child.collected.stdout?.readFrom(0)\n const stderr = child.collected.stderr?.readFrom(0)\n if (stdout?.lossy === true || stderr?.lossy === true) {\n throw new RequestError('TOO_LARGE', `${program} ${args[0] ?? ''} printed more than the output limit`)\n }\n const out = stdout?.text ?? ''\n const err = stderr?.text ?? ''\n if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) {\n throw new RequestError(\n 'GIT_FAILED',\n `${program} ${args[0] ?? ''} failed (${outcome.signal ?? outcome.exitCode}): ${firstLine(err)}`,\n excerpt(err),\n )\n }\n return { stdout: out, stderr: err, exitCode: outcome.exitCode }\n } finally {\n child.terminate()\n await child.waitForExit().catch(() => undefined)\n }\n } catch (error) {\n if (error instanceof RequestError) throw error\n if (timedOut) throw new RequestError('TIMEOUT', `${program} ${args[0] ?? ''} timed out`)\n if (callSignal.aborted) throw new RequestError('CANCELLED', 'the Git request was cancelled')\n throw new RequestError('SPAWN_FAILED', `${program} ${args[0] ?? ''} could not run: ${messageOf(error)}`)\n } finally {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n /**\n * Resolve the checkout directory a request belongs to.\n * @param sessionId - Session identity supplied by the page.\n * @returns the Session's absolute working directory.\n */\n function directoryOf(sessionId: unknown): string {\n if (typeof sessionId !== 'string' || sessionId.length === 0) {\n throw new RequestError('INVALID_REQUEST', 'sessionId must be a non-empty string')\n }\n // Session ids are branded strings; the non-empty check above is the admission.\n const session = ctx.sessions.get(sessionId as SessionId)\n if (session === undefined) throw new RequestError('NO_SESSION', 'the Session is not loaded in this process')\n const workingDirectory = ctx.get('workingDirectory')\n const directory: string | undefined = workingDirectory === undefined ? session.header.cwd : workingDirectory.get(session)\n if (directory === undefined || directory === '') {\n throw new RequestError('NO_WORKSPACE', 'the Session has no working directory')\n }\n return directory\n }\n\n /**\n * Build the model call a commit-message request runs, when the app provides\n * both an adapter and a default route. The panel keeps working without it.\n * @param sessionId - Session whose request routing the model call joins.\n * @param signal - cancellation of the whole HTTP request.\n * @returns the model seam, or undefined when no route is configured.\n */\n function createCommitMessageGenerator(sessionId: string, signal: AbortSignal): CommitMessageGenerator | undefined {\n const llm = (ctx as unknown as { get(name: string): unknown }).get('llm') as {\n stream?: (options: Record<string, unknown>) => AsyncIterable<unknown>\n resolveModelInfo?: (provider: string, model: string, signal?: AbortSignal) => Promise<unknown>\n } | undefined\n const defaults = (ctx as unknown as { get(name: string): unknown }).get('agentDefaultModel') as\n { currentSelection?: () => Record<string, unknown> } | undefined\n const selection = defaults?.currentSelection?.()\n if (llm === undefined || typeof llm.stream !== 'function') return undefined\n if (selection === undefined\n || typeof selection.provider !== 'string' || selection.provider.length === 0\n || typeof selection.model !== 'string' || selection.model.length === 0) return undefined\n const provider = selection.provider\n const model = selection.model\n // A one-shot auxiliary call should think as little as the route allows.\n const auxiliaryEffort = async (): Promise<string | undefined> => {\n try {\n const info = await llm.resolveModelInfo?.(provider, model, signal) as\n { reasoning?: { efforts?: Array<{ id?: unknown }> } } | undefined\n const efforts = (info?.reasoning?.efforts ?? [])\n .map(effort => typeof effort?.id === 'string' ? effort.id : undefined)\n .filter((id): id is string => id !== undefined)\n if (efforts.length === 0) return undefined\n return efforts.includes('off') ? 'off' : efforts[0]\n } catch {\n // A route that cannot describe itself keeps the configured effort.\n return typeof selection.reasoningEffort === 'string' ? selection.reasoningEffort : undefined\n }\n }\n return async (prompt: CommitMessagePrompt): Promise<string> => {\n const reasoningEffort = await auxiliaryEffort()\n const stream = llm.stream!({\n provider,\n model,\n ...reasoningEffort === undefined ? {} : { reasoningEffort },\n system: prompt.system,\n messages: [{ role: 'user', content: [{ type: 'text', text: prompt.user }] }],\n temperature: 0.2,\n maxTokens: COMMIT_MESSAGE_MAX_TOKENS,\n sessionId,\n purpose: COMMIT_MESSAGE_PURPOSE,\n signal,\n })\n let text = ''\n let reason: unknown\n let stopped = false\n for await (const chunk of stream) {\n const typed = chunk as { type?: unknown; text?: unknown; reason?: unknown }\n if (typed.type === 'text-delta' && typeof typed.text === 'string') {\n text += typed.text\n if (text.length >= COMMIT_MESSAGE_MAX_OUTPUT_CHARS) {\n stopped = true\n break\n }\n } else if (typed.type === 'finish') reason = typed.reason\n }\n if (!stopped) {\n const finish = reason as { kind?: unknown; failure?: { message?: unknown } } | undefined\n const failure = typeof finish?.failure?.message === 'string' ? finish.failure.message : undefined\n if (finish?.kind === 'error') throw new Error(`the model request failed${failure === undefined ? '' : `: ${failure}`}`)\n if (finish?.kind === 'aborted') throw new Error('the model request was aborted')\n if (finish?.kind === 'max-tokens' && text.trim().length > 0) return text\n if (finish?.kind !== 'stop') {\n throw new Error(`the model did not finish normally${typeof finish?.kind === 'string' ? ` (${finish.kind})` : ''}`)\n }\n }\n return text\n }\n }\n\n /**\n * Answer one decoded request with Git data.\n * @param body - the decoded body `{ sessionId, action, params }`.\n * @param signal - cancellation of the whole request.\n * @returns the action's JSON result.\n */\n async function dispatch(body: unknown, signal: AbortSignal): Promise<unknown> {\n if (body === null || typeof body !== 'object') {\n throw new RequestError('INVALID_REQUEST', 'the request body must be a JSON object')\n }\n const request = body as Record<string, unknown>\n const rawSessionId = request.sessionId\n const cwd = directoryOf(rawSessionId)\n // `directoryOf` admitted the addressed Session id as a non-empty string.\n const sessionId = rawSessionId as string\n const action = request.action\n if (typeof action !== 'string') throw new RequestError('INVALID_REQUEST', 'action must be a string')\n const params = request.params ?? {}\n if (params === null || typeof params !== 'object' || Array.isArray(params)) {\n throw new RequestError('INVALID_REQUEST', 'params must be a JSON object')\n }\n const fields = params as Record<string, unknown>\n const inflight = active.get(sessionId) ?? 0\n if (inflight >= MAX_INFLIGHT_PER_SESSION) {\n throw new RequestError('BUSY', 'too many Git requests are already running for this Session')\n }\n active.set(sessionId, inflight + 1)\n try {\n const exec = createExec({ cwd, signal })\n switch (action) {\n case 'summary': return await gitSummary({ exec, cwd, limits: LIMITS })\n case 'github': return await gitGithubInfo({ exec })\n case 'commitMessage': {\n const mode = fields.mode === 'improve' ? 'improve' as const : 'generate' as const\n const draft = typeof fields.draft === 'string' ? fields.draft : ''\n const language = typeof fields.language === 'string' && fields.language.length > 0 ? fields.language : 'en'\n const style = fields.style === 'conventional' || fields.style === 'single' || fields.style === 'detailed'\n ? fields.style\n : 'auto'\n const languagePinned = fields.languagePinned === true\n const context = await gitCommitMessageContext({ exec, cwd, limits: LIMITS })\n const deadline = AbortSignal.any([signal, AbortSignal.timeout(COMMIT_MESSAGE_TIMEOUT_MS)])\n try {\n return await generateCommitMessage({\n context, mode, draft, language, style, languagePinned,\n generate: createCommitMessageGenerator(sessionId, deadline),\n })\n } catch (error) {\n const expired = deadline.aborted && deadline.reason instanceof Error && deadline.reason.name === 'TimeoutError'\n if (expired) throw new RequestError('TIMEOUT', 'the commit message request timed out')\n throw error\n }\n }\n case 'status': return await gitStatus({ exec, cwd, limits: LIMITS })\n case 'commits': return await gitCommits({\n exec,\n cwd,\n limits: LIMITS,\n ref: requiredString(fields.ref, 'params.ref'),\n skip: optionalCount(fields.skip),\n limit: optionalCount(fields.limit),\n })\n case 'commitFiles': return await gitCommitFiles({\n exec,\n cwd,\n limits: LIMITS,\n hash: requiredString(fields.hash, 'params.hash'),\n })\n case 'commitDiff': return await gitCommitDiff({\n exec,\n cwd,\n limits: LIMITS,\n hash: requiredString(fields.hash, 'params.hash'),\n path: requiredString(fields.path, 'params.path'),\n })\n case 'stashDiff': return await gitStashDiff({ exec, cwd, limits: LIMITS, index: fields.index })\n case 'fileHistory': return await gitFileHistory({\n exec,\n cwd,\n limits: LIMITS,\n path: requiredString(fields.path, 'params.path'),\n skip: optionalCount(fields.skip),\n limit: optionalCount(fields.limit),\n })\n case 'diff': return await gitDiff({\n exec,\n cwd,\n limits: LIMITS,\n path: requiredString(fields.path, 'params.path'),\n staged: fields.staged === true,\n untracked: fields.untracked === true,\n })\n case 'action': {\n const operation = requiredString(fields.operation, 'params.operation')\n if (!OPERATIONS.includes(operation)) {\n throw new RequestError('INVALID_REQUEST', `unknown operation \"${operation}\"`)\n }\n return await gitAction({ exec, cwd, operation, params: fields })\n }\n default:\n throw new RequestError('INVALID_REQUEST', `unknown action \"${action}\"`)\n }\n } finally {\n const remaining = (active.get(sessionId) ?? 1) - 1\n if (remaining <= 0) active.delete(sessionId)\n else active.set(sessionId, remaining)\n }\n }\n\n /**\n * Answer one HTTP exchange; only same-origin JSON POSTs from the app page are admitted.\n * @param req - the request.\n * @param res - the response.\n * @returns settles after the response is written.\n */\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n if (req.method !== 'POST') {\n res.writeHead(405, { allow: 'POST' })\n res.end()\n return\n }\n // A cross-site page could otherwise drive Git through the open desktop app.\n const origin = req.headers.origin\n if (origin !== undefined && !sameHost(origin, req.headers.host)) {\n writeJson(res, 403, { ok: false, error: { code: 'FORBIDDEN', message: 'requests must come from the app origin' } })\n try { req.resume() } catch { /* the request body is intentionally not read */ }\n return\n }\n if (typeof req.headers['content-type'] !== 'string' || !req.headers['content-type'].startsWith('application/json')) {\n writeJson(res, 415, { ok: false, error: { code: 'INVALID_REQUEST', message: 'content-type must be application/json' } })\n try { req.resume() } catch { /* the request body is intentionally not read */ }\n return\n }\n const controller = new AbortController()\n res.on('close', () => { if (!res.writableEnded) controller.abort(new Error('response closed')) })\n req.on('aborted', () => { controller.abort(new Error('request aborted')) })\n req.on('error', () => { controller.abort(new Error('request failed')) })\n const timeout = setTimeout(() => { controller.abort(new Error('request timed out')) }, REQUEST_TIMEOUT_MS)\n timeout.unref?.()\n try {\n const body = await readJson(req, MAX_BODY_BYTES)\n const data = await dispatch(body, controller.signal)\n writeJson(res, 200, { ok: true, data })\n } catch (error) {\n const failure = isWireFailure(error)\n ? new RequestError(error.code, messageOf(error), excerpt(detailOf(error)))\n : new RequestError('INTERNAL', messageOf(error), excerpt(detailOf(error)))\n if (failure.code === 'INTERNAL') ctx.logger?.warn?.(error instanceof Error ? error : new Error(String(error)))\n if (res.headersSent) {\n res.destroy()\n return\n }\n writeJson(res, 200, { ok: false, error: { code: failure.code, message: failure.message, detail: failure.detail } })\n } finally {\n clearTimeout(timeout)\n }\n }\n\n ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, handler: (req, res) => handle(req, res) }), 'dsh-git-scm: route')\n}\n\n/** Read one required string field of a request's params. */\nfunction requiredString(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new RequestError('INVALID_REQUEST', `${field} must be a non-empty string`)\n }\n return value\n}\n\n/** Read an optional non-negative integer field of a request's params. */\nfunction optionalCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Whether a browser Origin names the same host as the request.\n * @param origin - the Origin header value.\n * @param host - the Host header value.\n * @returns whether the request is same-origin.\n */\nfunction sameHost(origin: string, host: string | undefined): boolean {\n if (typeof host !== 'string') return false\n try {\n return new URL(origin).host === host\n } catch {\n return false\n }\n}\n\n/**\n * Read a bounded JSON body.\n * @param req - the request.\n * @param limit - largest accepted body in bytes.\n * @returns the decoded body.\n */\nasync function readJson(req: IncomingMessage, limit: number): Promise<unknown> {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n size += chunk.length\n if (size > limit) throw new RequestError('INVALID_REQUEST', 'the request body is too large')\n chunks.push(chunk)\n }\n const text = Buffer.concat(chunks).toString('utf8')\n if (text.trim().length === 0) return {}\n try {\n return JSON.parse(text)\n } catch {\n throw new RequestError('INVALID_REQUEST', 'the request body is not valid JSON')\n }\n}\n\n/**\n * Write one JSON response.\n * @param res - the response.\n * @param status - HTTP status.\n * @param body - JSON-serializable body.\n */\nfunction writeJson(res: ServerResponse, status: number, body: unknown): void {\n const text = JSON.stringify(body)\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': Buffer.byteLength(text),\n 'cache-control': 'no-store',\n })\n res.end(text)\n}\n\n/**\n * The first non-empty line of Git's output, for a one-line diagnostic.\n * @param text - raw output.\n * @returns the first meaningful line.\n */\nfunction firstLine(text: unknown): string {\n return String(text ?? '').split(/\\r?\\n/).map(line => line.trim()).find(line => line.length > 0) ?? 'no diagnostic'\n}\n\n/**\n * Bound raw output attached to a failure report.\n * @param text - raw output or detail.\n * @returns at most 2000 characters, or null.\n */\nfunction excerpt(text: unknown): string | null {\n if (typeof text !== 'string' || text.length === 0) return null\n return text.length <= 2000 ? text : `${text.slice(0, 2000)}…`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,UAAwD,OAAO,OAAO;CACjF,GAAG,OAAO,YAAY;EACpB;EAAW;EAAiB;EAAkB;EAAkB;EAChE;EAAoC;EAAc;EAAyB;EAC3E;EAA2B;EAAc;EAAoB;EA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