@cam5/baby-bird 0.1.1 → 0.1.2
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 +37 -6
- package/dist/{chunk-7ALXKEST.js → chunk-YI2UL4IC.js} +189 -39
- package/dist/chunk-YI2UL4IC.js.map +1 -0
- package/dist/cli.js +153 -48
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +89 -13
- package/dist/index.js +13 -1
- package/package.json +1 -1
- package/dist/chunk-7ALXKEST.js.map +0 -1
|
@@ -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/core/prompt/json-schema.ts","../src/llm/claude-stream.ts","../src/llm/command.ts","../src/llm/index.ts","../src/core/progress.ts","../src/core/tour.ts","../src/core/chat.ts","../src/llm/chat.ts","../src/render/cli.ts","../src/render/highlight.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] new-file line numbers to narrow the hunk; fewer than two numbers means the whole hunk. */\n lines: z.array(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 type LlmKind = 'plain' | 'claude';\n\nexport interface LlmPreset {\n /** argv; when promptVia is \"arg\", any \"{prompt}\" token is replaced with the prompt. */\n command: string[];\n /**\n * argv for `bb ask`: an interactive chat about a tour. Tokens: \"{context-file}\" is the path of a\n * file holding the tour context (a system prompt), \"{context}\" is that text inline, and\n * \"{message}\" is the user's opening message (argv entries that are only \"{message}\" are dropped\n * when there is none).\n */\n chatCommand?: string[];\n promptVia?: PromptVia;\n /**\n * \"claude\": the Claude Code CLI; streaming flags and --json-schema are added\n * automatically so thinking can be shown live and the answer is schema-checked.\n * \"plain\" (default): stdout is the answer.\n */\n kind?: LlmKind;\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\n/** Claude Code interactive, with the tour context appended to its system prompt and the question as the opening message (after `--`, so a question starting with a dash is not read as a flag). */\nconst CLAUDE_CHAT = ['claude', '--append-system-prompt-file', '{context-file}', '--', '{message}'];\n\n/** Interactive variant of a Claude preset: the same model/effort flags, minus the print-mode ones. */\nconst claudeChat = (...flags: string[]): string[] => [CLAUDE_CHAT[0]!, ...flags, ...CLAUDE_CHAT.slice(1)];\n\nexport const BUILTIN_PRESETS: Readonly<Record<string, LlmPreset>> = Object.freeze({\n claude: {\n command: [...CLAUDE_BASE],\n chatCommand: claudeChat(),\n kind: 'claude',\n description: 'Claude Code CLI with its default model',\n },\n 'claude-sonnet': {\n command: [...CLAUDE_BASE, '--model', 'sonnet', '--effort', 'high'],\n chatCommand: claudeChat('--model', 'sonnet', '--effort', 'high'),\n kind: 'claude',\n description: 'Claude Code CLI, Sonnet at high effort',\n },\n 'claude-opus': {\n command: [...CLAUDE_BASE, '--model', 'opus', '--effort', 'high'],\n chatCommand: claudeChat('--model', 'opus', '--effort', 'high'),\n kind: 'claude',\n description: 'Claude Code CLI, Opus at high effort',\n },\n 'claude-fable': {\n command: [...CLAUDE_BASE, '--model', 'fable', '--effort', 'high'],\n chatCommand: claudeChat('--model', 'fable', '--effort', 'high'),\n kind: 'claude',\n description: 'Claude Code CLI, Fable at high effort',\n },\n 'claude-haiku': {\n command: [...CLAUDE_BASE, '--model', 'haiku'],\n chatCommand: claudeChat('--model', 'haiku'),\n kind: 'claude',\n description: 'Claude Code CLI, Haiku (fast and cheap)',\n },\n llm: {\n command: ['llm'],\n // `llm chat` has no opening-message argument; bb warns and the question is typed into the chat.\n chatCommand: ['llm', 'chat', '-s', '{context}'],\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']);\nconst LlmKindSchema = z.enum(['plain', 'claude']);\n\nexport const LlmPresetSchema = z.object({\n command: z.array(z.string()).min(1),\n chatCommand: z.array(z.string()).min(1).optional(),\n promptVia: PromptViaSchema.optional(),\n kind: LlmKindSchema.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 /** Interactive command for `bb ask`; when set it replaces the preset's chatCommand. Same tokens as a preset's. */\n chatCommand: z.array(z.string()).min(1).nullable(),\n promptVia: PromptViaSchema.nullable(),\n kind: LlmKindSchema.nullable(),\n /** Claude kind only: pass --json-schema so the CLI validates the answer itself. Off by default (see README). */\n jsonSchema: z.boolean(),\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 /** Language-aware token colors in excerpts. */\n highlight: z.enum(['auto', 'always', 'never']),\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 chatCommand: null,\n promptVia: null,\n kind: null,\n jsonSchema: false,\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, highlight: 'auto' },\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 kind: LlmKind;\n /** Whether to hand the answer schema to the runner (Claude kind only). */\n jsonSchema: boolean;\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, jsonSchema: llm.jsonSchema };\n\n if (llm.command) {\n return { command: [...llm.command, ...llm.args], promptVia: llm.promptVia ?? 'stdin', kind: llm.kind ?? 'plain', 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 kind: llm.kind ?? preset.kind ?? 'plain',\n preset: llm.preset,\n ...common,\n };\n}\n\nexport interface ResolvedChat {\n /** argv template; see LlmPreset.chatCommand for the tokens. */\n command: string[];\n /** Preset name the command came from, or null for llm.chatCommand / a custom command. */\n preset: string | null;\n env: Record<string, string>;\n}\n\n/** The interactive command `bb ask` runs. Errors when neither the preset nor llm.chatCommand provides one. */\nexport function resolveChat(config: Config): ResolvedChat {\n const { llm } = config;\n if (llm.chatCommand) return { command: [...llm.chatCommand], preset: null, env: llm.env };\n if (llm.command) {\n throw new ConfigError('llm.command is set but llm.chatCommand is not, so there is nothing to chat with.', 'Set llm.chatCommand (see README), or pick a preset with --preset.');\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 if (!preset.chatCommand) {\n const withChat = Object.entries(presets).filter(([, p]) => p.chatCommand).map(([n]) => n).sort().join(', ');\n throw new ConfigError(`Preset \"${llm.preset}\" has no chatCommand.`, `Add one under llm.presets.${llm.preset}.chatCommand, set llm.chatCommand, or use a preset that has one: ${withChat}.`);\n }\n return { command: [...preset.chatCommand], preset: llm.preset, env: llm.env };\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 range = ref.lines && ref.lines.length >= 2 ? ([ref.lines[0]!, ref.lines[1]!] as [number, number]) : undefined;\n const lines = sliceHunk(hit.hunk, range, 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 = 3;\n\nexport const PROMPT_HEADER_TEXT = `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\"). Narrow a hunk to the interesting part with \"lines\": [start, end] using NEW-file line numbers as they appear in the diff; prefer 10 to 30 lines over a whole hunk. Use an empty \"lines\" array for the whole hunk. 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\n%%OUTPUT_INSTRUCTION%%\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\nconst OUTPUT_PLAIN = 'Respond with ONLY a JSON object: no prose before or after it, and no code fences.';\nconst OUTPUT_STRUCTURED =\n 'Submit the tour through the structured output tool. Its input is the tour object itself, with title, summary and sections as top-level fields exactly as shown below (do not nest them under another key). Do not write prose before it.';\n\n/** The fixed part of the prompt; `structured` picks the wording for CLIs that enforce a schema themselves. */\nexport function promptHeader(structured: boolean): string {\n return PROMPT_HEADER_TEXT.replace('%%OUTPUT_INSTRUCTION%%', structured ? OUTPUT_STRUCTURED : OUTPUT_PLAIN);\n}\n\n/** Plain-output header, kept for callers that only need the default wording. */\nexport const PROMPT_HEADER = promptHeader(false);\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 { promptHeader } from './template.js';\n\n/** The change as gathered from git and the code host. */\nexport interface ChangeInput {\n source: TourSource;\n branch: string | null;\n diff: ParsedDiff;\n commits: CommitInfo[];\n pullRequest?: PullRequestInfo;\n}\n\nexport interface PromptInput extends ChangeInput {\n /** Soft budget for the whole prompt, in bytes. */\n maxBytes: number;\n /** The runner enforces the JSON schema itself (e.g. claude --json-schema); adjusts the output instruction. */\n structured?: boolean;\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 header = promptHeader(Boolean(input.structured));\n const change = renderChange(input, input.maxBytes - bytes(header) - 8);\n return { prompt: [header, change.text].join('\\n'), truncation: change.truncation };\n}\n\n/**\n * The change itself: source, PR text, commit subjects, the file table, and the diff with every\n * hunk labeled by id. Diffs are shortened biggest-file-first to fit `maxBytes`.\n */\nexport function renderChange(input: ChangeInput, maxBytes: number): { text: string; truncation: TruncationReport } {\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 = maxBytes - bytes(context);\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 return { text: [context, diffPreamble(truncation), ...blocks.map(text)].join('\\n'), truncation };\n}\n\nfunction bytes(s: string): number {\n return Buffer.byteLength(s, 'utf8');\n}\n\nfunction renderContext(input: ChangeInput): 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","/**\n * JSON Schema for the model's answer, handed to `claude --json-schema` so the\n * CLI enforces the shape itself. Kept deliberately simple (no tuples, no\n * optionals) for structured-output compatibility; zod does the final check.\n */\nexport const TOUR_JSON_SCHEMA = {\n type: 'object',\n description: 'The tour itself. Its fields (title, summary, sections) are the top-level properties of this object; do not wrap them in another key.',\n additionalProperties: false,\n required: ['title', 'summary', 'sections'],\n properties: {\n title: { type: 'string', description: 'Short imperative title naming the change, like a good commit subject.' },\n summary: { type: 'string', description: '2 to 4 sentences describing the whole change and its motivation.' },\n sections: {\n type: 'array',\n description: 'Ordered sections of the tour, 2 to 8 of them.',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['title', 'description', 'files', 'excerpts'],\n properties: {\n title: { type: 'string' },\n description: { type: 'string', description: 'Why, then what, then what to watch. 2 to 5 sentences.' },\n files: { type: 'array', items: { type: 'string' }, description: 'Paths this section is about, exactly as listed.' },\n excerpts: {\n type: 'array',\n description: '1 to 3 hunks that best show the idea.',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['hunk', 'lines', 'note'],\n properties: {\n hunk: { type: 'string', description: 'A hunk id exactly as given in the diff, e.g. \"F2.H1\".' },\n lines: {\n type: 'array',\n items: { type: 'integer' },\n description: 'Empty for the whole hunk, or [start, end] new-file line numbers to narrow it.',\n },\n note: { type: 'string', description: 'Under 15 words: what to look at. May be empty.' },\n },\n },\n },\n },\n },\n },\n },\n} as const;\n","import type { LlmEvent } from './provider.js';\n\n/**\n * Incremental parser for `claude -p --output-format stream-json --verbose\n * --include-partial-messages`. Emits thinking/text events as deltas arrive and\n * collects the final result (structured output when --json-schema is in use).\n */\nexport interface ClaudeStreamUsage {\n outputTokens?: number;\n thinkingTokens?: number;\n costUsd?: number;\n model?: string;\n}\n\nexport interface ClaudeStreamOutcome {\n /** Final answer text; structured output is serialized as JSON. */\n result: string | null;\n isError: boolean;\n errorMessage?: string;\n usage: ClaudeStreamUsage;\n /** Lines on stdout that were not JSON (for debugging). */\n unparsedLines: number;\n}\n\ntype Json = Record<string, unknown>;\n\nconst isObject = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nexport class ClaudeStreamParser {\n private buffer = '';\n private text = '';\n private partialJson = '';\n private messageStructured: string | null = null;\n private resultStructured: string | null = null;\n private resultText: string | null = null;\n private isError = false;\n private errorMessage: string | undefined;\n private usage: ClaudeStreamUsage = {};\n private unparsed = 0;\n\n constructor(private readonly onEvent: (event: LlmEvent) => void = () => {}) {}\n\n push(chunk: string): void {\n this.buffer += chunk;\n let idx: number;\n while ((idx = this.buffer.indexOf('\\n')) !== -1) {\n const line = this.buffer.slice(0, idx);\n this.buffer = this.buffer.slice(idx + 1);\n this.handleLine(line);\n }\n }\n\n finish(): ClaudeStreamOutcome {\n if (this.buffer.trim()) this.handleLine(this.buffer);\n this.buffer = '';\n const result =\n this.resultStructured ?? this.messageStructured ?? (this.partialJson.trim() || null) ?? (this.resultText?.trim() || null) ?? (this.text.trim() || null);\n const outcome: ClaudeStreamOutcome = { result, isError: this.isError, usage: this.usage, unparsedLines: this.unparsed };\n if (this.errorMessage) outcome.errorMessage = this.errorMessage;\n return outcome;\n }\n\n private handleLine(line: string): void {\n const trimmed = line.trim();\n if (!trimmed) return;\n let ev: unknown;\n try {\n ev = JSON.parse(trimmed);\n } catch {\n this.unparsed++;\n return;\n }\n if (!isObject(ev)) return;\n switch (ev.type) {\n case 'stream_event':\n if (isObject(ev.event)) this.handleStreamEvent(ev.event);\n break;\n case 'assistant':\n if (isObject(ev.message)) this.handleAssistant(ev.message);\n break;\n case 'user':\n if (isObject(ev.message)) this.handleUser(ev.message);\n break;\n case 'result':\n this.handleResult(ev);\n break;\n default:\n break;\n }\n }\n\n private handleStreamEvent(event: Json): void {\n switch (event.type) {\n case 'message_start': {\n const model = isObject(event.message) && typeof event.message.model === 'string' ? event.message.model : undefined;\n if (model) {\n this.usage.model = model;\n this.onEvent({ type: 'usage', model });\n }\n break;\n }\n case 'content_block_start': {\n const block = isObject(event.content_block) ? event.content_block : {};\n if (block.type === 'text' || block.type === 'tool_use') {\n // A fresh answer supersedes anything streamed before (e.g. after a schema rejection).\n this.text = '';\n this.partialJson = '';\n this.onEvent({ type: 'answer-start' });\n }\n break;\n }\n case 'content_block_delta': {\n const delta = isObject(event.delta) ? event.delta : {};\n if (delta.type === 'thinking_delta') {\n const text = typeof delta.thinking === 'string' ? delta.thinking : '';\n this.onEvent(text ? { type: 'thinking', text } : { type: 'thinking-pulse' });\n } else if (delta.type === 'text_delta' && typeof delta.text === 'string' && delta.text) {\n this.text += delta.text;\n this.onEvent({ type: 'text', text: delta.text });\n } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string' && delta.partial_json) {\n this.partialJson += delta.partial_json;\n this.onEvent({ type: 'text', text: delta.partial_json });\n }\n break;\n }\n case 'message_delta': {\n if (isObject(event.usage)) this.recordUsage(event.usage);\n break;\n }\n default:\n break;\n }\n }\n\n private handleAssistant(message: Json): void {\n if (!Array.isArray(message.content)) return;\n for (const block of message.content) {\n if (isObject(block) && block.type === 'tool_use' && isObject(block.input)) {\n this.messageStructured = JSON.stringify(block.input);\n }\n }\n }\n\n /** Tool results the CLI feeds back, e.g. a structured-output validation failure. */\n private handleUser(message: Json): void {\n if (!Array.isArray(message.content)) return;\n for (const block of message.content) {\n if (!isObject(block) || block.type !== 'tool_result' || block.is_error !== true) continue;\n const content = typeof block.content === 'string' ? block.content : JSON.stringify(block.content ?? '');\n this.onEvent({ type: 'notice', text: `Answer rejected (${content.replace(/^Output does not match required schema:\\s*/i, 'schema: ').slice(0, 300)}); the model is retrying` });\n }\n }\n\n private handleResult(ev: Json): void {\n if (isObject(ev.structured_output)) this.resultStructured = JSON.stringify(ev.structured_output);\n if (typeof ev.result === 'string') this.resultText = ev.result;\n const subtype = typeof ev.subtype === 'string' ? ev.subtype : '';\n if (ev.is_error === true || subtype.startsWith('error')) {\n this.isError = true;\n const errors = Array.isArray(ev.errors) ? ev.errors.filter((e) => typeof e === 'string').join('; ') : '';\n this.errorMessage = errors || (typeof ev.result === 'string' && ev.result) || subtype || 'unknown error';\n }\n if (isObject(ev.usage)) this.recordUsage(ev.usage);\n if (typeof ev.total_cost_usd === 'number') this.usage.costUsd = ev.total_cost_usd;\n this.onEvent({ type: 'usage', ...this.usage });\n }\n\n private recordUsage(usage: Json): void {\n if (typeof usage.output_tokens === 'number') this.usage.outputTokens = usage.output_tokens;\n const details = usage.output_tokens_details;\n if (isObject(details) && typeof details.thinking_tokens === 'number') this.usage.thinkingTokens = details.thinking_tokens;\n this.onEvent({ type: 'usage', ...this.usage });\n }\n}\n","import { spawn } from 'node:child_process';\nimport { StringDecoder } from 'node:string_decoder';\nimport { LlmFailedError } from '../core/errors.js';\nimport { ClaudeStreamParser } from './claude-stream.js';\nimport type { CompleteOptions, LlmProvider } from './provider.js';\n\nexport type CommandKind = 'plain' | 'claude';\n\nexport interface CommandProviderOptions {\n command: string[];\n promptVia: 'stdin' | 'arg';\n timeoutMs: number;\n /**\n * \"plain\": stdout is the answer. \"claude\": the command is the Claude Code CLI;\n * streaming flags (and --json-schema when a schema is given) are appended and\n * the stream-json output is parsed for live thinking/text events.\n */\n kind?: CommandKind;\n /** JSON Schema the answer must satisfy (Claude kind only). */\n jsonSchema?: object;\n env?: Record<string, string>;\n cwd?: string;\n debug?: (msg: string) => void;\n}\n\nconst STDERR_TAIL_LINES = 20;\nconst CLAUDE_STREAM_ARGS = ['--output-format', 'stream-json', '--verbose', '--include-partial-messages'];\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 get kind(): CommandKind {\n return this.opts.kind ?? 'plain';\n }\n\n describe(): string {\n return this.opts.command.map(shellQuote).join(' ');\n }\n\n /** The full argv that will run, including any flags added for the command kind. */\n argv(prompt?: string): string[] {\n let argv = [...this.opts.command];\n if (this.kind === 'claude') {\n argv.push(...CLAUDE_STREAM_ARGS);\n if (this.opts.jsonSchema) argv.push('--json-schema', JSON.stringify(this.opts.jsonSchema));\n }\n if (prompt !== undefined && this.opts.promptVia === 'arg') argv = argv.map((a) => a.replaceAll('{prompt}', prompt));\n return argv;\n }\n\n complete(prompt: string, opts: CompleteOptions = {}): Promise<string> {\n const { promptVia, timeoutMs } = this.opts;\n const onEvent = opts.onEvent ?? (() => {});\n const [bin, ...args] = this.argv(prompt) as [string, ...string[]];\n const debug = this.opts.debug ?? (() => {});\n const started = Date.now();\n debug(`running ${this.describe()}${this.kind === 'claude' ? ' (+stream-json)' : ''} (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 parser = this.kind === 'claude' ? new ClaudeStreamParser(onEvent) : null;\n const decoder = new StringDecoder('utf8');\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n let outBytes = 0;\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 onEvent({ type: 'started' });\n child.stdout.on('data', (b: Buffer) => {\n outBytes += b.length;\n if (parser) {\n parser.push(decoder.write(b));\n } else {\n out.push(b);\n onEvent({ type: 'output', bytes: outBytes });\n }\n });\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 stderr = Buffer.concat(err).toString('utf8');\n const tail = stderr.trim().split('\\n').slice(-STDERR_TAIL_LINES).join('\\n');\n debug(`command exited with ${signal ? `signal ${signal}` : `code ${code}`} after ${Date.now() - started}ms; ${outBytes} bytes of stdout`);\n\n if (parser) {\n parser.push(decoder.end());\n const outcome = parser.finish();\n if (outcome.unparsedLines) debug(`${outcome.unparsedLines} non-JSON line(s) on stdout were ignored`);\n if (outcome.isError) {\n reject(new LlmFailedError(`Claude reported an error: ${outcome.errorMessage ?? 'unknown'}`, { hint: tail || undefined }));\n return;\n }\n if (code !== 0) {\n reject(new LlmFailedError(`LLM command failed (${signal ? `signal ${signal}` : `exit ${code}`}): ${this.describe()}${tail ? '\\n' + tail : ''}`));\n return;\n }\n if (!outcome.result) {\n reject(new LlmFailedError('Claude produced no result.', { hint: 'Run with --debug to see what came back.' }));\n return;\n }\n resolve(outcome.result);\n return;\n }\n\n if (code !== 0) {\n reject(new LlmFailedError(`LLM command failed (${signal ? `signal ${signal}` : `exit ${code}`}): ${this.describe()}${tail ? '\\n' + tail : ''}`));\n return;\n }\n resolve(Buffer.concat(out).toString('utf8'));\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 { TOUR_JSON_SCHEMA } from '../core/prompt/json-schema.js';\nimport { CommandProvider } from './command.js';\nimport type { LlmProvider } from './provider.js';\n\nexport type { CompleteOptions, LlmEvent, LlmProvider } from './provider.js';\nexport { CommandProvider, type CommandKind } from './command.js';\nexport { ClaudeStreamParser, type ClaudeStreamOutcome, type ClaudeStreamUsage } from './claude-stream.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 kind: llm.kind,\n jsonSchema: llm.kind === 'claude' && llm.jsonSchema ? TOUR_JSON_SCHEMA : undefined,\n env: llm.env,\n cwd: opts.cwd,\n debug: opts.debug,\n });\n}\n","import type { LlmEvent } from '../llm/provider.js';\n\n/** Where the pipeline reports what it is doing. The CLI renders this live; other consumers may ignore it. */\nexport interface ProgressSink {\n /** A new stage began (e.g. \"Collecting the diff\"). */\n phase(label: string): void;\n /** Something happened inside the model call. */\n llm(event: LlmEvent): void;\n}\n\nexport const noProgress: ProgressSink = { phase() {}, llm() {} };\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 { noProgress, type ProgressSink } from './progress.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 /** Receives stage changes and model events; the CLI renders these live. */\n progress?: ProgressSink;\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 progress = opts.progress ?? noProgress;\n const { config } = opts;\n const llm = resolveLlm(config);\n const codehost = opts.codehost ?? createCodeHost(config, { debug });\n\n progress.phase('Working out what to tour');\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 progress.phase('Collecting the diff');\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 progress.phase('Building the prompt');\n const built = buildPrompt({ ...context, maxBytes: llm.maxPromptBytes, structured: llm.kind === 'claude' && llm.jsonSchema });\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 progress = opts.progress ?? noProgress;\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 progress.phase('Checking the cache');\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 progress.phase(`Asking ${llm.preset ?? llm.command[0]}`);\n const output = await completeWithRepair(provider, prep.built.prompt, debug, progress);\n\n progress.phase('Assembling the tour');\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, progress: ProgressSink): Promise<LlmTourOutput> {\n const onEvent = (event: Parameters<ProgressSink['llm']>[0]) => progress.llm(event);\n let raw = await provider.complete(prompt, { onEvent });\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 progress.phase('Asking again (the first answer was not valid JSON)');\n raw = await provider.complete(prompt + REPAIR_SUFFIX(first.reason), { onEvent });\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 { describeSource, renderChange, type ChangeInput, type TruncationReport } from './prompt/build.js';\nimport type { Excerpt, Section, Tour, TourSource } from './types.js';\n\nexport interface ChatContextInput {\n tour: Tour;\n /** The change the tour was built from, as gathered by prepareTour. */\n change: ChangeInput;\n /** Soft budget for the whole context, in bytes; the tour is always kept and the diff is shortened to fit. */\n maxBytes: number;\n /** Where the tour JSON lives on disk, when cached, so a tool-using assistant can open it. */\n tourPath?: string | null;\n}\n\nexport interface ChatContext {\n /** Markdown meant for a system prompt: framing, the tour, then the change and its diff. */\n text: string;\n truncation: TruncationReport;\n}\n\nconst FRAMING = `# About this conversation\n\nYou are chatting with a developer about one specific change in the git repository you are running in. \\`bb\\` (the baby-bird CLI) generated the guided code tour below for that change; the developer has it open next to this chat, so treat it as shared context. Answer questions about the change using the tour, the diff after it, and the repository's files whenever you can read them. Refer to tour sections by number and title, and to code by file path and line number. If the diff below was shortened to fit, say so instead of guessing at what was left out.`;\n\n/** The text `bb ask` hands to the chat command as context. */\nexport function buildChatContext(input: ChatContextInput): ChatContext {\n const head = [FRAMING, '', ...renderTour(input.tour, input.change, input.tourPath ?? null), ''].join('\\n');\n const change = renderChange(input.change, Math.max(0, input.maxBytes - Buffer.byteLength(head, 'utf8') - 1));\n return { text: head + change.text, truncation: change.truncation };\n}\n\nfunction renderTour(tour: Tour, change: ChangeInput, tourPath: string | null): string[] {\n const lines: string[] = [`# The code tour: ${tour.title}`, ''];\n // Same sentence the change section below uses, so the two never disagree.\n lines.push(`- Change: ${describeSource(change.source, change.branch)}`);\n lines.push(`- Revisions: ${describeRevisions(change.source)}`);\n if (tour.pullRequest) lines.push(`- Pull request #${tour.pullRequest.number}: ${tour.pullRequest.title}${tour.pullRequest.url ? ` (${tour.pullRequest.url})` : ''}`);\n lines.push(`- Size: ${tour.stats.files} file${tour.stats.files === 1 ? '' : 's'}, +${tour.stats.additions} -${tour.stats.deletions}, ${tour.sections.length} section${tour.sections.length === 1 ? '' : 's'}`);\n lines.push(`- Generated: ${tour.generatedAt} by ${tour.generator.preset ?? tour.generator.command[0] ?? 'unknown'}`);\n if (tourPath) lines.push(`- Tour JSON: ${tourPath}`);\n if (tour.summary.trim()) lines.push('', tour.summary.trim());\n tour.sections.forEach((s, i) => lines.push('', ...renderSection(s, i + 1)));\n return lines;\n}\n\n/** The SHAs behind the change, with the git command that reproduces the diff. */\nfunction describeRevisions(source: TourSource): string {\n const head = source.headSha.slice(0, 12);\n if (source.kind === 'working') return `HEAD is ${head}`;\n const base = (source.mergeBase ?? source.baseSha).slice(0, 12);\n return `base ${base}, head ${head}; \\`git diff ${base} ${head}\\` reproduces the diff`;\n}\n\nfunction renderSection(s: Section, n: number): string[] {\n const lines = [`## ${n}. ${s.title}`, '', `${s.stats.files} file${s.stats.files === 1 ? '' : 's'}, +${s.stats.additions} -${s.stats.deletions}`];\n if (s.description.trim()) lines.push('', s.description.trim());\n if (s.files.length) lines.push('', 'Files:', ...s.files.map((f) => `- ${f}`));\n for (const e of s.excerpts) lines.push('', ...renderExcerpt(e));\n return lines;\n}\n\nfunction renderExcerpt(e: Excerpt): string[] {\n const note = e.note ? ` — ${e.note}` : '';\n const lines = [`Excerpt \\`${e.file}:${e.newStart}\\` (hunk ${e.hunkId})${note}`, '', '```'];\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 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 lines.push(`${oldNo} ${newNo} │${sign}${l.text}`);\n }\n lines.push('```');\n return lines;\n}\n","import { spawn } from 'node:child_process';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { constants as osConstants, tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { LlmFailedError } from '../core/errors.js';\n\n/** Tokens a chat command's argv may use. */\nexport const CONTEXT_FILE_TOKEN = '{context-file}';\nexport const CONTEXT_TOKEN = '{context}';\nexport const MESSAGE_TOKEN = '{message}';\n\nexport interface ChatArgvInput {\n command: string[];\n contextFile: string;\n context: string;\n message?: string;\n}\n\n/** Fill the tokens in a chat command. Entries that are exactly \"{message}\" are dropped when there is no message. */\nexport function chatArgv(input: ChatArgvInput): string[] {\n const message = input.message?.trim() ?? '';\n const out: string[] = [];\n for (const arg of input.command) {\n if (arg === MESSAGE_TOKEN && !message) continue;\n out.push(arg.replaceAll(CONTEXT_FILE_TOKEN, input.contextFile).replaceAll(CONTEXT_TOKEN, input.context).replaceAll(MESSAGE_TOKEN, message));\n }\n return out;\n}\n\n/** Which tokens a chat command uses, so the caller can warn about a message or context that would go nowhere. */\nexport function chatSlots(command: string[]): { context: boolean; message: boolean } {\n const joined = command.join('\\0');\n return { context: joined.includes(CONTEXT_FILE_TOKEN) || joined.includes(CONTEXT_TOKEN), message: joined.includes(MESSAGE_TOKEN) };\n}\n\nexport interface LaunchChatOptions {\n /** argv template; see chatArgv for the tokens. */\n command: string[];\n /** The system-prompt-like context, written to a temp file for \"{context-file}\". */\n context: string;\n /** Opening message, if any. */\n message?: string;\n cwd: string;\n env?: Record<string, string>;\n debug?: (msg: string) => void;\n /** Defaults to the terminal (\"inherit\"); tests use \"ignore\". */\n stdio?: 'inherit' | 'ignore';\n}\n\nexport interface ChatOutcome {\n /** The command's exit code, or 128 + signal number when a signal ended it. */\n exitCode: number;\n signal: NodeJS.Signals | null;\n}\n\n/**\n * Run an interactive chat command in the foreground, attached to this terminal, and resolve when it\n * exits. Ctrl+C reaches the child through the terminal, so bb ignores SIGINT itself while the chat\n * runs; SIGTERM and SIGHUP are forwarded.\n */\nexport async function launchChat(opts: LaunchChatOptions): Promise<ChatOutcome> {\n const debug = opts.debug ?? (() => {});\n const dir = await mkdtemp(join(tmpdir(), 'bb-chat-'));\n const contextFile = join(dir, 'context.md');\n await writeFile(contextFile, opts.context, { encoding: 'utf8', mode: 0o600 });\n const [bin, ...args] = chatArgv({ command: opts.command, contextFile, context: opts.context, message: opts.message }) as [string, ...string[]];\n debug(`launching ${describeArgv([bin, ...args], opts.context)} (context ${Buffer.byteLength(opts.context)} bytes in ${contextFile})`);\n\n try {\n return await new Promise<ChatOutcome>((resolve, reject) => {\n const env = { ...process.env, ...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: opts.cwd, env, stdio: opts.stdio ?? 'inherit' });\n\n const onInt = () => {};\n const onTerm = () => child.kill('SIGTERM');\n const onHup = () => child.kill('SIGHUP');\n process.on('SIGINT', onInt);\n process.on('SIGTERM', onTerm);\n process.on('SIGHUP', onHup);\n const cleanup = () => {\n process.off('SIGINT', onInt);\n process.off('SIGTERM', onTerm);\n process.off('SIGHUP', onHup);\n };\n\n child.on('error', (e: NodeJS.ErrnoException) => {\n cleanup();\n if (e.code === 'ENOENT') {\n reject(new LlmFailedError(`Chat 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 ${bin}: ${e.message}`, { cause: e }));\n }\n });\n child.on('close', (code, signal) => {\n cleanup();\n debug(`chat exited with ${signal ? `signal ${signal}` : `code ${code}`}`);\n const exitCode = code ?? (signal ? 128 + (osConstants.signals[signal] ?? 0) : 1);\n resolve({ exitCode, signal });\n });\n });\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n\n/** argv for logs, with the inline context (if any) replaced by a placeholder. */\nfunction describeArgv(argv: string[], context: string): string {\n return argv.map((a) => (context && a.includes(context) ? a.replace(context, '<context>') : a)).map(quote).join(' ');\n}\n\nfunction quote(arg: string): string {\n if (arg === '') return '\"\"';\n return /^[\\w@%+=:,./{}-]+$/.test(arg) ? arg : `'${arg.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n","import pc from 'picocolors';\nimport { UsageError } from '../core/errors.js';\nimport type { Excerpt, Section, Tour, TourSource, TourStats } from '../core/types.js';\nimport { highlightCode, languageForPath, truncateAnsi } from './highlight.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 style: ExcerptStyle = { highlight: Boolean(opts.color && opts.highlight) };\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, style));\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, style));\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\ninterface ExcerptStyle {\n highlight: boolean;\n}\n\nfunction renderSection(s: Section, index: number, count: number, c: Colors, width: number, style: ExcerptStyle): 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, style));\n }\n return lines;\n}\n\nfunction renderExcerpt(e: Excerpt, c: Colors, width: number, style: ExcerptStyle): 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 // gutter = 3 spaces + old + space + new + \" │\" ; body = sign + text\n const budget = Math.max(20, width - (3 + w * 2 + 3) - 1);\n const texts = e.lines.map((l) => expandTabs(l.text));\n\n const lang = style.highlight ? languageForPath(e.file) : null;\n const highlighted = lang ? highlightCode(texts.join('\\n'), lang, c) : null;\n\n e.lines.forEach((l, i) => {\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 gutter = c.dim(` ${oldNo} ${newNo} │`);\n const plain = texts[i]!;\n\n if (!highlighted) {\n const signStyled = l.type === 'add' ? c.green(sign) : l.type === 'del' ? c.red(sign) : sign;\n lines.push(`${gutter}${signStyled}${truncate(plain, budget)}`);\n return;\n }\n\n // Syntax colors on the text; add/del expressed by a colored sign, no row background.\n // Deliberately not bold: terminals often render bold + a base color via their \"bright\"\n // palette slot, and some themes leave that slot washed out.\n const text = truncateAnsi(highlighted[i]!, budget);\n if (l.type === 'ctx') {\n lines.push(`${gutter} ${text}`);\n return;\n }\n const signStyled = l.type === 'add' ? c.green('+') : c.red('-');\n lines.push(`${gutter}${signStyled}${text}`);\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 { common, createLowlight } from 'lowlight';\nimport type pc from 'picocolors';\n\ntype Colors = ReturnType<typeof pc.createColors>;\ntype Styler = (s: string) => string;\n\nconst lowlight = createLowlight(common);\n\n/** Map file extensions / names to highlight.js language ids (only those in lowlight's `common` set). */\nconst BY_EXT: Record<string, string> = {\n ts: 'typescript', mts: 'typescript', cts: 'typescript', tsx: 'typescript',\n js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'javascript',\n json: 'json', jsonc: 'json', json5: 'json',\n py: 'python', pyi: 'python',\n rb: 'ruby', rake: 'ruby', gemspec: 'ruby',\n go: 'go', rs: 'rust', java: 'java', kt: 'kotlin', kts: 'kotlin', swift: 'swift', scala: 'scala',\n c: 'c', h: 'c', cc: 'cpp', cpp: 'cpp', cxx: 'cpp', hpp: 'cpp', hh: 'cpp', cs: 'csharp', m: 'objectivec', mm: 'objectivec',\n php: 'php', pl: 'perl', pm: 'perl', lua: 'lua', r: 'r', dart: 'dart',\n sh: 'bash', bash: 'bash', zsh: 'bash', fish: 'bash',\n yml: 'yaml', yaml: 'yaml', toml: 'ini', ini: 'ini', cfg: 'ini', conf: 'ini',\n md: 'markdown', markdown: 'markdown',\n html: 'xml', htm: 'xml', xml: 'xml', svg: 'xml', vue: 'xml',\n css: 'css', scss: 'scss', less: 'less',\n sql: 'sql', graphql: 'graphql', gql: 'graphql',\n diff: 'diff', patch: 'diff',\n makefile: 'makefile', mk: 'makefile',\n vb: 'vbnet', vbnet: 'vbnet', wasm: 'wasm',\n};\n\nconst BY_NAME: Record<string, string> = {\n makefile: 'makefile', gnumakefile: 'makefile', dockerfile: 'bash', rakefile: 'ruby', gemfile: 'ruby',\n '.bashrc': 'bash', '.zshrc': 'bash', '.profile': 'bash', 'cmakelists.txt': 'cmake',\n};\n\nexport function languageForPath(path: string): string | null {\n const base = path.slice(path.lastIndexOf('/') + 1).toLowerCase();\n const byName = BY_NAME[base];\n if (byName && lowlight.registered(byName)) return byName;\n const dot = base.lastIndexOf('.');\n if (dot === -1) return null;\n const lang = BY_EXT[base.slice(dot + 1)];\n return lang && lowlight.registered(lang) ? lang : null;\n}\n\n/** highlight.js scope -> style. Deliberately avoids green/red so add/del stays unambiguous. */\nfunction stylers(c: Colors): Record<string, Styler> {\n return {\n keyword: c.magenta, 'selector-tag': c.magenta, 'template-tag': c.magenta, doctag: c.magenta,\n string: c.yellow, regexp: c.yellow, 'template-variable': c.yellow, subst: (s) => s,\n comment: c.gray, quote: c.gray,\n number: c.cyan, literal: c.cyan, symbol: c.cyan, bullet: c.cyan, link: c.cyan,\n title: c.blue, section: c.blue, 'selector-id': c.blue, 'selector-class': c.blue,\n type: c.cyan, built_in: c.cyan, class: c.cyan,\n attr: c.blue, attribute: c.blue, property: c.blue, variable: (s) => s, params: (s) => s,\n meta: c.gray, tag: c.blue, name: c.blue, 'selector-attr': c.blue, 'selector-pseudo': c.blue,\n addition: (s) => s, deletion: (s) => s, emphasis: c.italic, strong: c.bold,\n };\n}\n\ninterface HastNode {\n type: string;\n value?: string;\n children?: HastNode[];\n properties?: { className?: string[] };\n}\n\n/**\n * Highlight `code` and return one ANSI-styled string per input line. Tokens\n * that span lines (block comments, template strings) are styled on every line.\n */\nexport function highlightCode(code: string, lang: string, c: Colors): string[] | null {\n if (!lowlight.registered(lang)) return null;\n let tree: HastNode;\n try {\n tree = lowlight.highlight(lang, code) as unknown as HastNode;\n } catch {\n return null;\n }\n const map = stylers(c);\n const lines: string[] = [''];\n\n const visit = (node: HastNode, style: Styler | null): void => {\n if (node.type === 'text' && typeof node.value === 'string') {\n const parts = node.value.split('\\n');\n parts.forEach((part, i) => {\n if (i > 0) lines.push('');\n if (part) lines[lines.length - 1] += style ? style(part) : part;\n });\n return;\n }\n let own = style;\n for (const cls of node.properties?.className ?? []) {\n const scope = cls.startsWith('hljs-') ? cls.slice(5) : cls;\n const s = map[scope];\n if (s) {\n own = s;\n break;\n }\n }\n for (const child of node.children ?? []) visit(child, own);\n };\n visit(tree, null);\n\n const expected = code.split('\\n').length;\n if (lines.length !== expected) return null; // defensive: never let a grammar quirk misalign the gutter\n return lines;\n}\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\\x1b\\[[0-9;]*m/g;\n\nexport function stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '');\n}\n\nexport function visibleLength(s: string): number {\n return stripAnsi(s).length;\n}\n\n/** Restore default foreground and intensity/italic/underline, but leave any background in place. */\nconst SOFT_RESET = '\\x1b[39m\\x1b[22m\\x1b[23m\\x1b[24m';\n\n/** Cut a styled string to `max` visible characters, keeping escape codes intact. */\nexport function truncateAnsi(s: string, max: number): string {\n if (visibleLength(s) <= max) return s;\n let out = '';\n let seen = 0;\n const limit = Math.max(0, max - 1);\n for (let i = 0; i < s.length; ) {\n if (s[i] === '\\x1b') {\n const m = /^\\x1b\\[[0-9;]*m/.exec(s.slice(i));\n if (m) {\n out += m[0];\n i += m[0].length;\n continue;\n }\n }\n if (seen >= limit) break;\n out += s[i];\n seen++;\n i++;\n }\n return out + SOFT_RESET + '…';\n}\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,EAEtB,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,CAAC,EAAE,SAAS;AAAA,EACxD,MAAM,EAAE,OAAO,EAAE,SAAS;AAC5B,CAAC;AAEM,IAAM,mBAAmB,EAAE,OAAO;AAAA,EACvC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,aAAa,EAAE,OAAO;AAAA,EACtB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACpC,UAAU,EAAE,MAAM,mBAAmB,EAAE,SAAS;AAClD,CAAC;AAEM,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,SAAS,EAAE,OAAO;AAAA,EAClB,UAAU,EAAE,MAAM,gBAAgB,EAAE,IAAI,CAAC;AAC3C,CAAC;AAOD,IAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,MAAM,EAAE,KAAK,CAAC,OAAO,OAAO,KAAK,CAAC;AAAA,EAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EACjC,OAAO,EAAE,O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ACvB,QAAM,IAAI,KAAK,MAAM,IAAI,EAAE;AAC3B,SAAO,GAAG,CAAC;AACb;;;AExMA,SAAS,SAAAG,cAAa;AAUtB,eAAsB,gBAAgB,QAAgB,MAAmC;AACvF,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,YAAY,OAAO,MAAM,IAAI,EAAE;AACrC,QAAM,aAAa,KAAK,SAAS,YAAa,KAAK,SAAS,UAAU,KAAK,SAAS,YAAY,KAAK,OAAO;AAC5G,MAAI,CAAC,YAAY;AACf,UAAM,YAAY,MAAM;AACxB;AAAA,EACF;AACA,QAAM,WAAY,IAAI,SAAS,IAAI,MAAM,KAAK,KAAM;AACpD,QAAM,MAAM,aAAa,UAAU,CAAC,IAAI,OAAO,cAAc;AAC7D,QAAM,IAAI,QAAc,CAAC,YAAY;AACnC,UAAM,QAAQA,OAAM,KAAK,EAAE,OAAO,MAAM,OAAO,CAAC,QAAQ,WAAW,SAAS,GAAG,IAAI,CAAC;AACpF,QAAI,WAAW;AACf,UAAM,GAAG,SAAS,MAAM;AACtB,iBAAW;AACX,cAAQ,OAAO,MAAM,MAAM;AAC3B,cAAQ;AAAA,IACV,CAAC;AACD,UAAM,GAAG,SAAS,MAAM;AACtB,UAAI,CAAC,SAAU,SAAQ;AAAA,IACzB,CAAC;AACD,UAAM,MAAM,GAAG,SAAS,MAAM;AAAA,IAAC,CAAC;AAChC,UAAM,MAAM,IAAI,MAAM;AAAA,EACxB,CAAC;AACH;AAGO,SAAS,YAAY,QAA+B;AACzD,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,YAAQ,OAAO,MAAM,QAAQ,MAAM,QAAQ,CAAC;AAAA,EAC9C,CAAC;AACH;","names":["z","z","gitRoot","common","quote","readFile","join","join","readFile","rename","execFile","execFile","join","join","spawn","rm","writeFile","join","join","writeFile","spawn","rm","renderSection","describeSource","visibleLength","renderExcerpt","signStyled","spawn"]}
|