@cam5/baby-bird 0.1.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/README.md +205 -0
- package/dist/chunk-RWSCST2I.js +1753 -0
- package/dist/chunk-RWSCST2I.js.map +1 -0
- package/dist/cli.js +326 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +648 -0
- package/dist/index.js +107 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/schema.ts","../src/core/errors.ts","../src/core/config.ts","../src/core/cache.ts","../src/core/json.ts","../src/git/parse.ts","../src/core/materialize.ts","../src/core/prompt/template.ts","../src/core/prompt/build.ts","../src/codehost/gh.ts","../src/codehost/none.ts","../src/codehost/index.ts","../src/git/exec.ts","../src/git/diff.ts","../src/git/range.ts","../src/llm/command.ts","../src/llm/index.ts","../src/core/tour.ts","../src/render/cli.ts","../src/render/pager.ts"],"sourcesContent":["import { z } from 'zod';\n\n/** What the model must return. Excerpts are references into the diff we sent. */\nexport const LlmExcerptRefSchema = z.object({\n hunk: z.string().min(1),\n /** Optional [start, end] range of new-file line numbers to narrow the hunk. */\n lines: z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()]).optional(),\n note: z.string().optional(),\n});\n\nexport const LlmSectionSchema = z.object({\n title: z.string().min(1),\n description: z.string(),\n files: z.array(z.string()).optional(),\n excerpts: z.array(LlmExcerptRefSchema).optional(),\n});\n\nexport const LlmTourOutputSchema = z.object({\n title: z.string().min(1),\n summary: z.string(),\n sections: z.array(LlmSectionSchema).min(1),\n});\n\nexport type LlmTourOutput = z.infer<typeof LlmTourOutputSchema>;\nexport type LlmSection = z.infer<typeof LlmSectionSchema>;\nexport type LlmExcerptRef = z.infer<typeof LlmExcerptRefSchema>;\n\n/** Persisted Tour, validated when read back from the cache. */\nconst HunkLineSchema = z.object({\n type: z.enum(['add', 'del', 'ctx']),\n oldNo: z.number().int().optional(),\n newNo: z.number().int().optional(),\n text: z.string(),\n});\n\nconst StatsSchema = z.object({\n files: z.number().int(),\n additions: z.number().int(),\n deletions: z.number().int(),\n});\n\nconst TourSourceSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('range'),\n base: z.string(),\n head: z.string(),\n baseSha: z.string(),\n headSha: z.string(),\n mergeBase: z.string().optional(),\n resolvedBy: z.enum(['explicit', 'pull-request', 'ancestor-branch', 'default-branch']),\n }),\n z.object({\n kind: z.literal('working'),\n headSha: z.string(),\n staged: z.boolean(),\n resolvedBy: z.enum(['explicit', 'dirty-tree']),\n }),\n]);\n\nexport const TourSchema = z.object({\n version: z.literal(1),\n generatedAt: z.string(),\n source: TourSourceSchema,\n generator: z.object({ preset: z.string().nullable(), command: z.array(z.string()) }),\n pullRequest: z.object({ number: z.number().int(), title: z.string(), url: z.string() }).optional(),\n title: z.string(),\n summary: z.string(),\n stats: StatsSchema,\n sections: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n files: z.array(z.string()),\n stats: StatsSchema,\n excerpts: z.array(\n z.object({\n file: z.string(),\n hunkId: z.string(),\n note: z.string().optional(),\n oldStart: z.number().int(),\n newStart: z.number().int(),\n lines: z.array(HunkLineSchema),\n }),\n ),\n }),\n ),\n});\n\nexport function formatIssues(error: z.ZodError): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.length ? issue.path.map(String).join('.') : '(root)';\n return `${path}: ${issue.message}`;\n })\n .join('; ');\n}\n","export class BbError extends Error {\n readonly exitCode: number;\n readonly hint: string | undefined;\n\n constructor(message: string, opts: { exitCode?: number; hint?: string; cause?: unknown } = {}) {\n super(message, opts.cause === undefined ? undefined : { cause: opts.cause });\n this.name = new.target.name;\n this.exitCode = opts.exitCode ?? 1;\n this.hint = opts.hint;\n }\n}\n\nexport class UsageError extends BbError {\n constructor(message: string, hint?: string) {\n super(message, { exitCode: 2, hint });\n }\n}\n\nexport class ConfigError extends BbError {\n constructor(message: string, hint?: string) {\n super(message, { exitCode: 2, hint });\n }\n}\n\nexport class NotARepoError extends BbError {\n constructor(cwd: string) {\n super(`Not a git repository: ${cwd}`, { exitCode: 3, hint: 'Run bb inside a git repository, or pass --cwd <dir>.' });\n }\n}\n\nexport class GitError extends BbError {\n constructor(message: string, opts: { hint?: string; cause?: unknown } = {}) {\n super(message, { exitCode: 3, ...opts });\n }\n}\n\nexport class NoChangesError extends BbError {\n constructor(message: string, hint?: string) {\n super(message, { exitCode: 3, hint });\n }\n}\n\nexport class LlmFailedError extends BbError {\n constructor(message: string, opts: { hint?: string; cause?: unknown } = {}) {\n super(message, { exitCode: 4, ...opts });\n }\n}\n\nexport class BadLlmOutputError extends BbError {\n readonly raw: string;\n\n constructor(message: string, raw: string, hint?: string) {\n super(message, { exitCode: 5, hint });\n this.raw = raw;\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { ConfigError } from './errors.js';\nimport { formatIssues } from './schema.js';\n\n// ---------------------------------------------------------------------------\n// LLM presets\n// ---------------------------------------------------------------------------\n\nexport type PromptVia = 'stdin' | 'arg';\n\nexport interface LlmPreset {\n /** argv; when promptVia is \"arg\", any \"{prompt}\" token is replaced with the prompt. */\n command: string[];\n promptVia?: PromptVia;\n description?: string;\n}\n\n/**\n * Claude Code in print mode, stripped down to behave like a plain completion:\n * no tools, no session persistence, and no settings/CLAUDE.md from the cwd.\n * (--bare would also skip keychain reads, which breaks keychain-based logins.)\n */\nconst CLAUDE_BASE = ['claude', '-p', '--no-session-persistence', '--setting-sources', '', '--tools', ''];\n\nexport const BUILTIN_PRESETS: Readonly<Record<string, LlmPreset>> = Object.freeze({\n claude: {\n command: [...CLAUDE_BASE],\n description: 'Claude Code CLI with its default model',\n },\n 'claude-sonnet': {\n command: [...CLAUDE_BASE, '--model', 'sonnet', '--effort', 'high'],\n description: 'Claude Code CLI, Sonnet at high effort',\n },\n 'claude-opus': {\n command: [...CLAUDE_BASE, '--model', 'opus', '--effort', 'high'],\n description: 'Claude Code CLI, Opus at high effort',\n },\n 'claude-fable': {\n command: [...CLAUDE_BASE, '--model', 'fable', '--effort', 'high'],\n description: 'Claude Code CLI, Fable at high effort',\n },\n 'claude-haiku': {\n command: [...CLAUDE_BASE, '--model', 'haiku'],\n description: 'Claude Code CLI, Haiku (fast and cheap)',\n },\n llm: {\n command: ['llm'],\n description: \"Simon Willison's llm CLI with its default model\",\n },\n});\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst PromptViaSchema = z.enum(['stdin', 'arg']);\n\nexport const LlmPresetSchema = z.object({\n command: z.array(z.string()).min(1),\n promptVia: PromptViaSchema.optional(),\n description: z.string().optional(),\n});\n\nexport const ConfigSchema = z.object({\n llm: z.object({\n preset: z.string().min(1),\n presets: z.record(z.string(), LlmPresetSchema),\n args: z.array(z.string()),\n command: z.array(z.string()).min(1).nullable(),\n promptVia: PromptViaSchema.nullable(),\n timeoutMs: z.number().int().positive(),\n maxPromptBytes: z.number().int().positive(),\n env: z.record(z.string(), z.string()),\n }),\n codehost: z.object({\n provider: z.enum(['gh', 'none']),\n }),\n git: z.object({\n defaultBranch: z.string().nullable(),\n exclude: z.array(z.string()),\n }),\n render: z.object({\n color: z.enum(['auto', 'always', 'never']),\n pager: z.enum(['auto', 'always', 'never']),\n maxExcerptLines: z.number().int().positive(),\n width: z.number().int().positive().nullable(),\n }),\n cache: z.object({\n enabled: z.boolean(),\n dir: z.string().nullable(),\n }),\n});\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\nexport const PartialConfigSchema = z.object({\n llm: ConfigSchema.shape.llm.partial().optional(),\n codehost: ConfigSchema.shape.codehost.partial().optional(),\n git: ConfigSchema.shape.git.partial().optional(),\n render: ConfigSchema.shape.render.partial().optional(),\n cache: ConfigSchema.shape.cache.partial().optional(),\n});\n\nexport type PartialConfig = z.infer<typeof PartialConfigSchema>;\n\nexport const DEFAULT_CONFIG: Config = {\n llm: {\n preset: 'claude',\n presets: {},\n args: [],\n command: null,\n promptVia: null,\n timeoutMs: 180_000,\n maxPromptBytes: 200_000,\n env: {},\n },\n codehost: { provider: 'gh' },\n git: {\n defaultBranch: null,\n exclude: [\n '**/pnpm-lock.yaml',\n '**/package-lock.json',\n '**/yarn.lock',\n '**/Cargo.lock',\n '**/*.min.*',\n '**/dist/**',\n '**/*.snap',\n '**/*.map',\n ],\n },\n render: { color: 'auto', pager: 'auto', maxExcerptLines: 60, width: null },\n cache: { enabled: true, dir: null },\n};\n\n// ---------------------------------------------------------------------------\n// Paths\n// ---------------------------------------------------------------------------\n\nexport function userConfigPath(env: NodeJS.ProcessEnv = process.env): string {\n const base = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim() !== '' ? env.XDG_CONFIG_HOME : join(homedir(), '.config');\n return join(base, 'baby-bird', 'config.json');\n}\n\nexport function defaultCacheDir(env: NodeJS.ProcessEnv = process.env): string {\n const base = env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.trim() !== '' ? env.XDG_CACHE_HOME : join(homedir(), '.cache');\n return join(base, 'baby-bird');\n}\n\nexport function projectConfigPath(gitRoot: string): string {\n return join(gitRoot, '.baby-bird', 'config.json');\n}\n\n// ---------------------------------------------------------------------------\n// Loading\n// ---------------------------------------------------------------------------\n\nexport type LayerName = 'defaults' | 'user' | 'project' | 'env' | 'flags';\n\nexport interface ConfigLayer {\n name: LayerName;\n /** File path for file-backed layers. */\n path?: string;\n /** Whether the layer contributed anything (file existed, env vars set, flags passed). */\n found: boolean;\n /** Short human description of what was applied (e.g. env var names). */\n detail?: string;\n data: PartialConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Git root for project-level config; null/undefined skips the project layer. */\n gitRoot?: string | null;\n env?: NodeJS.ProcessEnv;\n /** CLI flag overrides, applied last. */\n overrides?: PartialConfig;\n}\n\nexport interface LoadedConfig {\n config: Config;\n layers: ConfigLayer[];\n cacheDir: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Objects merge recursively; arrays and scalars replace. `undefined` never overrides. */\nexport function deepMerge<T>(base: T, patch: unknown): T {\n if (!isPlainObject(base) || !isPlainObject(patch)) {\n return (patch === undefined ? base : patch) as T;\n }\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue;\n const existing = out[key];\n out[key] = isPlainObject(existing) && isPlainObject(value) ? deepMerge(existing, value) : value;\n }\n return out as T;\n}\n\nasync function readFileLayer(name: LayerName, path: string): Promise<ConfigLayer> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { name, path, found: false, data: {} };\n }\n throw new ConfigError(`Could not read ${path}: ${(err as Error).message}`);\n }\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (err) {\n throw new ConfigError(`Invalid JSON in ${path}: ${(err as Error).message}`);\n }\n const parsed = PartialConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new ConfigError(`Invalid config in ${path}: ${formatIssues(parsed.error)}`);\n }\n return { name, path, found: true, data: parsed.data };\n}\n\nconst TRUTHY = new Set(['1', 'true', 'yes', 'on']);\n\nexport function envLayer(env: NodeJS.ProcessEnv): ConfigLayer {\n const data: PartialConfig = {};\n const applied: string[] = [];\n const llm: NonNullable<PartialConfig['llm']> = {};\n\n if (env.BB_PRESET) {\n llm.preset = env.BB_PRESET;\n applied.push('BB_PRESET');\n }\n if (env.BB_LLM_COMMAND) {\n const argv = shellSplit(env.BB_LLM_COMMAND);\n if (argv.length === 0) throw new ConfigError('BB_LLM_COMMAND is set but empty');\n llm.command = argv;\n applied.push('BB_LLM_COMMAND');\n }\n if (Object.keys(llm).length) data.llm = llm;\n\n if (env.BB_CODEHOST) {\n const provider = env.BB_CODEHOST as Config['codehost']['provider'];\n data.codehost = { provider };\n applied.push('BB_CODEHOST');\n }\n const cache: NonNullable<PartialConfig['cache']> = {};\n if (env.BB_CACHE_DIR) {\n cache.dir = env.BB_CACHE_DIR;\n applied.push('BB_CACHE_DIR');\n }\n if (env.BB_NO_CACHE !== undefined && TRUTHY.has(env.BB_NO_CACHE.toLowerCase())) {\n cache.enabled = false;\n applied.push('BB_NO_CACHE');\n }\n if (Object.keys(cache).length) data.cache = cache;\n\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== '') {\n data.render = { color: 'never' };\n applied.push('NO_COLOR');\n }\n\n return { name: 'env', found: applied.length > 0, detail: applied.join(', '), data };\n}\n\nexport async function loadConfig(opts: LoadConfigOptions = {}): Promise<LoadedConfig> {\n const env = opts.env ?? process.env;\n const layers: ConfigLayer[] = [{ name: 'defaults', found: true, data: DEFAULT_CONFIG }];\n\n layers.push(await readFileLayer('user', userConfigPath(env)));\n if (opts.gitRoot) {\n layers.push(await readFileLayer('project', projectConfigPath(opts.gitRoot)));\n }\n layers.push(envLayer(env));\n if (opts.overrides) {\n const found = Object.keys(opts.overrides).length > 0;\n layers.push({ name: 'flags', found, data: opts.overrides });\n }\n\n let merged: unknown = {};\n for (const layer of layers) merged = deepMerge(merged, layer.data);\n\n const parsed = ConfigSchema.safeParse(merged);\n if (!parsed.success) {\n throw new ConfigError(`Invalid configuration: ${formatIssues(parsed.error)}`);\n }\n const config = parsed.data;\n return { config, layers, cacheDir: config.cache.dir ?? defaultCacheDir(env) };\n}\n\n// ---------------------------------------------------------------------------\n// LLM resolution\n// ---------------------------------------------------------------------------\n\nexport interface ResolvedLlm {\n command: string[];\n promptVia: PromptVia;\n /** Preset name, or null when a custom command is in use. */\n preset: string | null;\n timeoutMs: number;\n maxPromptBytes: number;\n env: Record<string, string>;\n}\n\nexport function allPresets(config: Config): Record<string, LlmPreset> {\n return { ...BUILTIN_PRESETS, ...config.llm.presets };\n}\n\nexport function resolveLlm(config: Config): ResolvedLlm {\n const { llm } = config;\n const common = { timeoutMs: llm.timeoutMs, maxPromptBytes: llm.maxPromptBytes, env: llm.env };\n\n if (llm.command) {\n return { command: [...llm.command, ...llm.args], promptVia: llm.promptVia ?? 'stdin', preset: null, ...common };\n }\n\n const presets = allPresets(config);\n const preset = presets[llm.preset];\n if (!preset) {\n const names = Object.keys(presets).sort().join(', ');\n throw new ConfigError(`Unknown LLM preset \"${llm.preset}\"`, `Available presets: ${names}. Define your own under llm.presets, or set llm.command.`);\n }\n return {\n command: [...preset.command, ...llm.args],\n promptVia: llm.promptVia ?? preset.promptVia ?? 'stdin',\n preset: llm.preset,\n ...common,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------\n\n/** Minimal POSIX-ish shell splitting: whitespace separated, single/double quotes, backslash escapes. */\nexport function shellSplit(input: string): string[] {\n const out: string[] = [];\n let cur = '';\n let inToken = false;\n let quote: '\"' | \"'\" | null = null;\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]!;\n if (quote === \"'\") {\n if (ch === \"'\") quote = null;\n else cur += ch;\n continue;\n }\n if (quote === '\"') {\n if (ch === '\"') quote = null;\n else if (ch === '\\\\' && i + 1 < input.length && '\"\\\\$`'.includes(input[i + 1]!)) cur += input[++i];\n else cur += ch;\n continue;\n }\n if (ch === \"'\" || ch === '\"') {\n quote = ch;\n inToken = true;\n } else if (ch === '\\\\' && i + 1 < input.length) {\n cur += input[++i];\n inToken = true;\n } else if (/\\s/.test(ch)) {\n if (inToken) {\n out.push(cur);\n cur = '';\n inToken = false;\n }\n } else {\n cur += ch;\n inToken = true;\n }\n }\n if (quote) throw new ConfigError(`Unterminated quote in command: ${input}`);\n if (inToken) out.push(cur);\n return out;\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { TourSchema } from './schema.js';\nimport type { Tour } from './types.js';\n\nexport interface CacheEntry {\n key: string;\n path: string;\n tour: Tour;\n}\n\n/** Content-addressed store of generated tours: <dir>/tours/<sha256>.json */\nexport class TourCache {\n readonly toursDir: string;\n\n constructor(readonly dir: string) {\n this.toursDir = join(dir, 'tours');\n }\n\n static keyFor(prompt: string, command: string[]): string {\n return createHash('sha256')\n .update(createHash('sha256').update(prompt).digest('hex'))\n .update('\\0')\n .update(JSON.stringify(command))\n .digest('hex');\n }\n\n pathFor(key: string): string {\n return join(this.toursDir, `${key}.json`);\n }\n\n async get(key: string): Promise<Tour | null> {\n let text: string;\n try {\n text = await readFile(this.pathFor(key), 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n try {\n const parsed = TourSchema.safeParse(JSON.parse(text));\n return parsed.success ? (parsed.data as Tour) : null;\n } catch {\n return null;\n }\n }\n\n async put(key: string, tour: Tour): Promise<string> {\n await mkdir(this.toursDir, { recursive: true });\n const final = this.pathFor(key);\n const tmp = `${final}.${process.pid}.${Date.now()}.tmp`;\n await writeFile(tmp, JSON.stringify(tour, null, 2) + '\\n', 'utf8');\n await rename(tmp, final);\n return final;\n }\n\n async list(): Promise<CacheEntry[]> {\n let names: string[];\n try {\n names = await readdir(this.toursDir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const entries: CacheEntry[] = [];\n for (const name of names) {\n if (!name.endsWith('.json')) continue;\n const key = name.slice(0, -'.json'.length);\n const tour = await this.get(key);\n if (tour) entries.push({ key, path: this.pathFor(key), tour });\n }\n entries.sort((a, b) => b.tour.generatedAt.localeCompare(a.tour.generatedAt));\n return entries;\n }\n\n async clear(): Promise<number> {\n const entries = await this.list();\n await rm(this.toursDir, { recursive: true, force: true });\n return entries.length;\n }\n}\n","import { BadLlmOutputError } from './errors.js';\n\n/**\n * Pull a JSON object out of model output that may be wrapped in prose, code\n * fences, or a CLI's own JSON envelope (e.g. `claude --output-format json`).\n */\nexport function extractJson(text: string): unknown {\n const trimmed = text.trim();\n if (!trimmed) throw new BadLlmOutputError('The model returned empty output.', text);\n\n const candidates: string[] = [trimmed];\n for (const m of trimmed.matchAll(/```(?:json|JSON)?\\s*\\n?([\\s\\S]*?)```/g)) candidates.push(m[1]!.trim());\n const balanced = firstBalancedObject(trimmed);\n if (balanced) candidates.push(balanced);\n const first = trimmed.indexOf('{');\n const last = trimmed.lastIndexOf('}');\n if (first !== -1 && last > first) candidates.push(trimmed.slice(first, last + 1));\n\n for (const c of candidates) {\n const parsed = tryParse(c) ?? tryParse(repairUnescapedQuotes(c));\n if (parsed === undefined) continue;\n return unwrapEnvelope(parsed);\n }\n throw new BadLlmOutputError('Could not find a JSON object in the model output.', text, 'Run with --debug to see the raw output.');\n}\n\n/**\n * Escape double quotes that appear inside JSON strings without a backslash, a\n * common model slip when prose mentions flags like `--tools \"\"`. A quote is\n * treated as closing only when the next non-blank character could legally\n * follow a string (, } ] : or end of input).\n */\nexport function repairUnescapedQuotes(s: string): string {\n let out = '';\n let inString = false;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i]!;\n if (!inString) {\n if (ch === '\"') inString = true;\n out += ch;\n continue;\n }\n if (ch === '\\\\') {\n out += ch + (s[i + 1] ?? '');\n i++;\n continue;\n }\n if (ch === '\"') {\n let j = i + 1;\n while (j < s.length && (s[j] === ' ' || s[j] === '\\t' || s[j] === '\\r' || s[j] === '\\n')) j++;\n const next = s[j];\n if (next === undefined || next === ',' || next === '}' || next === ']' || next === ':') {\n inString = false;\n out += ch;\n } else {\n out += '\\\\\"';\n }\n continue;\n }\n out += ch;\n }\n return out;\n}\n\nfunction tryParse(s: string): unknown {\n try {\n return JSON.parse(s);\n } catch {\n return undefined;\n }\n}\n\n/** If the object looks like a CLI envelope ({ result: \"...\" }) rather than a tour, dig into it. */\nfunction unwrapEnvelope(value: unknown): unknown {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;\n const obj = value as Record<string, unknown>;\n if ('sections' in obj) return obj;\n for (const key of ['result', 'response', 'content', 'text', 'output']) {\n const inner = obj[key];\n if (typeof inner === 'string' && inner.includes('{')) {\n try {\n return extractJson(inner);\n } catch {\n // keep looking\n }\n }\n if (typeof inner === 'object' && inner !== null) return unwrapEnvelope(inner);\n }\n return obj;\n}\n\nfunction firstBalancedObject(s: string): string | null {\n const start = s.indexOf('{');\n if (start === -1) return null;\n let depth = 0;\n let inString = false;\n for (let i = start; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === '\\\\') i++;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') inString = true;\n else if (ch === '{') depth++;\n else if (ch === '}') {\n depth--;\n if (depth === 0) return s.slice(start, i + 1);\n }\n }\n return null;\n}\n","import type { DiffFile, FileStatus, Hunk, HunkLine, ParsedDiff } from '../core/types.js';\n\nconst HUNK_RE = /^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@ ?(.*)$/;\n\n/** Undo git's C-style quoting of unusual paths (\"a/we ird\\tname\"). */\nfunction unquote(path: string): string {\n if (!path.startsWith('\"') || !path.endsWith('\"')) return path;\n const inner = path.slice(1, -1);\n return inner.replace(/\\\\([abfnrtv\\\\\"]|[0-7]{3})/g, (_, esc: string) => {\n switch (esc) {\n case 'a': return '\\x07';\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n case '\\\\': return '\\\\';\n case '\"': return '\"';\n default: return String.fromCharCode(parseInt(esc, 8));\n }\n });\n}\n\nfunction stripPrefix(path: string, prefix: 'a/' | 'b/'): string {\n const p = unquote(path);\n return p.startsWith(prefix) ? p.slice(2) : p;\n}\n\n/** Best-effort split of the \"a/X b/Y\" part of a `diff --git` line. */\nfunction splitGitHeader(rest: string): { oldPath: string; newPath: string } {\n if (rest.startsWith('\"')) {\n // Quoted form: \"a/x\" \"b/y\"\n const m = /^(\"(?:[^\"\\\\]|\\\\.)*\") (\"(?:[^\"\\\\]|\\\\.)*\")$/.exec(rest);\n if (m) return { oldPath: stripPrefix(m[1]!, 'a/'), newPath: stripPrefix(m[2]!, 'b/') };\n }\n // Prefer a split where both sides are identical (the common, unrenamed case).\n let idx = rest.indexOf(' b/');\n while (idx !== -1) {\n const left = rest.slice(0, idx);\n const right = rest.slice(idx + 1);\n if (left.startsWith('a/') && right.startsWith('b/') && left.slice(2) === right.slice(2)) {\n return { oldPath: left.slice(2), newPath: right.slice(2) };\n }\n idx = rest.indexOf(' b/', idx + 1);\n }\n const first = rest.indexOf(' b/');\n if (first === -1) return { oldPath: rest, newPath: rest };\n return { oldPath: stripPrefix(rest.slice(0, first), 'a/'), newPath: stripPrefix(rest.slice(first + 1), 'b/') };\n}\n\ninterface PendingFile {\n oldPath: string;\n newPath: string;\n status: FileStatus;\n binary: boolean;\n hunks: Hunk[];\n}\n\n/**\n * Parse `git diff` output (with a/ b/ prefixes) into files, hunks and numbered lines.\n * Tolerant of mode-only changes, pure renames, binary files and \"\\ No newline\" markers.\n */\nexport function parseDiff(raw: string): ParsedDiff {\n const lines = raw.split('\\n');\n const files: DiffFile[] = [];\n let pending: PendingFile | null = null;\n let hunk: Hunk | null = null;\n let oldNo = 0;\n let newNo = 0;\n\n const flush = () => {\n if (!pending) return;\n const id = `F${files.length + 1}`;\n let additions = 0;\n let deletions = 0;\n pending.hunks.forEach((h, i) => {\n h.id = `${id}.H${i + 1}`;\n for (const l of h.lines) {\n if (l.type === 'add') additions++;\n else if (l.type === 'del') deletions++;\n }\n });\n const status = pending.status;\n const path = status === 'deleted' ? pending.oldPath : pending.newPath;\n const file: DiffFile = {\n id,\n path,\n status,\n binary: pending.binary,\n additions,\n deletions,\n hunks: pending.hunks,\n };\n if (status === 'renamed') file.oldPath = pending.oldPath;\n files.push(file);\n pending = null;\n hunk = null;\n };\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n\n if (line.startsWith('diff --git ')) {\n flush();\n const { oldPath, newPath } = splitGitHeader(line.slice('diff --git '.length));\n pending = { oldPath, newPath, status: 'modified', binary: false, hunks: [] };\n continue;\n }\n if (!pending) continue;\n\n if (hunk) {\n const c = line[0];\n if (c === ' ' || c === '+' || c === '-' || (line === '' && i < lines.length - 1 && hunkHasRoom(hunk))) {\n const text = line.slice(1);\n const entry: HunkLine = c === '+' ? { type: 'add', newNo: newNo++, text }\n : c === '-' ? { type: 'del', oldNo: oldNo++, text }\n : { type: 'ctx', oldNo: oldNo++, newNo: newNo++, text: c === undefined ? '' : text };\n hunk.lines.push(entry);\n continue;\n }\n if (line.startsWith('\\\\')) continue; // \"\\"\n hunk = null; // fall through: this line belongs to the file header of the next section\n }\n\n const hm = HUNK_RE.exec(line);\n if (hm) {\n hunk = {\n id: '',\n oldStart: Number(hm[1]),\n oldLines: hm[2] === undefined ? 1 : Number(hm[2]),\n newStart: Number(hm[3]),\n newLines: hm[4] === undefined ? 1 : Number(hm[4]),\n header: (hm[5] ?? '').trim(),\n lines: [],\n };\n oldNo = hunk.oldStart;\n newNo = hunk.newStart;\n pending.hunks.push(hunk);\n continue;\n }\n\n if (line.startsWith('--- ')) {\n const p = line.slice(4);\n if (p === '/dev/null') pending.status = 'added';\n else pending.oldPath = stripPrefix(p, 'a/');\n continue;\n }\n if (line.startsWith('+++ ')) {\n const p = line.slice(4);\n if (p === '/dev/null') pending.status = 'deleted';\n else pending.newPath = stripPrefix(p, 'b/');\n continue;\n }\n if (line.startsWith('rename from ')) {\n pending.oldPath = unquote(line.slice('rename from '.length));\n pending.status = 'renamed';\n continue;\n }\n if (line.startsWith('rename to ')) {\n pending.newPath = unquote(line.slice('rename to '.length));\n pending.status = 'renamed';\n continue;\n }\n if (line.startsWith('new file mode')) {\n pending.status = 'added';\n continue;\n }\n if (line.startsWith('deleted file mode')) {\n pending.status = 'deleted';\n continue;\n }\n if (line.startsWith('Binary files ') || line.startsWith('GIT binary patch')) {\n pending.binary = true;\n continue;\n }\n // index, similarity, old/new mode, copy from/to: ignored\n }\n flush();\n return { files };\n}\n\nfunction hunkHasRoom(h: Hunk): boolean {\n // An empty line inside a hunk (a context line whose content is empty and whose\n // leading space was stripped by some tool) only counts while the hunk is incomplete.\n let o = 0;\n let n = 0;\n for (const l of h.lines) {\n if (l.type !== 'add') o++;\n if (l.type !== 'del') n++;\n }\n return o < h.oldLines || n < h.newLines;\n}\n\nexport function diffStats(diff: ParsedDiff): { files: number; additions: number; deletions: number } {\n return diff.files.reduce(\n (acc, f) => ({ files: acc.files + 1, additions: acc.additions + f.additions, deletions: acc.deletions + f.deletions }),\n { files: 0, additions: 0, deletions: 0 },\n );\n}\n","import { diffStats } from '../git/parse.js';\nimport type { LlmTourOutput } from './schema.js';\nimport type { DiffFile, Excerpt, Hunk, HunkLine, ParsedDiff, Section, Tour, TourGenerator, TourSource, TourStats, PullRequestInfo } from './types.js';\n\nexport interface MaterializeInput {\n output: LlmTourOutput;\n diff: ParsedDiff;\n source: TourSource;\n generator: TourGenerator;\n pullRequest?: PullRequestInfo;\n maxExcerptLines: number;\n warn?: (msg: string) => void;\n now?: () => Date;\n}\n\nexport const OTHER_CHANGES_TITLE = 'Other changes';\n\n/**\n * Turn the model's section/reference output into a self-contained Tour by\n * slicing excerpts out of the real diff and computing all counts locally.\n */\nexport function materializeTour(input: MaterializeInput): Tour {\n const warn = input.warn ?? (() => {});\n const byPath = new Map<string, DiffFile>();\n const byOldPath = new Map<string, DiffFile>();\n const hunks = new Map<string, { file: DiffFile; hunk: Hunk }>();\n for (const f of input.diff.files) {\n byPath.set(f.path, f);\n if (f.oldPath) byOldPath.set(f.oldPath, f);\n for (const h of f.hunks) hunks.set(h.id, { file: f, hunk: h });\n }\n const lookupFile = (p: string) => byPath.get(p) ?? byPath.get(p.replace(/^\\.\\//, '')) ?? byOldPath.get(p);\n\n const claimed = new Set<string>();\n const sections: Section[] = [];\n\n for (const s of input.output.sections) {\n const files = new Set<string>();\n for (const p of s.files ?? []) {\n const f = lookupFile(p);\n if (f) files.add(f.path);\n else warn(`Section \"${s.title}\" references unknown file ${p}; ignoring`);\n }\n const excerpts: Excerpt[] = [];\n for (const ref of s.excerpts ?? []) {\n const hit = hunks.get(ref.hunk.trim());\n if (!hit) {\n warn(`Section \"${s.title}\" references unknown hunk ${ref.hunk}; ignoring`);\n continue;\n }\n files.add(hit.file.path);\n const lines = sliceHunk(hit.hunk, ref.lines, input.maxExcerptLines);\n const excerpt: Excerpt = {\n file: hit.file.path,\n hunkId: hit.hunk.id,\n oldStart: lines[0]?.oldNo ?? firstOld(lines) ?? hit.hunk.oldStart,\n newStart: lines[0]?.newNo ?? firstNew(lines) ?? hit.hunk.newStart,\n lines,\n };\n if (ref.note?.trim()) excerpt.note = ref.note.trim();\n excerpts.push(excerpt);\n }\n const fileList = [...files];\n for (const p of fileList) claimed.add(p);\n sections.push({\n id: `s${sections.length + 1}`,\n title: s.title.trim(),\n description: s.description.trim(),\n files: fileList,\n stats: statsFor(fileList, byPath),\n excerpts,\n });\n }\n\n const unclaimed = input.diff.files.map((f) => f.path).filter((p) => !claimed.has(p));\n if (unclaimed.length) {\n sections.push({\n id: `s${sections.length + 1}`,\n title: OTHER_CHANGES_TITLE,\n description: 'Files in this change that the sections above do not cover.',\n files: unclaimed,\n stats: statsFor(unclaimed, byPath),\n excerpts: [],\n });\n }\n\n const tour: Tour = {\n version: 1,\n generatedAt: (input.now?.() ?? new Date()).toISOString(),\n source: input.source,\n generator: input.generator,\n title: input.output.title.trim(),\n summary: input.output.summary.trim(),\n stats: diffStats(input.diff),\n sections,\n };\n if (input.pullRequest) {\n tour.pullRequest = { number: input.pullRequest.number, title: input.pullRequest.title, url: input.pullRequest.url };\n }\n return tour;\n}\n\nfunction statsFor(paths: string[], byPath: Map<string, DiffFile>): TourStats {\n let additions = 0;\n let deletions = 0;\n for (const p of paths) {\n const f = byPath.get(p);\n if (!f) continue;\n additions += f.additions;\n deletions += f.deletions;\n }\n return { files: paths.length, additions, deletions };\n}\n\nfunction firstOld(lines: HunkLine[]): number | undefined {\n return lines.find((l) => l.oldNo !== undefined)?.oldNo;\n}\nfunction firstNew(lines: HunkLine[]): number | undefined {\n return lines.find((l) => l.newNo !== undefined)?.newNo;\n}\n\n/**\n * Narrow a hunk to a [start, end] range of new-file line numbers. Deleted lines\n * are attributed to the new-file position where they would have been, so a\n * range keeps the removals that sit inside it.\n */\nexport function sliceHunk(hunk: Hunk, range: [number, number] | undefined, maxLines: number): HunkLine[] {\n let lines = hunk.lines;\n if (range) {\n const [a, b] = range;\n const start = Math.min(a, b);\n const end = Math.max(a, b);\n let cursor = hunk.newStart;\n const picked: HunkLine[] = [];\n for (const l of lines) {\n const pos = l.type === 'del' ? cursor : (l.newNo ?? cursor);\n if (l.type !== 'del') cursor = (l.newNo ?? cursor) + 1;\n if (pos >= start && pos <= end) picked.push(l);\n }\n if (picked.length > 0) lines = picked;\n }\n return lines.slice(0, maxLines);\n}\n","/** Bump whenever the prompt text or its assembly changes materially; it is part of the cache key. */\nexport const PROMPT_VERSION = 2;\n\nexport const PROMPT_HEADER = `You are writing a guided code tour of a change for a reviewer who has not seen it before.\n\nA code tour is an ordered list of sections. Each section explains one coherent part of the change: what it does, why it is there, and how it connects to the rest. Sections are ordered the way a reader should encounter them: start with the change that makes everything else make sense (a new type, an interface, a data model, a configuration knob), then the code that builds on it, then wiring and plumbing, then tests and housekeeping.\n\n## Rules\n\n- Produce between 2 and 8 sections. Fewer is better when the change is small; never pad.\n- Group by concept, not by file. A section may span many files, and a file may appear in several sections.\n- Every file in the change must be claimed by at least one section. Put unrelated housekeeping (formatting, generated code, renames, dependency bumps) in one short final section rather than sprinkling it around.\n- A section's description is 2 to 5 sentences of plain prose written for a colleague. Lead with the purpose (why), then what changed, then anything a reviewer should look at carefully: behavior changes, edge cases, risk. Do not narrate line by line and do not restate the diff.\n- Choose 1 to 3 excerpts per section: the hunks that best show the idea. Reference hunks by their id exactly as given (for example \"F2.H1\"). Optionally narrow a hunk with \"lines\": [start, end] using NEW-file line numbers as they appear in the diff. Never quote code in the JSON; the real diff is rendered from your references.\n- Give each excerpt a short \"note\" (under 15 words) saying what to look at.\n- The tour \"title\" is a short imperative phrase naming the change, like a good commit subject. The \"summary\" is 2 to 4 sentences describing the whole change and its motivation.\n- Use the pull request description and commit messages as evidence of intent, but trust the diff over them when they disagree.\n- If parts of the diff were truncated or omitted, still assign those files to sections based on their names and stats, and only reference hunks that were shown.\n- The JSON must be strictly valid. Inside a string, escape double quotes as \\\\\" or use single quotes when mentioning flags, code, or file names.\n\n## Output\n\nRespond with ONLY a JSON object: no prose before or after it, and no code fences.\n\n{\n \"title\": \"Short imperative title\",\n \"summary\": \"What this change does and why.\",\n \"sections\": [\n {\n \"title\": \"Section title\",\n \"description\": \"Why, then what, then what to watch.\",\n \"files\": [\"path/one.ts\", \"path/two.ts\"],\n \"excerpts\": [\n { \"hunk\": \"F1.H2\", \"note\": \"The new interface every provider implements\" },\n { \"hunk\": \"F3.H1\", \"lines\": [40, 58], \"note\": \"Where the fallback kicks in\" }\n ]\n }\n ]\n}\n`;\n\nexport const REPAIR_SUFFIX = (reason: string) => `\n\n---\n\nYour previous response could not be used: ${reason}\n\nRespond again with ONLY the JSON object described above. No prose, no code fences, no comments.`;\n","import type { CommitInfo, DiffFile, Hunk, ParsedDiff, PullRequestInfo, TourSource } from '../types.js';\nimport { diffStats } from '../../git/parse.js';\nimport { PROMPT_HEADER } from './template.js';\n\nexport interface PromptInput {\n source: TourSource;\n branch: string | null;\n diff: ParsedDiff;\n commits: CommitInfo[];\n pullRequest?: PullRequestInfo;\n /** Soft budget for the whole prompt, in bytes. */\n maxBytes: number;\n}\n\nexport interface TruncationReport {\n /** Files whose diff was cut down to the start of their first hunk. */\n truncated: string[];\n /** Files whose diff was left out entirely (names and stats only). */\n omitted: string[];\n}\n\nexport interface BuiltPrompt {\n prompt: string;\n truncation: TruncationReport;\n}\n\nconst KEEP_LINES = 40;\nconst MAX_PR_BODY_BYTES = 12_000;\n\nexport function buildPrompt(input: PromptInput): BuiltPrompt {\n const context = renderContext(input);\n const truncation: TruncationReport = { truncated: [], omitted: [] };\n const blocks = input.diff.files.map((file) => {\n const full = renderFile(file);\n const truncated = file.hunks.length ? renderTruncated(file) : null;\n return {\n file,\n full,\n // Only worth truncating when it actually saves space.\n truncated: truncated && bytes(truncated) < bytes(full) ? truncated : null,\n omitted: renderOmitted(file),\n mode: 'full' as 'full' | 'truncated' | 'omitted',\n };\n });\n const text = (b: (typeof blocks)[number]) => (b.mode === 'full' ? b.full : b.mode === 'truncated' ? b.truncated! : b.omitted);\n const total = () => bytes(diffPreamble(truncation)) + blocks.reduce((n, b) => n + bytes(text(b)), 0);\n const budget = input.maxBytes - bytes(PROMPT_HEADER) - bytes(context) - 8;\n\n if (total() > budget) {\n const bySize = [...blocks].sort((a, b) => bytes(b.full) - bytes(a.full));\n for (const block of bySize) {\n if (total() <= budget) break;\n if (!block.truncated) continue;\n block.mode = 'truncated';\n truncation.truncated.push(block.file.path);\n }\n for (const block of bySize) {\n if (total() <= budget) break;\n if (block.file.hunks.length === 0) continue;\n if (block.mode === 'truncated') truncation.truncated = truncation.truncated.filter((p) => p !== block.file.path);\n block.mode = 'omitted';\n truncation.omitted.push(block.file.path);\n }\n }\n\n const prompt = [PROMPT_HEADER, context, diffPreamble(truncation), ...blocks.map(text)].join('\\n');\n return { prompt, truncation };\n}\n\nfunction bytes(s: string): number {\n return Buffer.byteLength(s, 'utf8');\n}\n\nfunction renderContext(input: PromptInput): string {\n const parts: string[] = ['# The change', ''];\n\n parts.push('## Source');\n parts.push(describeSource(input.source, input.branch));\n parts.push('');\n\n if (input.pullRequest) {\n const pr = input.pullRequest;\n parts.push(`## Pull request #${pr.number}: ${pr.title.trim() || '(untitled)'}`);\n const body = pr.body.trim();\n parts.push(body ? clip(body, MAX_PR_BODY_BYTES) : '(no description)');\n parts.push('');\n }\n\n if (input.commits.length) {\n parts.push('## Commits (oldest first)');\n for (const c of [...input.commits].reverse()) parts.push(`- ${c.subject}`);\n parts.push('');\n }\n\n const stats = diffStats(input.diff);\n parts.push(`## Files (${stats.files} ${stats.files === 1 ? 'file' : 'files'}, +${stats.additions} -${stats.deletions})`);\n const idWidth = Math.max(...input.diff.files.map((f) => f.id.length), 2);\n for (const f of input.diff.files) {\n const status = f.binary ? 'binary' : f.status;\n const name = f.status === 'renamed' && f.oldPath ? `${f.oldPath} -> ${f.path}` : f.path;\n const counts = f.binary ? '' : ` +${f.additions} -${f.deletions}`;\n parts.push(`${f.id.padEnd(idWidth)} ${status.padEnd(8)} ${name}${counts}`);\n }\n parts.push('');\n return parts.join('\\n');\n}\n\nexport function describeSource(source: TourSource, branch: string | null): string {\n if (source.kind === 'working') {\n const what = source.staged ? 'Staged (uncommitted) changes' : 'Uncommitted changes in the working tree';\n return branch ? `${what} on branch ${branch}.` : `${what} (detached HEAD).`;\n }\n const mb = source.mergeBase ? ` (at merge-base ${source.mergeBase.slice(0, 7)})` : '';\n return `${source.head} compared against ${source.base}${mb}.`;\n}\n\nfunction diffPreamble(t: TruncationReport): string {\n const lines = ['## Diff', ''];\n if (t.truncated.length || t.omitted.length) {\n lines.push('Note: to fit the size budget, some diffs below were shortened.');\n if (t.truncated.length) lines.push(`- Truncated (only the shown hunk may be referenced): ${t.truncated.join(', ')}`);\n if (t.omitted.length) lines.push(`- Omitted entirely (assign by name and stats): ${t.omitted.join(', ')}`);\n lines.push('');\n }\n return lines.join('\\n');\n}\n\nfunction fileHeading(file: DiffFile): string {\n const status = file.binary ? 'binary' : file.status;\n const rename = file.status === 'renamed' && file.oldPath ? `, from ${file.oldPath}` : '';\n const counts = file.binary ? '' : `, +${file.additions} -${file.deletions}`;\n return `### ${file.id} ${file.path} (${status}${rename}${counts})`;\n}\n\nfunction renderHunk(hunk: Hunk, limit?: number): string[] {\n const out = [`[${hunk.id}] @@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@${hunk.header ? ' ' + hunk.header : ''}`];\n const lines = limit === undefined ? hunk.lines : hunk.lines.slice(0, limit);\n for (const l of lines) out.push((l.type === 'add' ? '+' : l.type === 'del' ? '-' : ' ') + l.text);\n return out;\n}\n\nfunction renderFile(file: DiffFile): string {\n const out = [fileHeading(file)];\n if (file.binary) out.push('(binary file, no textual diff)');\n else if (file.hunks.length === 0) out.push('(no content changes)');\n else for (const h of file.hunks) out.push(...renderHunk(h));\n out.push('');\n return out.join('\\n');\n}\n\nfunction renderTruncated(file: DiffFile): string {\n const first = file.hunks[0]!;\n const shown = Math.min(KEEP_LINES, first.lines.length);\n const totalLines = file.hunks.reduce((n, h) => n + h.lines.length, 0);\n const out = [fileHeading(file), ...renderHunk(first, shown)];\n out.push(`... [truncated: ${totalLines - shown} more lines across ${file.hunks.length} hunk${file.hunks.length === 1 ? '' : 's'}]`);\n out.push('');\n return out.join('\\n');\n}\n\nfunction renderOmitted(file: DiffFile): string {\n return [fileHeading(file), '(diff omitted for length)', ''].join('\\n');\n}\n\nfunction clip(text: string, maxBytes: number): string {\n if (bytes(text) <= maxBytes) return text;\n let cut = text.slice(0, maxBytes);\n while (bytes(cut) > maxBytes) cut = cut.slice(0, -100);\n return cut + '\\n... [description truncated]';\n}\n","import { execFile } from 'node:child_process';\nimport type { PullRequestInfo } from '../core/types.js';\nimport type { CodeHost } from './provider.js';\n\nconst FIELDS = 'number,title,body,url,baseRefName,headRefName,state';\n\nexport interface GhOptions {\n timeoutMs?: number;\n debug?: (msg: string) => void;\n}\n\n/** Reads the current branch's PR through the `gh` CLI. Never throws: any failure means \"no PR\". */\nexport class GhCodeHost implements CodeHost {\n readonly name = 'gh';\n private readonly timeoutMs: number;\n private readonly debug: (msg: string) => void;\n\n constructor(opts: GhOptions = {}) {\n this.timeoutMs = opts.timeoutMs ?? 15_000;\n this.debug = opts.debug ?? (() => {});\n }\n\n currentPullRequest(cwd: string): Promise<PullRequestInfo | null> {\n return new Promise((resolve) => {\n execFile(\n 'gh',\n ['pr', 'view', '--json', FIELDS],\n { cwd, timeout: this.timeoutMs, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 },\n (err, stdout, stderr) => {\n if (err) {\n const code = (err as NodeJS.ErrnoException).code;\n this.debug(\n code === 'ENOENT' ? 'gh is not installed; skipping pull request lookup' : `gh pr view failed: ${(stderr || err.message).trim()}`,\n );\n resolve(null);\n return;\n }\n try {\n const j = JSON.parse(stdout) as Record<string, unknown>;\n resolve({\n number: Number(j.number),\n title: String(j.title ?? ''),\n body: String(j.body ?? ''),\n url: String(j.url ?? ''),\n baseRefName: String(j.baseRefName ?? ''),\n headRefName: String(j.headRefName ?? ''),\n });\n } catch (parseErr) {\n this.debug(`gh returned unparseable JSON: ${(parseErr as Error).message}`);\n resolve(null);\n }\n },\n );\n });\n }\n}\n","import type { CodeHost } from './provider.js';\n\nexport class NoCodeHost implements CodeHost {\n readonly name = 'none';\n async currentPullRequest(): Promise<null> {\n return null;\n }\n}\n","import type { Config } from '../core/config.js';\nimport { GhCodeHost } from './gh.js';\nimport { NoCodeHost } from './none.js';\nimport type { CodeHost } from './provider.js';\n\nexport type { CodeHost } from './provider.js';\nexport { GhCodeHost } from './gh.js';\nexport { NoCodeHost } from './none.js';\n\nexport function createCodeHost(config: Config, opts: { debug?: (msg: string) => void } = {}): CodeHost {\n switch (config.codehost.provider) {\n case 'gh':\n return new GhCodeHost({ debug: opts.debug });\n case 'none':\n return new NoCodeHost();\n }\n}\n","import { execFile } from 'node:child_process';\nimport { GitError, NotARepoError } from '../core/errors.js';\n\nexport interface GitResult {\n stdout: string;\n stderr: string;\n code: number;\n}\n\nexport interface GitOptions {\n cwd: string;\n /** Resolve instead of throwing on a nonzero exit code. */\n allowFailure?: boolean;\n}\n\nconst MAX_BUFFER = 512 * 1024 * 1024;\n\n/** Run git with the given args; throws GitError on nonzero exit unless allowFailure. */\nexport function git(args: string[], opts: GitOptions): Promise<GitResult> {\n return new Promise((resolve, reject) => {\n execFile('git', args, { cwd: opts.cwd, maxBuffer: MAX_BUFFER, encoding: 'utf8' }, (err, stdout, stderr) => {\n const e = err as (NodeJS.ErrnoException & { code?: number | string }) | null;\n if (e && e.code === 'ENOENT') {\n reject(new GitError('git executable not found', { hint: 'Install git and make sure it is on your PATH.' }));\n return;\n }\n const code = e ? (typeof e.code === 'number' ? e.code : 1) : 0;\n if (code !== 0 && !opts.allowFailure) {\n const detail = stderr.trim() || stdout.trim() || `exit code ${code}`;\n reject(new GitError(`git ${args.slice(0, 2).join(' ')} failed: ${detail}`));\n return;\n }\n resolve({ stdout, stderr, code });\n });\n });\n}\n\nexport async function gitRoot(cwd: string): Promise<string> {\n const res = await git(['rev-parse', '--show-toplevel'], { cwd, allowFailure: true });\n if (res.code !== 0) throw new NotARepoError(cwd);\n return res.stdout.trim();\n}\n\n/** Resolve a ref to a full commit sha; null when it doesn't resolve. */\nexport async function revParse(ref: string, cwd: string): Promise<string | null> {\n const res = await git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], { cwd, allowFailure: true });\n return res.code === 0 ? res.stdout.trim() : null;\n}\n\nexport async function shortSha(sha: string, cwd: string): Promise<string> {\n const res = await git(['rev-parse', '--short', sha], { cwd, allowFailure: true });\n return res.code === 0 ? res.stdout.trim() : sha.slice(0, 7);\n}\n\n/** Current branch name, or null when HEAD is detached. */\nexport async function currentBranch(cwd: string): Promise<string | null> {\n const res = await git(['symbolic-ref', '--short', '--quiet', 'HEAD'], { cwd, allowFailure: true });\n return res.code === 0 ? res.stdout.trim() : null;\n}\n\nexport async function mergeBase(a: string, b: string, cwd: string): Promise<string | null> {\n const res = await git(['merge-base', a, b], { cwd, allowFailure: true });\n return res.code === 0 ? res.stdout.trim() : null;\n}\n\nexport async function localBranches(cwd: string): Promise<string[]> {\n const res = await git(['for-each-ref', '--format=%(refname:short)', 'refs/heads/'], { cwd });\n return res.stdout.split('\\n').map((s) => s.trim()).filter(Boolean);\n}\n\nexport function excludePathspecs(exclude: string[]): string[] {\n return exclude.map((glob) => `:(exclude,glob)${glob}`);\n}\n\n/** True when the working tree (tracked or untracked, minus excludes) differs from HEAD. */\nexport async function isDirty(cwd: string, exclude: string[]): Promise<boolean> {\n const res = await git(['status', '--porcelain', '--untracked-files=all', '--', '.', ...excludePathspecs(exclude)], { cwd });\n return res.stdout.trim().length > 0;\n}\n","import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { CommitInfo, ParsedDiff, TourSource } from '../core/types.js';\nimport { excludePathspecs, git } from './exec.js';\nimport { parseDiff } from './parse.js';\n\nconst DIFF_BASE_ARGS = ['diff', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/', '-M', '-U3'];\nconst MAX_UNTRACKED_BYTES = 2 * 1024 * 1024;\n\nexport interface CollectOptions {\n cwd: string;\n exclude: string[];\n warn?: (msg: string) => void;\n}\n\n/** Collect and parse the diff for a resolved source. */\nexport async function collectDiff(source: TourSource, opts: CollectOptions): Promise<ParsedDiff> {\n const pathspec = ['--', '.', ...excludePathspecs(opts.exclude)];\n let raw: string;\n\n if (source.kind === 'range') {\n raw = (await git([...DIFF_BASE_ARGS, source.baseSha, source.headSha, ...pathspec], { cwd: opts.cwd })).stdout;\n } else if (source.staged) {\n raw = (await git([...DIFF_BASE_ARGS, '--cached', ...pathspec], { cwd: opts.cwd })).stdout;\n } else {\n raw = (await git([...DIFF_BASE_ARGS, 'HEAD', ...pathspec], { cwd: opts.cwd })).stdout;\n raw += await untrackedDiff(opts, pathspec);\n }\n return parseDiff(raw);\n}\n\n/** Untracked files rendered as \"new file\" diffs so they take part in the tour. */\nasync function untrackedDiff(opts: CollectOptions, pathspec: string[]): Promise<string> {\n const list = await git(['ls-files', '--others', '--exclude-standard', '-z', ...pathspec], { cwd: opts.cwd });\n const paths = list.stdout.split('\\0').filter(Boolean);\n let out = '';\n for (const rel of paths) {\n const abs = join(opts.cwd, rel);\n try {\n const s = await stat(abs);\n if (!s.isFile()) continue;\n if (s.size > MAX_UNTRACKED_BYTES) {\n opts.warn?.(`Skipping large untracked file ${rel} (${Math.round(s.size / 1024)} KB)`);\n continue;\n }\n } catch {\n continue;\n }\n const res = await git(\n [...DIFF_BASE_ARGS, '--no-index', '--', '/dev/null', rel],\n { cwd: opts.cwd, allowFailure: true },\n );\n // --no-index exits 1 when files differ, which is the expected case.\n if (res.code > 1) {\n opts.warn?.(`Could not diff untracked file ${rel}: ${res.stderr.trim()}`);\n continue;\n }\n out += res.stdout;\n }\n return out;\n}\n\nexport async function collectCommits(source: TourSource, cwd: string, limit = 50): Promise<CommitInfo[]> {\n if (source.kind !== 'range') return [];\n const res = await git(\n ['log', '--no-merges', `--max-count=${limit}`, '--format=%h%x09%s', `${source.baseSha}..${source.headSha}`],\n { cwd, allowFailure: true },\n );\n if (res.code !== 0) return [];\n return res.stdout\n .split('\\n')\n .filter(Boolean)\n .map((line) => {\n const tab = line.indexOf('\\t');\n return { sha: line.slice(0, tab), subject: line.slice(tab + 1) };\n });\n}\n","import type { CodeHost } from '../codehost/provider.js';\nimport { NoChangesError, UsageError } from '../core/errors.js';\nimport type { PullRequestInfo, TourSource } from '../core/types.js';\nimport { currentBranch, git, isDirty, localBranches, mergeBase, revParse } from './exec.js';\n\nexport interface RangeRequest {\n /** Explicit range argument: \"A..B\", \"A...B\" or a single ref. */\n arg?: string;\n working?: boolean;\n staged?: boolean;\n}\n\nexport interface ResolveOptions {\n cwd: string;\n exclude: string[];\n /** Configured default branch; null means auto-detect. */\n defaultBranch: string | null;\n codehost: CodeHost;\n debug?: (msg: string) => void;\n}\n\nexport interface ResolvedRange {\n source: TourSource;\n branch: string | null;\n pullRequest?: PullRequestInfo;\n}\n\nconst MAX_ANCESTOR_CANDIDATES = 100;\n\nexport async function resolveRange(req: RangeRequest, opts: ResolveOptions): Promise<ResolvedRange> {\n const debug = opts.debug ?? (() => {});\n const { cwd } = opts;\n const branch = await currentBranch(cwd);\n const headSha = await revParse('HEAD', cwd);\n if (!headSha) {\n throw new NoChangesError('This repository has no commits yet.', 'Make an initial commit first.');\n }\n debug(`repository ${cwd} on ${branch ?? 'detached HEAD'} at ${headSha.slice(0, 12)}`);\n\n if (req.working && req.staged) throw new UsageError('--working and --staged are mutually exclusive.');\n if ((req.working || req.staged) && req.arg) throw new UsageError(`A range argument cannot be combined with --${req.working ? 'working' : 'staged'}.`);\n\n if (req.staged) return { source: { kind: 'working', headSha, staged: true, resolvedBy: 'explicit' }, branch };\n if (req.working) return { source: { kind: 'working', headSha, staged: false, resolvedBy: 'explicit' }, branch };\n\n if (req.arg) {\n return { source: await explicitRange(req.arg, headSha, cwd), branch };\n }\n\n // 1. Dirty working tree.\n if (await isDirty(cwd, opts.exclude)) {\n debug('working tree is dirty; touring uncommitted changes');\n return { source: { kind: 'working', headSha, staged: false, resolvedBy: 'dirty-tree' }, branch };\n }\n\n const defaultBranch = await detectDefaultBranch(opts.defaultBranch, cwd);\n debug(`default branch: ${defaultBranch ?? '(none)'}`);\n\n // 2. Pull request base.\n const pr = await opts.codehost.currentPullRequest(cwd);\n if (pr?.baseRefName) {\n const baseRef = await firstExistingRef([`origin/${pr.baseRefName}`, pr.baseRefName], cwd);\n if (baseRef) {\n debug(`pull request #${pr.number} targets ${pr.baseRefName}; using ${baseRef}`);\n const source = await rangeAtMergeBase(baseRef, headSha, branch ?? 'HEAD', 'pull-request', cwd);\n return { source, branch, pullRequest: pr };\n }\n debug(`pull request #${pr.number} targets ${pr.baseRefName}, but that ref is not available locally`);\n }\n\n const onDefault = defaultBranch !== null && branch !== null && stripRemote(defaultBranch) === branch;\n\n // 3. Nearest ancestor branch.\n if (!onDefault) {\n const nearest = await nearestAncestorBranch(branch, headSha, defaultBranch, cwd, debug);\n if (nearest) {\n debug(`nearest ancestor branch: ${nearest}`);\n const source = await rangeAtMergeBase(nearest, headSha, branch ?? 'HEAD', 'ancestor-branch', cwd);\n return { source, branch };\n }\n }\n\n // 4. Default branch.\n if (defaultBranch && !onDefault) {\n const source = await rangeAtMergeBase(defaultBranch, headSha, branch ?? 'HEAD', 'default-branch', cwd);\n return { source, branch };\n }\n\n throw new NoChangesError(\n onDefault ? `You're on ${branch} in ${cwd} with a clean working tree; nothing to tour.` : 'Could not infer what to compare against.',\n 'Pass a range explicitly, e.g. `bb HEAD~3`, `bb main..feature` or `bb --working`.',\n );\n}\n\nasync function explicitRange(arg: string, headSha: string, cwd: string): Promise<TourSource> {\n const three = arg.indexOf('...');\n const two = three === -1 ? arg.indexOf('..') : -1;\n\n if (three !== -1) {\n const base = arg.slice(0, three) || 'HEAD';\n const head = arg.slice(three + 3) || 'HEAD';\n const headResolved = await requireRef(head, cwd);\n return rangeAtMergeBase(base, headResolved, head, 'explicit', cwd);\n }\n if (two !== -1) {\n const base = arg.slice(0, two) || 'HEAD';\n const head = arg.slice(two + 2) || 'HEAD';\n const baseSha = await requireRef(base, cwd);\n const headResolved = await requireRef(head, cwd);\n if (baseSha === headResolved) throw new NoChangesError(`${base} and ${head} point at the same commit.`);\n return { kind: 'range', base, head, baseSha, headSha: headResolved, resolvedBy: 'explicit' };\n }\n // Bare ref: \"what did HEAD add on top of <ref>\" (three-dot semantics).\n return rangeAtMergeBase(arg, headSha, 'HEAD', 'explicit', cwd);\n}\n\nasync function requireRef(ref: string, cwd: string): Promise<string> {\n const sha = await revParse(ref, cwd);\n if (!sha) throw new UsageError(`Unknown git ref: ${ref}`);\n return sha;\n}\n\nasync function rangeAtMergeBase(\n base: string,\n headSha: string,\n headLabel: string,\n resolvedBy: Extract<TourSource, { kind: 'range' }>['resolvedBy'],\n cwd: string,\n): Promise<TourSource> {\n const baseTip = await requireRef(base, cwd);\n const mb = (await mergeBase(baseTip, headSha, cwd)) ?? baseTip;\n if (mb === headSha) {\n throw new NoChangesError(\n `${headLabel} has no commits on top of ${base}.`,\n base === headLabel ? undefined : `Did you mean \\`bb ${base}..${headLabel}\\`?`,\n );\n }\n const source: TourSource = { kind: 'range', base, head: headLabel, baseSha: mb, headSha, resolvedBy };\n if (mb !== baseTip) source.mergeBase = mb;\n return source;\n}\n\nasync function firstExistingRef(candidates: string[], cwd: string): Promise<string | null> {\n for (const ref of candidates) {\n if (await revParse(ref, cwd)) return ref;\n }\n return null;\n}\n\nfunction stripRemote(ref: string): string {\n return ref.startsWith('origin/') ? ref.slice('origin/'.length) : ref;\n}\n\nexport async function detectDefaultBranch(configured: string | null, cwd: string): Promise<string | null> {\n if (configured) return (await revParse(configured, cwd)) ? configured : null;\n const sym = await git(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], { cwd, allowFailure: true });\n if (sym.code === 0 && sym.stdout.trim()) return sym.stdout.trim();\n return firstExistingRef(['main', 'master', 'trunk', 'origin/main', 'origin/master'], cwd);\n}\n\nasync function nearestAncestorBranch(\n branch: string | null,\n headSha: string,\n defaultBranch: string | null,\n cwd: string,\n debug: (msg: string) => void,\n): Promise<string | null> {\n const branches = (await localBranches(cwd)).filter((b) => b !== branch);\n if (branches.length === 0) return null;\n if (branches.length > MAX_ANCESTOR_CANDIDATES) {\n debug(`skipping ancestor search: ${branches.length} local branches`);\n return null;\n }\n let best: { name: string; distance: number } | null = null;\n for (const name of branches) {\n const mb = await mergeBase(name, headSha, cwd);\n if (!mb || mb === headSha) continue; // unrelated, identical, or a descendant of HEAD\n const count = await git(['rev-list', '--count', `${mb}..${headSha}`], { cwd, allowFailure: true });\n const distance = count.code === 0 ? Number(count.stdout.trim()) : Number.POSITIVE_INFINITY;\n const isDefault = defaultBranch !== null && stripRemote(defaultBranch) === name;\n if (!best || distance < best.distance || (distance === best.distance && isDefault)) {\n best = { name, distance };\n }\n }\n return best?.name ?? null;\n}\n","import { spawn } from 'node:child_process';\nimport { LlmFailedError } from '../core/errors.js';\nimport type { LlmProvider } from './provider.js';\n\nexport interface CommandProviderOptions {\n command: string[];\n promptVia: 'stdin' | 'arg';\n timeoutMs: number;\n env?: Record<string, string>;\n cwd?: string;\n debug?: (msg: string) => void;\n}\n\nconst STDERR_TAIL_LINES = 20;\n\n/** Runs any CLI as the model: prompt in via stdin (or a {prompt} argv token), completion out via stdout. */\nexport class CommandProvider implements LlmProvider {\n constructor(private readonly opts: CommandProviderOptions) {\n if (opts.command.length === 0) throw new LlmFailedError('LLM command is empty.');\n }\n\n describe(): string {\n return this.opts.command.map(shellQuote).join(' ');\n }\n\n complete(prompt: string): Promise<string> {\n const { promptVia, timeoutMs } = this.opts;\n const argv = promptVia === 'arg' ? this.opts.command.map((a) => a.replaceAll('{prompt}', prompt)) : this.opts.command;\n const [bin, ...args] = argv as [string, ...string[]];\n const debug = this.opts.debug ?? (() => {});\n const started = Date.now();\n debug(`running ${this.describe()} (prompt ${Buffer.byteLength(prompt)} bytes via ${promptVia})`);\n\n return new Promise((resolve, reject) => {\n const env = { ...process.env, ...this.opts.env };\n // Claude Code refuses to start nested inside another Claude Code session.\n delete env.CLAUDECODE;\n const child = spawn(bin, args, { cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'] });\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n let settled = false;\n const finish = (fn: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n fn();\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish(() => reject(new LlmFailedError(`LLM command timed out after ${Math.round(timeoutMs / 1000)}s: ${this.describe()}`, {\n hint: 'Raise llm.timeoutMs in your config, or pick a faster preset.',\n })));\n }, timeoutMs);\n\n child.stdout.on('data', (b: Buffer) => out.push(b));\n child.stderr.on('data', (b: Buffer) => err.push(b));\n child.on('error', (e: NodeJS.ErrnoException) => {\n finish(() => {\n if (e.code === 'ENOENT') {\n reject(new LlmFailedError(`LLM command not found: ${bin}`, { hint: 'Install it, or choose another preset with --preset / llm.preset.', cause: e }));\n } else {\n reject(new LlmFailedError(`Could not run ${this.describe()}: ${e.message}`, { cause: e }));\n }\n });\n });\n child.on('close', (code, signal) => {\n finish(() => {\n const stdout = Buffer.concat(out).toString('utf8');\n const stderr = Buffer.concat(err).toString('utf8');\n debug(`command exited with ${signal ? `signal ${signal}` : `code ${code}`} after ${Date.now() - started}ms; ${stdout.length} bytes of stdout`);\n if (code !== 0) {\n const tail = stderr.trim().split('\\n').slice(-STDERR_TAIL_LINES).join('\\n');\n reject(new LlmFailedError(`LLM command failed (${signal ? `signal ${signal}` : `exit ${code}`}): ${this.describe()}${tail ? '\\n' + tail : ''}`));\n return;\n }\n resolve(stdout);\n });\n });\n\n if (promptVia === 'stdin') {\n child.stdin.on('error', () => {}); // EPIPE when the command exits early; the close handler reports it\n child.stdin.end(prompt);\n } else {\n child.stdin.end();\n }\n });\n }\n}\n\nfunction shellQuote(arg: string): string {\n if (arg === '') return '\"\"';\n return /^[\\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n","import type { ResolvedLlm } from '../core/config.js';\nimport { CommandProvider } from './command.js';\nimport type { LlmProvider } from './provider.js';\n\nexport type { LlmProvider } from './provider.js';\nexport { CommandProvider } from './command.js';\n\nexport function createProvider(llm: ResolvedLlm, opts: { cwd?: string; debug?: (msg: string) => void } = {}): LlmProvider {\n return new CommandProvider({\n command: llm.command,\n promptVia: llm.promptVia,\n timeoutMs: llm.timeoutMs,\n env: llm.env,\n cwd: opts.cwd,\n debug: opts.debug,\n });\n}\n","import { createCodeHost, type CodeHost } from '../codehost/index.js';\nimport { collectCommits, collectDiff } from '../git/diff.js';\nimport { resolveRange, type RangeRequest } from '../git/range.js';\nimport { createProvider, type LlmProvider } from '../llm/index.js';\nimport { TourCache } from './cache.js';\nimport { resolveLlm, type Config } from './config.js';\nimport { BadLlmOutputError, NoChangesError } from './errors.js';\nimport { extractJson } from './json.js';\nimport { materializeTour } from './materialize.js';\nimport { buildPrompt, type BuiltPrompt } from './prompt/build.js';\nimport { PROMPT_VERSION, REPAIR_SUFFIX } from './prompt/template.js';\nimport { formatIssues, LlmTourOutputSchema, type LlmTourOutput } from './schema.js';\nimport type { Tour, TourContext } from './types.js';\n\nexport interface TourOptions {\n /** Git root (or any directory inside the repository). */\n cwd: string;\n config: Config;\n cacheDir: string;\n range?: RangeRequest;\n /** Ignore a cached tour but still store the new one. */\n refresh?: boolean;\n /** Neither read nor write the cache. */\n noCache?: boolean;\n debug?: (msg: string) => void;\n warn?: (msg: string) => void;\n /** Injectable for tests. */\n provider?: LlmProvider;\n codehost?: CodeHost;\n}\n\nexport interface PreparedTour {\n context: TourContext;\n built: BuiltPrompt;\n command: string[];\n preset: string | null;\n cacheKey: string;\n}\n\nexport interface TourResult {\n tour: Tour;\n fromCache: boolean;\n cacheKey: string | null;\n cachePath: string | null;\n prompt: string;\n}\n\n/** Everything up to (but not including) the model call: git, code host, prompt, cache key. */\nexport async function prepareTour(opts: TourOptions): Promise<PreparedTour> {\n const debug = opts.debug ?? (() => {});\n const warn = opts.warn ?? (() => {});\n const { config } = opts;\n const llm = resolveLlm(config);\n const codehost = opts.codehost ?? createCodeHost(config, { debug });\n\n const resolved = await resolveRange(opts.range ?? {}, {\n cwd: opts.cwd,\n exclude: config.git.exclude,\n defaultBranch: config.git.defaultBranch,\n codehost,\n debug,\n });\n debug(`source: ${JSON.stringify(resolved.source)}`);\n\n const diff = await collectDiff(resolved.source, { cwd: opts.cwd, exclude: config.git.exclude, warn });\n if (diff.files.length === 0) {\n throw new NoChangesError('The selected range has no changes (after excludes).', 'Check git.exclude in your config, or pass a different range.');\n }\n const commits = await collectCommits(resolved.source, opts.cwd);\n\n const context: TourContext = { source: resolved.source, branch: resolved.branch, diff, commits };\n if (resolved.pullRequest) context.pullRequest = resolved.pullRequest;\n\n const built = buildPrompt({ ...context, maxBytes: llm.maxPromptBytes });\n if (built.truncation.truncated.length || built.truncation.omitted.length) {\n warn(`Prompt exceeded ${llm.maxPromptBytes} bytes; truncated ${built.truncation.truncated.length} and omitted ${built.truncation.omitted.length} file diff(s).`);\n }\n const cacheKey = TourCache.keyFor(`v${PROMPT_VERSION}\\n${built.prompt}`, llm.command);\n debug(`prompt ${Buffer.byteLength(built.prompt)} bytes, cache key ${cacheKey.slice(0, 12)}`);\n\n return { context, built, command: llm.command, preset: llm.preset, cacheKey };\n}\n\nexport async function generateTour(opts: TourOptions, prepared?: PreparedTour): Promise<TourResult> {\n const debug = opts.debug ?? (() => {});\n const warn = opts.warn ?? (() => {});\n const { config } = opts;\n const prep = prepared ?? (await prepareTour(opts));\n const useCache = config.cache.enabled && !opts.noCache;\n const cache = useCache ? new TourCache(opts.cacheDir) : null;\n\n if (cache && !opts.refresh) {\n const hit = await cache.get(prep.cacheKey);\n if (hit) {\n debug(`cache hit: ${cache.pathFor(prep.cacheKey)}`);\n return { tour: hit, fromCache: true, cacheKey: prep.cacheKey, cachePath: cache.pathFor(prep.cacheKey), prompt: prep.built.prompt };\n }\n debug('cache miss');\n }\n\n const llm = resolveLlm(config);\n const provider = opts.provider ?? createProvider(llm, { cwd: opts.cwd, debug });\n const output = await completeWithRepair(provider, prep.built.prompt, debug);\n\n const tour = materializeTour({\n output,\n diff: prep.context.diff,\n source: prep.context.source,\n generator: { preset: prep.preset, command: prep.command },\n pullRequest: prep.context.pullRequest,\n maxExcerptLines: config.render.maxExcerptLines,\n warn,\n });\n\n let cachePath: string | null = null;\n if (cache) {\n cachePath = await cache.put(prep.cacheKey, tour);\n debug(`cached: ${cachePath}`);\n }\n return { tour, fromCache: false, cacheKey: cache ? prep.cacheKey : null, cachePath, prompt: prep.built.prompt };\n}\n\n/** Ask once; if the answer isn't usable JSON matching the schema, ask once more with the reason. */\nasync function completeWithRepair(provider: LlmProvider, prompt: string, debug: (msg: string) => void): Promise<LlmTourOutput> {\n let raw = await provider.complete(prompt);\n debug(`raw model output (attempt 1):\\n${raw}`);\n const first = parseOutput(raw);\n if (first.ok) return first.value;\n\n debug(`attempt 1 unusable: ${first.reason}; retrying with repair prompt`);\n raw = await provider.complete(prompt + REPAIR_SUFFIX(first.reason));\n debug(`raw model output (attempt 2):\\n${raw}`);\n const second = parseOutput(raw);\n if (second.ok) return second.value;\n throw new BadLlmOutputError(`The model did not return a usable tour: ${second.reason}`, raw, 'Run with --debug to see the raw output, or try another preset.');\n}\n\nfunction parseOutput(raw: string): { ok: true; value: LlmTourOutput } | { ok: false; reason: string } {\n let json: unknown;\n try {\n json = extractJson(raw);\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) };\n }\n const parsed = LlmTourOutputSchema.safeParse(json);\n if (!parsed.success) return { ok: false, reason: `JSON did not match the schema (${formatIssues(parsed.error)})` };\n return { ok: true, value: parsed.data };\n}\n","import pc from 'picocolors';\nimport { UsageError } from '../core/errors.js';\nimport type { Excerpt, Section, Tour, TourSource, TourStats } from '../core/types.js';\nimport type { Renderer, RenderOptions } from './renderer.js';\n\ntype Colors = ReturnType<typeof pc.createColors>;\n\nconst MIN_WIDTH = 40;\nconst MAX_WIDTH = 120;\n\n/** Static, pager-friendly rendering of a Tour for a terminal. */\nexport class CliRenderer implements Renderer {\n render(tour: Tour, opts: RenderOptions): string {\n const c = pc.createColors(opts.color);\n const width = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, opts.width));\n const out: string[] = [];\n\n out.push(...renderHeader(tour, c, width, opts.fromCache ?? false));\n out.push('');\n\n if (opts.section !== undefined) {\n const section = tour.sections[opts.section - 1];\n if (!section) {\n throw new UsageError(`No section ${opts.section}; this tour has ${tour.sections.length} section${tour.sections.length === 1 ? '' : 's'}.`);\n }\n out.push(...renderSection(section, opts.section, tour.sections.length, c, width));\n } else {\n out.push(...renderToc(tour, c, width));\n out.push('');\n tour.sections.forEach((s, i) => {\n out.push(...renderSection(s, i + 1, tour.sections.length, c, width));\n out.push('');\n });\n }\n return out.join('\\n').replace(/\\n+$/, '') + '\\n';\n }\n}\n\nfunction renderHeader(tour: Tour, c: Colors, width: number, fromCache: boolean): string[] {\n const lines: string[] = [];\n lines.push(c.bold(`🐣 ${tour.title}`));\n lines.push(c.dim(describeSource(tour.source)));\n if (tour.pullRequest) {\n lines.push(c.dim(`PR #${tour.pullRequest.number}: ${tour.pullRequest.title}${tour.pullRequest.url ? ' ' + tour.pullRequest.url : ''}`));\n }\n const parts = [statsLine(tour.stats, c), `${tour.sections.length} section${tour.sections.length === 1 ? '' : 's'}`];\n const meta: string[] = [];\n if (tour.generator.preset) meta.push(tour.generator.preset);\n else if (tour.generator.command[0]) meta.push(tour.generator.command[0]);\n meta.push(fromCache ? `cached ${relativeTime(tour.generatedAt)}` : 'generated just now');\n lines.push(`${parts.join(c.dim(' · '))}${c.dim(' · ' + meta.join(', '))}`);\n if (tour.summary) {\n lines.push('');\n lines.push(...wrap(tour.summary, width));\n }\n return lines;\n}\n\nfunction renderToc(tour: Tour, c: Colors, width: number): string[] {\n const lines = [c.bold('Contents')];\n const numWidth = String(tour.sections.length).length;\n for (const [i, s] of tour.sections.entries()) {\n const n = String(i + 1).padStart(numWidth);\n const label = ` ${n}. ${s.title}`;\n const right = `${s.stats.files} file${s.stats.files === 1 ? '' : 's'} · ${statsLine(s.stats, c, true)}`;\n const rightPlain = `${s.stats.files} file${s.stats.files === 1 ? '' : 's'} · +${s.stats.additions} -${s.stats.deletions}`;\n const gap = Math.max(2, width - visibleLength(label) - rightPlain.length);\n lines.push(label + ' '.repeat(gap) + c.dim(right));\n }\n return lines;\n}\n\nfunction renderSection(s: Section, index: number, count: number, c: Colors, width: number): string[] {\n const lines: string[] = [];\n lines.push(c.dim('─'.repeat(width)));\n lines.push(c.bold(`${index}. ${s.title}`) + c.dim(` (${index}/${count})`));\n lines.push(` ${c.dim(`${s.stats.files} file${s.stats.files === 1 ? '' : 's'} · `)}${statsLine(s.stats, c, true)}`);\n if (s.description) {\n lines.push('');\n lines.push(...wrap(s.description, width - 3).map((l) => (l ? ' ' + l : '')));\n }\n if (s.files.length) {\n lines.push('');\n for (const f of s.files) lines.push(` ${c.cyan(f)}`);\n }\n for (const e of s.excerpts) {\n lines.push('');\n lines.push(...renderExcerpt(e, c, width));\n }\n return lines;\n}\n\nfunction renderExcerpt(e: Excerpt, c: Colors, width: number): string[] {\n const lines: string[] = [];\n const title = ` ${c.cyan(e.file)}${c.dim(':' + e.newStart)}`;\n lines.push(e.note ? `${title} ${c.italic(c.dim(e.note))}` : title);\n const maxNo = Math.max(...e.lines.map((l) => Math.max(l.oldNo ?? 0, l.newNo ?? 0)), 1);\n const w = String(maxNo).length;\n const budget = Math.max(20, width - (3 + w * 2 + 5));\n for (const l of e.lines) {\n const oldNo = l.oldNo === undefined ? ' '.repeat(w) : String(l.oldNo).padStart(w);\n const newNo = l.newNo === undefined ? ' '.repeat(w) : String(l.newNo).padStart(w);\n const sign = l.type === 'add' ? '+' : l.type === 'del' ? '-' : ' ';\n const text = truncate(expandTabs(l.text), budget);\n const gutter = c.dim(` ${oldNo} ${newNo} │`);\n const body = `${sign}${text}`;\n lines.push(`${gutter}${l.type === 'add' ? c.green(body) : l.type === 'del' ? c.red(body) : body}`);\n }\n return lines;\n}\n\nfunction statsLine(stats: TourStats, c: Colors, omitFiles = false): string {\n const counts = `${c.green(`+${stats.additions}`)} ${c.red(`-${stats.deletions}`)}`;\n return omitFiles ? counts : `${stats.files} file${stats.files === 1 ? '' : 's'} · ${counts}`;\n}\n\nexport function describeSource(source: TourSource): string {\n if (source.kind === 'working') {\n return source.staged ? 'Staged changes vs HEAD' : 'Working tree vs HEAD (uncommitted changes)';\n }\n const how =\n source.resolvedBy === 'pull-request' ? 'base from pull request'\n : source.resolvedBy === 'ancestor-branch' ? 'nearest ancestor branch'\n : source.resolvedBy === 'default-branch' ? 'default branch'\n : null;\n const mb = source.mergeBase ? ` (merge-base ${source.mergeBase.slice(0, 7)})` : '';\n return `${source.head} vs ${source.base}${mb}${how ? ` · ${how}` : ''}`;\n}\n\nexport function wrap(text: string, width: number): string[] {\n const out: string[] = [];\n for (const para of text.split(/\\n\\s*\\n/)) {\n const words = para.split(/\\s+/).filter(Boolean);\n let line = '';\n for (const word of words) {\n if (line && line.length + 1 + word.length > width) {\n out.push(line);\n line = word;\n } else {\n line = line ? `${line} ${word}` : word;\n }\n }\n if (line) out.push(line);\n out.push('');\n }\n while (out.length && out[out.length - 1] === '') out.pop();\n return out;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length > max ? s.slice(0, Math.max(0, max - 1)) + '…' : s;\n}\n\nfunction expandTabs(s: string): string {\n return s.replaceAll('\\t', ' ');\n}\n\nfunction visibleLength(s: string): number {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\\x1b\\[[0-9;]*m/g, '').length;\n}\n\nexport function relativeTime(iso: string, now: Date = new Date()): string {\n const ms = now.getTime() - new Date(iso).getTime();\n if (!Number.isFinite(ms) || ms < 0) return 'just now';\n const s = Math.round(ms / 1000);\n if (s < 60) return 'just now';\n const m = Math.round(s / 60);\n if (m < 60) return `${m} min ago`;\n const h = Math.round(m / 60);\n if (h < 48) return `${h} h ago`;\n const d = Math.round(h / 24);\n return `${d} days ago`;\n}\n","import { spawn } from 'node:child_process';\n\nexport interface PagerOptions {\n mode: 'auto' | 'always' | 'never';\n isTTY: boolean;\n rows: number;\n env?: NodeJS.ProcessEnv;\n}\n\n/** Write output to stdout, through $PAGER (default `less -RFX`) when it would not fit the screen. */\nexport async function writeMaybePaged(output: string, opts: PagerOptions): Promise<void> {\n const env = opts.env ?? process.env;\n const lineCount = output.split('\\n').length;\n const shouldPage = opts.mode === 'always' || (opts.mode === 'auto' && opts.isTTY && lineCount > opts.rows - 1);\n if (!shouldPage) {\n await writeStdout(output);\n return;\n }\n const pagerCmd = (env.PAGER && env.PAGER.trim()) || 'less';\n const cmd = pagerCmd === 'less' && !env.LESS ? 'less -RFX' : pagerCmd;\n await new Promise<void>((resolve) => {\n const child = spawn(cmd, { shell: true, stdio: ['pipe', 'inherit', 'inherit'], env });\n let fellBack = false;\n child.on('error', () => {\n fellBack = true;\n process.stdout.write(output);\n resolve();\n });\n child.on('close', () => {\n if (!fellBack) resolve();\n });\n child.stdin.on('error', () => {}); // pager quit early\n child.stdin.end(output);\n });\n}\n\n/** Write to stdout and resolve once the bytes are flushed (or the pipe is gone). */\nexport function writeStdout(output: string): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write(output, () => resolve());\n });\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAGX,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAEt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