@raegent/earshot 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,105 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../core/src/context/agents-md.ts", "../../providers/src/auth.ts", "../../providers/src/paths.ts", "../../providers/src/catalog/supported.ts", "../../providers/src/catalog/index.ts", "../../providers/src/registry.ts", "../../providers/src/wire/adapters.ts", "../../providers/src/errors.ts", "../../providers/src/wire/ai-sdk-prompt.ts", "../../providers/src/wire/ai-sdk.ts", "../../providers/src/wire/ollama.ts", "../../providers/src/builtin.ts", "../../providers/src/oauth/loopback.ts", "../../providers/src/oauth/openrouter.ts", "../../providers/src/oauth/pkce.ts", "../../core/src/context/shapers.ts", "../../core/src/context/compaction.ts", "../../core/src/context/system-prompt.ts", "../../core/src/memory/store.ts", "../../core/src/model.ts", "../../core/src/tools/fs-paths.ts", "../../core/src/tools/glob-match.ts", "../../core/src/permissions/rules.ts", "../../core/src/permissions/engine.ts", "../../core/src/permissions/settings.ts", "../../core/src/plan/index.ts", "../../core/src/scope/contract.ts", "../../core/src/skills/discover.ts", "../../core/src/skills/frontmatter.ts", "../../core/src/tools/types.ts", "../../core/src/tools/schema.ts", "../../core/src/tools/ask-user.ts", "../../core/src/tools/bash.ts", "../../core/src/tools/exec.ts", "../../core/src/tools/shell.ts", "../../core/src/tools/declare-scope.ts", "../../core/src/tools/edit.ts", "../../core/src/tools/diff.ts", "../../core/src/tools/glob.ts", "../../core/src/tools/walk.ts", "../../core/src/tools/grep.ts", "../../core/src/tools/ls.ts", "../../core/src/tools/read.ts", "../../core/src/tools/task.ts", "../../core/src/tools/todo.ts", "../../core/src/tools/web-fetch.ts", "../../core/src/tools/write.ts", "../../core/src/tools/jobs.ts", "../../core/src/tools/skill.ts", "../../core/src/tools/tool-search.ts", "../../core/src/tools/index.ts", "../../core/src/verify/detect.ts", "../../core/src/verify/run.ts", "../../core/src/agent.ts", "../../core/src/hooks/config.ts", "../../core/src/hooks/run.ts", "../../core/src/hooks/runner.ts", "../../core/src/memory/detect.ts", "../../core/src/undo/shadow-git.ts", "../../core/src/session/store.ts", "../../core/src/version.ts", "../../core/src/session/repair.ts", "../../core/src/session/create.ts", "../src/args.ts", "../../acp/src/events.ts", "../../acp/src/server.ts", "../src/extensions/index.ts", "../../mcp/src/client.ts", "../../mcp/src/config.ts", "../../mcp/src/tool.ts", "../../mcp/src/manager.ts", "../src/extensions/modules.ts", "../src/commands/acp.ts", "../src/commands/auth.ts", "../src/commands/doctor.ts", "../src/commands/extensions.ts", "../src/budget.ts", "../src/image.ts", "../src/output.ts", "../src/commands/headless.ts", "../../tui/src/app.tsx", "../../tui/src/components/markdown.tsx", "../../tui/src/theme.ts", "../../tui/src/components/memory-capture.tsx", "../../tui/src/components/permission.tsx", "../../tui/src/components/diff.tsx", "../../tui/src/components/question.tsx", "../../tui/src/components/text-input.tsx", "../../tui/src/components/status.tsx", "../../tui/src/components/tool-block.tsx", "../../tui/src/run.tsx", "../src/commands/interactive.ts", "../src/commands/mcp.ts", "../src/commands/models.ts", "../src/index.ts", "../src/main.ts"],
4
+ "sourcesContent": [
5
+ "import { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, parse, relative, sep } from 'node:path';\nimport { configDir } from '@earshot/providers';\n\n/** Checked in each directory, in order. The first that exists in a directory wins. */\nexport const MEMORY_FILENAMES = ['AGENTS.md', 'CLAUDE.md'];\n\nexport interface MemoryFile {\n path: string;\n content: string;\n /** `user` for the one in the config directory, `project` for the rest. */\n scope: 'user' | 'project';\n}\n\nasync function readIfPresent(path: string): Promise<string | undefined> {\n const info = await stat(path).catch(() => undefined);\n if (!info?.isFile()) return undefined;\n const content = await readFile(path, 'utf8').catch(() => undefined);\n return content?.trim() === '' ? undefined : content;\n}\n\nasync function readDirectory(dir: string): Promise<{ path: string; content: string } | undefined> {\n for (const name of MEMORY_FILENAMES) {\n const path = join(dir, name);\n const content = await readIfPresent(path);\n // AGENTS.md wins over CLAUDE.md in the same directory rather than both being\n // loaded: a project that has both almost always has one as a pointer to the\n // other, and concatenating them duplicates every instruction.\n if (content !== undefined) return { path, content };\n }\n return undefined;\n}\n\n/** Where the walk upward stops: a repository root, or the filesystem root. */\nasync function isBoundary(dir: string): Promise<boolean> {\n return (await stat(join(dir, '.git')).catch(() => undefined)) !== undefined;\n}\n\n/**\n * Collects instruction files from the config directory and from every directory\n * between the repository root and `cwd`.\n *\n * Ordered outermost-first so the nearest file is read last. Nothing here resolves\n * a conflict between two files: they are concatenated, and a model reading two\n * instructions on the same subject takes the later one. Making \"nearest wins\"\n * mechanical would mean parsing prose, which is not something to get subtly wrong.\n */\nexport async function loadMemoryFiles(cwd: string): Promise<MemoryFile[]> {\n const files: MemoryFile[] = [];\n\n const global = await readDirectory(configDir());\n if (global) files.push({ ...global, scope: 'user' });\n\n const chain: string[] = [];\n let dir = cwd;\n const home = homedir();\n const { root } = parse(cwd);\n\n while (true) {\n chain.push(dir);\n if (await isBoundary(dir)) break;\n // Never walks past the home directory: above it the files belong to other\n // projects, or to no project at all.\n if (dir === root || dir === home) break;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n for (const directory of chain.reverse()) {\n const found = await readDirectory(directory);\n if (found) files.push({ ...found, scope: 'project' });\n }\n return files;\n}\n\n/** Renders loaded files into the system prompt, each labelled with its path. */\nexport function renderMemory(files: MemoryFile[], cwd: string): string {\n if (files.length === 0) return '';\n const sections = files.map((file) => {\n const label = file.scope === 'user' ? file.path : displayRelative(cwd, file.path);\n return `<memory path=\"${label}\">\\n${file.content.trim()}\\n</memory>`;\n });\n return (\n 'Instructions from the user and this project. They take precedence over your ' +\n 'defaults. Where two conflict, the later one is nearer to the working directory ' +\n `and wins.\\n\\n${sections.join('\\n\\n')}`\n );\n}\n\nfunction displayRelative(cwd: string, path: string): string {\n const rel = relative(cwd, path);\n return rel.startsWith('..') ? path : rel.split(sep).join('/');\n}\n",
6
+ "import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { authFile } from './paths.ts';\nimport type { AuthSpec, Credentials, Provider } from './types.ts';\n\ntype AuthFileShape = { version: 1; providers: Record<string, Credentials> };\n\n/**\n * Credential store. On-disk file is 0600 and written atomically; OAuth refreshes\n * take a lock file so two concurrent earshot processes cannot clobber each other.\n */\nexport class AuthStore {\n #path: string;\n #cache: AuthFileShape | undefined;\n\n constructor(path = authFile()) {\n this.#path = path;\n }\n\n async #load(): Promise<AuthFileShape> {\n if (this.#cache) return this.#cache;\n try {\n const raw = await readFile(this.#path, 'utf8');\n const parsed = JSON.parse(raw) as AuthFileShape;\n this.#cache = parsed.providers ? parsed : { version: 1, providers: {} };\n } catch {\n this.#cache = { version: 1, providers: {} };\n }\n return this.#cache;\n }\n\n async get(providerId: string): Promise<Credentials | undefined> {\n return (await this.#load()).providers[providerId];\n }\n\n async set(providerId: string, creds: Credentials): Promise<void> {\n const data = await this.#load();\n data.providers[providerId] = creds;\n await this.#flush(data);\n }\n\n async remove(providerId: string): Promise<void> {\n const data = await this.#load();\n delete data.providers[providerId];\n await this.#flush(data);\n }\n\n async #flush(data: AuthFileShape): Promise<void> {\n await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });\n const tmp = `${this.#path}.${process.pid}.tmp`;\n await writeFile(tmp, `${JSON.stringify(data, null, 2)}\\n`, { mode: 0o600 });\n await rename(tmp, this.#path);\n this.#cache = data;\n }\n}\n\nexport interface ResolveAuthOptions {\n /** From `--api-key` or equivalent; highest precedence. */\n cliApiKey?: string;\n env?: NodeJS.ProcessEnv;\n store?: AuthStore;\n}\n\n/**\n * Resolution order (plan §Auth resolution):\n * CLI flag -> env var -> auth.json -> provider-native ambient credentials.\n */\nexport async function resolveCredentials(\n provider: Provider,\n opts: ResolveAuthOptions = {},\n): Promise<Credentials | undefined> {\n const env = opts.env ?? process.env;\n if (opts.cliApiKey) return { type: 'api-key', apiKey: opts.cliApiKey };\n\n for (const name of envVarsOf(provider.auth)) {\n const value = env[name];\n if (value) return { type: 'api-key', apiKey: value };\n }\n\n const stored = await (opts.store ?? new AuthStore()).get(provider.id);\n if (stored) return stored;\n\n if (provider.auth.kind === 'ambient' || provider.auth.kind === 'none') {\n return { type: 'ambient' };\n }\n return undefined;\n}\n\nfunction envVarsOf(auth: AuthSpec): string[] {\n return 'envVars' in auth && auth.envVars ? auth.envVars : [];\n}\n",
7
+ "import { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\n/** XDG on Linux/mac, %APPDATA%/%LOCALAPPDATA% on Windows. */\nexport function configDir(): string {\n const env = process.env.EARSHOT_CONFIG_DIR;\n if (env) return env;\n if (platform() === 'win32') {\n return join(process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), 'earshot');\n }\n return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'earshot');\n}\n\nexport function dataDir(): string {\n const env = process.env.EARSHOT_DATA_DIR;\n if (env) return env;\n if (platform() === 'win32') {\n return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'earshot');\n }\n return join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'earshot');\n}\n\nexport const authFile = (): string => join(configDir(), 'auth.json');\nexport const sessionsDir = (): string => join(dataDir(), 'sessions');\n",
8
+ "import type { WireApiKind } from '../types.ts';\n\n/**\n * The provider table. Adding a vendor is an entry here plus, if it is not already\n * OpenAI-compatible, a wire adapter - which is the whole point of the layer.\n *\n * `catalogId` is the models.dev provider id the snapshot is pruned to. `baseUrl`\n * is only needed where models.dev has no `api` field for the provider.\n */\nexport interface SupportedProvider {\n id: string;\n catalogId: string;\n api: WireApiKind;\n /** Overrides the catalog's `api` field. */\n baseUrl?: string;\n /** Overrides the catalog's `env` list. */\n envVars?: string[];\n auth?: 'api-key' | 'oauth' | 'ambient' | 'none';\n notice?: string;\n}\n\nexport const SUPPORTED_PROVIDERS: SupportedProvider[] = [\n // --- first-class adapters -------------------------------------------------\n { id: 'anthropic', catalogId: 'anthropic', api: 'anthropic-messages' },\n { id: 'openai', catalogId: 'openai', api: 'openai-responses' },\n { id: 'google', catalogId: 'google', api: 'google-generative-ai' },\n\n // --- ambient-credential clouds -------------------------------------------\n { id: 'bedrock', catalogId: 'amazon-bedrock', api: 'bedrock-converse', auth: 'ambient' },\n { id: 'vertex', catalogId: 'google-vertex', api: 'google-vertex', auth: 'ambient' },\n { id: 'azure', catalogId: 'azure', api: 'azure-openai' },\n\n // --- OpenAI-compatible vendors: a base URL and an env var, nothing more ---\n // OpenRouter publishes a PKCE flow for third-party apps: `earshot auth login\n // openrouter` uses it, and an API key still works exactly as before.\n { id: 'openrouter', catalogId: 'openrouter', api: 'openai-completions', auth: 'oauth' },\n {\n id: 'groq',\n catalogId: 'groq',\n api: 'openai-completions',\n baseUrl: 'https://api.groq.com/openai/v1',\n },\n { id: 'deepseek', catalogId: 'deepseek', api: 'openai-completions' },\n { id: 'xai', catalogId: 'xai', api: 'openai-completions', baseUrl: 'https://api.x.ai/v1' },\n {\n id: 'mistral',\n catalogId: 'mistral',\n api: 'openai-completions',\n baseUrl: 'https://api.mistral.ai/v1',\n },\n {\n id: 'together',\n catalogId: 'togetherai',\n api: 'openai-completions',\n baseUrl: 'https://api.together.xyz/v1',\n },\n { id: 'fireworks', catalogId: 'fireworks-ai', api: 'openai-completions' },\n {\n id: 'cerebras',\n catalogId: 'cerebras',\n api: 'openai-completions',\n baseUrl: 'https://api.cerebras.ai/v1',\n },\n {\n id: 'deepinfra',\n catalogId: 'deepinfra',\n api: 'openai-completions',\n baseUrl: 'https://api.deepinfra.com/v1/openai',\n },\n { id: 'nebius', catalogId: 'nebius', api: 'openai-completions' },\n { id: 'llama', catalogId: 'llama', api: 'openai-completions' },\n\n // --- local runtimes -------------------------------------------------------\n {\n id: 'lmstudio',\n catalogId: 'lmstudio',\n api: 'openai-completions',\n baseUrl: 'http://127.0.0.1:1234/v1',\n auth: 'none',\n notice: 'LM Studio does not stream tool calls; earshot falls back to a buffered call.',\n },\n];\n\nexport const SUPPORTED_PROVIDER_IDS: string[] = [\n ...new Set(SUPPORTED_PROVIDERS.map((p) => p.catalogId)),\n];\n",
9
+ "import type { Model, ModelCapabilities, ModelCost, WireApiKind } from '../types.ts';\nimport snapshot from './snapshot.json' with { type: 'json' };\nimport { SUPPORTED_PROVIDERS, type SupportedProvider } from './supported.ts';\n\nexport type { SupportedProvider } from './supported.ts';\nexport { SUPPORTED_PROVIDER_IDS, SUPPORTED_PROVIDERS } from './supported.ts';\n\nexport interface CatalogModel {\n id: string;\n name: string;\n context: number;\n output: number;\n reasoning: boolean;\n tools: boolean;\n vision: boolean;\n cost?: ModelCost;\n releaseDate?: string;\n}\n\nexport interface CatalogProvider {\n id: string;\n name: string;\n env: string[];\n api?: string;\n doc?: string;\n models: Record<string, CatalogModel>;\n}\n\nexport interface Catalog {\n generatedAt: string;\n source: string;\n providers: Record<string, CatalogProvider>;\n}\n\nconst bundled = snapshot as unknown as Catalog;\n\n/**\n * The model catalog. Defaults to the snapshot vendored at build time; a refresh\n * (`earshot models --refresh`) swaps in a live copy, and user config can override\n * or add entries for models the registry does not know about yet.\n */\nexport class ModelCatalog {\n #catalog: Catalog;\n #overrides: Record<string, Partial<CatalogModel>> = {};\n\n constructor(catalog: Catalog = bundled) {\n this.#catalog = catalog;\n }\n\n get generatedAt(): string {\n return this.#catalog.generatedAt;\n }\n\n provider(catalogId: string): CatalogProvider | undefined {\n return this.#catalog.providers[catalogId];\n }\n\n /** Keyed `\"<providerId>/<modelId>\"`; merged over the catalog entry. */\n applyOverrides(overrides: Record<string, Partial<CatalogModel>>): void {\n this.#overrides = { ...this.#overrides, ...overrides };\n }\n\n /** Builds the unified `Model` list for one supported provider. */\n modelsFor(supported: SupportedProvider): Model[] {\n const provider = this.provider(supported.catalogId);\n if (!provider) return [];\n return Object.values(provider.models).map((m) =>\n this.#toModel({ ...m, ...this.#overrides[`${supported.id}/${m.id}`] }, supported),\n );\n }\n\n #toModel(m: CatalogModel, supported: SupportedProvider): Model {\n const capabilities: ModelCapabilities = {\n tools: m.tools,\n vision: m.vision,\n reasoning: m.reasoning,\n // Providers that will 400 unless prior reasoning blocks are replayed verbatim.\n ...(m.reasoning && REASONING_REPLAY.has(supported.api) ? { reasoningReplay: true } : {}),\n };\n return {\n id: m.id,\n providerId: supported.id,\n name: m.name,\n contextWindow: m.context,\n maxOutputTokens: m.output,\n capabilities,\n api: supported.api,\n ...(m.cost ? { cost: m.cost } : {}),\n ...(m.releaseDate ? { releaseDate: m.releaseDate } : {}),\n };\n }\n}\n\nconst REASONING_REPLAY: Set<WireApiKind> = new Set([\n 'anthropic-messages',\n 'openai-responses',\n 'openai-codex-responses',\n 'google-generative-ai',\n 'google-vertex',\n]);\n\n/** Fetches a fresh catalog from models.dev, pruned the same way as the snapshot. */\nexport async function fetchCatalog(source = bundled.source): Promise<Catalog> {\n const response = await fetch(source);\n if (!response.ok) throw new Error(`models.dev returned ${response.status}`);\n const raw = (await response.json()) as Record<string, RawProvider>;\n\n const providers: Record<string, CatalogProvider> = {};\n for (const id of new Set(SUPPORTED_PROVIDERS.map((p) => p.catalogId))) {\n const p = raw[id];\n if (!p) continue;\n providers[id] = {\n id,\n name: p.name,\n env: p.env ?? [],\n ...(p.api ? { api: p.api } : {}),\n ...(p.doc ? { doc: p.doc } : {}),\n models: Object.fromEntries(\n Object.entries(p.models)\n .filter(([, m]) => (m.modalities?.output ?? ['text']).includes('text'))\n .filter(([, m]) => (m.limit?.context ?? 0) > 0)\n .map(([modelId, m]) => [\n modelId,\n {\n id: m.id,\n name: m.name,\n context: m.limit?.context || 128_000,\n output: m.limit?.output || 8_192,\n reasoning: m.reasoning ?? false,\n tools: m.tool_call ?? true,\n vision: m.modalities?.input?.includes('image') ?? false,\n ...(m.release_date ? { releaseDate: m.release_date } : {}),\n ...(m.cost\n ? {\n cost: {\n input: m.cost.input ?? 0,\n output: m.cost.output ?? 0,\n ...(m.cost.cache_read != null ? { cacheRead: m.cost.cache_read } : {}),\n ...(m.cost.cache_write != null ? { cacheWrite: m.cost.cache_write } : {}),\n },\n }\n : {}),\n },\n ]),\n ),\n };\n }\n return { generatedAt: new Date().toISOString(), source, providers };\n}\n\ninterface RawProvider {\n name: string;\n env?: string[];\n npm?: string;\n api?: string;\n doc?: string;\n models: Record<\n string,\n {\n id: string;\n name: string;\n reasoning?: boolean;\n tool_call?: boolean;\n release_date?: string;\n modalities?: { input?: string[]; output?: string[] };\n limit?: { context?: number; output?: number };\n cost?: { input?: number; output?: number; cache_read?: number; cache_write?: number };\n }\n >;\n}\n",
10
+ "import type { Model, Provider, WireApi, WireApiKind } from './types.ts';\n\n/**\n * Holds the built-in and user-configured providers plus their models.\n * Adding a provider means registering one object here - no other file changes.\n */\nexport class ProviderRegistry {\n #providers = new Map<string, Provider>();\n #wires = new Map<WireApiKind, WireApi>();\n\n register(provider: Provider): this {\n if (this.#providers.has(provider.id)) {\n throw new Error(`provider \"${provider.id}\" is already registered`);\n }\n this.#providers.set(provider.id, provider);\n return this;\n }\n\n registerWire(wire: WireApi): this {\n this.#wires.set(wire.kind, wire);\n return this;\n }\n\n get(id: string): Provider | undefined {\n return this.#providers.get(id);\n }\n\n list(): Provider[] {\n return [...this.#providers.values()];\n }\n\n models(): Model[] {\n return this.list().flatMap((p) => p.models());\n }\n\n /** Resolve \"provider/model\" or a bare model id (first match wins). */\n resolveModel(ref: string): { provider: Provider; model: Model } | undefined {\n const slash = ref.indexOf('/');\n if (slash > 0) {\n const provider = this.#providers.get(ref.slice(0, slash));\n const modelId = ref.slice(slash + 1);\n const model = provider?.models().find((m) => m.id === modelId);\n if (provider && model) return { provider, model };\n }\n for (const provider of this.#providers.values()) {\n const model = provider.models().find((m) => m.id === ref);\n if (model) return { provider, model };\n }\n return undefined;\n }\n\n wireFor(provider: Provider, model: Model): WireApi {\n const kind = typeof provider.api === 'function' ? provider.api(model) : provider.api;\n const wire = this.#wires.get(kind);\n if (!wire) throw new Error(`no wire adapter registered for \"${kind}\"`);\n return wire;\n }\n}\n",
11
+ "import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport { createAzure } from '@ai-sdk/azure';\nimport { createGoogleGenerativeAI } from '@ai-sdk/google';\nimport { createVertex } from '@ai-sdk/google-vertex';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { LanguageModelV4 } from '@ai-sdk/provider';\nimport type { WireApi, WireContext } from '../types.ts';\nimport { createAiSdkWire } from './ai-sdk.ts';\nimport { ollamaNativeWire } from './ollama.ts';\n\n/**\n * Every wire adapter earshot ships. Each is a two-line binding of an AI SDK\n * provider package to the shared bridge, which is what keeps adding a vendor\n * cheap: an OpenAI-compatible vendor needs no adapter at all, only a base URL.\n */\n\nconst key = (ctx: WireContext): string =>\n ctx.credentials.apiKey ?? ctx.credentials.accessToken ?? '';\n\nconst common = (ctx: WireContext) => ({\n ...(ctx.baseUrl ? { baseURL: ctx.baseUrl } : {}),\n ...(ctx.headers ? { headers: ctx.headers } : {}),\n ...(ctx.fetch ? { fetch: ctx.fetch } : {}),\n});\n\nexport const anthropicWire: WireApi = createAiSdkWire('anthropic-messages', (modelId, ctx) =>\n createAnthropic({ apiKey: key(ctx), ...common(ctx) })(modelId),\n);\n\nexport const openaiResponsesWire: WireApi = createAiSdkWire('openai-responses', (modelId, ctx) =>\n createOpenAI({ apiKey: key(ctx), ...common(ctx) }).responses(modelId),\n);\n\nexport const googleWire: WireApi = createAiSdkWire('google-generative-ai', (modelId, ctx) =>\n createGoogleGenerativeAI({ apiKey: key(ctx), ...common(ctx) })(modelId),\n);\n\n/**\n * The workhorse: every OpenAI-compatible vendor (OpenRouter, Groq, DeepSeek, xAI,\n * Mistral, Together, Fireworks, Cerebras, LM Studio, vLLM, llama.cpp, and any\n * custom base URL) runs through this one adapter.\n */\nexport const openaiCompatibleWire: WireApi = createAiSdkWire(\n 'openai-completions',\n (modelId, ctx): LanguageModelV4 => {\n if (!ctx.baseUrl) throw new Error('an OpenAI-compatible provider requires a baseUrl');\n return createOpenAICompatible({\n name: 'openai-compatible',\n baseURL: ctx.baseUrl,\n ...(ctx.credentials.apiKey ? { apiKey: ctx.credentials.apiKey } : {}),\n ...(ctx.headers ? { headers: ctx.headers } : {}),\n ...(ctx.fetch ? { fetch: ctx.fetch } : {}),\n })(modelId);\n },\n);\n\n/** Credentials come from the AWS chain (env, profile, IMDS) when not set explicitly. */\nexport const bedrockWire: WireApi = createAiSdkWire('bedrock-converse', (modelId, ctx) => {\n const extra = ctx.credentials.extra ?? {};\n return createAmazonBedrock({\n ...(typeof extra.region === 'string' ? { region: extra.region } : {}),\n ...(ctx.credentials.apiKey ? { apiKey: ctx.credentials.apiKey } : {}),\n ...common(ctx),\n })(modelId);\n});\n\n/** Uses Google Application Default Credentials when no key is supplied. */\nexport const vertexWire: WireApi = createAiSdkWire('google-vertex', (modelId, ctx) => {\n const extra = ctx.credentials.extra ?? {};\n return createVertex({\n ...(typeof extra.project === 'string' ? { project: extra.project } : {}),\n ...(typeof extra.location === 'string' ? { location: extra.location } : {}),\n ...common(ctx),\n })(modelId);\n});\n\nexport const azureWire: WireApi = createAiSdkWire('azure-openai', (modelId, ctx) => {\n const extra = ctx.credentials.extra ?? {};\n return createAzure({\n apiKey: key(ctx),\n ...(typeof extra.resourceName === 'string' ? { resourceName: extra.resourceName } : {}),\n ...common(ctx),\n }).responses(modelId);\n});\n\nexport const ALL_WIRES: WireApi[] = [\n anthropicWire,\n openaiResponsesWire,\n googleWire,\n openaiCompatibleWire,\n bedrockWire,\n vertexWire,\n azureWire,\n ollamaNativeWire,\n];\n",
12
+ "import type { EarshotError } from './types.ts';\n\nexport function earshotError(\n kind: EarshotError['kind'],\n message: string,\n opts: { retryable?: boolean; status?: number; cause?: unknown } = {},\n): EarshotError {\n return {\n kind,\n message,\n retryable: opts.retryable ?? (kind === 'rate_limit' || kind === 'server' || kind === 'network'),\n ...(opts.status !== undefined ? { status: opts.status } : {}),\n ...(opts.cause !== undefined ? { cause: opts.cause } : {}),\n };\n}\n\n/** Map an HTTP status to our error taxonomy. Adapters refine `message`. */\nexport function errorFromStatus(status: number, message: string, cause?: unknown): EarshotError {\n const kind: EarshotError['kind'] =\n status === 401 || status === 403\n ? 'auth'\n : status === 429\n ? 'rate_limit'\n : status >= 500\n ? 'server'\n : 'invalid_request';\n return earshotError(kind, message, { status, ...(cause !== undefined ? { cause } : {}) });\n}\n\nexport class AbortedError extends Error {\n constructor() {\n super('aborted');\n this.name = 'AbortedError';\n }\n}\n",
13
+ "import type {\n LanguageModelV4FilePart,\n LanguageModelV4Message,\n LanguageModelV4Prompt,\n LanguageModelV4ReasoningPart,\n LanguageModelV4TextPart,\n LanguageModelV4ToolCallPart,\n LanguageModelV4ToolResultOutput,\n LanguageModelV4ToolResultPart,\n SharedV4FileData,\n} from '@ai-sdk/provider';\nimport type {\n ImagePart,\n Message,\n ModelRequest,\n ToolResultOutput,\n ToolResultPart,\n} from '../types.ts';\n\n/**\n * Unified messages -> LanguageModelV4 prompt.\n *\n * Our `providerMetadata` maps onto the spec's per-part `providerOptions`, which is\n * how round-trip-critical data survives: OpenAI's encrypted reasoning payloads and\n * Gemini's thought signatures are read back off the assistant parts we stored and\n * handed straight back to the provider untouched.\n */\nexport function toPrompt(req: ModelRequest): LanguageModelV4Prompt {\n const prompt: LanguageModelV4Prompt = [];\n if (req.system) prompt.push({ role: 'system', content: req.system });\n for (const message of req.messages) {\n prompt.push(...convertMessage(message));\n }\n return prompt;\n}\n\nfunction convertMessage(message: Message): LanguageModelV4Message[] {\n const opts = (meta: Message['providerMetadata']) => (meta ? { providerOptions: meta } : {});\n\n switch (message.role) {\n case 'system': {\n const text = message.content\n .filter((p) => p.type === 'text')\n .map((p) => p.text)\n .join('\\n');\n return text ? [{ role: 'system', content: text }] : [];\n }\n\n case 'user': {\n const content: Array<LanguageModelV4TextPart | LanguageModelV4FilePart> = [];\n for (const part of message.content) {\n if (part.type === 'text') {\n content.push({ type: 'text', text: part.text, ...opts(part.providerMetadata) });\n } else if (part.type === 'image') {\n content.push(imageToFilePart(part));\n }\n }\n return content.length ? [{ role: 'user', content }] : [];\n }\n\n case 'assistant': {\n const content: Array<\n LanguageModelV4TextPart | LanguageModelV4ReasoningPart | LanguageModelV4ToolCallPart\n > = [];\n for (const part of message.content) {\n switch (part.type) {\n case 'text':\n content.push({ type: 'text', text: part.text, ...opts(part.providerMetadata) });\n break;\n case 'reasoning':\n content.push({ type: 'reasoning', text: part.text, ...opts(part.providerMetadata) });\n break;\n case 'tool_call':\n content.push({\n type: 'tool-call',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...opts(part.providerMetadata),\n });\n break;\n default:\n break;\n }\n }\n return content.length ? [{ role: 'assistant', content }] : [];\n }\n\n case 'tool': {\n const content = message.content\n .filter((p): p is ToolResultPart => p.type === 'tool_result')\n .map(toToolResultPart);\n return content.length ? [{ role: 'tool', content }] : [];\n }\n }\n}\n\nfunction toToolResultPart(part: ToolResultPart): LanguageModelV4ToolResultPart {\n return {\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: toToolOutput(part.output, part.isError ?? false),\n ...(part.providerMetadata ? { providerOptions: part.providerMetadata } : {}),\n };\n}\n\nfunction toToolOutput(output: ToolResultOutput, isError: boolean): LanguageModelV4ToolResultOutput {\n switch (output.type) {\n case 'text':\n return isError\n ? { type: 'error-text', value: output.value }\n : { type: 'text', value: output.value };\n case 'json':\n return isError\n ? { type: 'error-json', value: output.value as never }\n : { type: 'json', value: output.value as never };\n case 'content':\n return {\n type: 'content',\n value: output.value.map((p) =>\n p.type === 'text'\n ? { type: 'text' as const, text: p.text }\n : { type: 'file' as const, mediaType: p.mediaType, data: toFileData(p.data) },\n ),\n };\n }\n}\n\n/** Base64 payloads pass through as data; https references stay references so the\n * provider fetches them itself rather than us inlining megabytes into the prompt. */\nfunction toFileData(data: string): SharedV4FileData {\n return /^https?:\\/\\//i.test(data) ? { type: 'url', url: new URL(data) } : { type: 'data', data };\n}\n\nfunction imageToFilePart(part: ImagePart): LanguageModelV4FilePart {\n return {\n type: 'file',\n mediaType: part.mediaType,\n data: toFileData(part.data),\n ...(part.providerMetadata ? { providerOptions: part.providerMetadata } : {}),\n };\n}\n",
14
+ "import type {\n LanguageModelV4,\n LanguageModelV4CallOptions,\n LanguageModelV4FinishReason,\n LanguageModelV4StreamPart,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport { earshotError } from '../errors.ts';\nimport type {\n FinishReason,\n Message,\n MessagePart,\n ModelRequest,\n ProviderMetadata,\n ReasoningEffort,\n StreamEvent,\n Usage,\n WireApi,\n WireApiKind,\n WireContext,\n} from '../types.ts';\nimport { toPrompt } from './ai-sdk-prompt.ts';\n\n/** Builds the concrete LanguageModelV4 for a request. One per provider package. */\nexport type ModelFactory = (modelId: string, ctx: WireContext) => LanguageModelV4;\n\n/**\n * The single bridge between our unified types and the AI SDK's LanguageModelV4\n * spec. Every AI SDK provider package becomes an earshot wire adapter by passing\n * its model factory here, which is what keeps \"adding a provider\" to a config entry.\n */\nexport function createAiSdkWire(kind: WireApiKind, factory: ModelFactory): WireApi {\n return {\n kind,\n async *stream(req, ctx) {\n yield* streamViaAiSdk(factory(req.modelId, ctx), req);\n },\n };\n}\n\nexport async function* streamViaAiSdk(\n model: LanguageModelV4,\n req: ModelRequest,\n): AsyncIterable<StreamEvent> {\n const builder = new MessageBuilder();\n let usage: Usage = { inputTokens: 0, outputTokens: 0 };\n let finished = false;\n\n let stream: ReadableStream<LanguageModelV4StreamPart>;\n try {\n ({ stream } = await model.doStream(toCallOptions(req)));\n } catch (error) {\n yield { type: 'error', error: toEarshotError(error) };\n return;\n }\n\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n for (const event of mapPart(value, builder)) {\n if (event.type === 'usage') usage = event.usage;\n if (event.type === 'finish') finished = true;\n yield event;\n }\n }\n } catch (error) {\n if (req.abortSignal?.aborted) {\n yield { type: 'finish', reason: 'abort', usage, message: builder.build() };\n return;\n }\n yield { type: 'error', error: toEarshotError(error) };\n return;\n } finally {\n reader.releaseLock();\n }\n\n // Some providers close the stream without a terminal finish part; the agent loop\n // relies on exactly one finish event carrying the assembled message.\n if (!finished) {\n yield { type: 'finish', reason: 'stop', usage, message: builder.build() };\n }\n}\n\nfunction toCallOptions(req: ModelRequest): LanguageModelV4CallOptions {\n return {\n prompt: toPrompt(req),\n ...(req.maxOutputTokens !== undefined ? { maxOutputTokens: req.maxOutputTokens } : {}),\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.abortSignal ? { abortSignal: req.abortSignal } : {}),\n ...(req.reasoningEffort ? { reasoning: toReasoning(req.reasoningEffort) } : {}),\n ...(req.providerOptions ? { providerOptions: req.providerOptions } : {}),\n ...(req.tools?.length\n ? {\n tools: req.tools.map((tool) => ({\n type: 'function' as const,\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n }\n : {}),\n ...(req.toolChoice\n ? { toolChoice: { type: req.toolChoice === 'auto' ? 'auto' : req.toolChoice } }\n : {}),\n };\n}\n\ntype SdkReasoning = NonNullable<LanguageModelV4CallOptions['reasoning']>;\n\nfunction toReasoning(effort: ReasoningEffort): SdkReasoning {\n return effort satisfies SdkReasoning;\n}\n\n/**\n * Accumulates streamed parts into the assistant message that gets appended to\n * history. Text and reasoning arrive as start/delta/end runs keyed by id, so each\n * run becomes one part - preserving per-part providerMetadata for replay.\n */\nclass MessageBuilder {\n #parts: MessagePart[] = [];\n #open = new Map<string, { index: number; kind: 'text' | 'reasoning' }>();\n\n startRun(id: string, kind: 'text' | 'reasoning', meta?: ProviderMetadata): void {\n const part: MessagePart =\n kind === 'text'\n ? { type: 'text', text: '', ...(meta ? { providerMetadata: meta } : {}) }\n : { type: 'reasoning', text: '', ...(meta ? { providerMetadata: meta } : {}) };\n this.#open.set(id, { index: this.#parts.push(part) - 1, kind });\n }\n\n appendRun(id: string, kind: 'text' | 'reasoning', delta: string): void {\n let open = this.#open.get(id);\n if (!open) {\n this.startRun(id, kind);\n open = this.#open.get(id) as { index: number; kind: 'text' | 'reasoning' };\n }\n const part = this.#parts[open.index];\n if (part && (part.type === 'text' || part.type === 'reasoning')) part.text += delta;\n }\n\n /** End-of-run metadata wins: providers attach signatures and encrypted blobs here. */\n endRun(id: string, meta?: ProviderMetadata): void {\n const open = this.#open.get(id);\n this.#open.delete(id);\n if (!open || !meta) return;\n const part = this.#parts[open.index];\n if (part) part.providerMetadata = { ...part.providerMetadata, ...meta };\n }\n\n addToolCall(toolCallId: string, toolName: string, input: unknown, meta?: ProviderMetadata): void {\n this.#parts.push({\n type: 'tool_call',\n toolCallId,\n toolName,\n input,\n ...(meta ? { providerMetadata: meta } : {}),\n });\n }\n\n build(): Message {\n // Empty runs are dropped: Anthropic rejects zero-length content blocks.\n return {\n role: 'assistant',\n content: this.#parts.filter(\n (p) => !((p.type === 'text' || p.type === 'reasoning') && p.text === ''),\n ),\n };\n }\n}\n\nfunction mapPart(part: LanguageModelV4StreamPart, builder: MessageBuilder): StreamEvent[] {\n switch (part.type) {\n case 'text-start':\n builder.startRun(part.id, 'text', part.providerMetadata);\n return [];\n case 'text-delta':\n builder.appendRun(part.id, 'text', part.delta);\n return [{ type: 'text_delta', text: part.delta }];\n case 'text-end':\n builder.endRun(part.id, part.providerMetadata);\n return [];\n\n case 'reasoning-start':\n builder.startRun(part.id, 'reasoning', part.providerMetadata);\n return [];\n case 'reasoning-delta':\n builder.appendRun(part.id, 'reasoning', part.delta);\n return [\n {\n type: 'reasoning_delta',\n text: part.delta,\n ...(part.providerMetadata ? { providerMetadata: part.providerMetadata } : {}),\n },\n ];\n case 'reasoning-end':\n builder.endRun(part.id, part.providerMetadata);\n return [];\n\n case 'tool-input-start':\n return [{ type: 'tool_call_start', toolCallId: part.id, toolName: part.toolName }];\n case 'tool-input-delta':\n return [{ type: 'tool_call_delta', toolCallId: part.id, argsTextDelta: part.delta }];\n case 'tool-input-end':\n return [];\n\n case 'tool-call': {\n // Spec carries tool input as a JSON string; everything above us wants a value.\n const input = parseToolInput(part.input);\n builder.addToolCall(part.toolCallId, part.toolName, input, part.providerMetadata);\n return [\n {\n type: 'tool_call_end',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input,\n ...(part.providerMetadata ? { providerMetadata: part.providerMetadata } : {}),\n },\n ];\n }\n\n case 'finish': {\n const usage = toUsage(part.usage);\n return [\n { type: 'usage', usage },\n {\n type: 'finish',\n reason: toFinishReason(part.finishReason),\n usage,\n message: builder.build(),\n },\n ];\n }\n\n case 'error':\n return [{ type: 'error', error: toEarshotError(part.error) }];\n\n default:\n // stream-start, response-metadata, raw, source, file, and provider-executed\n // tool results carry nothing the agent loop acts on yet.\n return [];\n }\n}\n\nfunction parseToolInput(input: unknown): unknown {\n if (typeof input !== 'string') return input;\n if (input.trim() === '') return {};\n try {\n return JSON.parse(input);\n } catch {\n return input;\n }\n}\n\nfunction toUsage(usage: LanguageModelV4Usage): Usage {\n return {\n inputTokens: usage.inputTokens.total ?? 0,\n outputTokens: usage.outputTokens.total ?? 0,\n ...(usage.outputTokens.reasoning != null\n ? { reasoningTokens: usage.outputTokens.reasoning }\n : {}),\n ...(usage.inputTokens.cacheRead != null\n ? { cacheReadTokens: usage.inputTokens.cacheRead }\n : {}),\n ...(usage.inputTokens.cacheWrite != null\n ? { cacheWriteTokens: usage.inputTokens.cacheWrite }\n : {}),\n };\n}\n\nfunction toFinishReason(reason: LanguageModelV4FinishReason): FinishReason {\n // `raw` preserves vendor detail the unified value flattens away - Anthropic's\n // \"refusal\" is a distinct stop reason the loop must not treat as a normal stop.\n if (reason.raw === 'refusal') return 'refusal';\n switch (reason.unified) {\n case 'stop':\n return 'stop';\n case 'length':\n return 'length';\n case 'tool-calls':\n return 'tool_calls';\n case 'content-filter':\n return 'content_filter';\n case 'error':\n return 'error';\n default:\n return 'stop';\n }\n}\n\nfunction toEarshotError(error: unknown) {\n const e = error as {\n name?: string;\n statusCode?: number;\n message?: string;\n isRetryable?: boolean;\n };\n if (e?.name === 'AbortError')\n return earshotError('abort', 'request aborted', { retryable: false });\n\n const status = typeof e?.statusCode === 'number' ? e.statusCode : undefined;\n const message = e?.message ?? String(error);\n const kind =\n status === 401 || status === 403\n ? 'auth'\n : status === 429\n ? 'rate_limit'\n : status !== undefined && status >= 500\n ? 'server'\n : status !== undefined\n ? 'invalid_request'\n : 'unknown';\n\n // Context overflow is only ever a 400 with a vendor-specific message.\n const overflow = /context length|too many tokens|maximum context|prompt is too long/i.test(\n message,\n );\n return earshotError(overflow ? 'context_overflow' : kind, message, {\n ...(status !== undefined ? { status } : {}),\n cause: error,\n });\n}\n",
15
+ "import { earshotError, errorFromStatus } from '../errors.ts';\nimport type {\n Message,\n MessagePart,\n ModelRequest,\n StreamEvent,\n ToolCallPart,\n Usage,\n WireApi,\n WireContext,\n} from '../types.ts';\n\n/**\n * Ollama's native `/api/chat`, written by hand.\n *\n * The one adapter that is not a binding to an AI SDK provider package, because\n * the alternative is worse: Ollama's OpenAI-compatible `/v1` drops tool calls\n * from streamed responses entirely, so a local model could either stream or use\n * tools but not both. Ollama's own endpoint streams tool calls, and it is a\n * newline-delimited JSON protocol with about six fields - small enough to be\n * cheaper to write than to work around.\n */\nexport const ollamaNativeWire: WireApi = {\n kind: 'ollama-native',\n async *stream(req: ModelRequest, ctx: WireContext): AsyncIterable<StreamEvent> {\n const root = (ctx.baseUrl ?? 'http://127.0.0.1:11434').replace(/\\/v1\\/?$/, '');\n const body = {\n model: req.modelId,\n messages: toOllamaMessages(req),\n stream: true,\n ...(req.tools?.length ? { tools: req.tools.map(toOllamaTool) } : {}),\n options: {\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.maxOutputTokens !== undefined ? { num_predict: req.maxOutputTokens } : {}),\n },\n };\n\n let response: Response;\n try {\n response = await fetch(`${root}/api/chat`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...(ctx.headers ?? {}) },\n body: JSON.stringify(body),\n ...(req.abortSignal ? { signal: req.abortSignal } : {}),\n });\n } catch (error) {\n yield { type: 'error', error: fromThrown(error) };\n return;\n }\n\n if (!response.ok || !response.body) {\n const text = await response.text().catch(() => '');\n yield {\n type: 'error',\n error: errorFromStatus(response.status, `ollama returned ${response.status}: ${text}`),\n };\n return;\n }\n\n const content: MessagePart[] = [];\n let text = '';\n let reasoning = '';\n const usage: Usage = { inputTokens: 0, outputTokens: 0 };\n let reason: 'stop' | 'length' | 'tool_calls' = 'stop';\n let calls = 0;\n\n try {\n for await (const chunk of ndjson(response.body)) {\n if (chunk.error) {\n yield { type: 'error', error: earshotError('server', String(chunk.error)) };\n return;\n }\n const message = chunk.message as Record<string, unknown> | undefined;\n\n // Ollama streams reasoning as a separate `thinking` field rather than\n // inline, so it never has to be recovered from tags in the text.\n const thinking = typeof message?.thinking === 'string' ? message.thinking : '';\n if (thinking !== '') {\n reasoning += thinking;\n yield { type: 'reasoning_delta', text: thinking };\n }\n\n const delta = typeof message?.content === 'string' ? message.content : '';\n if (delta !== '') {\n text += delta;\n yield { type: 'text_delta', text: delta };\n }\n\n for (const call of asArray(message?.tool_calls)) {\n const fn = (call as { function?: Record<string, unknown> }).function ?? {};\n const name = typeof fn.name === 'string' ? fn.name : '';\n if (name === '') continue;\n // Ollama emits a whole call at once rather than streaming its\n // arguments, and gives it no id, so one is synthesised - the loop\n // matches results to calls by id and cannot use an empty one.\n const toolCallId = `ollama_${Date.now().toString(36)}_${calls++}`;\n const part: ToolCallPart = {\n type: 'tool_call',\n toolCallId,\n toolName: name,\n input: fn.arguments ?? {},\n };\n yield { type: 'tool_call_start', toolCallId, toolName: name };\n yield { type: 'tool_call_end', toolCallId, toolName: name, input: part.input };\n content.push(part);\n reason = 'tool_calls';\n }\n\n if (chunk.done === true) {\n usage.inputTokens = numberOf(chunk.prompt_eval_count);\n usage.outputTokens = numberOf(chunk.eval_count);\n if (chunk.done_reason === 'length') reason = 'length';\n }\n }\n } catch (error) {\n yield { type: 'error', error: fromThrown(error) };\n return;\n }\n\n // Reasoning first, then text, then calls: the order the loop replays them in\n // and the order every other adapter produces.\n const assembled: MessagePart[] = [\n ...(reasoning !== '' ? [{ type: 'reasoning' as const, text: reasoning }] : []),\n ...(text !== '' ? [{ type: 'text' as const, text }] : []),\n ...content,\n ];\n const message: Message = { role: 'assistant', content: assembled };\n\n yield { type: 'usage', usage };\n yield { type: 'finish', reason, usage, message };\n },\n};\n\n/**\n * An abort is not a failure to report as one: the loop distinguishes the user\n * interrupting from the server falling over, and treating both as `network`\n * would make an interrupted turn look retryable.\n */\nfunction fromThrown(error: unknown) {\n const message = (error as Error)?.message ?? String(error);\n if ((error as Error)?.name === 'AbortError') {\n return earshotError('abort', 'the request was interrupted', { retryable: false });\n }\n return earshotError('network', `could not reach ollama: ${message}`);\n}\n\n/** Ollama's chat format: a flat list of role/content, with tool results by name. */\nfunction toOllamaMessages(req: ModelRequest): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n if (req.system) out.push({ role: 'system', content: req.system });\n\n for (const message of req.messages) {\n if (message.role === 'tool') {\n // One entry per result: Ollama has no multi-part tool message, and merging\n // them would lose which result answered which call.\n for (const part of message.content) {\n if (part.type !== 'tool_result') continue;\n out.push({ role: 'tool', tool_name: part.toolName, content: outputText(part.output) });\n }\n continue;\n }\n\n const text = message.content\n .filter((part) => part.type === 'text')\n .map((part) => (part.type === 'text' ? part.text : ''))\n .join('');\n const toolCalls = message.content\n .filter((part): part is ToolCallPart => part.type === 'tool_call')\n .map((part) => ({ function: { name: part.toolName, arguments: part.input } }));\n\n if (text === '' && toolCalls.length === 0) continue;\n out.push({\n role: message.role,\n content: text,\n ...(toolCalls.length ? { tool_calls: toolCalls } : {}),\n });\n }\n return out;\n}\n\nfunction toOllamaTool(tool: { name: string; description: string; inputSchema: unknown }) {\n return {\n type: 'function',\n function: { name: tool.name, description: tool.description, parameters: tool.inputSchema },\n };\n}\n\nfunction outputText(output: { type: string; value: unknown }): string {\n if (output.type === 'text') return String(output.value);\n return JSON.stringify(output.value);\n}\n\nfunction asArray(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction numberOf(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\n/**\n * Ollama's stream is one JSON object per line. Buffered across chunks because a\n * chunk boundary lands mid-line often enough that parsing per chunk works in\n * testing and fails on a long response.\n */\nasync function* ndjson(body: ReadableStream<Uint8Array>): AsyncGenerator<Record<string, unknown>> {\n const decoder = new TextDecoder();\n let buffer = '';\n\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let newline = buffer.indexOf('\\n');\n while (newline !== -1) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line !== '') yield JSON.parse(line) as Record<string, unknown>;\n newline = buffer.indexOf('\\n');\n }\n }\n const rest = buffer.trim();\n if (rest !== '') yield JSON.parse(rest) as Record<string, unknown>;\n}\n",
16
+ "import { ModelCatalog, SUPPORTED_PROVIDERS, type SupportedProvider } from './catalog/index.ts';\nimport { ProviderRegistry } from './registry.ts';\nimport type { AuthSpec, Model, Provider, WireContext } from './types.ts';\nimport { ALL_WIRES } from './wire/adapters.ts';\n\n/** Builds one `Provider` from a table entry plus the catalog. */\nexport function buildProvider(entry: SupportedProvider, catalog: ModelCatalog): Provider {\n const info = catalog.provider(entry.catalogId);\n const envVars = entry.envVars ?? info?.env ?? [];\n const baseUrl = entry.baseUrl ?? info?.api;\n const models = catalog.modelsFor(entry);\n\n return {\n id: entry.id,\n name: info?.name ?? entry.id,\n auth: toAuthSpec(entry, envVars, info?.doc),\n ...(baseUrl ? { baseUrl } : {}),\n api: entry.api,\n models: () => models,\n ...(entry.notice ? { notice: entry.notice } : {}),\n };\n}\n\nfunction toAuthSpec(entry: SupportedProvider, envVars: string[], doc?: string): AuthSpec {\n const helpUrl = doc ? { helpUrl: doc } : {};\n switch (entry.auth) {\n case 'none':\n return { kind: 'none' };\n case 'ambient':\n return {\n kind: 'ambient',\n description:\n entry.id === 'bedrock'\n ? 'the AWS credential chain (env, shared config, or instance role)'\n : 'Google Application Default Credentials',\n };\n case 'oauth':\n return { kind: 'oauth', flow: 'pkce', envVars, ...helpUrl };\n default:\n return { kind: 'api-key', envVars, ...helpUrl };\n }\n}\n\n/**\n * A user-configured OpenAI-compatible endpoint: any vendor or local runtime with\n * a base URL. This is the escape hatch that means an unknown provider never\n * requires a code change.\n */\nexport interface CustomProviderConfig {\n id: string;\n name?: string;\n baseUrl: string;\n apiKeyEnv?: string;\n models: Array<{\n id: string;\n name?: string;\n context?: number;\n output?: number;\n reasoning?: boolean;\n vision?: boolean;\n tools?: boolean;\n }>;\n}\n\nexport function customProvider(config: CustomProviderConfig): Provider {\n const models: Model[] = config.models.map((m) => ({\n id: m.id,\n providerId: config.id,\n name: m.name ?? m.id,\n contextWindow: m.context ?? 128_000,\n maxOutputTokens: m.output ?? 8_192,\n capabilities: {\n tools: m.tools ?? true,\n vision: m.vision ?? false,\n reasoning: m.reasoning ?? false,\n },\n api: 'openai-completions',\n }));\n\n return {\n id: config.id,\n name: config.name ?? config.id,\n auth: config.apiKeyEnv ? { kind: 'api-key', envVars: [config.apiKeyEnv] } : { kind: 'none' },\n baseUrl: config.baseUrl,\n api: 'openai-completions',\n models: () => models,\n };\n}\n\n/**\n * Ollama, over its own `/api/chat` rather than its OpenAI-compatible `/v1`.\n *\n * The compatible endpoint drops tool calls from streamed responses, which for a\n * coding agent means a local model can stream or use tools but not both. The\n * native endpoint does neither, so it is worth the one hand-written adapter in\n * the project. Model discovery stays live: whatever the user has pulled.\n */\nexport function ollamaProvider(\n baseUrl = process.env.OLLAMA_HOST ?? 'http://127.0.0.1:11434',\n): Provider {\n return {\n id: 'ollama',\n name: 'Ollama',\n auth: { kind: 'none' },\n baseUrl: baseUrl.replace(/\\/$/, ''),\n api: 'ollama-native',\n models: () => [],\n async fetchModels(ctx: WireContext): Promise<Model[]> {\n const root = (ctx.baseUrl ?? `${baseUrl}/v1`).replace(/\\/v1\\/?$/, '');\n const response = await fetch(`${root}/api/tags`);\n if (!response.ok) throw new Error(`ollama returned ${response.status}`);\n const body = (await response.json()) as {\n models?: Array<{ name: string; details?: { parameter_size?: string } }>;\n };\n return (body.models ?? []).map((m) => ({\n id: m.name,\n providerId: 'ollama',\n name: m.name,\n contextWindow: 32_768,\n maxOutputTokens: 8_192,\n capabilities: { tools: true, vision: false, reasoning: false },\n api: 'ollama-native' as const,\n }));\n },\n };\n}\n\nexport interface BuildRegistryOptions {\n catalog?: ModelCatalog;\n custom?: CustomProviderConfig[];\n}\n\n/** The registry earshot boots with: every built-in provider and every wire adapter. */\nexport function buildRegistry(opts: BuildRegistryOptions = {}): ProviderRegistry {\n const catalog = opts.catalog ?? new ModelCatalog();\n const registry = new ProviderRegistry();\n\n for (const wire of ALL_WIRES) registry.registerWire(wire);\n for (const entry of SUPPORTED_PROVIDERS) registry.register(buildProvider(entry, catalog));\n registry.register(ollamaProvider());\n for (const config of opts.custom ?? []) registry.register(customProvider(config));\n\n return registry;\n}\n",
17
+ "import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\n\nexport interface LoopbackResult {\n /** Where to send the browser back to. Only known once the port is bound. */\n redirectUri: string;\n /** Resolves with the query parameters of the first callback request. */\n code: Promise<URLSearchParams>;\n close(): void;\n}\n\nconst PAGE = (message: string) =>\n `<!doctype html><meta charset=\"utf-8\"><title>earshot</title>` +\n `<body style=\"font:16px system-ui;padding:3rem;max-width:32rem\">` +\n `<h1 style=\"font-size:1.2rem\">${message}</h1>` +\n `<p>You can close this tab and go back to your terminal.</p>`;\n\n/**\n * A one-shot loopback listener for an OAuth redirect.\n *\n * Bound to 127.0.0.1 on a port the OS picks, and closed as soon as it has the\n * one request it exists for. Not localhost: on a machine where that resolves to\n * ::1 first the provider's redirect and this listener end up on different\n * addresses, and the flow hangs with no error anywhere.\n */\nexport async function listenForCallback(timeoutMs = 300_000): Promise<LoopbackResult> {\n let settle: (params: URLSearchParams) => void = () => {};\n let fail: (error: Error) => void = () => {};\n const code = new Promise<URLSearchParams>((resolve, reject) => {\n settle = resolve;\n fail = reject;\n });\n\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? '/', 'http://127.0.0.1');\n // Browsers ask for a favicon on the way past; answering it as the callback\n // would end the flow with no code in hand.\n if (url.pathname === '/favicon.ico') {\n response.writeHead(404).end();\n return;\n }\n const params = url.searchParams;\n const failed = params.get('error');\n response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n response.end(PAGE(failed ? `Sign-in failed: ${failed}` : 'Signed in to earshot.'));\n if (failed) fail(new Error(`the provider returned \"${failed}\"`));\n else settle(params);\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n\n const timer = setTimeout(() => {\n fail(new Error('timed out waiting for the browser to come back'));\n server.close();\n }, timeoutMs);\n timer.unref();\n\n const { port } = server.address() as AddressInfo;\n const close = () => {\n clearTimeout(timer);\n server.close();\n };\n void code.then(close, close);\n\n return { redirectUri: `http://127.0.0.1:${port}/callback`, code, close };\n}\n",
18
+ "import { spawn } from 'node:child_process';\nimport { platform } from 'node:os';\nimport type { Credentials } from '../types.ts';\nimport { listenForCallback } from './loopback.ts';\nimport { createPkcePair, type PkcePair } from './pkce.ts';\n\nconst AUTH_URL = 'https://openrouter.ai/auth';\nconst EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';\n\nexport class OAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OAuthError';\n }\n}\n\nexport function authorizeUrl(redirectUri: string, pkce: PkcePair): string {\n const url = new URL(AUTH_URL);\n url.searchParams.set('callback_url', redirectUri);\n url.searchParams.set('code_challenge', pkce.challenge);\n url.searchParams.set('code_challenge_method', pkce.method);\n return url.toString();\n}\n\n/**\n * Trades the authorisation code for an OpenRouter key.\n *\n * OpenRouter's PKCE flow hands back a normal API key rather than a\n * refreshable token, so what gets stored is `api-key` credentials like any\n * other - there is no refresh path to get wrong, and revoking it is something\n * the user does on their own dashboard rather than something earshot manages.\n */\nexport async function exchangeCode(\n code: string,\n pkce: PkcePair,\n doFetch: typeof fetch = fetch,\n): Promise<Credentials> {\n const response = await doFetch(EXCHANGE_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n code,\n code_verifier: pkce.verifier,\n code_challenge_method: pkce.method,\n }),\n }).catch((error: Error) => {\n throw new OAuthError(`could not reach OpenRouter: ${error.message}`);\n });\n\n const body = (await response.json().catch(() => undefined)) as { key?: unknown } | undefined;\n if (!response.ok) {\n throw new OAuthError(\n `OpenRouter refused the code (${response.status}). Start again with \\`earshot auth login openrouter\\`.`,\n );\n }\n if (typeof body?.key !== 'string' || body.key === '') {\n throw new OAuthError('OpenRouter returned no key');\n }\n return { type: 'api-key', apiKey: body.key };\n}\n\nexport interface LoginOptions {\n /** Called with the URL, so a caller can print it as well as open it. */\n onUrl?: (url: string) => void;\n openBrowser?: boolean;\n fetch?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * The whole flow: bind a loopback port, send the user to OpenRouter, wait for\n * the redirect, exchange the code.\n *\n * The URL is always printed, not only opened. A browser that fails to launch -\n * over SSH, in a container, on a machine with no default handler - is the\n * common case for a terminal tool, and a flow that only opens one leaves the\n * user with nothing to do.\n */\nexport async function loginToOpenRouter(options: LoginOptions = {}): Promise<Credentials> {\n const pkce = createPkcePair();\n const listener = await listenForCallback(options.timeoutMs ?? 300_000);\n\n try {\n const url = authorizeUrl(listener.redirectUri, pkce);\n options.onUrl?.(url);\n if (options.openBrowser !== false) openBrowser(url);\n\n const params = await listener.code;\n const code = params.get('code');\n if (!code) throw new OAuthError('OpenRouter came back without an authorisation code');\n return await exchangeCode(code, pkce, options.fetch ?? fetch);\n } finally {\n listener.close();\n }\n}\n\n/** Best effort, and deliberately not awaited: the flow does not depend on it. */\nfunction openBrowser(url: string): void {\n const [command, args] =\n platform() === 'darwin'\n ? ['open', [url]]\n : platform() === 'win32'\n ? ['cmd', ['/c', 'start', '', url]]\n : ['xdg-open', [url]];\n try {\n const child = spawn(command, args, { stdio: 'ignore', detached: true });\n child.on('error', () => {});\n child.unref();\n } catch {\n // The URL was printed; that is the fallback.\n }\n}\n",
19
+ "import { createHash, randomBytes } from 'node:crypto';\n\nexport interface PkcePair {\n verifier: string;\n challenge: string;\n method: 'S256';\n}\n\n/**\n * A PKCE verifier and its S256 challenge.\n *\n * The verifier never leaves this process until the code exchange, which is the\n * point of PKCE: the authorisation code that arrives on a loopback redirect is\n * useless to anything that did not generate the verifier, so another program\n * watching the callback cannot spend it.\n */\nexport function createPkcePair(): PkcePair {\n // 32 bytes of randomness, base64url'd to 43 characters - the shortest length\n // RFC 7636 allows, and the length every provider tested accepts.\n const verifier = base64url(randomBytes(32));\n const challenge = base64url(createHash('sha256').update(verifier).digest());\n return { verifier, challenge, method: 'S256' };\n}\n\nexport function base64url(buffer: Buffer): string {\n return buffer.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n",
20
+ "import type { Message, MessagePart, ToolResultPart } from '@earshot/providers';\n\n/**\n * What runs over the message list before each model call, cheapest first.\n *\n * Every shaper is a pure function from messages to messages. Nothing here may\n * touch `Agent.history`: history is append-only because Anthropic rejects a\n * request containing edited thinking blocks, so shaping produces the array sent\n * on this one request and leaves the transcript alone.\n */\nexport interface ShaperOptions {\n /** Longest a single tool result may be before it is truncated. */\n maxResultChars: number;\n /** Tool results from batches older than this are reduced to a stub. */\n keepDetailedBatches: number;\n /** Longest a stub may be. */\n stubChars: number;\n}\n\nexport const DEFAULT_SHAPER_OPTIONS: ShaperOptions = {\n maxResultChars: 20_000,\n keepDetailedBatches: 6,\n stubChars: 200,\n};\n\n/**\n * Rough token count.\n *\n * Four characters per token is wrong for every tokenizer and close enough for\n * all three uses here - deciding when to compact, drawing a percentage, and\n * ordering shapers. Being exact would mean shipping a tokenizer per provider to\n * make a progress bar one percent more accurate.\n */\nexport function estimateTokens(messages: Message[], system = ''): number {\n let chars = system.length;\n for (const message of messages) {\n for (const part of message.content) chars += partChars(part);\n // Role, delimiters and tool-call framing the provider adds around each part.\n chars += 16;\n }\n return Math.ceil(chars / 4);\n}\n\nfunction partChars(part: MessagePart): number {\n switch (part.type) {\n case 'text':\n case 'reasoning':\n return part.text.length;\n case 'tool_call':\n return part.toolName.length + JSON.stringify(part.input ?? null).length;\n case 'tool_result':\n return part.toolName.length + outputText(part).length;\n // An image costs tokens by dimension, which we do not have here. A flat\n // estimate keeps it from reading as free, which is the failure that matters.\n case 'image':\n return 4000;\n default:\n return 0;\n }\n}\n\n/** The text of a tool result, whatever shape the output took. */\nexport function outputText(part: ToolResultPart): string {\n const { output } = part;\n switch (output.type) {\n case 'text':\n return output.value;\n case 'json':\n return JSON.stringify(output.value);\n case 'content':\n return output.value\n .map((item) => (item.type === 'text' ? item.text : `[${item.mediaType}]`))\n .join('\\n');\n default:\n return '';\n }\n}\n\nfunction withText(part: ToolResultPart, text: string): ToolResultPart {\n return { ...part, output: { type: 'text', value: text } };\n}\n\n/**\n * Caps one oversized result rather than dropping it.\n *\n * The head and the tail are kept and the middle is elided: a 200k-line grep is\n * useless in full, but its first hits and the total at the end are exactly what\n * the model needs, and keeping only the head loses the summary line that most\n * tools print last.\n */\nexport function capResults(messages: Message[], options: ShaperOptions): Message[] {\n return messages.map((message) => {\n if (message.role !== 'tool') return message;\n let changed = false;\n const content = message.content.map((part) => {\n if (part.type !== 'tool_result') return part;\n const text = outputText(part);\n if (text.length <= options.maxResultChars) return part;\n changed = true;\n const half = Math.floor((options.maxResultChars - 80) / 2);\n const dropped = text.length - half * 2;\n return withText(\n part,\n `${text.slice(0, half)}\\n\\n... ${dropped} characters elided by earshot ...\\n\\n${text.slice(-half)}`,\n );\n });\n return changed ? { ...message, content } : message;\n });\n}\n\n/**\n * Replaces the body of older tool results with a one-line stub.\n *\n * The result *part* stays: a provider rejects the next request if an assistant\n * tool call has no matching result, so pruning may only shrink a result, never\n * remove it. Recent batches are left intact because that is the work the model\n * is still reasoning about.\n */\nexport function pruneResults(messages: Message[], options: ShaperOptions): Message[] {\n const toolMessages = messages.filter((message) => message.role === 'tool');\n const cutoff = toolMessages.length - options.keepDetailedBatches;\n if (cutoff <= 0) return messages;\n\n let seen = 0;\n return messages.map((message) => {\n if (message.role !== 'tool') return message;\n const index = seen++;\n if (index >= cutoff) return message;\n\n let changed = false;\n const content = message.content.map((part) => {\n if (part.type !== 'tool_result') return part;\n const text = outputText(part);\n if (text.length <= options.stubChars) return part;\n changed = true;\n const first = text.split('\\n', 1)[0]?.slice(0, options.stubChars) ?? '';\n return withText(\n part,\n `[${part.toolName} result from an earlier step, ${text.length} characters, elided]${\n first ? `\\n${first}` : ''\n }`,\n );\n });\n return changed ? { ...message, content } : message;\n });\n}\n\n/** Runs the cheap shapers in order. Compaction is separate: it costs a model call. */\nexport function shapeMessages(\n messages: Message[],\n options: ShaperOptions = DEFAULT_SHAPER_OPTIONS,\n): Message[] {\n return pruneResults(capResults(messages, options), options);\n}\n",
21
+ "import type { Message } from '@earshot/providers';\nimport { estimateTokens } from './shapers.ts';\n\nexport interface CompactionPolicy {\n /** Fraction of the context window at which compaction runs. */\n threshold: number;\n /** Turns kept verbatim after the summary. A turn is one user or assistant message. */\n keepRecentMessages: number;\n}\n\nexport const DEFAULT_COMPACTION_POLICY: CompactionPolicy = {\n threshold: 0.8,\n keepRecentMessages: 8,\n};\n\nexport interface CompactionInput {\n messages: Message[];\n system: string;\n contextWindow: number;\n policy?: CompactionPolicy;\n /** Open todos, carried across the cut because they are the unfinished work. */\n todos?: string[];\n /** Files the session has touched, carried for the same reason. */\n filesTouched?: string[];\n /** Writes the summary. The agent passes one that calls the model. */\n summarize: (messages: Message[]) => Promise<string>;\n}\n\nexport interface CompactionResult {\n /** What to send on this request. */\n messages: Message[];\n /** The summary text, for the `summary` session entry and for the status line. */\n summary: string;\n /** How many messages the summary stands in for. */\n replaced: number;\n}\n\nexport function shouldCompact(\n messages: Message[],\n system: string,\n contextWindow: number,\n policy: CompactionPolicy = DEFAULT_COMPACTION_POLICY,\n): boolean {\n if (contextWindow <= 0) return false;\n return estimateTokens(messages, system) > contextWindow * policy.threshold;\n}\n\n/**\n * Indices the history can be cut at without orphaning a tool result.\n *\n * A kept tail that begins with a result whose call was dropped is rejected by\n * every provider, so the cut may only fall where each call in the tail still has\n * its own result there. Index 0 is always valid and is the fallback.\n */\nexport function safeCutPoints(messages: Message[]): number[] {\n const points: number[] = [];\n for (let cut = 0; cut < messages.length; cut++) {\n const calls = new Set<string>();\n let orphan = false;\n for (const message of messages.slice(cut)) {\n for (const part of message.content) {\n if (part.type === 'tool_call') calls.add(part.toolCallId);\n if (part.type === 'tool_result' && !calls.has(part.toolCallId)) orphan = true;\n }\n if (orphan) break;\n }\n if (!orphan) points.push(cut);\n }\n return points;\n}\n\n/**\n * Replaces the old part of the history with a model-written summary.\n *\n * The caller decides what to do with the result: the agent sends\n * `result.messages` and appends a `summary` entry to the session, which records\n * what the summary replaced without removing any of it from the file. The\n * transcript on disk stays complete; only the request shrinks.\n */\nexport async function compact(input: CompactionInput): Promise<CompactionResult | undefined> {\n const policy = input.policy ?? DEFAULT_COMPACTION_POLICY;\n const wanted = Math.max(0, input.messages.length - policy.keepRecentMessages);\n // The largest safe cut no later than the one we wanted, so a batch that\n // straddles the boundary is kept whole rather than truncated.\n const cut = safeCutPoints(input.messages)\n .filter((point) => point <= wanted)\n .at(-1);\n if (cut === undefined || cut === 0) return undefined;\n\n const summary = await input.summarize(input.messages.slice(0, cut));\n const carried = [\n summary.trim(),\n section('Open todos', input.todos),\n section('Files touched so far', input.filesTouched),\n ]\n .filter((part) => part !== '')\n .join('\\n\\n');\n\n const preamble: Message = {\n role: 'user',\n content: [\n {\n type: 'text',\n text:\n `<context-summary>\\nThe earlier part of this session was summarised to fit the ` +\n `context window. It is a summary, not a transcript: if a detail matters, read the ` +\n `file rather than trusting a recollection of it.\\n\\n${carried}\\n</context-summary>`,\n },\n ],\n };\n\n return {\n messages: [preamble, ...input.messages.slice(cut)],\n summary: carried,\n replaced: cut,\n };\n}\n\nfunction section(title: string, items?: string[]): string {\n if (!items?.length) return '';\n return `${title}:\\n${items.map((item) => `- ${item}`).join('\\n')}`;\n}\n\n/** The instruction the summarising call is given. */\nexport const SUMMARY_PROMPT =\n 'Summarise the conversation so far for your own use after the earlier messages are ' +\n 'dropped. Write it as notes to yourself, not as a report to the user. Cover: what the ' +\n 'user asked for and any constraints or preferences they stated verbatim; decisions made ' +\n 'and why; what has been changed, file by file; what is still unfinished; anything that ' +\n 'failed or is unverified. Preserve exact names, paths and commands. Do not congratulate ' +\n 'anyone and do not claim anything was verified unless the transcript shows it was.';\n",
22
+ "import { platform } from 'node:os';\nimport { loadMemories, renderMemories } from '../memory/store.ts';\nimport type { PermissionMode } from '../permissions/engine.ts';\nimport { loadMemoryFiles, renderMemory } from './agents-md.ts';\n\n/**\n * How readily the agent stops to ask. It moves one threshold and nothing else:\n * what counts as \"two readings that lead to different work\". It never turns\n * asking off, because a question the agent cannot ask becomes a guess the user\n * pays for, and never makes asking free, because a prompt for something with an\n * obvious default is its own failure.\n */\nexport type Curiosity = 'low' | 'normal' | 'high';\n\nexport const CURIOSITY_LEVELS: Curiosity[] = ['low', 'normal', 'high'];\n\nexport function isCuriosity(value: unknown): value is Curiosity {\n return typeof value === 'string' && (CURIOSITY_LEVELS as string[]).includes(value);\n}\n\nexport interface SystemPromptOptions {\n cwd: string;\n mode: PermissionMode;\n /** Defaults to `normal`. */\n curiosity?: Curiosity;\n /** Model reference, so the model can answer \"what are you\" accurately. */\n model: string;\n /** Rendered instead of being read from disk, in tests. */\n memory?: string;\n /** Rendered instead of being read from disk, in tests. */\n preferences?: string;\n /** The skill index: what exists and what each is for, never the bodies. */\n skills?: string;\n extra?: string;\n}\n\n/**\n * The behavioural half of \"a harness that actually listens\". Everything here is\n * a rule the project exists to enforce, so each line should be traceable to a\n * failure mode rather than to a style preference.\n */\nconst BASE = `You are earshot, a coding agent running in the user's terminal.\n\nDo the task the user asked for. Not a larger one, not a smaller one. If you spot\nsomething else worth fixing, say so in a sentence and leave it alone unless they\nask - an unrequested refactor buried in a bug fix is a change the user did not\nreview.\n\nBefore your first change of a task, call declare_scope: the files you expect to\ntouch, one paragraph on what changes and what does not, and a rough size. It is\nnot paperwork - editing a file you did not list, adding a dependency, renaming or\ndeleting files, reformatting, removing a test, or a change several times your own\nestimate will stop and ask the user before it happens.\n\nSay why before you act. One line, immediately before each batch of tool calls,\nnaming what you are about to do and what you expect to find or change. One line\nis the budget - it exists so the user can catch a wrong turn after one line of\noutput instead of forty, and a paragraph does not do that.\n\nRead before you change. Every edit must be to a file you have read this session,\nand \\`find\\` strings must match the file exactly, including indentation.\n\nPrefer the read, glob and grep tools over the equivalent shell commands: they are\nfaster, they respect ignore files, and their output is shaped for you.\n\nWhen you are done, say what you did in a sentence or two. Do not restate the diff\nthe user can already see, and do not claim something works if you did not run it.\nIf you could not verify something, say which part and why.\n\nReport failures plainly. A test that fails, a command that errored, a step you\nskipped - say so, with the output. Silence about a problem reads as success and\nis the single most expensive thing you can do here.`;\n\nexport async function buildSystemPrompt(options: SystemPromptOptions): Promise<string> {\n const memory = options.memory ?? renderMemory(await loadMemoryFiles(options.cwd), options.cwd);\n // Assembled here alongside AGENTS.md rather than merged into it: the two are\n // different things and are labelled as such. AGENTS.md is written by hand and\n // committed; a preference is captured from something the user said, carries\n // its provenance, and is deleted with one command.\n const preferences = options.preferences ?? renderMemories(await loadMemories(options.cwd));\n\n const sections = [\n BASE,\n curiositySection(options.curiosity ?? 'normal'),\n modeSection(options.mode),\n `<environment>\\nWorking directory: ${options.cwd}\\nPlatform: ${platform()}\\nModel: ${options.model}\\n</environment>`,\n memory,\n preferences,\n options.skills ?? '',\n options.extra ?? '',\n ];\n return sections.filter((section) => section.trim() !== '').join('\\n\\n');\n}\n\n/**\n * Where the line sits between asking and deciding.\n *\n * The shared half is fixed at every level: never ask for permission to act -\n * that is the harness's job, not the model's - and never ask about something\n * with an obvious default. Only the threshold moves.\n */\nfunction curiositySection(curiosity: Curiosity): string {\n const shared =\n 'Use the ask_user tool, with 2-4 concrete options rather than an open question. Never ' +\n 'ask for permission to act: permission is handled by the harness, not by you. Never ask ' +\n 'about a choice with an obvious default.';\n\n switch (curiosity) {\n case 'low':\n return (\n `<curiosity>low</curiosity>\\nDecide rather than ask. State the assumption you made in ` +\n `one line and keep going; ask only when proceeding either way would be unsafe or would ` +\n `waste the work if the guess is wrong. ${shared}`\n );\n case 'high':\n return (\n `<curiosity>high</curiosity>\\nAsk whenever a second reading of the request is ` +\n `plausible, before doing work that assumes the first one. The user has said they would ` +\n `rather answer a question than review the wrong thing. ${shared}`\n );\n default:\n return (\n `<curiosity>normal</curiosity>\\nAsk rather than guess when the answer would change ` +\n `what you build, and decide the rest yourself. A question costs one round trip; the ` +\n `wrong assumption costs the whole task. ${shared}`\n );\n }\n}\n\n/**\n * The model is told the mode because a refusal it cannot explain looks like a\n * bug to the user. In plan mode especially, it needs to know that the denial is\n * the design rather than something to route around with a different tool.\n */\nfunction modeSection(mode: PermissionMode): string {\n switch (mode) {\n case 'plan':\n return (\n '<mode>plan</mode>\\nYou are in plan mode: you can read and search, but every tool ' +\n 'that changes anything will be refused. Investigate, then present a plan and stop. ' +\n 'Do not attempt to make changes by another route.'\n );\n case 'accept-edits':\n return (\n '<mode>accept-edits</mode>\\nFile edits inside the working directory are approved ' +\n 'automatically. Commands and network access still prompt the user, so batch them ' +\n 'rather than interrupting repeatedly.'\n );\n case 'auto':\n return (\n '<mode>auto</mode>\\nMost actions run without prompting. Be correspondingly careful ' +\n 'with anything destructive or hard to undo.'\n );\n case 'yolo':\n return (\n '<mode>yolo</mode>\\nNothing prompts. The user has accepted that; be careful with ' +\n 'anything you cannot undo, and prefer reversible steps.'\n );\n default:\n return (\n '<mode>ask</mode>\\nActions that change files, run commands or reach the network ' +\n 'prompt the user for approval first.'\n );\n }\n}\n",
23
+ "import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { configDir } from '@earshot/providers';\n\n/**\n * One remembered preference.\n *\n * Provenance is the reason this is a store of its own rather than lines appended\n * to AGENTS.md. A rule the user cannot trace back to something they said is a\n * rule they cannot judge, so every memory records the sentence it came from and\n * when - and `/memory` can show and delete exactly that.\n */\nexport interface Memory {\n id: string;\n scope: MemoryScope;\n /** The rule itself, in the imperative, as it will be given to the model. */\n text: string;\n /** What the user actually said, verbatim. */\n source: string;\n created: string;\n path: string;\n}\n\nexport type MemoryScope = 'user' | 'project';\n\nexport interface NewMemory {\n text: string;\n source: string;\n scope: MemoryScope;\n}\n\nexport function memoryDir(scope: MemoryScope, cwd: string): string {\n return scope === 'user' ? join(configDir(), 'memories') : join(cwd, '.earshot', 'memories');\n}\n\n/**\n * Reads both scopes, user first so a project memory is read last and wins.\n *\n * An unreadable or malformed file is skipped rather than failing the session:\n * these are hand-editable by design, and a typo in one of them must not be able\n * to stop the agent from starting.\n */\nexport async function loadMemories(cwd: string): Promise<Memory[]> {\n const memories: Memory[] = [];\n for (const scope of ['user', 'project'] as MemoryScope[]) {\n const dir = memoryDir(scope, cwd);\n const names = await readdir(dir).catch(() => [] as string[]);\n for (const name of names.sort()) {\n if (!name.endsWith('.md')) continue;\n const path = join(dir, name);\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n const parsed = parseMemory(raw, path, scope);\n if (parsed) memories.push(parsed);\n }\n }\n return memories;\n}\n\nexport async function saveMemory(memory: NewMemory, cwd: string): Promise<Memory> {\n const dir = memoryDir(memory.scope, cwd);\n await mkdir(dir, { recursive: true });\n\n const id = memoryId(memory.text);\n const created = new Date().toISOString();\n const path = join(dir, `${id}.md`);\n const body = [\n '---',\n `id: ${id}`,\n `created: ${created}`,\n `source: ${quote(memory.source)}`,\n '---',\n '',\n memory.text.trim(),\n '',\n ].join('\\n');\n\n await writeFile(path, body, 'utf8');\n return {\n id,\n scope: memory.scope,\n text: memory.text.trim(),\n source: memory.source,\n created,\n path,\n };\n}\n\nexport async function deleteMemory(id: string, cwd: string): Promise<boolean> {\n for (const scope of ['user', 'project'] as MemoryScope[]) {\n const path = join(memoryDir(scope, cwd), `${id}.md`);\n const gone = await rm(path).then(\n () => true,\n () => false,\n );\n if (gone) return true;\n }\n return false;\n}\n\n/**\n * Renders the index that sits in the system prompt on every turn.\n *\n * The id is included because the model is asked to name it when a memory changes\n * what it does - \"applying your rule: use bun, not npm\" is only checkable if the\n * user can go and look at that rule.\n */\nexport function renderMemories(memories: Memory[]): string {\n if (memories.length === 0) return '';\n const lines = memories.map(\n (memory) => `- [${memory.id}] (${memory.scope}) ${memory.text.replace(/\\n+/g, ' ')}`,\n );\n return (\n 'Preferences the user has asked you to remember. They are instructions, not ' +\n 'suggestions, and they outrank your defaults. When one of them changes what you do, ' +\n 'say so in one short clause naming it, so the user can see which rule acted and ' +\n `remove it if it is wrong.\\n\\n<preferences>\\n${lines.join('\\n')}\\n</preferences>`\n );\n}\n\n/** A stable, readable file name derived from the rule itself. */\nexport function memoryId(text: string): string {\n const slug = text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '')\n .split('-')\n .slice(0, 6)\n .join('-');\n return slug === '' ? `memory-${Date.now().toString(36)}` : slug;\n}\n\n/**\n * Frontmatter, hand-parsed.\n *\n * A YAML dependency would buy nothing here: these files have three scalar keys,\n * and the failure mode of a real parser - throwing on a file a user hand-edited\n * slightly wrong - is worse than ignoring a key we do not recognise.\n */\nfunction parseMemory(raw: string, path: string, scope: MemoryScope): Memory | undefined {\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/.exec(raw);\n if (!match) return undefined;\n const [, front = '', body = ''] = match;\n\n const fields = new Map<string, string>();\n for (const line of front.split(/\\r?\\n/)) {\n const at = line.indexOf(':');\n if (at <= 0) continue;\n fields.set(line.slice(0, at).trim(), unquote(line.slice(at + 1).trim()));\n }\n\n const text = body.trim();\n if (text === '') return undefined;\n const id = fields.get('id') ?? (path.split(/[/\\\\]/).pop() ?? '').replace(/\\.md$/, '');\n return {\n id,\n scope,\n text,\n source: fields.get('source') ?? '',\n created: fields.get('created') ?? '',\n path,\n };\n}\n\nfunction quote(value: string): string {\n return JSON.stringify(value.replace(/\\s+/g, ' ').trim());\n}\n\nfunction unquote(value: string): string {\n if (!value.startsWith('\"')) return value;\n try {\n return JSON.parse(value) as string;\n } catch {\n return value.slice(1, -1);\n }\n}\n",
24
+ "import {\n type Credentials,\n type Model,\n type ModelRequest,\n type Provider,\n type ProviderRegistry,\n resolveCredentials,\n type StreamEvent,\n type WireContext,\n} from '@earshot/providers';\n\nexport interface ResolvedModel {\n provider: Provider;\n model: Model;\n credentials: Credentials;\n}\n\nexport class MissingCredentialsError extends Error {\n constructor(readonly provider: Provider) {\n super(describeMissingAuth(provider));\n this.name = 'MissingCredentialsError';\n }\n}\n\nexport class UnknownModelError extends Error {\n constructor(readonly ref: string) {\n super(`unknown model \"${ref}\"`);\n this.name = 'UnknownModelError';\n }\n}\n\n/**\n * Binds a model reference to a provider and its credentials. This is the single\n * place the CLI, the TUI and subagents go to turn \"anthropic/claude-opus-5\" into\n * something callable, so auth failures surface once, with a usable message.\n */\nexport async function resolveModel(\n registry: ProviderRegistry,\n ref: string,\n opts: { apiKey?: string; env?: NodeJS.ProcessEnv } = {},\n): Promise<ResolvedModel> {\n const found = registry.resolveModel(ref) ?? (await discoverModel(registry, ref));\n if (!found) throw new UnknownModelError(ref);\n\n const credentials = await resolveCredentials(found.provider, {\n ...(opts.apiKey ? { cliApiKey: opts.apiKey } : {}),\n ...(opts.env ? { env: opts.env } : {}),\n });\n if (!credentials) throw new MissingCredentialsError(found.provider);\n\n return { ...found, credentials };\n}\n\n/**\n * Providers with live model discovery (Ollama, and any local runtime) publish no\n * static catalog, so a reference to one never matches until we ask the server what\n * it has. Only providers that opt in with `fetchModels` are probed, and a probe\n * that fails is treated as \"no such model\" rather than an error - the server\n * simply may not be running.\n */\nasync function discoverModel(\n registry: ProviderRegistry,\n ref: string,\n): Promise<{ provider: Provider; model: Model } | undefined> {\n const slash = ref.indexOf('/');\n const candidates = registry\n .list()\n .filter((p) => p.fetchModels)\n .filter((p) => (slash > 0 ? p.id === ref.slice(0, slash) : true));\n\n const wanted = slash > 0 ? ref.slice(slash + 1) : ref;\n\n for (const provider of candidates) {\n try {\n const models = await provider.fetchModels?.({\n credentials: { type: 'ambient' },\n ...(provider.baseUrl ? { baseUrl: provider.baseUrl } : {}),\n });\n const model = models?.find((m) => m.id === wanted);\n if (model) return { provider, model };\n } catch {\n // The runtime is not reachable; fall through to \"unknown model\".\n }\n }\n return undefined;\n}\n\nfunction describeMissingAuth(provider: Provider): string {\n const { auth } = provider;\n const how =\n auth.kind === 'api-key' && auth.envVars.length\n ? `set ${auth.envVars.join(' or ')}, or run \\`earshot auth login ${provider.id}\\``\n : auth.kind === 'oauth'\n ? `run \\`earshot auth login ${provider.id}\\``\n : auth.kind === 'ambient'\n ? `configure ${auth.description}`\n : 'no credentials are configured';\n return `no credentials for ${provider.name}: ${how}`;\n}\n\n/** Opens a stream for one model call. Transforms run here, in declared order. */\nexport function streamModel(\n registry: ProviderRegistry,\n resolved: ResolvedModel,\n request: Omit<ModelRequest, 'modelId'>,\n): AsyncIterable<StreamEvent> {\n const { provider, model, credentials } = resolved;\n const wire = registry.wireFor(provider, model);\n\n let req: ModelRequest = { ...request, modelId: model.id };\n for (const transform of provider.transforms ?? []) req = transform.apply(req, model);\n\n const ctx: WireContext = {\n credentials,\n ...(provider.baseUrl ? { baseUrl: provider.baseUrl } : {}),\n };\n return wire.stream(req, ctx);\n}\n\n/** USD for one turn, from catalog pricing. Cache reads and writes price separately. */\nexport function turnCost(\n model: Model,\n usage: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n },\n): number {\n const cost = model.cost;\n if (!cost) return 0;\n const per = (tokens: number, rate: number) => (tokens / 1_000_000) * rate;\n // Cached reads are billed at the cache rate instead of the input rate, so they\n // must not also be counted as fresh input.\n const cacheRead = usage.cacheReadTokens ?? 0;\n const cacheWrite = usage.cacheWriteTokens ?? 0;\n const freshInput = Math.max(0, usage.inputTokens - cacheRead);\n return (\n per(freshInput, cost.input) +\n per(usage.outputTokens, cost.output) +\n per(cacheRead, cost.cacheRead ?? cost.input) +\n per(cacheWrite, cost.cacheWrite ?? cost.input)\n );\n}\n",
25
+ "import { isAbsolute, relative, resolve, sep } from 'node:path';\n\n/** Resolves a tool-supplied path against the session cwd. */\nexport function resolvePath(cwd: string, path: string): string {\n return isAbsolute(path) ? resolve(path) : resolve(cwd, path);\n}\n\n/**\n * Whether `path` is inside `cwd`. Writes outside the working directory always\n * prompt regardless of configured rules, so this decides when the gate escalates.\n * Compared case-sensitively even on Windows: over-prompting is the safe error.\n */\nexport function isInside(cwd: string, path: string): boolean {\n const rel = relative(resolve(cwd), resolve(path));\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);\n}\n\n/** `src/main.ts` when inside cwd, an absolute path when outside. */\nexport function displayPath(cwd: string, path: string): string {\n const abs = resolve(path);\n return isInside(cwd, abs) ? relative(resolve(cwd), abs).split(sep).join('/') : abs;\n}\n",
26
+ "/**\n * Glob matching over `/`-separated paths. Hand-rolled because the one thing a\n * dependency would add here is `**` semantics, and getting those wrong is the\n * whole bug surface - so they are tested directly instead.\n *\n * Supports `*` (no separator), `**` (any depth, including none), `?`, and\n * `{a,b}` alternation. A leading `**\\/` is implied for a pattern with no\n * separator, so `*.ts` matches `src/main.ts` the way every other tool behaves.\n */\nexport function globToRegExp(pattern: string): RegExp {\n const implicitlyRecursive = !pattern.includes('/');\n const source = implicitlyRecursive ? `**/${pattern}` : pattern;\n return new RegExp(`^${compile(source)}$`);\n}\n\nexport function matchesGlob(pattern: string, path: string): boolean {\n return globToRegExp(pattern).test(path);\n}\n\nfunction compile(pattern: string): string {\n let out = '';\n for (let i = 0; i < pattern.length; i++) {\n const ch = pattern[i] as string;\n if (ch === '*') {\n if (pattern[i + 1] === '*') {\n // `**/` collapses to \"any number of segments, including zero\", which is\n // what makes `src/**/*.ts` match `src/main.ts` and not just nested files.\n i++;\n if (pattern[i + 1] === '/') {\n i++;\n out += '(?:[^/]+/)*';\n } else {\n out += '.*';\n }\n } else {\n out += '[^/]*';\n }\n } else if (ch === '?') {\n out += '[^/]';\n } else if (ch === '{') {\n const end = pattern.indexOf('}', i);\n if (end === -1) {\n out += '\\\\{';\n } else {\n const alts = pattern.slice(i + 1, end).split(',');\n out += `(?:${alts.map(compile).join('|')})`;\n i = end;\n }\n } else {\n out += ch.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n }\n return out;\n}\n",
27
+ "import { matchesGlob } from '../tools/glob-match.ts';\n\nexport type RuleEffect = 'allow' | 'deny' | 'ask';\n\n/** Where a rule came from. Narrower scopes are listed first in explanations. */\nexport type RuleScope = 'global' | 'project' | 'local' | 'session';\n\nexport interface Rule {\n /** Tool name as written in the rule, e.g. `Bash`, `Edit`, `WebFetch`. */\n tool: string;\n /** Pattern inside the parentheses. Absent means \"every use of this tool\". */\n pattern?: string;\n effect: RuleEffect;\n scope: RuleScope;\n /** The rule as written, for showing the user why something was decided. */\n source: string;\n}\n\nexport class RuleSyntaxError extends Error {\n constructor(rule: string, reason: string) {\n super(`bad permission rule \"${rule}\": ${reason}`);\n this.name = 'RuleSyntaxError';\n }\n}\n\n/**\n * Parses `Tool(pattern)` or a bare `Tool`.\n *\n * The pattern is not itself parsed here: what it means depends on the tool, and\n * a command pattern and a path pattern match very differently (see `ruleMatches`).\n */\nexport function parseRule(text: string, effect: RuleEffect, scope: RuleScope): Rule {\n const trimmed = text.trim();\n if (trimmed === '') throw new RuleSyntaxError(text, 'empty');\n\n const open = trimmed.indexOf('(');\n if (open === -1) {\n if (!/^[A-Za-z_][\\w-]*$/.test(trimmed)) throw new RuleSyntaxError(text, 'not a tool name');\n return { tool: trimmed, effect, scope, source: trimmed };\n }\n if (!trimmed.endsWith(')')) throw new RuleSyntaxError(text, 'missing closing parenthesis');\n\n const tool = trimmed.slice(0, open).trim();\n const pattern = trimmed.slice(open + 1, -1).trim();\n if (!/^[A-Za-z_][\\w-]*$/.test(tool)) throw new RuleSyntaxError(text, 'not a tool name');\n if (pattern === '') throw new RuleSyntaxError(text, 'empty pattern');\n\n return { tool, pattern, effect, scope, source: trimmed };\n}\n\n/**\n * Tools whose target is a path, and so is matched with path-glob semantics where\n * `*` stops at a separator. Everything else is matched as a command string.\n */\nconst PATH_TOOLS = new Set(['Edit', 'Write', 'Read']);\n\n/** Operators that chain one command into another inside a single `bash` call. */\nconst CHAIN = /\\s*(?:&&|\\|\\||;|\\|)\\s*/;\n\nexport function ruleMatches(rule: Rule, tool: string, target: string): boolean {\n if (rule.tool !== tool) return false;\n if (rule.pattern === undefined) return true;\n\n if (PATH_TOOLS.has(rule.tool)) return matchesGlob(rule.pattern, target);\n\n // A command is only covered when *every* segment of it is covered. Without\n // this, `Bash(npm run *)` would allow `npm run build && rm -rf ~`, because the\n // string does start with the approved prefix. Splitting is deliberately\n // conservative: an operator inside a quoted argument produces extra segments\n // that fail to match, which over-prompts rather than under-prompts.\n const segments = target.split(CHAIN).filter((segment) => segment.trim() !== '');\n if (segments.length === 0) return false;\n return segments.every((segment) => matchesCommand(rule.pattern as string, segment.trim()));\n}\n\n/**\n * Command matching, where `*` spans anything including spaces - `git *` covers\n * `git log --oneline -5`. Path-glob semantics would stop at a separator and make\n * `Bash(git *)` fail on any command containing a path, which is most of them.\n */\nexport function matchesCommand(pattern: string, command: string): boolean {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\?]/g, '\\\\$&').replace(/\\*/g, '[\\\\s\\\\S]*');\n return new RegExp(`^${escaped}$`).test(command);\n}\n\n/**\n * The first matching deny rule, if any. Deny is evaluated before everything else\n * and is never overridden by an allow rule at any scope, so this is checked on\n * its own rather than folded into a single ordered pass.\n */\nexport function firstDeny(rules: Rule[], tool: string, target: string): Rule | undefined {\n return rules.find((rule) => rule.effect === 'deny' && ruleMatches(rule, tool, target));\n}\n\nexport function firstAllow(rules: Rule[], tool: string, target: string): Rule | undefined {\n return rules.find((rule) => rule.effect === 'allow' && ruleMatches(rule, tool, target));\n}\n\nexport function firstAsk(rules: Rule[], tool: string, target: string): Rule | undefined {\n return rules.find((rule) => rule.effect === 'ask' && ruleMatches(rule, tool, target));\n}\n",
28
+ "import { isInside } from '../tools/fs-paths.ts';\nimport type { PermissionRequest, Tool } from '../tools/types.ts';\nimport { firstAllow, firstAsk, firstDeny, type Rule, type RuleScope } from './rules.ts';\n\n/**\n * How much the agent may do without asking.\n *\n * - `plan` - read and search only; every mutating tool is refused, so the\n * model produces a plan instead of changes.\n * - `ask` - the default. Anything mutating prompts unless a rule allows it.\n * - `accept-edits` - file edits inside the working directory go through; commands\n * and network access still prompt.\n * - `auto` - anything not explicitly denied goes through.\n * - `yolo` - no prompts at all, including writes outside the working\n * directory. Deny rules still apply: they are the one thing that\n * no mode overrides.\n */\nexport type PermissionMode = 'plan' | 'ask' | 'accept-edits' | 'auto' | 'yolo';\n\nexport const PERMISSION_MODES: PermissionMode[] = ['plan', 'ask', 'accept-edits', 'auto', 'yolo'];\n\nexport function isPermissionMode(value: string): value is PermissionMode {\n return (PERMISSION_MODES as string[]).includes(value);\n}\n\nexport type Decision =\n | { outcome: 'allow'; reason: string }\n | { outcome: 'deny'; reason: string }\n | { outcome: 'ask'; reason: string; request: PermissionRequest };\n\n/** Tools that edit files, as opposed to running commands or reaching the network. */\nconst EDIT_TOOLS = new Set(['Edit', 'Write']);\n\nexport interface GateOptions {\n mode: PermissionMode;\n rules: Rule[];\n cwd: string;\n}\n\n/**\n * Decides one tool call. Pure: it reads rules and the request and returns a\n * decision, so the whole policy is testable without a terminal attached.\n *\n * Order is the policy, and it is deliberately not \"most specific wins\":\n *\n * 1. A matching deny rule refuses, always. No mode and no allow rule overrides it.\n * 2. Read-only tools never prompt.\n * 3. `plan` refuses every mutating tool.\n * 4. A write outside the working directory prompts, whatever the rules say,\n * unless the user has explicitly chosen `yolo`.\n * 5. `yolo` allows.\n * 6. A matching ask rule prompts even when a later allow rule would match.\n * 7. A matching allow rule allows.\n * 8. Otherwise the mode decides.\n */\nexport function decide(\n tool: Tool<never>,\n request: PermissionRequest | undefined,\n options: GateOptions,\n): Decision {\n const { mode, rules, cwd } = options;\n\n if (request) {\n const denied = firstDeny(rules, request.tool, request.target);\n if (denied) {\n return { outcome: 'deny', reason: `denied by rule ${denied.source} (${denied.scope})` };\n }\n }\n\n if (tool.readOnly || !request) {\n return { outcome: 'allow', reason: 'read-only' };\n }\n\n if (mode === 'plan') {\n return {\n outcome: 'deny',\n reason:\n `${tool.name} changes state, and the session is in plan mode. Present the plan ` +\n 'and let the user approve it; do not try another tool to work around this.',\n };\n }\n\n const outside = (request.writes ?? []).filter((path) => !isInside(cwd, path));\n if (outside.length > 0 && mode !== 'yolo') {\n // Not overridable by an allow rule: a project's own settings file must not be\n // able to grant that project write access to the rest of the machine.\n return {\n outcome: 'ask',\n reason: `writes outside the working directory: ${outside.join(', ')}`,\n request,\n };\n }\n\n if (mode === 'yolo') return { outcome: 'allow', reason: 'yolo mode' };\n\n const asked = firstAsk(rules, request.tool, request.target);\n if (asked) {\n return { outcome: 'ask', reason: `rule ${asked.source} (${asked.scope})`, request };\n }\n\n const allowed = firstAllow(rules, request.tool, request.target);\n if (allowed) {\n return { outcome: 'allow', reason: `allowed by rule ${allowed.source} (${allowed.scope})` };\n }\n\n if (mode === 'auto') return { outcome: 'allow', reason: 'auto mode' };\n if (mode === 'accept-edits' && EDIT_TOOLS.has(request.tool)) {\n return { outcome: 'allow', reason: 'accept-edits mode' };\n }\n\n return { outcome: 'ask', reason: 'no rule covers this', request };\n}\n\n/** What the user picked at a prompt. */\nexport type PromptChoice =\n | { kind: 'allow-once' }\n | { kind: 'allow-always'; scope: RuleScope }\n | { kind: 'deny'; message?: string };\n\n/**\n * Asks the user. The prompt must show `request.detail` - the real command or the\n * real diff - because a prompt showing a paraphrase is one people learn to\n * approve without reading.\n */\nexport type PermissionPrompt = (\n request: PermissionRequest,\n reason: string,\n) => Promise<PromptChoice>;\n\n/** Turns \"always allow this\" into the rule that will be persisted. */\nexport function ruleFromChoice(request: PermissionRequest, scope: RuleScope): Rule {\n // The rule generalises to the tool's whole target rather than to a wildcard: a\n // user approving `git status` has not approved `git push --force`.\n const source = `${request.tool}(${request.target})`;\n return { tool: request.tool, pattern: request.target, effect: 'allow', scope, source };\n}\n",
29
+ "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { configDir } from '@earshot/providers';\nimport { type Curiosity, isCuriosity } from '../context/system-prompt.ts';\nimport { isPermissionMode, type PermissionMode } from './engine.ts';\nimport { parseRule, type Rule, type RuleScope, RuleSyntaxError } from './rules.ts';\n\nexport interface SettingsFile {\n permissions?: {\n allow?: string[];\n deny?: string[];\n ask?: string[];\n defaultMode?: string;\n };\n curiosity?: string;\n /** Session budget in USD. A turn stops and asks before spending past it. */\n maxCostUsd?: number;\n}\n\nexport interface LoadedSettings {\n rules: Rule[];\n /** From the narrowest scope that sets one. */\n defaultMode?: PermissionMode;\n /** Preferences, like `defaultMode`: the narrowest scope that sets one wins. */\n curiosity?: Curiosity;\n maxCostUsd?: number;\n /** Rules that failed to parse, reported rather than silently dropped. */\n problems: string[];\n}\n\nexport const PROJECT_SETTINGS = join('.earshot', 'settings.json');\nexport const LOCAL_SETTINGS = join('.earshot', 'settings.local.json');\n\nexport function settingsPath(scope: RuleScope, cwd: string): string {\n if (scope === 'global') return join(configDir(), 'settings.json');\n if (scope === 'project') return join(cwd, PROJECT_SETTINGS);\n if (scope === 'local') return join(cwd, LOCAL_SETTINGS);\n throw new Error(`scope \"${scope}\" is not persisted`);\n}\n\nasync function readSettings(path: string): Promise<SettingsFile | undefined> {\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) return undefined;\n try {\n return JSON.parse(raw) as SettingsFile;\n } catch (error) {\n throw new Error(`${path} is not valid JSON: ${(error as Error).message}`);\n }\n}\n\n/**\n * Loads global, then project, then local settings.\n *\n * Rules from every scope are concatenated rather than overriding one another -\n * a narrower scope cannot remove a broader scope's deny rule, which is the whole\n * point of deny-first. `defaultMode` is the exception: it is a preference, not a\n * restriction, so the narrowest scope that sets one wins.\n */\nexport async function loadSettings(cwd: string): Promise<LoadedSettings> {\n const scopes: RuleScope[] = ['global', 'project', 'local'];\n const rules: Rule[] = [];\n const problems: string[] = [];\n let defaultMode: PermissionMode | undefined;\n let curiosity: Curiosity | undefined;\n let maxCostUsd: number | undefined;\n\n for (const scope of scopes) {\n const path = settingsPath(scope, cwd);\n const file = await readSettings(path).catch((error: Error) => {\n problems.push(error.message);\n return undefined;\n });\n if (!file) continue;\n\n if (file.curiosity !== undefined) {\n if (isCuriosity(file.curiosity)) curiosity = file.curiosity;\n else problems.push(`${path}: \"${file.curiosity}\" is not a curiosity level`);\n }\n\n if (file.maxCostUsd !== undefined) {\n if (\n typeof file.maxCostUsd === 'number' &&\n Number.isFinite(file.maxCostUsd) &&\n file.maxCostUsd > 0\n ) {\n maxCostUsd = file.maxCostUsd;\n } else {\n problems.push(`${path}: \"maxCostUsd\" must be a positive number of dollars`);\n }\n }\n\n if (!file.permissions) continue;\n\n // Deny rules are collected first within each scope so an explanation names\n // the deny rule rather than a coincidentally earlier allow rule.\n for (const [effect, list] of [\n ['deny', file.permissions.deny],\n ['ask', file.permissions.ask],\n ['allow', file.permissions.allow],\n ] as const) {\n for (const text of list ?? []) {\n try {\n rules.push(parseRule(text, effect, scope));\n } catch (error) {\n if (!(error instanceof RuleSyntaxError)) throw error;\n problems.push(`${path}: ${error.message}`);\n }\n }\n }\n\n const mode = file.permissions.defaultMode;\n if (mode !== undefined) {\n if (isPermissionMode(mode)) defaultMode = mode;\n else problems.push(`${path}: \"${mode}\" is not a permission mode`);\n }\n }\n\n // Deny rules sort ahead of the rest so `firstDeny` and the explanations it\n // produces are stable regardless of which scope contributed what.\n rules.sort((a, b) => Number(b.effect === 'deny') - Number(a.effect === 'deny'));\n return {\n rules,\n ...(defaultMode ? { defaultMode } : {}),\n ...(curiosity ? { curiosity } : {}),\n ...(maxCostUsd !== undefined ? { maxCostUsd } : {}),\n problems,\n };\n}\n\n/**\n * Appends one allow rule to a settings file, preserving whatever else is in it.\n * Read-modify-write rather than a rewrite from the in-memory rule set: the file\n * is the user's, and may hold settings this version does not know about.\n */\nexport async function persistRule(rule: Rule, scope: RuleScope, cwd: string): Promise<string> {\n const path = settingsPath(scope, cwd);\n const existing = (await readSettings(path).catch(() => undefined)) ?? {};\n\n const permissions = existing.permissions ?? {};\n const list = permissions[rule.effect] ?? [];\n if (!list.includes(rule.source)) list.push(rule.source);\n\n const next: SettingsFile = { ...existing, permissions: { ...permissions, [rule.effect]: list } };\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(next, null, 2)}\\n`, 'utf8');\n return path;\n}\n",
30
+ "import { spawn } from 'node:child_process';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { dataDir } from '@earshot/providers';\n\n/**\n * A plan you can edit.\n *\n * The plan lives in a file rather than in the conversation, and that is the\n * whole point: a plan you can only accept or reject is a prompt. You edit it -\n * in $EDITOR, or in your own editor at the path this prints - and what gets\n * pinned into the run is what the file says when you approve it, not what the\n * model wrote.\n */\nexport function planPath(sessionId: string): string {\n return join(dataDir(), 'plans', `${sessionId}.md`);\n}\n\nexport const PLAN_PROMPT =\n 'Produce a plan and stop. Do not change anything: state what you would do, ' +\n 'file by file, with the behaviour that changes and the behaviour that does not, ' +\n 'and name anything you are unsure about rather than deciding it quietly. The ' +\n 'user will edit this plan before approving it, so write it for them to change.';\n\nexport async function savePlan(path: string, text: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, text.endsWith('\\n') ? text : `${text}\\n`, 'utf8');\n}\n\nexport async function readPlan(path: string): Promise<string | undefined> {\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n return raw?.trim() === '' ? undefined : raw;\n}\n\n/**\n * The approved plan, as it goes into the system prompt.\n *\n * Named as the user's, because it is: they edited it and approved it, and the\n * model needs to treat a line it did not write as binding rather than as a\n * suggestion it made earlier.\n */\nexport function renderPlan(text: string): string {\n return (\n '<plan>\\n' +\n 'The user approved this plan for the work in progress, after editing it. It is\\n' +\n 'their instruction, not your earlier draft: where it differs from what you would\\n' +\n 'have done, it wins. If following it turns out to be wrong, say so and stop -\\n' +\n 'do not quietly do something else.\\n\\n' +\n `${text.trim()}\\n</plan>`\n );\n}\n\nexport interface EditorResult {\n edited: boolean;\n /** What to tell the user. Always set, including on success. */\n message: string;\n}\n\n/**\n * Opens the plan in $VISUAL or $EDITOR.\n *\n * Falls back to naming the path rather than guessing at an editor: launching\n * something the user did not configure, into a terminal earshot is already\n * drawing in, is a worse outcome than one line telling them where the file is.\n */\nexport async function openInEditor(\n path: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<EditorResult> {\n const editor = env.VISUAL ?? env.EDITOR;\n if (!editor || editor.trim() === '') {\n return {\n edited: false,\n message: `no $EDITOR set. Edit ${path} in your own editor, then run /plan approve.`,\n };\n }\n\n const code = await new Promise<number | null>((resolve) => {\n // The editor takes the terminal: it is interactive, and piping its stdio\n // would leave the user typing into something they cannot see.\n const child = spawn(editor, [path], { stdio: 'inherit', shell: true });\n child.on('error', () => resolve(-1));\n child.on('close', (status) => resolve(status));\n });\n\n if (code !== 0) {\n return {\n edited: false,\n message: `${editor} exited ${code ?? 'on a signal'}; ${path} is unchanged as far as earshot knows.`,\n };\n }\n return {\n edited: true,\n message: `edited ${path}. Run /plan approve to pin it, or /plan show to read it back.`,\n };\n}\n",
31
+ "import { relative, sep } from 'node:path';\nimport { matchesGlob } from '../tools/glob-match.ts';\nimport type { PermissionRequest } from '../tools/types.ts';\n\n/**\n * What the agent said it was going to do, before it did any of it.\n *\n * The scope is declared by the model in its own words and its own file list.\n * That is the point: a contract the agent wrote is one it can be held to, and\n * the check below is a comparison against that statement rather than a guess at\n * what the user meant.\n */\nexport interface Scope {\n /** Paths or globs, relative to the working directory. */\n files: string[];\n /** One paragraph: which behaviours change, and which do not. */\n intent: string;\n /** The agent's own estimate of the size of the change, in changed lines. */\n estimatedLines?: number;\n}\n\nexport type ScopeConcern =\n | { kind: 'undeclared'; summary: string }\n | { kind: 'out-of-scope-file'; summary: string; path: string }\n | { kind: 'new-dependency'; summary: string }\n | { kind: 'rename-or-delete'; summary: string }\n | { kind: 'formatting-sweep'; summary: string }\n | { kind: 'test-removal'; summary: string }\n | { kind: 'over-budget'; summary: string; changed: number; budget: number };\n\nexport interface ScopeOptions {\n /**\n * Smallest turn that can be over budget. Below it the guard stays quiet: a\n * fifty-line change is not a scope violation whatever the estimate said, and\n * a guard that fires on those trains people to confirm without reading.\n */\n floorLines: number;\n /** How far past the agent's own estimate a turn may go before it confirms. */\n overrunFactor: number;\n /** Fires on the first mutating call when nothing has been declared. */\n requireDeclaration: boolean;\n}\n\nexport const DEFAULT_SCOPE_OPTIONS: ScopeOptions = {\n floorLines: 150,\n overrunFactor: 3,\n requireDeclaration: false,\n};\n\nconst DEPENDENCY_FILES = [\n 'package.json',\n 'bun.lock',\n 'bun.lockb',\n 'package-lock.json',\n 'pnpm-lock.yaml',\n 'yarn.lock',\n 'Cargo.toml',\n 'Cargo.lock',\n 'go.mod',\n 'go.sum',\n 'requirements.txt',\n 'pyproject.toml',\n 'Gemfile',\n];\n\n/** `npm i x`, `bun add x`, `cargo add x`, `pip install x`, and the rest. */\nconst INSTALL_COMMAND =\n /\\b(?:npm|bun|pnpm|yarn)\\s+(?:add|install|i)\\b|\\bcargo\\s+add\\b|\\b(?:pip|pip3|uv)\\s+(?:add|install)\\b|\\bgo\\s+get\\b/;\n\nconst MOVE_COMMAND = /\\b(?:rm|mv|git\\s+rm|git\\s+mv)\\b/;\n\nconst TEST_PATH = /(^|[/\\\\])(?:tests?|__tests__|spec)[/\\\\]|\\.(?:test|spec)\\.[cm]?[jt]sx?$/;\n\nconst TEST_DECLARATION = /\\b(?:test|it|describe)\\s*[.(]|\\bdef\\s+test_|\\bfunc\\s+Test[A-Z]/;\n\n/**\n * Tracks the declared scope for a turn and reports what falls outside it.\n *\n * Deliberately not a line count. A line count either fires on every large change\n * the user actually asked for or never fires on the small wrong ones, so the\n * check is categorical - a file nobody mentioned, a dependency nobody asked for,\n * a rename, a formatting sweep, a deleted test - and the size limit is only a\n * backstop for the case where none of those name the problem.\n */\nexport class ScopeContract {\n private scope: Scope | undefined;\n private changedLines = 0;\n /** Concerns already confirmed, so the same one is not raised twice a turn. */\n private readonly accepted = new Set<string>();\n private readonly options: ScopeOptions;\n\n constructor(\n private readonly cwd: string,\n options: Partial<ScopeOptions> = {},\n ) {\n this.options = { ...DEFAULT_SCOPE_OPTIONS, ...options };\n }\n\n get declared(): Scope | undefined {\n return this.scope;\n }\n\n declare(scope: Scope): void {\n this.scope = scope;\n this.changedLines = 0;\n this.accepted.clear();\n }\n\n /** Widens the scope after the user confirmed something outside it. */\n widen(concern: ScopeConcern, path?: string): void {\n this.accepted.add(concern.kind);\n if (path && this.scope) this.scope = { ...this.scope, files: [...this.scope.files, path] };\n }\n\n /** Starts a new turn: the budget is per turn, the declaration is not. */\n beginTurn(): void {\n this.changedLines = 0;\n this.accepted.clear();\n }\n\n /**\n * Called after a change was approved and applied, so the running total counts\n * what happened rather than what was proposed.\n */\n record(request: PermissionRequest): void {\n this.changedLines += countChangedLines(request.detail);\n }\n\n /** The first thing about this call that falls outside what was declared. */\n check(request: PermissionRequest): ScopeConcern | undefined {\n const concern = this.classify(request);\n if (!concern || this.accepted.has(concern.kind)) return undefined;\n return concern;\n }\n\n private classify(request: PermissionRequest): ScopeConcern | undefined {\n const scope = this.scope;\n if (!scope) {\n if (!this.options.requireDeclaration) return undefined;\n return {\n kind: 'undeclared',\n summary:\n 'This is the first change of the turn and no scope was declared. Say which files ' +\n 'will change and what will change about them first.',\n };\n }\n\n const paths = (request.writes ?? []).map((path) => this.display(path));\n\n for (const path of paths) {\n // Named explicitly, not merely matched: a broad glob like `**` should not\n // silently license adding a dependency, which is the change most likely to\n // outlive the task that introduced it.\n if (isDependencyFile(path) && !scope.files.includes(path)) {\n return {\n kind: 'new-dependency',\n summary: `${path} declares this project's dependencies and is not in the declared scope.`,\n };\n }\n if (!this.covers(scope, path)) {\n return {\n kind: 'out-of-scope-file',\n path,\n summary: `${path} is not one of the files this turn said it would change (${scope.files.join(', ')}).`,\n };\n }\n }\n\n if (request.tool === 'Bash') {\n if (INSTALL_COMMAND.test(request.target)) {\n return {\n kind: 'new-dependency',\n summary: 'This command adds a dependency, which the task did not ask for.',\n };\n }\n if (MOVE_COMMAND.test(request.target)) {\n return {\n kind: 'rename-or-delete',\n summary: 'This command renames or deletes files, which the task did not ask for.',\n };\n }\n }\n\n const diff = summariseDiff(request.detail);\n if (diff.changed >= 20 && diff.whitespaceOnly) {\n return {\n kind: 'formatting-sweep',\n summary: `This change rewrites ${diff.changed} lines without changing what any of them say.`,\n };\n }\n if (diff.removedTests > 0 && paths.some((path) => TEST_PATH.test(path))) {\n return {\n kind: 'test-removal',\n summary: `This removes ${diff.removedTests} test${diff.removedTests === 1 ? '' : 's'}. A test that is in the way is usually reporting something real.`,\n };\n }\n\n const budget = Math.max(\n this.options.floorLines,\n (scope.estimatedLines ?? 0) * this.options.overrunFactor,\n );\n const total = this.changedLines + diff.changed;\n if (total > budget) {\n return {\n kind: 'over-budget',\n changed: total,\n budget,\n summary:\n `This turn has changed ${total} lines against an estimate of ` +\n `${scope.estimatedLines ?? 'none'}. A change several times the size of the one ` +\n 'described is usually a different change.',\n };\n }\n return undefined;\n }\n\n private covers(scope: Scope, path: string): boolean {\n return scope.files.some(\n (pattern) => pattern === path || matchesGlob(pattern, path) || path.startsWith(`${pattern}/`),\n );\n }\n\n private display(path: string): string {\n const rel = relative(this.cwd, path);\n return rel === '' || rel.startsWith('..') ? path : rel.split(sep).join('/');\n }\n}\n\nfunction isDependencyFile(path: string): boolean {\n const name = path.split('/').pop() ?? path;\n return DEPENDENCY_FILES.includes(name);\n}\n\nexport function countChangedLines(diff: string): number {\n return summariseDiff(diff).changed;\n}\n\ninterface DiffSummary {\n changed: number;\n /** True when the added and removed lines differ only in whitespace. */\n whitespaceOnly: boolean;\n removedTests: number;\n}\n\n/**\n * Reads the unified diff the permission prompt already shows.\n *\n * Nothing here re-derives the change from the tool input: the diff is what the\n * user was shown and approved, so it is also what the guard should measure.\n */\nexport function summariseDiff(detail: string): DiffSummary {\n const added: string[] = [];\n const removed: string[] = [];\n for (const line of detail.split('\\n')) {\n if (line.startsWith('+++') || line.startsWith('---') || line.startsWith('@@')) continue;\n if (line.startsWith('+')) added.push(line.slice(1));\n else if (line.startsWith('-')) removed.push(line.slice(1));\n }\n\n const squash = (lines: string[]) => lines.join('').replace(/\\s+/g, '');\n const removedTests = removed.filter((line) => TEST_DECLARATION.test(line)).length;\n const addedTests = added.filter((line) => TEST_DECLARATION.test(line)).length;\n\n return {\n changed: added.length + removed.length,\n whitespaceOnly: added.length > 0 && removed.length > 0 && squash(added) === squash(removed),\n removedTests: Math.max(0, removedTests - addedTests),\n };\n}\n",
32
+ "import { readdir, readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { configDir } from '@earshot/providers';\nimport { parseFrontmatter, parseList } from './frontmatter.ts';\n\nexport type ExtensionScope = 'user' | 'project';\n\nexport interface Skill {\n /**\n * From the file or directory name, never from the frontmatter. The name is\n * what the model and the user address a skill by, and letting a file choose a\n * name that is not its own is how one skill impersonates another.\n */\n name: string;\n description: string;\n scope: ExtensionScope;\n path: string;\n /**\n * Tools this skill may use while it is active. It can only ever remove tools\n * from what the session already allows - see `narrow()`.\n */\n allowedTools: string[];\n body: string;\n}\n\nexport interface SlashCommand {\n name: string;\n description: string;\n scope: ExtensionScope;\n path: string;\n /** The prompt, with `$ARGUMENTS` still in it. */\n body: string;\n}\n\nexport interface Discovered {\n skills: Skill[];\n commands: SlashCommand[];\n problems: string[];\n}\n\n/**\n * A skill body is text the model will act on, and an enormous one would crowd\n * out the conversation it was meant to help with.\n */\nexport const MAX_SKILL_CHARS = 32_000;\n\nconst NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;\n\nexport function skillsDir(scope: ExtensionScope, cwd: string): string {\n return scope === 'user' ? join(configDir(), 'skills') : join(cwd, '.earshot', 'skills');\n}\n\nexport function commandsDir(scope: ExtensionScope, cwd: string): string {\n return scope === 'user' ? join(configDir(), 'commands') : join(cwd, '.earshot', 'commands');\n}\n\n/**\n * Skills and slash commands from the user's config directory and from the\n * project.\n *\n * The user's own skills win a name collision, and the project's is reported\n * rather than dropped silently. That is the opposite of how AGENTS.md resolves,\n * deliberately: a project file is content someone cloned, and a repository being\n * able to replace the meaning of a command the user wrote themselves is a\n * different thing from it adding one of its own.\n */\nexport async function discoverExtensions(cwd: string): Promise<Discovered> {\n const problems: string[] = [];\n const skills = new Map<string, Skill>();\n const commands = new Map<string, SlashCommand>();\n\n for (const scope of ['user', 'project'] as ExtensionScope[]) {\n for (const skill of await readSkills(scope, cwd, problems)) {\n const existing = skills.get(skill.name);\n if (existing) {\n problems.push(\n `skill \"${skill.name}\" in ${skill.path} is shadowed by the one in ${existing.path}`,\n );\n continue;\n }\n skills.set(skill.name, skill);\n }\n for (const command of await readCommands(scope, cwd, problems)) {\n const existing = commands.get(command.name);\n if (existing) {\n problems.push(\n `command /${command.name} in ${command.path} is shadowed by the one in ${existing.path}`,\n );\n continue;\n }\n commands.set(command.name, command);\n }\n }\n\n return {\n skills: [...skills.values()].sort((a, b) => a.name.localeCompare(b.name)),\n commands: [...commands.values()].sort((a, b) => a.name.localeCompare(b.name)),\n problems,\n };\n}\n\nasync function readSkills(\n scope: ExtensionScope,\n cwd: string,\n problems: string[],\n): Promise<Skill[]> {\n const dir = skillsDir(scope, cwd);\n const entries = await readdir(dir).catch(() => [] as string[]);\n const skills: Skill[] = [];\n\n for (const entry of entries.sort()) {\n // Both layouts are accepted: a directory holding SKILL.md alongside whatever\n // else it references, and a single file for a skill that is only prose.\n const asDirectory = join(dir, entry, 'SKILL.md');\n const asFile = join(dir, entry);\n const isDirectory = await stat(join(dir, entry))\n .then((info) => info.isDirectory())\n .catch(() => false);\n const path = isDirectory ? asDirectory : asFile;\n if (!isDirectory && !entry.endsWith('.md')) continue;\n\n const name = isDirectory ? entry : entry.replace(/\\.md$/, '');\n if (!NAME.test(name)) {\n problems.push(`skill \"${name}\" in ${dir} does not have a usable name`);\n continue;\n }\n\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) {\n if (isDirectory) problems.push(`${join(dir, entry)} has no SKILL.md`);\n continue;\n }\n\n const { fields, body } = parseFrontmatter(raw);\n if (body.trim() === '') {\n problems.push(`skill \"${name}\" (${path}) is empty`);\n continue;\n }\n skills.push({\n name,\n description: fields.get('description') ?? `the \"${name}\" skill`,\n scope,\n path,\n allowedTools: parseList(fields.get('allowed-tools')),\n body: body.length > MAX_SKILL_CHARS ? `${body.slice(0, MAX_SKILL_CHARS)}\\n\\n[...]` : body,\n });\n }\n return skills;\n}\n\nasync function readCommands(\n scope: ExtensionScope,\n cwd: string,\n problems: string[],\n): Promise<SlashCommand[]> {\n const dir = commandsDir(scope, cwd);\n const entries = await readdir(dir).catch(() => [] as string[]);\n const commands: SlashCommand[] = [];\n\n for (const entry of entries.sort()) {\n if (!entry.endsWith('.md')) continue;\n const name = entry.replace(/\\.md$/, '');\n if (!NAME.test(name)) {\n problems.push(`command \"${name}\" in ${dir} does not have a usable name`);\n continue;\n }\n const path = join(dir, entry);\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n\n const { fields, body } = parseFrontmatter(raw);\n if (body.trim() === '') {\n problems.push(`command /${name} (${path}) is empty`);\n continue;\n }\n commands.push({\n name,\n description: fields.get('description') ?? `the /${name} command`,\n scope,\n path,\n body,\n });\n }\n return commands;\n}\n\n/**\n * Expands a slash command into the prompt it stands for.\n *\n * `$ARGUMENTS` is everything after the command name; `$1`..`$9` are the\n * whitespace-separated words. A placeholder with nothing to fill it becomes an\n * empty string rather than being left in the prompt, where the model would read\n * `$2` as something it was meant to work out.\n */\nexport function expandCommand(command: SlashCommand, argument = ''): string {\n const words = argument.trim() === '' ? [] : argument.trim().split(/\\s+/);\n return command.body\n .replace(/\\$ARGUMENTS\\b/g, argument.trim())\n .replace(/\\$([1-9])\\b/g, (_, index: string) => words[Number(index) - 1] ?? '');\n}\n\n/**\n * The index that sits in the system prompt: what exists and what each is for,\n * never the bodies. A skill's body is loaded when it is used, which is the whole\n * reason a skill is not just more system prompt.\n */\nexport function renderSkillIndex(skills: Skill[]): string {\n if (skills.length === 0) return '';\n const lines = skills.map((skill) => `- ${skill.name}: ${skill.description}`);\n return (\n 'Skills available in this project. Each is a set of instructions written for a ' +\n 'particular kind of task. Load one with the `skill` tool when the task at hand is ' +\n 'one it covers, and follow it in place of your default approach.\\n\\n' +\n `<skills>\\n${lines.join('\\n')}\\n</skills>`\n );\n}\n\n/**\n * What a skill's `allowed-tools` means: the intersection with what the session\n * already offers. A skill file is content that may have come from a repository\n * someone cloned, so it can say \"while doing this, only these tools\" and be\n * believed, and it cannot say \"while doing this, also allow rm -rf\" at all.\n */\nexport function narrow(available: string[], allowed: string[]): string[] {\n if (allowed.length === 0) return available;\n const wanted = new Set(allowed);\n const kept = available.filter((name) => wanted.has(name));\n // Asking must always be possible: a skill that narrowed away the ability to\n // ask would turn \"ask rather than guess\" off by writing a list.\n if (!kept.includes('ask_user') && available.includes('ask_user')) kept.push('ask_user');\n return kept;\n}\n",
33
+ "/**\n * Frontmatter, hand-parsed, for the same reason the memory store parses its own:\n * these files are hand-written, and a real YAML parser's failure mode - throwing\n * on a file someone indented slightly wrong - is worse than ignoring a key we do\n * not recognise.\n */\nexport interface Frontmatter {\n fields: Map<string, string>;\n body: string;\n}\n\nexport function parseFrontmatter(raw: string): Frontmatter {\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/.exec(raw);\n if (!match) return { fields: new Map(), body: raw.trim() };\n\n const [, front = '', body = ''] = match;\n const fields = new Map<string, string>();\n for (const line of front.split(/\\r?\\n/)) {\n // Continuation lines of a block scalar are not supported and are skipped\n // rather than misread as keys.\n if (/^\\s/.test(line)) continue;\n const at = line.indexOf(':');\n if (at <= 0) continue;\n fields.set(line.slice(0, at).trim().toLowerCase(), unquote(line.slice(at + 1).trim()));\n }\n return { fields, body: body.trim() };\n}\n\n/** `a, b` and `[a, b]` both read as a list; anything else reads as one item. */\nexport function parseList(value: string | undefined): string[] {\n if (value === undefined) return [];\n const inner = value.trim().replace(/^\\[/, '').replace(/\\]$/, '');\n return inner\n .split(',')\n .map((item) => unquote(item.trim()))\n .filter((item) => item !== '');\n}\n\nfunction unquote(value: string): string {\n if (value.startsWith('\"') && value.endsWith('\"') && value.length > 1) {\n try {\n return JSON.parse(value) as string;\n } catch {\n return value.slice(1, -1);\n }\n }\n if (value.startsWith(\"'\") && value.endsWith(\"'\") && value.length > 1) return value.slice(1, -1);\n return value;\n}\n",
34
+ "import type { ToolDefinition, ToolResultOutput } from '@earshot/providers';\nimport type { ScopeContract } from '../scope/contract.ts';\nimport type { BackgroundJobs } from './jobs.ts';\n\n/**\n * A permission-relevant description of what a call is about to do. The gate sees\n * only this, never the tool itself, so a new tool cannot accidentally bypass the\n * rules by forgetting to describe itself: `permission()` is required on every\n * tool that is not `readOnly`.\n */\nexport interface PermissionRequest {\n /** Rule name the pattern matches against, e.g. `Bash`, `Edit`, `Write`. */\n tool: string;\n /** The string a rule pattern is matched against: a command, or a path. */\n target: string;\n /** One line for the prompt header, e.g. `git status`. */\n title: string;\n /** The full command, or a unified diff. Shown verbatim - never a summary. */\n detail: string;\n /** Absolute paths this call writes to. Writes outside cwd always prompt. */\n writes?: string[];\n}\n\nexport interface ToolContext {\n cwd: string;\n signal: AbortSignal;\n /** Asks the user a question mid-turn; resolves with their answer. */\n ask(question: string, options?: string[]): Promise<string>;\n /** Session-scoped todo list, shared by the `todo` tool and the status line. */\n todos: TodoStore;\n /** Session-scoped background processes started by `bash`. */\n jobs: BackgroundJobs;\n /** What the agent declared it would change, and the guard that holds it to it. */\n scope: ScopeContract;\n /**\n * Runs a nested agent with its own context window and returns its answer. It\n * inherits the session's permission rules, scope contract and cost; absent\n * when the session cannot nest one, which includes inside a subagent.\n */\n runSubagent?(request: SubagentRequest, signal: AbortSignal): Promise<SubagentResult>;\n /**\n * Narrows the tools offered to the model for the rest of the turn. Only ever\n * a restriction: the names are intersected with what the session already\n * allows, so nothing here can grant a tool the user did not.\n */\n restrictTools?(names: string[] | undefined): void;\n /** Records that a file was read, so `edit`/`write` can require a prior read. */\n markRead(path: string): void;\n hasRead(path: string): boolean;\n env: NodeJS.ProcessEnv;\n}\n\nexport interface SubagentRequest {\n /** One line naming the sub-task, for the prompt and the transcript. */\n description: string;\n /** The whole task: a subagent sees none of the parent's conversation. */\n prompt: string;\n /** Tools it may use. Intersected with the parent's; never a superset. */\n tools?: string[];\n}\n\nexport interface SubagentResult {\n /** What it answered. The parent gets this, never the subagent's transcript. */\n text: string;\n steps: number;\n costUsd: number;\n /** Set when it stopped for a reason other than finishing. */\n stoppedBecause?: 'aborted' | 'max_steps' | 'error' | 'budget';\n}\n\nexport interface TodoItem {\n id: string;\n text: string;\n status: 'pending' | 'in_progress' | 'done';\n}\n\nexport interface TodoStore {\n list(): TodoItem[];\n replace(items: TodoItem[]): void;\n}\n\nexport interface ToolResult {\n output: ToolResultOutput;\n isError?: boolean;\n /** One line for the collapsed tool block in the TUI. */\n title?: string;\n}\n\nexport interface Tool<Input = unknown> {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n /**\n * Read-only calls are executed in parallel; everything else is serialised, in\n * the order the model emitted it. A tool that mutates anything - the file\n * system, the network, a process - is not read-only.\n */\n readOnly: boolean;\n /**\n * A deferred tool is registered and callable but kept out of the tool list\n * sent to the model until `tool_search` surfaces it. Set on MCP tools once a\n * session has more of them than a prompt can carry honestly: a hundred\n * schemas in every request is context the user pays for on every turn and the\n * model reads past on most of them.\n */\n deferred?: boolean;\n /** Throws `ToolInputError` when the model sends something unusable. */\n parse(input: unknown): Input;\n /** Required unless `readOnly`; enforced by `defineTool`. */\n permission?(input: Input, ctx: ToolContext): PermissionRequest;\n execute(input: Input, ctx: ToolContext): Promise<ToolResult>;\n}\n\nexport class ToolInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ToolInputError';\n }\n}\n\n/** Fails loudly at construction rather than letting a mutating tool skip the gate. */\nexport function defineTool<Input>(tool: Tool<Input>): Tool<Input> {\n if (!tool.readOnly && !tool.permission) {\n throw new Error(`tool \"${tool.name}\" mutates state but declares no permission()`);\n }\n return tool;\n}\n\nexport function toolDefinition(tool: Tool<never>): ToolDefinition {\n return { name: tool.name, description: tool.description, inputSchema: tool.inputSchema };\n}\n\nexport function text(value: string): ToolResultOutput {\n return { type: 'text', value };\n}\n",
35
+ "import { ToolInputError } from './types.ts';\n\n/**\n * Just enough JSON Schema to describe tool inputs, plus matching runtime readers.\n * Deliberately not zod: `zod` is external to the bundle for the provider SDKs'\n * benefit, and tool schemas are simple enough that a dependency would cost more\n * than it saves. The readers below are the only validation a tool needs, and\n * they produce messages the model can act on rather than a schema dump.\n */\nexport type JsonSchema = Record<string, unknown>;\n\nexport function object(\n properties: Record<string, JsonSchema>,\n required: string[] = [],\n): JsonSchema {\n return { type: 'object', properties, required, additionalProperties: false };\n}\n\nexport const str = (description: string): JsonSchema => ({ type: 'string', description });\nexport const num = (description: string): JsonSchema => ({ type: 'number', description });\nexport const bool = (description: string): JsonSchema => ({ type: 'boolean', description });\nexport const arr = (items: JsonSchema, description: string): JsonSchema => ({\n type: 'array',\n items,\n description,\n});\nexport const enumOf = (values: string[], description: string): JsonSchema => ({\n type: 'string',\n enum: values,\n description,\n});\n\nfunction record(input: unknown): Record<string, unknown> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ToolInputError('expected an object of arguments');\n }\n return input as Record<string, unknown>;\n}\n\nexport function requireString(input: unknown, key: string): string {\n const value = record(input)[key];\n if (typeof value !== 'string') throw new ToolInputError(`\"${key}\" must be a string`);\n return value;\n}\n\nexport function optionalString(input: unknown, key: string): string | undefined {\n const value = record(input)[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string') throw new ToolInputError(`\"${key}\" must be a string`);\n return value;\n}\n\nexport function optionalNumber(input: unknown, key: string): number | undefined {\n const value = record(input)[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ToolInputError(`\"${key}\" must be a number`);\n }\n return value;\n}\n\nexport function optionalBoolean(input: unknown, key: string): boolean | undefined {\n const value = record(input)[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'boolean') throw new ToolInputError(`\"${key}\" must be a boolean`);\n return value;\n}\n\nexport function requireArray(input: unknown, key: string): unknown[] {\n const value = record(input)[key];\n if (!Array.isArray(value)) throw new ToolInputError(`\"${key}\" must be an array`);\n return value;\n}\n\n/**\n * `exactOptionalPropertyTypes` forbids assigning `undefined` to an optional\n * property, so optional fields are spread in conditionally rather than assigned.\n */\nexport function opt<K extends string, V>(key: K, value: V | undefined): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n",
36
+ "import { arr, object, opt, requireArray, requireString, str } from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\ninterface AskUserInput {\n question: string;\n options?: string[];\n}\n\n/**\n * The tool the whole \"actually listens\" premise rests on: the model asks rather\n * than guessing. It is read-only in the permission sense - it changes nothing and\n * must never itself be gated, because a prompt asking permission to ask a question\n * is precisely the friction that trains people to stop reading prompts.\n */\nexport const askUserTool: Tool<AskUserInput> = defineTool<AskUserInput>({\n name: 'ask_user',\n description:\n 'Ask the user a question and wait for their answer. Use this when the request ' +\n 'is ambiguous in a way that would change what you build, rather than guessing ' +\n 'and building the wrong thing. Do not use it for choices with an obvious ' +\n 'default, or to ask permission for an action - that is handled separately.',\n readOnly: true,\n inputSchema: object(\n {\n question: str('The question, specific enough to answer in one line.'),\n options: arr(str('One choice.'), 'Suggested answers. The user may ignore them.'),\n },\n ['question'],\n ),\n parse: (input) => {\n const question = requireString(input, 'question');\n if (question.trim() === '') throw new ToolInputError('\"question\" must not be empty');\n const raw = (input as Record<string, unknown>).options;\n const options =\n raw === undefined || raw === null\n ? undefined\n : requireArray(input, 'options').map((option, i) => {\n if (typeof option !== 'string')\n throw new ToolInputError(`option ${i + 1} must be a string`);\n return option;\n });\n return { question, ...opt('options', options) };\n },\n async execute(input, ctx) {\n const answer = await ctx.ask(input.question, input.options);\n return { output: text(answer), title: input.question };\n },\n});\n",
37
+ "import { spawn } from 'node:child_process';\nimport { DEFAULT_MAX_OUTPUT_BYTES, exec } from './exec.ts';\nimport type { BackgroundJob, BackgroundJobs } from './jobs.ts';\nimport {\n bool,\n num,\n object,\n opt,\n optionalBoolean,\n optionalNumber,\n optionalString,\n requireString,\n str,\n} from './schema.ts';\nimport { resolveShell } from './shell.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst MAX_TIMEOUT_MS = 600_000;\n\ninterface BashInput {\n command: string;\n description?: string;\n timeoutMs?: number;\n background?: boolean;\n}\n\nexport const bashTool: Tool<BashInput> = defineTool<BashInput>({\n name: 'bash',\n description:\n 'Run a shell command in the working directory. Use `background: true` for ' +\n 'long-running processes such as dev servers; the call returns immediately with ' +\n 'a job id. Prefer the `read`, `glob` and `grep` tools over cat, find and grep.',\n readOnly: false,\n inputSchema: object(\n {\n command: str('The shell command to run.'),\n description: str('A short description of what the command does, in active voice.'),\n timeoutMs: num(\n `Timeout in milliseconds. Defaults to ${DEFAULT_TIMEOUT_MS}, max ${MAX_TIMEOUT_MS}.`,\n ),\n background: bool('Run detached and return a job id instead of waiting.'),\n },\n ['command'],\n ),\n parse: (input) => {\n const command = requireString(input, 'command');\n if (command.trim() === '') throw new ToolInputError('\"command\" must not be empty');\n const timeoutMs = optionalNumber(input, 'timeoutMs');\n if (timeoutMs !== undefined && (timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS)) {\n throw new ToolInputError(`\"timeoutMs\" must be between 1 and ${MAX_TIMEOUT_MS}`);\n }\n return {\n command,\n ...opt('description', optionalString(input, 'description')),\n ...opt('timeoutMs', timeoutMs),\n ...opt('background', optionalBoolean(input, 'background')),\n };\n },\n permission(input) {\n return {\n tool: 'Bash',\n // Matched against the raw command so a rule like `Bash(git *)` means what it\n // reads. The gate never sees a paraphrase of the command, only the command.\n target: input.command,\n title: input.command.split('\\n')[0] ?? input.command,\n detail: input.command,\n };\n },\n async execute(input, ctx) {\n const shell = resolveShell(ctx.env);\n\n if (input.background) {\n const job = startBackground(\n shell.file,\n shell.args,\n input.command,\n ctx.cwd,\n ctx.env,\n ctx.jobs,\n );\n return {\n output: text(\n `started ${job.id} in the background\\n\\n` +\n 'Read its output with the `bash_output` tool; it keeps running until the ' +\n 'session ends or you kill it.',\n ),\n title: `${input.command} (background)`,\n };\n }\n\n const result = await exec(shell.file, [...shell.args, input.command], {\n cwd: ctx.cwd,\n env: ctx.env,\n signal: ctx.signal,\n timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n });\n\n const parts: string[] = [];\n if (result.stdout.trim() !== '') parts.push(result.stdout.trimEnd());\n if (result.stderr.trim() !== '') parts.push(`[stderr]\\n${result.stderr.trimEnd()}`);\n if (result.timedOut) {\n parts.push(`[timed out after ${input.timeoutMs ?? DEFAULT_TIMEOUT_MS}ms and was killed]`);\n }\n if (result.code !== 0 && result.code !== null) parts.push(`[exit ${result.code}]`);\n if (parts.length === 0) parts.push('(no output)');\n\n const body = parts.join('\\n');\n const truncated = body.length >= DEFAULT_MAX_OUTPUT_BYTES ? '\\n\\n[output truncated]' : '';\n\n return {\n output: text(body + truncated),\n // A non-zero exit is reported to the model as an error result so it does not\n // read a failed build as a successful one, but it is not thrown: the loop\n // must keep going and let the model react to the output.\n ...(result.code !== 0 && result.code !== null ? { isError: true } : {}),\n title: input.command.split('\\n')[0] ?? input.command,\n };\n },\n});\n\nfunction startBackground(\n file: string,\n args: string[],\n command: string,\n cwd: string,\n env: NodeJS.ProcessEnv,\n jobs: BackgroundJobs,\n): BackgroundJob {\n const child = spawn(file, [...args, command], {\n cwd,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: false,\n });\n\n const job: BackgroundJob = {\n id: jobs.nextId(),\n command,\n output: '',\n exitCode: null,\n running: true,\n kill: () => {\n child.kill('SIGTERM');\n setTimeout(() => child.kill('SIGKILL'), 2000).unref();\n },\n };\n\n const append = (chunk: Buffer) => {\n job.output = (job.output + chunk.toString('utf8')).slice(-DEFAULT_MAX_OUTPUT_BYTES);\n };\n child.stdout?.on('data', append);\n child.stderr?.on('data', append);\n child.on('close', (code) => {\n job.running = false;\n job.exitCode = code;\n });\n child.on('error', (error) => {\n job.running = false;\n job.output += `\\n[failed to start: ${error.message}]`;\n });\n\n jobs.add(job);\n return job;\n}\n\ninterface BashOutputInput {\n id: string;\n kill?: boolean;\n}\n\nexport const bashOutputTool: Tool<BashOutputInput> = defineTool<BashOutputInput>({\n name: 'bash_output',\n description: 'Read the accumulated output of a background job started by `bash`.',\n readOnly: true,\n inputSchema: object(\n {\n id: str('The job id returned by `bash` with background: true.'),\n kill: bool('Terminate the job after reading its output.'),\n },\n ['id'],\n ),\n parse: (input) => ({\n id: requireString(input, 'id'),\n ...opt('kill', optionalBoolean(input, 'kill')),\n }),\n async execute(input, ctx) {\n const job = ctx.jobs.get(input.id);\n if (!job) throw new ToolInputError(`no background job \"${input.id}\"`);\n if (input.kill && job.running) job.kill();\n\n const status = job.running ? 'running' : `exited ${job.exitCode ?? 'unknown'}`;\n return {\n output: text(`[${job.id}: ${status}]\\n${job.output === '' ? '(no output yet)' : job.output}`),\n title: `${job.id} (${status})`,\n };\n },\n});\n",
38
+ "import { spawn } from 'node:child_process';\n\nexport interface ExecResult {\n stdout: string;\n stderr: string;\n code: number | null;\n signal: NodeJS.Signals | null;\n timedOut: boolean;\n}\n\nexport interface ExecOptions {\n cwd: string;\n env?: NodeJS.ProcessEnv;\n timeoutMs?: number;\n signal?: AbortSignal;\n /** Output beyond this is truncated; a runaway command must not eat the window. */\n maxBytes?: number;\n /** Written to the child's stdin and closed. Absent means stdin is /dev/null. */\n stdin?: string;\n}\n\n/**\n * How long a killed child gets before `exec` stops waiting for it.\n *\n * A timeout that does not bound how long the call takes is not a timeout. A\n * child that spawned its own children leaves them holding the pipes open, so\n * `close` never fires however dead the child itself is - which turns a hook with\n * a 10 second timeout into a turn that waits for whatever it started.\n */\nexport const KILL_GRACE_MS = 2_000;\n\nexport const DEFAULT_MAX_OUTPUT_BYTES = 60_000;\n\n/**\n * Runs a command without a shell. Callers that need shell semantics pass the\n * shell explicitly (see `bash.ts`), which keeps the one place that interprets\n * user-visible command strings small enough to reason about.\n */\nexport function exec(file: string, args: string[], options: ExecOptions): Promise<ExecResult> {\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n return new Promise((resolve, reject) => {\n const child = spawn(file, args, {\n cwd: options.cwd,\n ...(options.env ? { env: options.env } : {}),\n stdio: [options.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n // Its own process group on POSIX, so `kill` can reach what it started.\n // Windows has no groups; `signalTree` uses taskkill /T there instead.\n detached: process.platform !== 'win32',\n });\n\n if (options.stdin !== undefined) {\n // A child that never reads stdin makes this write fail with EPIPE, which\n // is its choice to make and not an error worth failing the call over.\n child.stdin?.on('error', () => {});\n child.stdin?.end(options.stdin);\n }\n\n let stdout = '';\n let stderr = '';\n let timedOut = false;\n let settled = false;\n\n const collect = (into: 'out' | 'err') => (chunk: Buffer) => {\n const current = into === 'out' ? stdout : stderr;\n if (current.length >= maxBytes) return;\n const next = current + chunk.toString('utf8');\n if (into === 'out') stdout = next.slice(0, maxBytes);\n else stderr = next.slice(0, maxBytes);\n };\n child.stdout?.on('data', collect('out'));\n child.stderr?.on('data', collect('err'));\n\n // SIGTERM first so the child can clean up; SIGKILL only if it ignores that.\n // The whole process group, not just the child: a shell command that started\n // something else leaves that something else running, and holding our pipes.\n const kill = () => {\n signalTree(child, 'SIGTERM');\n setTimeout(() => signalTree(child, 'SIGKILL'), 1000).unref();\n // And a deadline on waiting, because a grandchild we could not reach can\n // keep the pipes open indefinitely and there is nothing more to wait for.\n setTimeout(() => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve({ stdout, stderr, code: null, signal: 'SIGKILL', timedOut });\n }, KILL_GRACE_MS).unref();\n };\n\n const timer = options.timeoutMs\n ? setTimeout(() => {\n timedOut = true;\n kill();\n }, options.timeoutMs)\n : undefined;\n timer?.unref();\n\n const onAbort = () => kill();\n options.signal?.addEventListener('abort', onAbort, { once: true });\n\n const cleanup = () => {\n if (timer) clearTimeout(timer);\n options.signal?.removeEventListener('abort', onAbort);\n };\n\n child.on('error', (error) => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n });\n child.on('close', (code, signal) => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve({ stdout, stderr, code, signal, timedOut });\n });\n });\n}\n\n/** Whether an executable is runnable, cached for the life of the process. */\nconst probes = new Map<string, Promise<boolean>>();\n\nexport function hasExecutable(file: string, cwd = process.cwd()): Promise<boolean> {\n const cached = probes.get(file);\n if (cached) return cached;\n const probe = exec(file, ['--version'], { cwd, timeoutMs: 3000 })\n .then((result) => result.code === 0)\n .catch(() => false);\n probes.set(file, probe);\n return probe;\n}\n\n/**\n * Kills a child and anything it started.\n *\n * POSIX: the negative pid signals the process group, which the child leads\n * because it was spawned detached. Windows has no process groups, so this is\n * `taskkill /T`, which walks the tree the same way.\n */\nfunction signalTree(child: ReturnType<typeof spawn>, signal: 'SIGTERM' | 'SIGKILL'): void {\n const pid = child.pid;\n if (pid === undefined) return;\n if (process.platform === 'win32') {\n // /F only on the second pass: the first is the child's chance to exit\n // cleanly, and taskkill without /F asks rather than terminates.\n const args = ['/PID', String(pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])];\n try {\n spawn('taskkill', args, { stdio: 'ignore' }).on('error', () => {});\n } catch {\n child.kill(signal);\n }\n return;\n }\n try {\n process.kill(-pid, signal);\n } catch {\n // The group is already gone, or we never led one; the child alone will do.\n try {\n child.kill(signal);\n } catch {\n // Already reaped.\n }\n }\n}\n",
39
+ "import { existsSync } from 'node:fs';\nimport { platform } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Where the `bash` tool's shell comes from.\n *\n * On Windows this is Git Bash, and only Git Bash. The alternative considered was\n * falling back to PowerShell when Git Bash is absent, which would have meant the\n * agent's most-used tool speaks two different dialects depending on the machine:\n * quoting, pipelines, `&&`, `$(...)` and path separators all differ, permission\n * rules like `Bash(git *)` would match different strings, and every command the\n * model writes would need translating. One dialect everywhere is worth an install\n * step on the platform where `git` already ships the shell in question.\n */\nexport interface ShellSpec {\n /** Absolute path or bare name of the shell executable. */\n file: string;\n /** Arguments that precede the command string. */\n args: string[];\n}\n\nexport class ShellNotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ShellNotFoundError';\n }\n}\n\n/** Standard install locations for Git for Windows, in preference order. */\nfunction windowsCandidates(env: NodeJS.ProcessEnv): string[] {\n const roots = [\n env.ProgramFiles,\n env['ProgramFiles(x86)'],\n env.LOCALAPPDATA ? join(env.LOCALAPPDATA, 'Programs') : undefined,\n ].filter((root): root is string => typeof root === 'string' && root !== '');\n\n const fromGitRoots = roots.flatMap((root) => [\n join(root, 'Git', 'bin', 'bash.exe'),\n join(root, 'Git', 'usr', 'bin', 'bash.exe'),\n ]);\n // An explicit override wins: some people install Git somewhere else entirely.\n return [...(env.EARSHOT_BASH ? [env.EARSHOT_BASH] : []), ...fromGitRoots];\n}\n\nconst WINDOWS_HELP =\n 'earshot needs Git Bash to run shell commands on Windows. Install Git for Windows ' +\n '(https://git-scm.com/download/win), or set EARSHOT_BASH to the full path of a ' +\n 'bash.exe. PowerShell is not used: one shell dialect on every platform is what ' +\n 'keeps commands and permission rules portable.';\n\n/**\n * Resolves the shell once per session. Throws rather than degrading, because a\n * silent fallback to a different shell is exactly the failure this design avoids.\n *\n * `hostPlatform` is a parameter rather than a direct `platform()` read so that a\n * caller which was itself given a platform can pass the same one down. Reading\n * the real platform here made platform-injecting tests exercise whichever branch\n * the CI runner happened to be, not the branch they named: `/doctor`'s Linux test\n * took the Git Bash path on the Windows runner and reported a failing shell check.\n * It narrows nothing - Windows still means Git Bash or an error, never PowerShell.\n */\nexport function resolveShell(\n env: NodeJS.ProcessEnv = process.env,\n hostPlatform: NodeJS.Platform = platform(),\n): ShellSpec {\n if (hostPlatform !== 'win32') {\n // Not `-lc`: a login shell re-runs the user's profile on every call, which is\n // slow and lets a profile's `cd` silently move the command's working directory.\n return { file: env.EARSHOT_BASH ?? '/bin/bash', args: ['-c'] };\n }\n\n for (const candidate of windowsCandidates(env)) {\n if (existsSync(candidate)) return { file: candidate, args: ['-c'] };\n }\n throw new ShellNotFoundError(WINDOWS_HELP);\n}\n",
40
+ "import {\n arr,\n num,\n object,\n opt,\n optionalNumber,\n requireArray,\n requireString,\n str,\n} from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\ninterface DeclareScopeInput {\n files: string[];\n intent: string;\n estimatedLines?: number;\n}\n\n/**\n * The agent writes down what it is about to change, before it changes anything.\n *\n * Read-only in the permission sense - it touches nothing - but it is the thing\n * the scope guard measures every later edit against, so a turn that skips it\n * gets no guard at all. The system prompt asks for it; the guard is what makes\n * the asking mean something.\n */\nexport const declareScopeTool: Tool<DeclareScopeInput> = defineTool<DeclareScopeInput>({\n name: 'declare_scope',\n description:\n 'State the scope of the change you are about to make, before your first edit or ' +\n 'command that changes anything. List the files you expect to touch and say in one ' +\n 'paragraph what changes and what does not. Editing a file you did not list, adding a ' +\n 'dependency, renaming or deleting files, reformatting, or a change several times ' +\n 'larger than your estimate will stop and ask the user. Call it again if the work ' +\n 'turns out to be genuinely bigger than you thought.',\n readOnly: true,\n inputSchema: object(\n {\n files: arr(\n str('A path or glob relative to the working directory.'),\n 'Files you will change.',\n ),\n intent: str('One paragraph: which behaviours change, and which explicitly do not.'),\n estimated_lines: num('Rough number of lines you expect to add and remove in total.'),\n },\n ['files', 'intent'],\n ),\n parse: (input) => {\n const intent = requireString(input, 'intent');\n if (intent.trim() === '') throw new ToolInputError('\"intent\" must not be empty');\n const files = requireArray(input, 'files').map((file, i) => {\n if (typeof file !== 'string') throw new ToolInputError(`file ${i + 1} must be a string`);\n return file;\n });\n if (files.length === 0) throw new ToolInputError('\"files\" must name at least one file');\n return { files, intent, ...opt('estimatedLines', optionalNumber(input, 'estimated_lines')) };\n },\n async execute(input, ctx) {\n ctx.scope.declare({\n files: input.files,\n intent: input.intent,\n ...opt('estimatedLines', input.estimatedLines),\n });\n return {\n output: text(\n `scope recorded: ${input.files.join(', ')}. Anything outside it will ask the user first.`,\n ),\n title: `scope: ${input.files.join(', ')}`,\n };\n },\n});\n",
41
+ "import { readFileSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { unifiedDiff } from './diff.ts';\nimport { displayPath, resolvePath } from './fs-paths.ts';\nimport {\n arr,\n bool,\n object,\n opt,\n optionalBoolean,\n requireArray,\n requireString,\n str,\n} from './schema.ts';\nimport { defineTool, type Tool, type ToolContext, ToolInputError, text } from './types.ts';\n\nexport interface Replacement {\n find: string;\n replace: string;\n replaceAll?: boolean;\n}\n\ninterface EditInput extends Replacement {\n path: string;\n}\n\ninterface MultiEditInput {\n path: string;\n edits: Replacement[];\n}\n\n/**\n * Applies exact-string replacements in order, each against the result of the last.\n *\n * A `find` that matches more than once is an error rather than a first-match\n * replacement: the model cannot see which occurrence it hit, so silently picking\n * one is how an edit lands in the wrong function. The fix is for the model to\n * include more surrounding context, which the message says.\n */\nexport function applyEdits(source: string, edits: Replacement[], label: string): string {\n let out = source;\n for (const [i, edit] of edits.entries()) {\n const where = edits.length > 1 ? ` (edit ${i + 1})` : '';\n if (edit.find === '') throw new ToolInputError(`\"find\" must not be empty${where}`);\n if (edit.find === edit.replace) {\n throw new ToolInputError(`\"find\" and \"replace\" are identical${where}`);\n }\n\n const count = occurrences(out, edit.find);\n if (count === 0) {\n throw new ToolInputError(\n `\"find\" does not appear in ${label}${where}. The text must match the file byte for byte, ` +\n 'including indentation.',\n );\n }\n if (count > 1 && !edit.replaceAll) {\n throw new ToolInputError(\n `\"find\" appears ${count} times in ${label}${where}. Include enough surrounding lines to ` +\n 'make it unique, or set replaceAll.',\n );\n }\n out = edit.replaceAll\n ? out.split(edit.find).join(edit.replace)\n : out.replace(edit.find, edit.replace);\n }\n return out;\n}\n\nfunction occurrences(haystack: string, needle: string): number {\n let n = 0;\n let at = haystack.indexOf(needle);\n while (at !== -1) {\n n++;\n at = haystack.indexOf(needle, at + needle.length);\n }\n return n;\n}\n\nfunction parseReplacement(input: unknown, index?: number): Replacement {\n try {\n return {\n find: requireString(input, 'find'),\n replace: requireString(input, 'replace'),\n ...opt('replaceAll', optionalBoolean(input, 'replaceAll')),\n };\n } catch (error) {\n const where = index === undefined ? '' : ` in edit ${index + 1}`;\n throw new ToolInputError(`${(error as Error).message}${where}`);\n }\n}\n\nconst replacementSchema = object(\n {\n find: str('Exact text to find, including indentation. Must be unique in the file.'),\n replace: str('Text to replace it with.'),\n replaceAll: bool('Replace every occurrence instead of requiring a unique match.'),\n },\n ['find', 'replace'],\n);\n\nfunction editPermission(cwd: string, path: string, edits: Replacement[], verb: string) {\n const abs = resolvePath(cwd, path);\n const shown = displayPath(cwd, abs);\n let before: string;\n try {\n before = readFileSync(abs, 'utf8');\n } catch {\n throw new ToolInputError(`no such file: ${shown}`);\n }\n // Applied here as well as in execute so the prompt shows the diff that will\n // actually land, and so a non-matching `find` fails before the user is asked.\n const after = applyEdits(before, edits, shown);\n return {\n tool: 'Edit',\n target: shown,\n title: `${verb} ${shown}`,\n detail: unifiedDiff(shown, before, after) || '(no change)',\n writes: [abs],\n };\n}\n\nasync function runEdits(path: string, edits: Replacement[], ctx: ToolContext) {\n const abs = resolvePath(ctx.cwd, path);\n const shown = displayPath(ctx.cwd, abs);\n if (!ctx.hasRead(abs)) {\n throw new ToolInputError(`read ${shown} before editing it`);\n }\n const before = await readFile(abs, 'utf8');\n const after = applyEdits(before, edits, shown);\n await writeFile(abs, after, 'utf8');\n const changed = unifiedDiff(shown, before, after);\n return {\n output: text(changed === '' ? `${shown} was already in the requested state` : changed),\n title: shown,\n };\n}\n\nexport const editTool: Tool<EditInput> = defineTool<EditInput>({\n name: 'edit',\n description:\n 'Replace an exact string in a file. The file must have been read first, and ' +\n '`find` must appear exactly once unless replaceAll is set.',\n readOnly: false,\n inputSchema: object(\n {\n path: str('Path to the file, absolute or relative to the working directory.'),\n find: str('Exact text to find, including indentation. Must be unique in the file.'),\n replace: str('Text to replace it with.'),\n replaceAll: bool('Replace every occurrence instead of requiring a unique match.'),\n },\n ['path', 'find', 'replace'],\n ),\n parse: (input) => ({ path: requireString(input, 'path'), ...parseReplacement(input) }),\n permission: (input, ctx) => editPermission(ctx.cwd, input.path, [input], 'edit'),\n execute: (input, ctx) => runEdits(input.path, [input], ctx),\n});\n\nexport const multiEditTool: Tool<MultiEditInput> = defineTool<MultiEditInput>({\n name: 'multi_edit',\n description:\n 'Apply several exact-string replacements to one file, in order, each against ' +\n 'the result of the last. All succeed or none are written.',\n readOnly: false,\n inputSchema: object(\n {\n path: str('Path to the file, absolute or relative to the working directory.'),\n edits: arr(replacementSchema, 'Replacements to apply in order.'),\n },\n ['path', 'edits'],\n ),\n parse: (input) => {\n const edits = requireArray(input, 'edits').map((edit, i) => parseReplacement(edit, i));\n if (edits.length === 0) throw new ToolInputError('\"edits\" must not be empty');\n return { path: requireString(input, 'path'), edits };\n },\n permission: (input, ctx) =>\n editPermission(ctx.cwd, input.path, input.edits, `apply ${input.edits.length} edits to`),\n execute: (input, ctx) => runEdits(input.path, input.edits, ctx),\n});\n",
42
+ "/**\n * A unified diff, generated in-process. The permission prompt must show the real\n * change - a summary is exactly the thing that lets a bad edit through - so this\n * is on the path of every `write`, `edit` and `multi_edit` approval.\n */\nexport function unifiedDiff(path: string, before: string, after: string, context = 3): string {\n const a = before === '' ? [] : before.split('\\n');\n const b = after === '' ? [] : after.split('\\n');\n const ops = diffLines(a, b);\n if (ops.every((op) => op.kind === 'same')) return '';\n\n const lines: string[] = [`--- a/${path}`, `+++ b/${path}`];\n for (const hunk of hunks(ops, context)) {\n lines.push(\n `@@ -${hunk.aStart + 1},${hunk.aCount} +${hunk.bStart + 1},${hunk.bCount} @@`,\n ...hunk.lines,\n );\n }\n return lines.join('\\n');\n}\n\ntype Op = { kind: 'same' | 'del' | 'add'; text: string };\n\n/**\n * Plain LCS. Tool edits are small and local; the quadratic table is cheaper in\n * both code and wall time than a Myers implementation at these sizes, and a\n * whole-file rewrite degrades to \"delete everything, add everything\", which is\n * the correct diff anyway.\n */\nfunction diffLines(a: string[], b: string[]): Op[] {\n const n = a.length;\n const m = b.length;\n const table: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));\n for (let i = n - 1; i >= 0; i--) {\n const row = table[i] as number[];\n const next = table[i + 1] as number[];\n for (let j = m - 1; j >= 0; j--) {\n row[j] =\n a[i] === b[j]\n ? (next[j + 1] as number) + 1\n : Math.max(next[j] as number, row[j + 1] as number);\n }\n }\n\n const ops: Op[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n ops.push({ kind: 'same', text: a[i] as string });\n i++;\n j++;\n } else if ((table[i + 1]?.[j] as number) >= (table[i]?.[j + 1] as number)) {\n ops.push({ kind: 'del', text: a[i] as string });\n i++;\n } else {\n ops.push({ kind: 'add', text: b[j] as string });\n j++;\n }\n }\n while (i < n) ops.push({ kind: 'del', text: a[i++] as string });\n while (j < m) ops.push({ kind: 'add', text: b[j++] as string });\n return ops;\n}\n\ninterface Hunk {\n aStart: number;\n bStart: number;\n aCount: number;\n bCount: number;\n lines: string[];\n}\n\nfunction hunks(ops: Op[], context: number): Hunk[] {\n const changed = ops.map((op) => op.kind !== 'same');\n const keep = ops.map((_, i) =>\n changed.slice(Math.max(0, i - context), i + context + 1).some(Boolean),\n );\n\n const out: Hunk[] = [];\n let aLine = 0;\n let bLine = 0;\n let current: Hunk | undefined;\n\n for (const [i, op] of ops.entries()) {\n if (keep[i]) {\n current ??= { aStart: aLine, bStart: bLine, aCount: 0, bCount: 0, lines: [] };\n if (op.kind === 'same') {\n current.lines.push(` ${op.text}`);\n current.aCount++;\n current.bCount++;\n } else if (op.kind === 'del') {\n current.lines.push(`-${op.text}`);\n current.aCount++;\n } else {\n current.lines.push(`+${op.text}`);\n current.bCount++;\n }\n } else if (current) {\n out.push(current);\n current = undefined;\n }\n if (op.kind !== 'add') aLine++;\n if (op.kind !== 'del') bLine++;\n }\n if (current) out.push(current);\n return out;\n}\n",
43
+ "import { stat } from 'node:fs/promises';\nimport { displayPath, resolvePath } from './fs-paths.ts';\nimport { globToRegExp } from './glob-match.ts';\nimport { num, object, opt, optionalNumber, optionalString, requireString, str } from './schema.ts';\nimport { defineTool, type Tool, text } from './types.ts';\nimport { loadGitignore, walk } from './walk.ts';\n\nconst DEFAULT_LIMIT = 200;\n\ninterface GlobInput {\n pattern: string;\n path?: string;\n limit?: number;\n}\n\nexport const globTool: Tool<GlobInput> = defineTool<GlobInput>({\n name: 'glob',\n description:\n 'Find files by glob pattern. Supports *, **, ? and {a,b}. A pattern with no ' +\n 'slash matches at any depth, so `*.ts` finds `src/main.ts`. Results are sorted ' +\n 'by most recently modified.',\n readOnly: true,\n inputSchema: object(\n {\n pattern: str('Glob pattern, e.g. `src/**/*.ts` or `*.json`.'),\n path: str('Directory to search under. Defaults to the working directory.'),\n limit: num(`Maximum results. Defaults to ${DEFAULT_LIMIT}.`),\n },\n ['pattern'],\n ),\n parse: (input) => ({\n pattern: requireString(input, 'pattern'),\n ...opt('path', optionalString(input, 'path')),\n ...opt('limit', optionalNumber(input, 'limit')),\n }),\n async execute(input, ctx) {\n const root = resolvePath(ctx.cwd, input.path ?? '.');\n const limit = input.limit ?? DEFAULT_LIMIT;\n const matcher = globToRegExp(input.pattern);\n const ignore = await loadGitignore(root);\n\n const found: Array<{ rel: string; mtimeMs: number }> = [];\n for await (const entry of walk({ root, ignore, signal: ctx.signal })) {\n if (!matcher.test(entry.rel)) continue;\n const info = await stat(entry.path).catch(() => undefined);\n found.push({ rel: entry.rel, mtimeMs: info?.mtimeMs ?? 0 });\n }\n\n // Recency ordering is the useful default: the files a developer is working in\n // are the ones they just touched, and the limit should cut the stale tail.\n found.sort((a, b) => b.mtimeMs - a.mtimeMs);\n const shown = found.slice(0, limit);\n const where = displayPath(ctx.cwd, root);\n\n if (shown.length === 0) {\n return { output: text(`no files match ${input.pattern}`), title: input.pattern };\n }\n const more = found.length > shown.length ? `\\n\\n… ${found.length - shown.length} more` : '';\n return {\n output: text(shown.map((f) => f.rel).join('\\n') + more),\n title: `${input.pattern} in ${where} (${found.length} matches)`,\n };\n },\n});\n",
44
+ "import { readdir, readFile } from 'node:fs/promises';\nimport { join, relative, sep } from 'node:path';\nimport { globToRegExp } from './glob-match.ts';\n\n/** Never worth walking, and walking them is how a glob call takes 40 seconds. */\nconst ALWAYS_SKIP = new Set([\n '.git',\n 'node_modules',\n '.next',\n '.turbo',\n 'dist',\n 'build',\n 'target',\n 'vendor',\n '__pycache__',\n '.venv',\n '.mypy_cache',\n '.pytest_cache',\n]);\n\nexport interface WalkOptions {\n /** Absolute root to walk. */\n root: string;\n /** Stops the walk once this many files have been yielded. */\n limit?: number;\n signal?: AbortSignal;\n /** Additional ignore matcher, e.g. the compiled .gitignore. */\n ignore?: (relativePath: string, isDir: boolean) => boolean;\n}\n\nexport interface WalkEntry {\n /** Absolute path. */\n path: string;\n /** Path relative to the root, always `/`-separated. */\n rel: string;\n mtimeMs: number;\n}\n\n/** Breadth-first so a `limit` cut keeps shallow, more relevant files. */\nexport async function* walk(options: WalkOptions): AsyncGenerator<WalkEntry> {\n const { root, ignore, signal } = options;\n const limit = options.limit ?? Number.POSITIVE_INFINITY;\n let yielded = 0;\n const queue: string[] = [root];\n\n while (queue.length > 0 && yielded < limit) {\n const dir = queue.shift() as string;\n signal?.throwIfAborted();\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const abs = join(dir, entry.name);\n const rel = relative(root, abs).split(sep).join('/');\n if (ALWAYS_SKIP.has(entry.name)) continue;\n if (ignore?.(rel, entry.isDirectory())) continue;\n if (entry.isDirectory()) {\n queue.push(abs);\n } else if (entry.isFile()) {\n if (yielded >= limit) return;\n yielded++;\n yield { path: abs, rel, mtimeMs: 0 };\n }\n }\n }\n}\n\n/**\n * A deliberately partial .gitignore reader: the root file only, no negation, no\n * nested .gitignore files. Full gitignore semantics are a project of their own;\n * a missed ignore costs one listed file, while shelling out to git would cost a\n * subprocess on every glob and grep call.\n */\nexport async function loadGitignore(\n root: string,\n): Promise<(rel: string, isDir: boolean) => boolean> {\n const raw = await readFile(join(root, '.gitignore'), 'utf8').catch(() => '');\n const patterns = raw\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && !line.startsWith('#') && !line.startsWith('!'))\n .map((line) => line.replace(/\\/+$/, '').replace(/^\\//, ''));\n\n if (patterns.length === 0) return () => false;\n const matchers = patterns.map((pattern) => globToRegExp(pattern));\n\n return (rel) => {\n // A directory entry is matched by its own path; files under an ignored\n // directory never come up, because the walk stops descending into it.\n for (const matcher of matchers) if (matcher.test(rel)) return true;\n return false;\n };\n}\n",
45
+ "import { readFile, stat } from 'node:fs/promises';\nimport { exec, hasExecutable } from './exec.ts';\nimport { displayPath, resolvePath } from './fs-paths.ts';\nimport { globToRegExp } from './glob-match.ts';\nimport {\n bool,\n num,\n object,\n opt,\n optionalBoolean,\n optionalNumber,\n optionalString,\n requireString,\n str,\n} from './schema.ts';\nimport { defineTool, type Tool, type ToolContext, ToolInputError, text } from './types.ts';\nimport { loadGitignore, walk } from './walk.ts';\n\nconst DEFAULT_LIMIT = 100;\n/** Larger files are almost always generated; scanning them rarely pays. */\nconst MAX_FILE_BYTES = 2_000_000;\n\ninterface GrepInput {\n pattern: string;\n path?: string;\n include?: string;\n ignoreCase?: boolean;\n limit?: number;\n}\n\nexport const grepTool: Tool<GrepInput> = defineTool<GrepInput>({\n name: 'grep',\n description:\n 'Search file contents with a regular expression. Returns `path:line:text` for ' +\n 'each match. Uses ripgrep when installed and an equivalent in-process search ' +\n 'otherwise, so results do not depend on what the machine happens to have.',\n readOnly: true,\n inputSchema: object(\n {\n pattern: str('Regular expression to search for.'),\n path: str('Directory or file to search. Defaults to the working directory.'),\n include: str('Only search files matching this glob, e.g. `*.ts`.'),\n ignoreCase: bool('Match case-insensitively.'),\n limit: num(`Maximum matching lines. Defaults to ${DEFAULT_LIMIT}.`),\n },\n ['pattern'],\n ),\n parse: (input) => ({\n pattern: requireString(input, 'pattern'),\n ...opt('path', optionalString(input, 'path')),\n ...opt('include', optionalString(input, 'include')),\n ...opt('ignoreCase', optionalBoolean(input, 'ignoreCase')),\n ...opt('limit', optionalNumber(input, 'limit')),\n }),\n async execute(input, ctx) {\n const root = resolvePath(ctx.cwd, input.path ?? '.');\n const limit = input.limit ?? DEFAULT_LIMIT;\n\n // Compiled up front so a bad pattern surfaces as a tool input error the model\n // can fix, rather than as an exit code, and so both back ends reject alike.\n let regexp: RegExp;\n try {\n regexp = new RegExp(input.pattern, input.ignoreCase ? 'i' : '');\n } catch (error) {\n throw new ToolInputError(`invalid regular expression: ${(error as Error).message}`);\n }\n\n const matches = (await hasExecutable('rg', ctx.cwd))\n ? await ripgrep(input, root, limit, ctx)\n : await jsGrep(input, regexp, root, limit, ctx);\n\n const where = displayPath(ctx.cwd, root);\n if (matches.length === 0) {\n return { output: text(`no matches for ${input.pattern} in ${where}`), title: input.pattern };\n }\n const capped = matches.slice(0, limit);\n const more =\n matches.length > capped.length ? `\\n\\n... ${matches.length - capped.length} more` : '';\n return {\n output: text(capped.join('\\n') + more),\n title: `${input.pattern} in ${where} (${matches.length} matches)`,\n };\n },\n});\n\nasync function ripgrep(\n input: GrepInput,\n root: string,\n limit: number,\n ctx: ToolContext,\n): Promise<string[]> {\n const args = ['--line-number', '--no-heading', '--color=never', '--max-count', String(limit)];\n if (input.ignoreCase) args.push('--ignore-case');\n if (input.include) args.push('--glob', input.include);\n args.push('--regexp', input.pattern, root);\n\n const result = await exec('rg', args, { cwd: ctx.cwd, signal: ctx.signal });\n // ripgrep exits 1 for \"no matches\", which is not a failure; 2 and up are.\n if (result.code !== null && result.code > 1) {\n throw new ToolInputError(result.stderr.trim() || `ripgrep exited ${result.code}`);\n }\n return result.stdout\n .split('\\n')\n .filter((line) => line !== '')\n .map((line) => relativise(line, root, ctx.cwd));\n}\n\n/** ripgrep echoes the absolute root it was given; the model wants project paths. */\nfunction relativise(line: string, root: string, cwd: string): string {\n if (!line.startsWith(root)) return line;\n const rest = line.slice(root.length).replace(/^[/\\\\]/, '');\n const prefix = displayPath(cwd, root);\n return prefix === '.' || prefix === '' ? rest : `${prefix}/${rest}`;\n}\n\nasync function jsGrep(\n input: GrepInput,\n regexp: RegExp,\n root: string,\n limit: number,\n ctx: ToolContext,\n): Promise<string[]> {\n const include = input.include ? globToRegExp(input.include) : undefined;\n const out: string[] = [];\n\n const info = await stat(root).catch(() => undefined);\n if (!info) throw new ToolInputError(`no such path: ${displayPath(ctx.cwd, root)}`);\n\n if (info.isFile()) {\n await scan(root, displayPath(ctx.cwd, root), regexp, out, limit);\n return out;\n }\n\n const ignore = await loadGitignore(root);\n for await (const entry of walk({ root, ignore, signal: ctx.signal })) {\n if (include && !include.test(entry.rel)) continue;\n if (await scan(entry.path, entry.rel, regexp, out, limit)) break;\n }\n return out;\n}\n\n/** Returns true once the limit is exceeded, so the walk can stop early. */\nasync function scan(\n path: string,\n label: string,\n regexp: RegExp,\n out: string[],\n limit: number,\n): Promise<boolean> {\n const content = await readFile(path, 'utf8').catch(() => undefined);\n if (content === undefined || content.length > MAX_FILE_BYTES) return false;\n // A NUL byte near the start is the cheap, conventional binary-file test.\n if (content.slice(0, 1024).includes('\\u0000')) return false;\n\n for (const [i, line] of content.split('\\n').entries()) {\n if (!regexp.test(line)) continue;\n out.push(`${label}:${i + 1}:${line.slice(0, 400)}`);\n if (out.length > limit) return true;\n }\n return false;\n}\n",
46
+ "import { readdir, stat } from 'node:fs/promises';\nimport { displayPath, resolvePath } from './fs-paths.ts';\nimport { object, optionalString, str } from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\ninterface LsInput {\n path?: string;\n}\n\nexport const lsTool: Tool<LsInput> = defineTool<LsInput>({\n name: 'ls',\n description:\n 'List the entries of one directory. Use `glob` to find files by pattern across ' +\n 'a tree; this tool does not recurse.',\n readOnly: true,\n inputSchema: object({ path: str('Directory to list. Defaults to the working directory.') }, []),\n parse: (input) => {\n const path = optionalString(input, 'path');\n return path === undefined ? {} : { path };\n },\n async execute(input, ctx) {\n const abs = resolvePath(ctx.cwd, input.path ?? '.');\n const info = await stat(abs).catch(() => undefined);\n if (!info) throw new ToolInputError(`no such directory: ${displayPath(ctx.cwd, abs)}`);\n if (!info.isDirectory())\n throw new ToolInputError(`${displayPath(ctx.cwd, abs)} is a file; use read`);\n\n const entries = await readdir(abs, { withFileTypes: true });\n const rows = entries\n .map((entry) => (entry.isDirectory() ? `${entry.name}/` : entry.name))\n .sort((a, b) => {\n const dirA = a.endsWith('/');\n const dirB = b.endsWith('/');\n return dirA === dirB ? a.localeCompare(b) : dirA ? -1 : 1;\n });\n\n return {\n output: text(rows.length === 0 ? '(empty directory)' : rows.join('\\n')),\n title: `${displayPath(ctx.cwd, abs)} (${rows.length} entries)`,\n };\n },\n});\n",
47
+ "import { readFile, stat } from 'node:fs/promises';\nimport { displayPath, resolvePath } from './fs-paths.ts';\nimport { num, object, opt, optionalNumber, requireString, str } from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\n/** Lines beyond this are truncated unless the model asks for a window. */\nconst DEFAULT_LIMIT = 2000;\n/** Longer lines are almost always minified or binary-ish; they blow the context. */\nconst MAX_LINE = 2000;\n\ninterface ReadInput {\n path: string;\n offset?: number;\n limit?: number;\n}\n\nexport const readTool: Tool<ReadInput> = defineTool<ReadInput>({\n name: 'read',\n description:\n 'Read a file from disk. Returns cat -n style numbered lines. Prefer reading a ' +\n 'whole file over guessing a window; use offset/limit only for large files.',\n readOnly: true,\n inputSchema: object(\n {\n path: str('Path to the file, absolute or relative to the working directory.'),\n offset: num('1-based line to start from.'),\n limit: num('Maximum number of lines to return.'),\n },\n ['path'],\n ),\n parse: (input) => ({\n path: requireString(input, 'path'),\n ...opt('offset', optionalNumber(input, 'offset')),\n ...opt('limit', optionalNumber(input, 'limit')),\n }),\n async execute(input, ctx) {\n const abs = resolvePath(ctx.cwd, input.path);\n const info = await stat(abs).catch(() => undefined);\n if (!info) throw new ToolInputError(`no such file: ${displayPath(ctx.cwd, abs)}`);\n if (info.isDirectory()) {\n throw new ToolInputError(`${displayPath(ctx.cwd, abs)} is a directory; use ls`);\n }\n\n const raw = await readFile(abs, 'utf8');\n // Reading is what unlocks editing: the loop refuses an edit to a file this\n // session has not seen, so a stale model guess cannot silently overwrite work.\n ctx.markRead(abs);\n\n if (raw === '') return { output: text('(empty file)'), title: displayPath(ctx.cwd, abs) };\n\n const all = raw.split('\\n');\n const start = Math.max(0, (input.offset ?? 1) - 1);\n const limit = input.limit ?? DEFAULT_LIMIT;\n const slice = all.slice(start, start + limit);\n\n const body = slice\n .map((line, i) => {\n const shown = line.length > MAX_LINE ? `${line.slice(0, MAX_LINE)}… (truncated)` : line;\n return `${String(start + i + 1).padStart(6)}\\t${shown}`;\n })\n .join('\\n');\n\n const omitted = all.length - (start + slice.length);\n const note = omitted > 0 ? `\\n\\n… ${omitted} more lines; read with offset to continue` : '';\n return {\n output: text(body + note),\n title: `${displayPath(ctx.cwd, abs)} (${all.length} lines)`,\n };\n },\n});\n",
48
+ "import { arr, object, opt, requireString, str } from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\nexport interface TaskInput {\n description: string;\n prompt: string;\n tools?: string[];\n}\n\n/**\n * The tools a subagent gets when the caller names none: the ones that only look.\n *\n * A subagent is most often used to search or read something large without\n * spending the parent's context on it, and defaulting to that means the common\n * case cannot change anything at all.\n */\nexport const DEFAULT_SUBAGENT_TOOLS = ['read', 'ls', 'glob', 'grep', 'ask_user', 'todo'];\n\n/**\n * Runs a sub-task in a nested agent with its own context window.\n *\n * Not read-only: what the subagent does is gated call by call inside it, but\n * starting one is itself worth showing the user, and a subagent that could run\n * concurrently with the parent's own reads would race them.\n */\nexport const taskTool: Tool<TaskInput> = defineTool<TaskInput>({\n name: 'task',\n description:\n 'Run a self-contained sub-task in a nested agent with its own context window, and get ' +\n 'back its answer rather than its transcript. Use it for work that would fill this ' +\n 'conversation with output you do not need to keep - searching a large codebase, ' +\n 'reading a long file to answer one question. The subagent sees none of this ' +\n 'conversation, so the prompt must contain everything it needs.',\n readOnly: false,\n inputSchema: object(\n {\n description: str('One short line naming the sub-task, e.g. \"find the retry logic\".'),\n prompt: str('The whole task. The subagent sees nothing else, so include the context.'),\n tools: arr(\n { type: 'string' },\n 'Tool names it may use. Defaults to the read-only ones. Anything here that this ' +\n 'session does not already allow is ignored.',\n ),\n },\n ['description', 'prompt'],\n ),\n parse: (input) => {\n const description = requireString(input, 'description');\n const prompt = requireString(input, 'prompt');\n if (prompt.trim() === '') throw new ToolInputError('\"prompt\" cannot be empty');\n const raw = (input as { tools?: unknown }).tools;\n if (raw !== undefined && !Array.isArray(raw))\n throw new ToolInputError('\"tools\" must be a list');\n const tools = raw?.map(String);\n return { description, prompt, ...opt('tools', tools) };\n },\n permission: (input) => ({\n tool: 'Task',\n target: input.description,\n title: `run a subagent: ${input.description}`,\n detail:\n `${input.prompt}\\n\\nTools: ${(input.tools ?? DEFAULT_SUBAGENT_TOOLS).join(', ')}\\n\\n` +\n \"It inherits this session's permission rules and declared scope, and anything it \" +\n 'does that needs approval will still ask.',\n }),\n async execute(input, ctx) {\n const run = ctx.runSubagent;\n if (!run) {\n throw new ToolInputError('this session cannot run a subagent; do the work here instead');\n }\n\n const result = await run(\n {\n description: input.description,\n prompt: input.prompt,\n ...opt('tools', input.tools),\n },\n ctx.signal,\n );\n\n // The subagent's answer, and the fact that it did not finish if it did not.\n // A truncated run reported as a complete answer is the same failure as\n // \"done\" from a turn whose tests never ran.\n const warning =\n result.stoppedBecause === undefined\n ? ''\n : `\\n\\n[the subagent stopped early: ${result.stoppedBecause}. Treat this answer as ` +\n 'incomplete and say so.]';\n\n return {\n output: text(`${result.text || '(the subagent produced no answer)'}${warning}`),\n ...(result.stoppedBecause === 'error' ? { isError: true } : {}),\n title: `${input.description} - ${result.steps} step${result.steps === 1 ? '' : 's'}, $${result.costUsd.toFixed(4)}`,\n };\n },\n});\n",
49
+ "import { arr, enumOf, object, requireArray, requireString, str } from './schema.ts';\nimport { defineTool, type TodoItem, type Tool, ToolInputError, text } from './types.ts';\n\ninterface TodoInput {\n items: TodoItem[];\n}\n\nconst STATUSES = ['pending', 'in_progress', 'done'] as const;\n\n/**\n * The list is replaced wholesale rather than patched. Incremental updates need\n * stable ids the model has to track across a long turn, and a model that loses\n * track produces a list that silently diverges from what it is doing; sending the\n * whole list every time makes the state the model believes in the state we show.\n */\nexport const todoTool: Tool<TodoInput> = defineTool<TodoInput>({\n name: 'todo',\n description:\n 'Record the plan for a multi-step task, replacing the current list. Keep exactly ' +\n 'one item in_progress, and mark items done as you finish them rather than in a ' +\n 'batch at the end. Skip it for single-step work.',\n readOnly: true,\n inputSchema: object(\n {\n items: arr(\n object(\n {\n id: str('Stable identifier for the item.'),\n text: str('What the step is, in the imperative.'),\n status: enumOf([...STATUSES], 'pending, in_progress, or done.'),\n },\n ['id', 'text', 'status'],\n ),\n 'The complete todo list, replacing any previous one.',\n ),\n },\n ['items'],\n ),\n parse: (input) => {\n const items = requireArray(input, 'items').map((raw, i) => {\n const status = requireString(raw, 'status');\n if (!(STATUSES as readonly string[]).includes(status)) {\n throw new ToolInputError(`item ${i + 1}: status must be one of ${STATUSES.join(', ')}`);\n }\n return {\n id: requireString(raw, 'id'),\n text: requireString(raw, 'text'),\n status: status as TodoItem['status'],\n };\n });\n const inProgress = items.filter((item) => item.status === 'in_progress');\n if (inProgress.length > 1) {\n throw new ToolInputError('only one item may be in_progress at a time');\n }\n return { items };\n },\n async execute(input, ctx) {\n ctx.todos.replace(input.items);\n const done = input.items.filter((item) => item.status === 'done').length;\n const rendered = input.items.map((item) => `${marker(item.status)} ${item.text}`).join('\\n');\n return {\n output: text(rendered === '' ? 'todo list cleared' : rendered),\n title: `${done}/${input.items.length} done`,\n };\n },\n});\n\nfunction marker(status: TodoItem['status']): string {\n return status === 'done' ? '[x]' : status === 'in_progress' ? '[~]' : '[ ]';\n}\n\n/** The default in-memory store; the TUI reads it to render the status line. */\nexport class MemoryTodoStore {\n private items: TodoItem[] = [];\n\n list(): TodoItem[] {\n return [...this.items];\n }\n\n replace(items: TodoItem[]): void {\n this.items = [...items];\n }\n}\n",
50
+ "import { num, object, opt, optionalNumber, requireString, str } from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\nconst DEFAULT_MAX_CHARS = 40_000;\nconst TIMEOUT_MS = 30_000;\n\ninterface WebFetchInput {\n url: string;\n maxChars?: number;\n}\n\nexport const webFetchTool: Tool<WebFetchInput> = defineTool<WebFetchInput>({\n name: 'web_fetch',\n description:\n 'Fetch a URL and return its text content, with HTML reduced to readable text. ' +\n 'Use it to read documentation, changelogs and issues the user points at.',\n // Not read-only: it reaches the network, so it can leak what the agent is\n // working on to a third party and can be pointed at an internal address. The\n // gate sees the URL.\n readOnly: false,\n inputSchema: object(\n {\n url: str('Absolute http(s) URL to fetch.'),\n maxChars: num(`Maximum characters to return. Defaults to ${DEFAULT_MAX_CHARS}.`),\n },\n ['url'],\n ),\n parse: (input) => {\n const url = requireString(input, 'url');\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new ToolInputError(`\"${url}\" is not a valid URL`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new ToolInputError('only http and https URLs can be fetched');\n }\n return { url, ...opt('maxChars', optionalNumber(input, 'maxChars')) };\n },\n permission: (input) => ({\n tool: 'WebFetch',\n target: new URL(input.url).host,\n title: `fetch ${input.url}`,\n detail: input.url,\n }),\n async execute(input, ctx) {\n const response = await fetch(input.url, {\n redirect: 'follow',\n signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(TIMEOUT_MS)]),\n headers: { accept: 'text/html,text/plain,application/json;q=0.9,*/*;q=0.8' },\n }).catch((error: Error) => {\n throw new ToolInputError(`fetch failed: ${error.message}`);\n });\n\n if (!response.ok) {\n return {\n output: text(`${response.status} ${response.statusText} from ${input.url}`),\n isError: true,\n title: `${input.url} (${response.status})`,\n };\n }\n\n const contentType = response.headers.get('content-type') ?? '';\n const body = await response.text();\n const content = contentType.includes('html') ? htmlToText(body) : body;\n\n const max = input.maxChars ?? DEFAULT_MAX_CHARS;\n const clipped = content.length > max ? `${content.slice(0, max)}\\n\\n[truncated]` : content;\n return { output: text(clipped), title: input.url };\n },\n});\n\n/**\n * A deliberately crude HTML-to-text pass: drop the parts that are never content,\n * unwrap the rest, and decode the handful of entities that actually show up. A\n * real parser would be a dependency and a maintenance surface for output the\n * model reads approximately anyway.\n */\nexport function htmlToText(html: string): string {\n return html\n .replace(/<(script|style|noscript|svg|head)\\b[^>]*>[\\s\\S]*?<\\/\\1>/gi, ' ')\n .replace(/<!--[\\s\\S]*?-->/g, ' ')\n .replace(/<\\/(p|div|li|tr|h[1-6]|section|article)>/gi, '\\n')\n .replace(/<br\\s*\\/?>/gi, '\\n')\n .replace(/<li\\b[^>]*>/gi, '- ')\n .replace(/<[^>]+>/g, ' ')\n .replace(/&nbsp;/g, ' ')\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&amp;/g, '&')\n .replace(/[ \\t]+/g, ' ')\n .replace(/\\n{3,}/g, '\\n\\n')\n .split('\\n')\n .map((line) => line.trim())\n .join('\\n')\n .trim();\n}\n",
51
+ "import { readFileSync } from 'node:fs';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { unifiedDiff } from './diff.ts';\nimport { displayPath, resolvePath } from './fs-paths.ts';\nimport { object, requireString, str } from './schema.ts';\nimport { defineTool, type Tool, text } from './types.ts';\n\ninterface WriteInput {\n path: string;\n content: string;\n}\n\nexport const writeTool: Tool<WriteInput> = defineTool<WriteInput>({\n name: 'write',\n description:\n 'Write a file, creating it or replacing its entire contents. Prefer `edit` for ' +\n 'changes to an existing file; this tool discards everything it does not repeat.',\n readOnly: false,\n inputSchema: object(\n {\n path: str('Path to the file, absolute or relative to the working directory.'),\n content: str('The complete new contents of the file.'),\n },\n ['path', 'content'],\n ),\n parse: (input) => ({\n path: requireString(input, 'path'),\n content: requireString(input, 'content'),\n }),\n permission(input, ctx) {\n const abs = resolvePath(ctx.cwd, input.path);\n const shown = displayPath(ctx.cwd, abs);\n // Synchronous by necessity: the gate runs before execute, and the prompt must\n // show a real diff. A file that cannot be read is a creation, which diffs\n // against the empty string and renders as an all-additions hunk.\n const before = readTextSync(abs);\n return {\n tool: 'Write',\n target: shown,\n title: `${before === undefined ? 'create' : 'overwrite'} ${shown}`,\n detail: unifiedDiff(shown, before ?? '', input.content) || '(no change)',\n writes: [abs],\n };\n },\n async execute(input, ctx) {\n const abs = resolvePath(ctx.cwd, input.path);\n await mkdir(dirname(abs), { recursive: true });\n const before = await readFile(abs, 'utf8').catch(() => undefined);\n await writeFile(abs, input.content, 'utf8');\n ctx.markRead(abs);\n const lines = input.content === '' ? 0 : input.content.split('\\n').length;\n return {\n output: text(\n `${before === undefined ? 'created' : 'wrote'} ${displayPath(ctx.cwd, abs)} (${lines} lines)`,\n ),\n title: displayPath(ctx.cwd, abs),\n };\n },\n});\n\n/** `undefined` rather than throwing: an unreadable path is a file creation. */\nfunction readTextSync(path: string): string | undefined {\n try {\n return readFileSync(path, 'utf8');\n } catch {\n return undefined;\n }\n}\n",
52
+ "export interface BackgroundJob {\n id: string;\n command: string;\n /** Appended to as the process runs; read by the `bash_output` tool. */\n output: string;\n exitCode: number | null;\n running: boolean;\n kill(): void;\n}\n\n/**\n * Background jobs outlive the tool call that started them, so the registry hangs\n * off the tool context rather than a module global: two sessions in one process\n * (the TUI running a subagent, say) must not see each other's jobs.\n */\nexport class BackgroundJobs {\n private readonly jobs = new Map<string, BackgroundJob>();\n private counter = 0;\n\n nextId(): string {\n this.counter += 1;\n return `bg_${this.counter}`;\n }\n\n add(job: BackgroundJob): void {\n this.jobs.set(job.id, job);\n }\n\n get(id: string): BackgroundJob | undefined {\n return this.jobs.get(id);\n }\n\n list(): BackgroundJob[] {\n return [...this.jobs.values()];\n }\n\n /** Called when a session ends: a stray dev server must not survive it. */\n killAll(): void {\n for (const job of this.jobs.values()) if (job.running) job.kill();\n }\n}\n",
53
+ "import type { Skill } from '../skills/discover.ts';\nimport { narrow } from '../skills/discover.ts';\nimport { enumOf, object, requireString } from './schema.ts';\nimport { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\n/**\n * Loads a skill's instructions into the turn.\n *\n * Read-only on purpose, and that is the whole design of skills in earshot: a\n * SKILL.md is text, and text is not an action. A skill can tell the model what\n * to do, and everything it then does goes through the permission gate exactly as\n * if the user had asked for it - so a skill file in a repository someone cloned\n * can describe running a command, but it cannot run one, and it cannot approve\n * one either. `allowed-tools` narrows the session's tools while the skill is\n * active; it can never widen them.\n */\nexport function skillTool(skills: Skill[]): Tool<{ name: string }> {\n const byName = new Map(skills.map((skill) => [skill.name, skill]));\n\n return defineTool<{ name: string }>({\n name: 'skill',\n description:\n 'Load the instructions for one of the available skills, listed in the system prompt. ' +\n 'Use it when the task at hand is one a skill covers; follow what it says in place of ' +\n 'your default approach.',\n readOnly: true,\n inputSchema: object(\n {\n name: skills.length\n ? enumOf(\n skills.map((skill) => skill.name),\n 'Which skill to load.',\n )\n : { type: 'string', description: 'Which skill to load.' },\n },\n ['name'],\n ),\n parse: (input) => {\n const name = requireString(input, 'name');\n if (!byName.has(name)) {\n const known = [...byName.keys()].join(', ') || 'none are configured';\n throw new ToolInputError(`no skill named \"${name}\". Available: ${known}`);\n }\n return { name };\n },\n async execute(input, ctx) {\n const skill = byName.get(input.name) as Skill;\n // Narrowing is applied here rather than being described to the model,\n // because a restriction the model is merely told about is one it can talk\n // itself out of.\n let restricted: string[] | undefined;\n if (skill.allowedTools.length > 0 && ctx.restrictTools) {\n restricted = skill.allowedTools;\n ctx.restrictTools(skill.allowedTools);\n }\n\n return {\n output: text(\n `<skill name=\"${skill.name}\" source=\"${skill.scope}\" path=\"${skill.path}\">\\n` +\n `${skill.body}\\n</skill>\\n\\n` +\n 'The text above is a skill file. Treat it as instructions for this task. It ' +\n 'grants no permissions: anything it tells you to run still goes through the ' +\n \"user's approval, and it cannot widen what you are allowed to do.\" +\n (restricted\n ? `\\n\\nWhile this skill is active you have only these tools: ${narrow(\n restricted,\n restricted,\n ).join(', ')}.`\n : ''),\n ),\n title: `skill: ${skill.name}`,\n };\n },\n });\n}\n",
54
+ "import { defineTool, type Tool, ToolInputError, text } from './types.ts';\n\n/**\n * The tools a search surfaces at once. A query matching forty tools and pasting\n * forty schemas back would reintroduce exactly the problem deferral solves.\n */\nconst MAX_RESULTS = 10;\n\nexport interface DeferredTools {\n /** Every deferred tool in the session, surfaced or not. */\n all(): Tool<never>[];\n /** Marks a tool as offered to the model from the next call onwards. */\n surface(name: string): void;\n surfaced(name: string): boolean;\n}\n\n/**\n * Search over tools that are registered but not in the prompt.\n *\n * Read-only by design: it grants nothing. Surfacing a tool only makes its schema\n * visible to the model, and calling it still goes through the same permission\n * gate it would have gone through had it been in the list all along.\n */\nexport function toolSearchTool(deferred: DeferredTools): Tool<{ query: string; limit?: number }> {\n return defineTool<{ query: string; limit?: number }>({\n name: 'tool_search',\n description:\n `${deferred.all().length} further tools are available but not listed above, because ` +\n 'listing them all would cost more context than they are worth. This finds them and ' +\n 'adds them to your tool list. Search by what you want to do (\"create a pull request\", ' +\n '\"query the database\"), by server name, or by an exact tool name. Call it before ' +\n 'concluding a capability is missing.',\n readOnly: true,\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Words to match against tool names and descriptions.',\n },\n limit: {\n type: 'number',\n description: `Maximum tools to surface, 1-${MAX_RESULTS}. Defaults to ${MAX_RESULTS}.`,\n },\n },\n required: ['query'],\n },\n parse: (input) => {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ToolInputError('expected an object with a \"query\" string');\n }\n const { query, limit } = input as { query?: unknown; limit?: unknown };\n if (typeof query !== 'string' || query.trim() === '') {\n throw new ToolInputError('\"query\" must be a non-empty string');\n }\n if (limit !== undefined && (typeof limit !== 'number' || !Number.isFinite(limit))) {\n throw new ToolInputError('\"limit\" must be a number');\n }\n return { query, ...(limit === undefined ? {} : { limit }) };\n },\n async execute(input) {\n const limit = Math.min(MAX_RESULTS, Math.max(1, Math.trunc(input.limit ?? MAX_RESULTS)));\n const matches = rank(deferred.all(), input.query).slice(0, limit);\n if (matches.length === 0) {\n return {\n output: text(`No unlisted tool matches \"${input.query}\".`),\n title: `tool_search: no match for \"${input.query}\"`,\n };\n }\n\n for (const tool of matches) deferred.surface(tool.name);\n const body = matches\n .map(\n (tool) =>\n `${tool.name}\\n${tool.description}\\ninput schema: ${JSON.stringify(tool.inputSchema)}`,\n )\n .join('\\n\\n');\n return {\n output: text(\n `${matches.length} tool${matches.length === 1 ? '' : 's'} added to your tool list. ` +\n `You can call ${matches.length === 1 ? 'it' : 'them'} now.\\n\\n${body}`,\n ),\n title: `tool_search: ${matches.map((tool) => tool.name).join(', ')}`,\n };\n },\n });\n}\n\n/**\n * Substring scoring over name and description. Deliberately not fuzzy: a search\n * that silently matches something close is how the model ends up calling the\n * wrong server's `delete` tool. An unmatched query returns nothing and says so.\n */\nfunction rank(tools: Tool<never>[], query: string): Tool<never>[] {\n const terms = query\n .toLowerCase()\n .split(/[^a-z0-9]+/i)\n .filter((term) => term.length > 1);\n if (terms.length === 0) return [];\n\n const scored: Array<{ tool: Tool<never>; score: number }> = [];\n for (const tool of tools) {\n const name = tool.name.toLowerCase();\n const description = tool.description.toLowerCase();\n let score = 0;\n for (const term of terms) {\n if (name.includes(term)) score += 3;\n else if (description.includes(term)) score += 1;\n }\n if (score > 0) scored.push({ tool, score });\n }\n\n // Ties broken by name so the same query surfaces the same tools every time;\n // a search whose results shift between runs is not one a user can rely on.\n scored.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name));\n return scored.map((entry) => entry.tool);\n}\n",
55
+ "import type { ToolDefinition } from '@earshot/providers';\nimport { askUserTool } from './ask-user.ts';\nimport { bashOutputTool, bashTool } from './bash.ts';\nimport { declareScopeTool } from './declare-scope.ts';\nimport { editTool, multiEditTool } from './edit.ts';\nimport { globTool } from './glob.ts';\nimport { grepTool } from './grep.ts';\nimport { lsTool } from './ls.ts';\nimport { readTool } from './read.ts';\nimport { taskTool } from './task.ts';\nimport { todoTool } from './todo.ts';\nimport type { Tool } from './types.ts';\nimport { webFetchTool } from './web-fetch.ts';\nimport { writeTool } from './write.ts';\n\nexport * from './diff.ts';\nexport { applyEdits } from './edit.ts';\nexport * from './exec.ts';\nexport * from './fs-paths.ts';\nexport * from './glob-match.ts';\nexport * from './jobs.ts';\nexport * from './schema.ts';\nexport * from './shell.ts';\nexport { skillTool } from './skill.ts';\nexport * from './task.ts';\nexport * from './todo.ts';\nexport * from './tool-search.ts';\nexport * from './types.ts';\nexport * from './walk.ts';\nexport { htmlToText } from './web-fetch.ts';\n\n/**\n * Order matters only for how the model reads the list, and reading tools first is\n * the order we want it to work in: look before you change anything.\n */\nexport const BUILTIN_TOOLS: Tool<never>[] = [\n readTool,\n lsTool,\n globTool,\n grepTool,\n editTool,\n multiEditTool,\n writeTool,\n bashTool,\n bashOutputTool,\n webFetchTool,\n askUserTool,\n todoTool,\n declareScopeTool,\n taskTool,\n] as unknown as Tool<never>[];\n\nexport class ToolRegistry {\n private readonly tools = new Map<string, Tool<never>>();\n\n constructor(tools: Iterable<Tool<never>> = BUILTIN_TOOLS) {\n for (const tool of tools) this.add(tool);\n }\n\n add(tool: Tool<never>): void {\n if (this.tools.has(tool.name)) throw new Error(`duplicate tool \"${tool.name}\"`);\n this.tools.set(tool.name, tool);\n }\n\n get(name: string): Tool<never> | undefined {\n return this.tools.get(name);\n }\n\n list(): Tool<never>[] {\n return [...this.tools.values()];\n }\n\n /** Only the tools a given permission mode allows are offered to the model. */\n definitions(filter?: (tool: Tool<never>) => boolean): ToolDefinition[] {\n return this.list()\n .filter((tool) => filter?.(tool) ?? true)\n .map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n }));\n }\n}\n",
56
+ "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { MEMORY_FILENAMES } from '../context/agents-md.ts';\n\nexport interface VerifyCommand {\n command: string;\n /** Where it came from, so the user can see why this command and not another. */\n source: string;\n}\n\n/**\n * Finds the command that proves the change works.\n *\n * Declaration beats detection: a project that says how it is tested is telling\n * the truth about itself, while a `test` script can be a placeholder that exits\n * zero. Nothing is invented - if none of these turn anything up, verification\n * simply does not run and the agent has to say so rather than claim it passed.\n */\nexport async function detectTestCommand(cwd: string): Promise<VerifyCommand | undefined> {\n return (\n (await fromSettings(cwd)) ??\n (await fromInstructions(cwd)) ??\n (await fromPackageJson(cwd)) ??\n (await fromMakefile(cwd))\n );\n}\n\nasync function fromSettings(cwd: string): Promise<VerifyCommand | undefined> {\n for (const name of ['settings.local.json', 'settings.json']) {\n const path = join(cwd, '.earshot', name);\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n try {\n const parsed = JSON.parse(raw) as { verify?: { test?: string } };\n const command = parsed.verify?.test;\n if (typeof command === 'string' && command.trim() !== '') {\n return { command: command.trim(), source: `.earshot/${name}` };\n }\n } catch {\n // A settings file that does not parse is reported elsewhere; here it just\n // means no declared command.\n }\n }\n return undefined;\n}\n\n/** `- \\`bun test\\` - test suite`, the shape AGENTS.md documents commands in. */\nconst INSTRUCTION_LINE = /^\\s*[-*]?\\s*`([^`]+)`\\s*[-–:]\\s*(.*)$/;\n\nasync function fromInstructions(cwd: string): Promise<VerifyCommand | undefined> {\n for (const name of MEMORY_FILENAMES) {\n const raw = await readFile(join(cwd, name), 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n for (const line of raw.split('\\n')) {\n const match = INSTRUCTION_LINE.exec(line);\n const command = match?.[1]?.trim();\n const description = match?.[2] ?? '';\n if (!command || !/\\btests?\\b|\\btest suite\\b/i.test(description)) continue;\n // \"`bun test` - test suite\", not \"`bun run lint` - biome\".\n if (!/\\btests?\\b/i.test(command)) continue;\n return { command, source: name };\n }\n }\n return undefined;\n}\n\nasync function fromPackageJson(cwd: string): Promise<VerifyCommand | undefined> {\n const raw = await readFile(join(cwd, 'package.json'), 'utf8').catch(() => undefined);\n if (raw === undefined) return undefined;\n try {\n const parsed = JSON.parse(raw) as { scripts?: Record<string, string> };\n const script = parsed.scripts?.test;\n if (typeof script !== 'string' || script.trim() === '') return undefined;\n // The npm-init default, which exits 1 and proves nothing.\n if (/no test specified/i.test(script)) return undefined;\n return { command: 'npm test', source: 'package.json' };\n } catch {\n return undefined;\n }\n}\n\nasync function fromMakefile(cwd: string): Promise<VerifyCommand | undefined> {\n const raw = await readFile(join(cwd, 'Makefile'), 'utf8').catch(() => undefined);\n if (raw === undefined) return undefined;\n return /^test\\s*:/m.test(raw) ? { command: 'make test', source: 'Makefile' } : undefined;\n}\n",
57
+ "import { exec } from '../tools/exec.ts';\nimport { resolveShell } from '../tools/shell.ts';\n\nexport interface VerificationResult {\n command: string;\n source: string;\n exitCode: number | null;\n /** Combined output, verbatim. Never summarised - that is the whole point. */\n output: string;\n timedOut: boolean;\n}\n\n/**\n * Runs the project's own test command and returns exactly what it printed.\n *\n * The output is reported rather than characterised. \"Tests pass\" from an agent\n * that did not run them is the single most expensive thing this harness can say,\n * and a summary of the output is where that claim hides.\n */\nexport async function runVerification(\n command: string,\n source: string,\n options: { cwd: string; env?: NodeJS.ProcessEnv; signal?: AbortSignal; timeoutMs?: number },\n): Promise<VerificationResult> {\n // resolveShell throws on Windows without Git Bash. That is a reportable\n // outcome here, not a crash: the turn still happened, and the agent has to say\n // the change is unverified rather than dying at the end of it.\n const result = await (async () => {\n const shell = resolveShell(options.env ?? process.env);\n return exec(shell.file, [...shell.args, command], {\n cwd: options.cwd,\n ...(options.env ? { env: options.env } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n timeoutMs: options.timeoutMs ?? 300_000,\n });\n })().catch((error: Error) => ({\n stdout: '',\n stderr: `could not run ${command}: ${error.message}`,\n code: null,\n signal: null,\n timedOut: false,\n }));\n\n return {\n command,\n source,\n exitCode: result.code,\n output: [result.stdout, result.stderr]\n .filter((part) => part.trim() !== '')\n .join('\\n')\n .trim(),\n timedOut: result.timedOut,\n };\n}\n",
58
+ "import type {\n EarshotError,\n ImagePart,\n Message,\n ProviderRegistry,\n TextPart,\n ToolCallPart,\n ToolDefinition,\n ToolResultOutput,\n ToolResultPart,\n Usage,\n} from '@earshot/providers';\n\nexport type UserPromptPart = TextPart | ImagePart;\nexport type UserPrompt = string | UserPromptPart[];\n\nimport {\n type CompactionPolicy,\n compact,\n DEFAULT_SHAPER_OPTIONS,\n estimateTokens,\n type ShaperOptions,\n SUMMARY_PROMPT,\n shapeMessages,\n shouldCompact,\n} from './context/index.ts';\nimport type { HookEvent } from './hooks/config.ts';\nimport type { HookOutcome } from './hooks/run.ts';\nimport type { HookRunner } from './hooks/runner.ts';\nimport type { ResolvedModel } from './model.ts';\nimport { streamModel, turnCost } from './model.ts';\nimport {\n decide,\n type PermissionMode,\n type PermissionPrompt,\n ruleFromChoice,\n} from './permissions/engine.ts';\nimport type { Rule } from './permissions/rules.ts';\nimport { persistRule } from './permissions/settings.ts';\nimport { renderPlan } from './plan/index.ts';\nimport { type ScopeConcern, ScopeContract, type ScopeOptions } from './scope/index.ts';\nimport { narrow } from './skills/discover.ts';\nimport { BUILTIN_TOOLS, ToolRegistry } from './tools/index.ts';\nimport { BackgroundJobs } from './tools/jobs.ts';\nimport { DEFAULT_SUBAGENT_TOOLS } from './tools/task.ts';\nimport { MemoryTodoStore } from './tools/todo.ts';\nimport { toolSearchTool } from './tools/tool-search.ts';\nimport {\n type PermissionRequest,\n type SubagentRequest,\n type SubagentResult,\n type Tool,\n type ToolContext,\n ToolInputError,\n type ToolResult,\n} from './tools/types.ts';\nimport type { ShadowGit, SnapshotFile } from './undo/shadow-git.ts';\nimport { detectTestCommand, runVerification, type VerificationResult } from './verify/index.ts';\n\n/** Everything the TUI and the headless renderer need to show a turn. */\nexport type AgentEvent =\n | { type: 'model_start'; model: string }\n | { type: 'text_delta'; text: string }\n | { type: 'reasoning_delta'; text: string }\n | { type: 'message'; message: Message }\n | { type: 'tool_start'; call: ToolCallPart }\n | { type: 'tool_end'; toolCallId: string; toolName: string; result: ToolResult }\n | { type: 'permission'; request: PermissionRequest; reason: string }\n | { type: 'usage'; usage: Usage; costUsd: number }\n | { type: 'compacted'; replaced: number; summary: string }\n | { type: 'scope_concern'; concern: ScopeConcern; accepted: boolean }\n | { type: 'verification'; result: VerificationResult }\n | { type: 'hook'; event: HookEvent; blocked?: string; problems: string[] }\n | { type: 'subagent'; description: string; steps: number; costUsd: number }\n /**\n * The one-line \"why\" in front of a tool batch. Emitted for every batch,\n * including one the model gave no reason for - a missing intent line is\n * itself worth seeing, and reporting nothing would hide it.\n */\n | { type: 'intent'; text: string | undefined; calls: number }\n /**\n * The session budget was reached. Emitted whether the user then raises it or\n * stops: a run that quietly spent past its limit and a run that was allowed\n * to should not look the same in a transcript.\n */\n | { type: 'budget'; spentUsd: number; limitUsd: number; raisedTo?: number }\n | { type: 'turn_end'; reason: 'stop' | 'aborted' | 'max_steps' | 'error' | 'budget' }\n | { type: 'error'; error: EarshotError };\n\nexport interface AgentOptions {\n registry: ProviderRegistry;\n model: ResolvedModel;\n cwd: string;\n system: string;\n mode: PermissionMode;\n rules: Rule[];\n /** Called when a call needs approval. Without one, every ask becomes a denial. */\n prompt?: PermissionPrompt;\n /** Called by the `ask_user` tool. Without one, the tool reports it cannot ask. */\n ask?: (question: string, options?: string[]) => Promise<string>;\n tools?: Tool<never>[];\n /** Guards against a model that loops on tools forever. */\n maxSteps?: number;\n env?: NodeJS.ProcessEnv;\n /** Called with every message appended to history, for session persistence. */\n onMessage?: (message: Message) => void | Promise<void>;\n /** Snapshot store for undo. Absent means this session keeps no undo history. */\n shadow?: ShadowGit;\n /** Overrides for the context shapers. */\n shapers?: Partial<ShaperOptions>;\n compaction?: Partial<CompactionPolicy>;\n /**\n * Called when compaction has written a summary, so the session can append a\n * `summary` entry. The entry records what was summarised; it removes nothing.\n */\n onCompaction?: (summary: string, historyCut: number) => void | Promise<void>;\n /** Overrides for the scope guard. */\n scope?: Partial<ScopeOptions>;\n /**\n * Running the project's tests after a turn that changed files, and reporting\n * what they printed. `enabled: false` turns it off; `command` overrides\n * detection.\n */\n verify?: { enabled?: boolean; command?: string; timeoutMs?: number };\n /** User-configured hooks. Absent means nothing is hooked and nothing is run. */\n hooks?: HookRunner;\n /**\n * Shared rather than constructed, so a subagent is held to the same scope the\n * parent declared. A subagent with a scope of its own would be a hole straight\n * through the contract: the parent says which files it will touch, and then\n * spawns something that never agreed to it.\n */\n scopeContract?: ScopeContract;\n /** Set on a subagent. Its cost lands on the parent's total, not beside it. */\n onCost?: (costUsd: number) => void;\n /**\n * Session budget in USD. Checked before each model call rather than after:\n * stopping once the money is gone is not a budget, it is a receipt.\n */\n maxCostUsd?: number;\n /**\n * Asked when the budget is reached. Returns a new, higher limit to continue\n * with, or undefined to stop. Absent means stop - a headless run must not\n * block forever waiting for a terminal that is not there.\n */\n confirmBudget?: (spentUsd: number, limitUsd: number) => Promise<number | undefined>;\n /** Steps a subagent this agent spawns may take. */\n subagentMaxSteps?: number;\n}\n\nconst DEFAULT_MAX_STEPS = 100;\n\n/**\n * The agent loop.\n *\n * History is a single flat list and is only ever appended to. That is not a\n * simplification: Anthropic rejects a request whose history contains edited\n * thinking blocks, so any feature that looks like rewriting the past (compaction,\n * rewind) has to be expressed as new entries instead. Every other provider is\n * treated as if it had the same rule, so there is one code path rather than two.\n */\nexport class Agent {\n readonly history: Message[] = [];\n readonly todos = new MemoryTodoStore();\n readonly scope: ScopeContract;\n readonly jobs = new BackgroundJobs();\n\n private readonly tools: ToolRegistry;\n private readonly readFiles = new Set<string>();\n /** Messages typed while a turn is running, injected at the next model call. */\n private readonly queued: Message[] = [];\n private rules: Rule[];\n private mode: PermissionMode;\n private totalCostUsd = 0;\n private maxCostUsd: number | undefined;\n /**\n * Mutable so a memory captured mid-session applies from the next call rather\n * than from the next session - a preference the user has to restart to see\n * honoured reads as one that was ignored.\n */\n private systemPrompt: string;\n /**\n * The approved plan, kept beside the system prompt rather than merged into\n * it: the prompt is rebuilt whenever a memory changes, and a plan folded into\n * that string would be lost the next time it was.\n */\n private plan: string | undefined;\n /** Pre-change hashes for the batch currently executing. */\n private batchSnapshot: SnapshotFile[] = [];\n /** Events raised while a call ran, drained by the batch loop that owns it. */\n private readonly pending: AgentEvent[] = [];\n /**\n * Where the live request starts, and what stands in for everything before it.\n * Compaction cannot shorten `history` - that would rewrite the past - so it\n * records a cut and a preamble, and the request is rebuilt from those.\n */\n private compactedAt = 0;\n private compactionPreamble: Message | undefined;\n /** Tokens in the last request actually sent, for the status line. */\n private lastRequestTokens = 0;\n /** Whether anything has been changed since the last end-of-turn check. */\n private mutatedSinceCheck = false;\n private checksThisTurn = 0;\n /**\n * Installed after construction by the TUI, which cannot supply them earlier:\n * both resolve against React state that does not exist until the app mounts.\n */\n private promptFn: PermissionPrompt | undefined;\n private askFn: ((question: string, options?: string[]) => Promise<string>) | undefined;\n /**\n * Set by a skill that declares `allowed-tools`, and cleared at the start of\n * every turn: a narrowing that outlived the task it was written for would\n * silently remove tools from work the skill knows nothing about.\n */\n private toolRestriction: string[] | undefined;\n /**\n * Deferred tools `tool_search` has surfaced. Session-scoped rather than\n * per-turn: a tool the model went looking for in one turn is exactly the tool\n * the follow-up turn needs, and making it search again would be theatre.\n */\n private readonly surfacedTools = new Set<string>();\n\n constructor(private readonly options: AgentOptions) {\n this.tools = new ToolRegistry(options.tools ?? (BUILTIN_TOOLS as Tool<never>[]));\n if (this.tools.list().some((tool) => tool.deferred)) {\n this.tools.add(\n toolSearchTool({\n all: () => this.tools.list().filter((tool) => tool.deferred),\n surface: (name) => {\n this.surfacedTools.add(name);\n },\n surfaced: (name) => this.surfacedTools.has(name),\n }) as unknown as Tool<never>,\n );\n }\n this.scope = options.scopeContract ?? new ScopeContract(options.cwd, options.scope ?? {});\n this.rules = [...options.rules];\n this.mode = options.mode;\n this.promptFn = options.prompt;\n this.askFn = options.ask;\n this.systemPrompt = options.system;\n this.maxCostUsd = options.maxCostUsd;\n }\n\n get budgetUsd(): number | undefined {\n return this.maxCostUsd;\n }\n\n /** Undefined removes the budget. Used by `/cost` and by the overrun prompt. */\n setBudget(maxCostUsd: number | undefined): void {\n this.maxCostUsd = maxCostUsd;\n }\n\n /** Replaces the approval callback. Passing undefined turns every ask into a denial. */\n setPrompt(prompt: PermissionPrompt | undefined): void {\n this.promptFn = prompt;\n }\n\n setAsk(ask: ((question: string, options?: string[]) => Promise<string>) | undefined): void {\n this.askFn = ask;\n }\n\n get cwd(): string {\n return this.options.cwd;\n }\n\n get system(): string {\n return this.systemPrompt;\n }\n\n setSystem(system: string): void {\n this.systemPrompt = system;\n }\n\n /** Pins an approved plan for the rest of the run. Undefined clears it. */\n setPlan(plan: string | undefined): void {\n this.plan = plan?.trim() === '' ? undefined : plan;\n }\n\n get pinnedPlan(): string | undefined {\n return this.plan;\n }\n\n /** What is actually sent as the system prompt: the prompt plus any plan. */\n private get effectiveSystem(): string {\n return this.plan === undefined\n ? this.systemPrompt\n : `${this.systemPrompt}\\n\\n${renderPlan(this.plan)}`;\n }\n\n get permissionMode(): PermissionMode {\n return this.mode;\n }\n\n setPermissionMode(mode: PermissionMode): void {\n this.mode = mode;\n }\n\n get costUsd(): number {\n return this.totalCostUsd;\n }\n\n /**\n * Adds to this session's spend. A subagent calls its parent's, so one session\n * has one number: a budget that a subagent could spend outside would not be a\n * budget.\n */\n private addCost(costUsd: number): void {\n this.totalCostUsd += costUsd;\n this.options.onCost?.(costUsd);\n }\n\n /** Estimated tokens in the last request, and the window they have to fit in. */\n get contextUse(): { tokens: number; window: number } {\n return { tokens: this.lastRequestTokens, window: this.options.model.model.contextWindow ?? 0 };\n }\n\n /** Files read or written this session, in the order they were first touched. */\n get touchedFiles(): string[] {\n return [...this.readFiles];\n }\n\n /**\n * Queues a message to be delivered at the next model call rather than\n * interrupting. This is what steering is: the user redirects the work without\n * cancelling the turn and losing everything the model has already done.\n */\n steer(text: string): void {\n this.queued.push({ role: 'user', content: [{ type: 'text', text }] });\n }\n\n get pendingSteers(): number {\n return this.queued.length;\n }\n\n /**\n * Replaces the in-memory history, for `/rewind` and `/fork`.\n *\n * The transcript on disk is untouched: rewinding points the next append at an\n * earlier entry and the abandoned branch stays in the file. What changes is\n * only which messages the next request is built from - and the compaction\n * state resets with them, since a summary of messages that are no longer in\n * the history would describe work the model can no longer see.\n */\n replaceHistory(messages: Message[]): void {\n this.history.length = 0;\n this.history.push(...messages);\n this.compactedAt = 0;\n this.compactionPreamble = undefined;\n }\n\n /** Ends the session's background processes. Safe to call more than once. */\n dispose(): void {\n this.jobs.killAll();\n }\n\n async *runTurn(prompt: UserPrompt, signal: AbortSignal): AsyncGenerator<AgentEvent> {\n // The budget is per turn; the declaration outlives one, because a follow-up\n // like \"now do the same for the other file\" is the same piece of work.\n this.scope.beginTurn();\n this.options.hooks?.beginTurn();\n this.toolRestriction = undefined;\n this.mutatedSinceCheck = false;\n this.checksThisTurn = 0;\n\n const promptText = userPromptText(prompt);\n const promptParts: UserPromptPart[] =\n typeof prompt === 'string'\n ? [{ type: 'text', text: prompt }]\n : prompt.map((part) => ({ ...part }));\n if (\n promptParts.some((part) => part.type === 'image') &&\n !this.options.model.model.capabilities.vision\n ) {\n yield {\n type: 'error',\n error: {\n kind: 'invalid_request',\n message: `${this.options.model.model.name} does not support image input`,\n retryable: false,\n },\n };\n yield { type: 'turn_end', reason: 'error' };\n return;\n }\n\n const submitted = await this.options.hooks?.userPromptSubmit(promptText, signal);\n if (submitted) {\n yield hookEvent('UserPromptSubmit', submitted);\n if (submitted.decision === 'deny') {\n // The prompt is not appended at all. A blocked prompt that still entered\n // history would come back on the next request as something the user\n // asked for and the agent ignored.\n yield { type: 'turn_end', reason: 'stop' };\n return;\n }\n }\n\n const context = submitted?.context ?? [];\n const content: UserPromptPart[] =\n context.length > 0 && promptParts.length === 1 && promptParts[0]?.type === 'text'\n ? [\n {\n type: 'text',\n text: `${promptParts[0].text}\\n\\n<hook-context>\\n${context.join('\\n\\n')}\\n</hook-context>`,\n },\n ]\n : [\n ...promptParts,\n ...(context.length\n ? [\n {\n type: 'text' as const,\n text: `<hook-context>\\n${context.join('\\n\\n')}\\n</hook-context>`,\n },\n ]\n : []),\n ];\n await this.append({\n role: 'user',\n content,\n });\n\n const maxSteps = this.options.maxSteps ?? DEFAULT_MAX_STEPS;\n const modelName = `${this.options.model.provider.id}/${this.options.model.model.id}`;\n\n for (let step = 0; step < maxSteps; step++) {\n if (signal.aborted) {\n yield { type: 'turn_end', reason: 'aborted' };\n return;\n }\n\n // Steering messages land here, between one model call and the next, which\n // is the only point where history can grow without contradicting a tool\n // call the model is still waiting on a result for.\n while (this.queued.length > 0) {\n await this.append(this.queued.shift() as Message);\n }\n\n const overrun = await this.checkBudget();\n if (overrun) {\n yield overrun.event;\n if (overrun.stop) {\n yield { type: 'turn_end', reason: 'budget' };\n return;\n }\n }\n\n for await (const event of this.prepareRequest(signal)) yield event;\n const messages = this.requestMessages();\n this.lastRequestTokens = estimateTokens(messages, this.effectiveSystem);\n\n yield { type: 'model_start', model: modelName };\n\n let assistant: Message | undefined;\n let failed: EarshotError | undefined;\n\n for await (const event of streamModel(this.options.registry, this.options.model, {\n system: this.effectiveSystem,\n messages,\n tools: this.offeredTools(),\n abortSignal: signal,\n })) {\n switch (event.type) {\n case 'text_delta':\n yield { type: 'text_delta', text: event.text };\n break;\n case 'reasoning_delta':\n yield { type: 'reasoning_delta', text: event.text };\n break;\n case 'finish': {\n assistant = event.message;\n const costUsd = turnCost(this.options.model.model, event.usage);\n this.addCost(costUsd);\n yield { type: 'usage', usage: event.usage, costUsd };\n break;\n }\n case 'error':\n failed = event.error;\n break;\n default:\n break;\n }\n }\n\n if (failed) {\n yield { type: 'error', error: failed };\n yield { type: 'turn_end', reason: failed.kind === 'abort' ? 'aborted' : 'error' };\n return;\n }\n if (!assistant) {\n yield { type: 'turn_end', reason: signal.aborted ? 'aborted' : 'error' };\n return;\n }\n\n // Appended verbatim, including providerMetadata: an assistant message that\n // is not replayed exactly is what breaks the next request on providers that\n // sign or encrypt their reasoning.\n await this.append(assistant);\n yield { type: 'message', message: assistant };\n\n const calls = assistant.content.filter(\n (part): part is ToolCallPart => part.type === 'tool_call',\n );\n if (calls.length === 0) {\n const check = await this.selfCheck(signal);\n if (!check) {\n const stop = await this.options.hooks?.stop(signal);\n if (stop) {\n yield hookEvent('Stop', stop);\n if (stop.decision === 'deny') {\n await this.append({\n role: 'user',\n content: [\n {\n type: 'text',\n text:\n `<hook>\\nA Stop hook asked you to keep going: ${\n stop.reason ?? 'no reason given'\n }\\nThis message is from the harness, not the user. If you believe the ` +\n `work is finished, say so and stop.\\n</hook>`,\n },\n ],\n });\n continue;\n }\n }\n yield { type: 'turn_end', reason: 'stop' };\n return;\n }\n if (check.verification) yield { type: 'verification', result: check.verification };\n await this.append(check.message);\n continue;\n }\n\n yield { type: 'intent', text: intentOf(assistant), calls: calls.length };\n\n const results: ToolResultPart[] = [];\n this.batchSnapshot = [];\n for await (const event of this.runCalls(calls, results, signal)) yield event;\n await this.commitSnapshot(calls);\n\n // Results are appended in the order the model emitted the calls, not the\n // order they finished, so a replayed transcript is deterministic even\n // though read-only calls ran concurrently.\n await this.append({ role: 'tool', content: results });\n\n if (signal.aborted) {\n yield { type: 'turn_end', reason: 'aborted' };\n return;\n }\n }\n\n yield { type: 'turn_end', reason: 'max_steps' };\n }\n\n /**\n * Whether this session may make another model call.\n *\n * The check is before the call, so the limit is a decision point rather than\n * a post-mortem. Raising it is the user's, and only ever upwards: a callback\n * that answers with a limit already spent would loop.\n */\n private async checkBudget(): Promise<{ event: AgentEvent; stop: boolean } | undefined> {\n const limitUsd = this.maxCostUsd;\n if (limitUsd === undefined || this.totalCostUsd < limitUsd) return undefined;\n\n const spentUsd = this.totalCostUsd;\n const raisedTo = await (this.options.confirmBudget ?? defaultBudgetPrompt(this.askFn))(\n spentUsd,\n limitUsd,\n );\n if (raisedTo === undefined || !Number.isFinite(raisedTo) || raisedTo <= spentUsd) {\n return { event: { type: 'budget', spentUsd, limitUsd }, stop: true };\n }\n this.maxCostUsd = raisedTo;\n return { event: { type: 'budget', spentUsd, limitUsd, raisedTo }, stop: false };\n }\n\n /**\n * The tools this call offers the model. A skill's `allowed-tools` is applied\n * as an intersection with what the session already has, never as a union, so a\n * skill file cannot hand itself a tool the user's settings withheld.\n */\n private offeredTools(): ToolDefinition[] {\n const all = this.tools.definitions(\n (tool) => !tool.deferred || this.surfacedTools.has(tool.name),\n );\n if (!this.toolRestriction) return all;\n const kept = new Set(\n narrow(\n all.map((tool) => tool.name),\n this.toolRestriction,\n ),\n );\n return all.filter((tool) => kept.has(tool.name));\n }\n\n /**\n * Read-only calls run concurrently; anything that mutates runs one at a time.\n * Two edits to the same file in one batch would otherwise race, and the second\n * would be applied against content the first had already replaced.\n */\n private async *runCalls(\n calls: ToolCallPart[],\n into: ToolResultPart[],\n signal: AbortSignal,\n ): AsyncGenerator<AgentEvent> {\n const parallel: Array<{ index: number; promise: Promise<ToolResultPart> }> = [];\n const slots = new Array<ToolResultPart | undefined>(calls.length);\n\n for (const [index, call] of calls.entries()) {\n const tool = this.tools.get(call.toolName);\n if (tool?.readOnly) {\n yield { type: 'tool_start', call };\n parallel.push({ index, promise: this.runOne(tool, call, signal) });\n }\n }\n\n for (const [index, call] of calls.entries()) {\n const tool = this.tools.get(call.toolName);\n if (tool?.readOnly) continue;\n if (signal.aborted) break;\n yield { type: 'tool_start', call };\n const part = await this.runOne(tool, call, signal);\n slots[index] = part;\n while (this.pending.length > 0) yield this.pending.shift() as AgentEvent;\n yield {\n type: 'tool_end',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n result: asResult(part),\n };\n }\n\n for (const { index, promise } of parallel) {\n const part = await promise;\n slots[index] = part;\n while (this.pending.length > 0) yield this.pending.shift() as AgentEvent;\n const call = calls[index] as ToolCallPart;\n yield {\n type: 'tool_end',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n result: asResult(part),\n };\n }\n\n // Every call gets a result, including ones skipped by an abort: a provider\n // rejects an assistant tool call that has no matching result on the next turn.\n for (const [index, call] of calls.entries()) {\n into.push(slots[index] ?? errorPart(call, 'interrupted before this tool ran'));\n }\n }\n\n private async runOne(\n tool: Tool<never> | undefined,\n call: ToolCallPart,\n signal: AbortSignal,\n ): Promise<ToolResultPart> {\n if (!tool) return errorPart(call, `no tool named \"${call.toolName}\"`);\n\n let input: never;\n try {\n input = tool.parse(call.input) as never;\n } catch (error) {\n return errorPart(call, (error as Error).message);\n }\n\n const ctx = this.context(signal);\n\n // Hooks run before the gate, and can only make the answer stricter: a deny\n // stops the call, an ask turns an allow into a prompt, and an approve is\n // read, reported and ignored.\n const before = await this.options.hooks?.preToolUse(call.toolName, input, signal);\n if (before) {\n this.pending.push(hookEvent('PreToolUse', before));\n if (before.decision === 'deny') {\n return errorPart(call, before.reason ?? `a PreToolUse hook blocked ${call.toolName}`);\n }\n }\n\n let request: PermissionRequest | undefined;\n try {\n request = tool.permission?.(input, ctx);\n } catch (error) {\n // A permission() that throws is usually a bad path or a `find` that does not\n // match - a model error, reported as one, before the user is ever prompted.\n return errorPart(call, (error as Error).message);\n }\n\n let decision = decide(tool, request, {\n mode: this.mode,\n rules: this.rules,\n cwd: this.options.cwd,\n });\n\n if (decision.outcome === 'deny') return errorPart(call, decision.reason);\n\n // A hook asking for confirmation is honoured even for a read-only tool, which\n // has no PermissionRequest of its own; one is built from the call so the\n // prompt still shows what is actually about to happen.\n if (before?.decision === 'ask' && decision.outcome === 'allow') {\n const asked = request ?? {\n tool: call.toolName,\n target: call.toolName,\n title: call.toolName,\n detail: `${call.toolName}(${JSON.stringify(call.input, null, 2)})`,\n };\n decision = {\n outcome: 'ask',\n reason: before.reason ?? 'a PreToolUse hook asked for confirmation',\n request: asked,\n };\n }\n\n if (decision.outcome === 'ask') {\n const prompt = this.promptFn;\n if (!prompt) {\n return errorPart(\n call,\n `${decision.reason}, and this session cannot prompt for approval. Ask the user ` +\n 'to re-run with a permission mode or rule that allows it.',\n );\n }\n const choice = await prompt(decision.request, decision.reason);\n if (choice.kind === 'deny') {\n return errorPart(call, choice.message ?? 'the user declined this action');\n }\n if (choice.kind === 'allow-always') {\n const rule = ruleFromChoice(decision.request, choice.scope);\n this.rules = [...this.rules, rule];\n if (choice.scope !== 'session') {\n await persistRule(rule, choice.scope, this.options.cwd).catch(() => undefined);\n }\n }\n }\n\n if (request) {\n const concern = this.scope.check(request);\n if (concern) {\n const accepted = await this.confirmScope(concern, request);\n this.pending.push({ type: 'scope_concern', concern, accepted });\n if (!accepted) {\n return errorPart(\n call,\n `${concern.summary} The user did not approve going outside the declared scope. ` +\n 'Do the part that is in scope, and tell them what you left out and why.',\n );\n }\n }\n // Counted after approval, so the running total is what was actually done.\n this.scope.record(request);\n this.mutatedSinceCheck = true;\n }\n\n // Hashed here, immediately before the change and after approval, so the\n // recorded contents are what was on disk when the tool ran.\n await this.captureWrites(request?.writes ?? []);\n\n try {\n const result = await tool.execute(input, ctx);\n const after = await this.options.hooks?.postToolUse(\n call.toolName,\n input,\n result.output,\n signal,\n );\n if (after) this.pending.push(hookEvent('PostToolUse', after));\n return {\n type: 'tool_result',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n output: withHookContext(result.output, after?.context ?? []),\n ...(result.isError ? { isError: true } : {}),\n };\n } catch (error) {\n // A failing tool is data for the model, not a crash: it is expected to read\n // the message and try something else.\n const message =\n error instanceof ToolInputError\n ? error.message\n : `${call.toolName} failed: ${(error as Error).message}`;\n return errorPart(call, message);\n }\n }\n\n /**\n * Asks before doing something the turn did not say it would do.\n *\n * The prompt carries the real diff or command, exactly as an ordinary\n * permission prompt does - a scope prompt that summarised the change would\n * hide the thing the user is being asked to judge. \"Always\" widens the scope\n * for this session only; unlike a permission choice it persists no rule,\n * because the next task will have a different scope.\n */\n private async confirmScope(concern: ScopeConcern, request: PermissionRequest): Promise<boolean> {\n const prompt = this.promptFn;\n if (!prompt) return false;\n const choice = await prompt(\n {\n tool: 'Scope',\n target: request.target,\n title: `outside the declared scope: ${request.title}`,\n detail: `${concern.summary}\\n\\n${request.detail}`,\n ...(request.writes ? { writes: request.writes } : {}),\n },\n concern.summary,\n );\n if (choice.kind === 'deny') return false;\n if (choice.kind === 'allow-always') {\n this.scope.widen(concern, concern.kind === 'out-of-scope-file' ? concern.path : undefined);\n }\n return true;\n }\n\n /**\n * The end-of-turn check: run the project's tests, and make the model compare\n * what was asked for with what changed before it answers.\n *\n * It runs only on a turn that changed something, and at most twice, so a\n * model that keeps editing after a failure still terminates. The output is\n * handed over verbatim - a summary of it is exactly where \"tests pass\" from an\n * agent that never ran them hides.\n */\n private async selfCheck(\n signal: AbortSignal,\n ): Promise<{ message: Message; verification?: VerificationResult } | undefined> {\n if (!this.mutatedSinceCheck || this.checksThisTurn >= 2 || signal.aborted) return undefined;\n this.mutatedSinceCheck = false;\n this.checksThisTurn++;\n\n const configured = this.options.verify;\n const detected =\n configured?.enabled === false\n ? undefined\n : configured?.command\n ? { command: configured.command, source: 'configuration' }\n : await detectTestCommand(this.options.cwd);\n\n const verification = detected\n ? await runVerification(detected.command, detected.source, {\n cwd: this.options.cwd,\n env: this.options.env ?? process.env,\n signal,\n ...(configured?.timeoutMs !== undefined ? { timeoutMs: configured.timeoutMs } : {}),\n })\n : undefined;\n\n const evidence = verification\n ? `\\`${verification.command}\\` (from ${verification.source}) exited ` +\n `${verification.timedOut ? 'after timing out' : String(verification.exitCode)}. Its ` +\n `output, verbatim:\\n\\n${verification.output || '(no output)'}`\n : 'No test command was detected for this project, so nothing was verified. Say that ' +\n 'plainly rather than implying the change works.';\n\n return {\n message: {\n role: 'user',\n content: [\n {\n type: 'text',\n text:\n `<self-check>\\nThis turn changed files. Before you answer, compare the original ` +\n `request with what actually changed, and report anything you skipped, narrowed, ` +\n `left unverified or that is failing. Four of five things done is that report, ` +\n `not \"done\".\\n\\n${evidence}\\n\\nIf something is failing, fix it or say what is ` +\n `failing and why - do not describe the run as passing. This message is from the ` +\n `harness, not the user; answer them, not it.\\n</self-check>`,\n },\n ],\n },\n ...(verification ? { verification } : {}),\n };\n }\n\n /** Records pre-change contents for paths not already captured in this batch. */\n private async captureWrites(paths: string[]): Promise<void> {\n const shadow = this.options.shadow;\n if (!shadow) return;\n for (const path of paths) {\n if (this.batchSnapshot.some((file) => file.path === path)) continue;\n this.batchSnapshot.push({ path, before: await shadow.hashFile(path) });\n }\n }\n\n /**\n * Writes one snapshot record per tool batch. Per-batch rather than per-call so\n * undo restores a coherent unit: a `multi_edit` across three files, or an edit\n * plus the command that formatted it, is one step back rather than three.\n */\n private async commitSnapshot(calls: ToolCallPart[]): Promise<void> {\n const shadow = this.options.shadow;\n if (!shadow || this.batchSnapshot.length === 0) return;\n const label = calls.map((call) => call.toolName).join(', ');\n await shadow.record(this.batchSnapshot, label).catch(() => undefined);\n this.batchSnapshot = [];\n }\n\n /**\n * The messages for one request: the live tail of history, any compaction\n * preamble in front of it, then the cheap shapers. A copy, never the live\n * array - an adapter that reads messages lazily would otherwise see entries\n * appended after the request was made.\n */\n private requestMessages(): Message[] {\n const tail = this.history.slice(this.compactedAt);\n const base = this.compactionPreamble ? [this.compactionPreamble, ...tail] : tail;\n return shapeMessages(base, { ...DEFAULT_SHAPER_OPTIONS, ...this.options.shapers });\n }\n\n /** Compacts if the shaped request would still be too large for the window. */\n private async *prepareRequest(signal: AbortSignal): AsyncGenerator<AgentEvent> {\n const window = this.options.model.model.contextWindow ?? 0;\n const policy = { threshold: 0.8, keepRecentMessages: 8, ...this.options.compaction };\n const shaped = this.requestMessages();\n if (!shouldCompact(shaped, this.effectiveSystem, window, policy)) return;\n\n const result = await compact({\n messages: shaped,\n system: this.effectiveSystem,\n contextWindow: window,\n policy,\n todos: this.todos\n .list()\n .filter((todo) => todo.status !== 'done')\n .map((todo) => todo.text),\n filesTouched: this.touchedFiles,\n summarize: (messages) => this.summarise(messages, signal),\n }).catch(() => undefined);\n if (!result) return;\n\n // The cut is expressed against the shaped array, which has the same length\n // and order as the tail it was built from, minus the preamble.\n const offset = this.compactionPreamble ? 1 : 0;\n this.compactedAt += Math.max(0, result.replaced - offset);\n this.compactionPreamble = result.messages[0];\n this.lastRequestTokens = estimateTokens(this.requestMessages(), this.effectiveSystem);\n // The cut is reported as a history index, not as a count of shaped\n // messages: the session layer maps it back to the entry ids the summary\n // stands in for, and those are indexed by history position.\n await this.options.onCompaction?.(result.summary, this.compactedAt);\n yield { type: 'compacted', replaced: result.replaced, summary: result.summary };\n }\n\n /** One extra model call, with no tools: the summary that compaction stands on. */\n private async summarise(messages: Message[], signal: AbortSignal): Promise<string> {\n let text = '';\n for await (const event of streamModel(this.options.registry, this.options.model, {\n system: SUMMARY_PROMPT,\n messages: [...messages, { role: 'user', content: [{ type: 'text', text: SUMMARY_PROMPT }] }],\n abortSignal: signal,\n })) {\n if (event.type === 'text_delta') text += event.text;\n if (event.type === 'finish') {\n for (const part of event.message.content) {\n if (part.type === 'text' && text === '') text = part.text;\n }\n }\n if (event.type === 'error') throw new Error(event.error.message);\n }\n if (text.trim() === '') throw new Error('the model returned an empty summary');\n return text;\n }\n\n private context(signal: AbortSignal): ToolContext {\n return {\n cwd: this.options.cwd,\n signal,\n todos: this.todos,\n jobs: this.jobs,\n scope: this.scope,\n env: this.options.env ?? process.env,\n ask: async (question, choices) => {\n const ask = this.askFn;\n if (!ask) {\n throw new ToolInputError(\n 'this session cannot ask the user a question; decide with the information you have ' +\n 'and state the assumption you made',\n );\n }\n return ask(question, choices);\n },\n restrictTools: (names) => {\n this.toolRestriction = names;\n },\n // Absent on a subagent, so nesting stops at one level: an agent that could\n // spawn agents that spawn agents has no bound anyone can reason about.\n ...(this.options.onCost\n ? {}\n : { runSubagent: (request, sub) => this.subagent(request, sub) }),\n markRead: (path) => {\n this.readFiles.add(path);\n },\n hasRead: (path) => this.readFiles.has(path),\n };\n }\n\n /**\n * Runs a nested agent and returns its answer.\n *\n * What it inherits is the whole design. Permission mode and rules, so nothing\n * it does escapes the gate. The parent's ScopeContract object, so a file\n * nobody declared still prompts. The parent's cost total, so one session has\n * one number. What it does not inherit is context: it starts empty and is\n * given the prompt, which is the point - and it hands back an answer, not a\n * transcript, so the parent's window holds the conclusion rather than the\n * work.\n */\n private async subagent(request: SubagentRequest, signal: AbortSignal): Promise<SubagentResult> {\n const allowed = new Set(request.tools?.length ? request.tools : DEFAULT_SUBAGENT_TOOLS);\n // Intersection, never a union: a subagent cannot be handed a tool the parent\n // session does not have, whoever named it.\n const tools = this.tools\n .list()\n .filter((tool) => allowed.has(tool.name) && tool.name !== 'task');\n\n // The parent's persistence callbacks are dropped rather than passed on: a\n // subagent's messages are not the session's transcript, and writing them\n // there would replay them on the next resume as if the user had said them.\n const { onMessage: _persist, onCompaction: _summarised, ...inherited } = this.options;\n\n const child = new Agent({\n ...inherited,\n system:\n // The plan travels with it: a subagent working outside the plan the user\n // approved is the same hole as one working outside the declared scope.\n `${this.effectiveSystem}\\n\\n<subagent>\\nYou are running as a subagent for one ` +\n `self-contained task: ${request.description}. You cannot see the conversation that ` +\n 'sent you here, and only your final message is returned - so answer in full, and ' +\n 'say plainly what you could not find or could not do rather than implying success.' +\n '\\n</subagent>',\n tools,\n scopeContract: this.scope,\n onCost: (costUsd) => this.addCost(costUsd),\n maxSteps: this.options.subagentMaxSteps ?? 30,\n });\n child.setPrompt(this.promptFn);\n child.setAsk(this.askFn);\n\n let text = '';\n let steps = 0;\n let stoppedBecause: SubagentResult['stoppedBecause'];\n const before = this.totalCostUsd;\n\n for await (const event of child.runTurn(request.prompt, signal)) {\n if (event.type === 'model_start') steps++;\n if (event.type === 'message') {\n const said = event.message.content\n .filter((part) => part.type === 'text')\n .map((part) => (part.type === 'text' ? part.text : ''))\n .join('');\n if (said.trim() !== '') text = said;\n }\n if (event.type === 'turn_end' && event.reason !== 'stop') stoppedBecause = event.reason;\n if (event.type === 'error') stoppedBecause = 'error';\n // Prompts and scope questions the subagent raised are the user's to see.\n if (event.type === 'permission' || event.type === 'scope_concern' || event.type === 'hook') {\n this.pending.push(event);\n }\n }\n child.dispose();\n\n const costUsd = this.totalCostUsd - before;\n this.pending.push({ type: 'subagent', description: request.description, steps, costUsd });\n return { text: text.trim(), steps, costUsd, ...(stoppedBecause ? { stoppedBecause } : {}) };\n }\n\n private async append(message: Message): Promise<void> {\n this.history.push(message);\n await this.options.onMessage?.(message);\n }\n}\n\n/**\n * The line the model said before reaching for a tool.\n *\n * The first line of the text it emitted alongside the calls, not all of it: the\n * point of the intent line is that one line of output is enough to catch a wrong\n * turn, and a paragraph is not one line.\n */\nfunction intentOf(assistant: Message): string | undefined {\n const said = assistant.content\n .filter((part) => part.type === 'text')\n .map((part) => (part.type === 'text' ? part.text : ''))\n .join(' ')\n .trim();\n if (said === '') return undefined;\n return said\n .split(/\\r?\\n/)\n .find((line) => line.trim() !== '')\n ?.trim();\n}\n\nfunction hookEvent(event: HookEvent, outcome: HookOutcome): AgentEvent {\n return {\n type: 'hook',\n event,\n ...(outcome.decision === 'deny' && outcome.reason ? { blocked: outcome.reason } : {}),\n problems: outcome.problems,\n };\n}\n\n/**\n * A PostToolUse hook's output, attached to the result the model reads. Appended\n * rather than substituted: the tool's own output is what actually happened, and\n * a hook commenting on it must not be able to replace it.\n */\nfunction withHookContext(output: ToolResultOutput, context: string[]): ToolResultOutput {\n if (context.length === 0) return output;\n const note = `<hook-context>\\n${context.join('\\n\\n')}\\n</hook-context>`;\n if (output.type === 'text') return { type: 'text', value: `${output.value}\\n\\n${note}` };\n return {\n type: 'content',\n value: [\n ...(output.type === 'content'\n ? output.value\n : [{ type: 'text' as const, text: JSON.stringify(output.value) }]),\n { type: 'text', text: note },\n ],\n };\n}\n\nfunction errorPart(call: ToolCallPart, message: string): ToolResultPart {\n return {\n type: 'tool_result',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n output: { type: 'text', value: message },\n isError: true,\n };\n}\n\nfunction asResult(part: ToolResultPart): ToolResult {\n return { output: part.output, ...(part.isError ? { isError: true } : {}) };\n}\n\n/**\n * The budget question, asked through whatever the session uses to ask the user\n * anything else. A session with no way to ask - headless, or a subagent - stops\n * rather than blocking on a terminal that is not there.\n */\nfunction defaultBudgetPrompt(\n ask: ((question: string, options?: string[]) => Promise<string>) | undefined,\n): (spentUsd: number, limitUsd: number) => Promise<number | undefined> {\n if (!ask) return async () => undefined;\n return async (spentUsd, limitUsd) => {\n const answer = await ask(\n `This session has spent $${spentUsd.toFixed(2)} against a $${limitUsd.toFixed(2)} budget. ` +\n 'Continue?',\n ['Stop here', `Raise the budget to $${(limitUsd * 2).toFixed(2)}`, 'Remove the budget'],\n );\n if (answer.startsWith('Raise')) return limitUsd * 2;\n if (answer.startsWith('Remove')) return Number.MAX_SAFE_INTEGER;\n return undefined;\n };\n}\n\nfunction userPromptText(prompt: UserPrompt): string {\n if (typeof prompt === 'string') return prompt;\n return prompt\n .map((part) => (part.type === 'text' ? part.text : `[${part.mediaType} image]`))\n .join('\\n\\n');\n}\n",
59
+ "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { configDir } from '@earshot/providers';\nimport type { RuleScope } from '../permissions/rules.ts';\nimport { LOCAL_SETTINGS, PROJECT_SETTINGS } from '../permissions/settings.ts';\n\n/**\n * The events a hook can be attached to.\n *\n * Deliberately a closed set matching Claude Code's names, so hooks people\n * already have keep working. Events earshot has no equivalent for are not\n * invented here; a hook attached to one is reported rather than silently never\n * firing.\n */\nexport const HOOK_EVENTS = [\n 'SessionStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'Stop',\n 'SessionEnd',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\nexport interface HookDefinition {\n event: HookEvent;\n /** Tool-name pattern for the tool events; absent means every tool. */\n matcher?: string;\n command: string;\n timeoutMs: number;\n /** Which settings file it came from, for explaining what ran. */\n scope: RuleScope;\n}\n\nexport interface LoadedHooks {\n hooks: HookDefinition[];\n problems: string[];\n}\n\nexport const DEFAULT_HOOK_TIMEOUT_MS = 60_000;\n\ninterface SettingsShape {\n hooks?: Record<string, unknown>;\n}\n\nfunction settingsPath(scope: RuleScope, cwd: string): string {\n if (scope === 'global') return join(configDir(), 'settings.json');\n if (scope === 'project') return join(cwd, PROJECT_SETTINGS);\n return join(cwd, LOCAL_SETTINGS);\n}\n\n/**\n * Hooks from every scope, concatenated rather than overriding one another - the\n * same rule permission rules follow, and for the same reason: a project's\n * checked-in settings must not be able to remove a hook the user set globally.\n */\nexport async function loadHooks(cwd: string): Promise<LoadedHooks> {\n const hooks: HookDefinition[] = [];\n const problems: string[] = [];\n\n for (const scope of ['global', 'project', 'local'] as RuleScope[]) {\n const path = settingsPath(scope, cwd);\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n\n let file: SettingsShape;\n try {\n file = JSON.parse(raw) as SettingsShape;\n } catch {\n // The permission loader reports the same file; saying it twice is noise.\n continue;\n }\n\n for (const [event, groups] of Object.entries(file.hooks ?? {})) {\n if (!(HOOK_EVENTS as readonly string[]).includes(event)) {\n problems.push(`${path}: earshot has no \"${event}\" hook event, so it will never fire`);\n continue;\n }\n if (!Array.isArray(groups)) {\n problems.push(`${path}: \"hooks.${event}\" must be a list`);\n continue;\n }\n for (const group of groups) {\n hooks.push(...parseGroup(group, event as HookEvent, scope, path, problems));\n }\n }\n }\n\n return { hooks, problems };\n}\n\nfunction parseGroup(\n group: unknown,\n event: HookEvent,\n scope: RuleScope,\n path: string,\n problems: string[],\n): HookDefinition[] {\n if (typeof group !== 'object' || group === null) {\n problems.push(`${path}: a \"${event}\" entry is not an object`);\n return [];\n }\n const entry = group as { matcher?: unknown; hooks?: unknown };\n const matcher =\n typeof entry.matcher === 'string' && entry.matcher !== '' ? entry.matcher : undefined;\n if (!Array.isArray(entry.hooks)) {\n problems.push(`${path}: a \"${event}\" entry has no \"hooks\" list`);\n return [];\n }\n\n const out: HookDefinition[] = [];\n for (const hook of entry.hooks) {\n if (typeof hook !== 'object' || hook === null) continue;\n const item = hook as { type?: unknown; command?: unknown; timeout?: unknown };\n if (item.type !== undefined && item.type !== 'command') {\n problems.push(`${path}: only \"command\" hooks are supported, not \"${String(item.type)}\"`);\n continue;\n }\n if (typeof item.command !== 'string' || item.command.trim() === '') {\n problems.push(`${path}: a \"${event}\" hook has no command`);\n continue;\n }\n out.push({\n event,\n ...(matcher !== undefined ? { matcher } : {}),\n command: item.command,\n // Claude Code's field is seconds; a hook config people already have must\n // not become a sixty-times-longer timeout here.\n timeoutMs:\n typeof item.timeout === 'number' && item.timeout > 0\n ? item.timeout * 1000\n : DEFAULT_HOOK_TIMEOUT_MS,\n scope,\n });\n }\n return out;\n}\n",
60
+ "import { exec } from '../tools/exec.ts';\nimport { resolveShell } from '../tools/shell.ts';\nimport type { HookDefinition, HookEvent } from './config.ts';\n\n/** The JSON a hook reads on stdin. Field names match Claude Code's. */\nexport interface HookInput {\n session_id: string;\n transcript_path?: string;\n cwd: string;\n hook_event_name: HookEvent;\n tool_name?: string;\n tool_input?: unknown;\n tool_response?: unknown;\n prompt?: string;\n stop_hook_active?: boolean;\n}\n\nexport interface HookOutcome {\n /**\n * What the hooks decided. `deny` blocks; `ask` forces a prompt even where a\n * rule would allow. There is no `allow`: see `applyJson`.\n */\n decision?: 'deny' | 'ask';\n reason?: string;\n /** Text to put in front of the model. */\n context: string[];\n /** Shown to the user. A hook that failed is reported, never obeyed. */\n problems: string[];\n /** A hook asked the session to stop. */\n stop?: string;\n}\n\nexport const MAX_HOOK_OUTPUT_CHARS = 10_000;\n\nconst EMPTY: HookOutcome = { context: [], problems: [] };\n\nexport function matches(hook: HookDefinition, toolName: string | undefined): boolean {\n if (hook.matcher === undefined || hook.matcher === '*') return true;\n if (toolName === undefined) return false;\n try {\n return new RegExp(`^(?:${hook.matcher})$`).test(toolName);\n } catch {\n // A matcher that is not a regex is treated as a literal name rather than\n // matching everything, which is the failure that would silently run a hook\n // on every tool the agent has.\n return hook.matcher === toolName;\n }\n}\n\nexport interface RunOptions {\n cwd: string;\n env: NodeJS.ProcessEnv;\n signal?: AbortSignal;\n}\n\n/**\n * Runs every hook attached to an event and folds their answers into one.\n *\n * Hooks run concurrently: they are independent, and a chain of them run in\n * series would put the sum of their timeouts in front of every tool call. A\n * hook that fails, times out, or prints something unparseable contributes a\n * problem and nothing else - the only things that can stop a tool are an\n * explicit block and exit code 2.\n */\nexport async function runHooks(\n hooks: HookDefinition[],\n input: HookInput,\n options: RunOptions,\n): Promise<HookOutcome> {\n if (hooks.length === 0) return EMPTY;\n\n const shell = resolveShell(options.env);\n const payload = JSON.stringify(input);\n const outcome: HookOutcome = { context: [], problems: [] };\n\n const results = await Promise.all(\n hooks.map(async (hook) => {\n try {\n const result = await exec(shell.file, [...shell.args, hook.command], {\n cwd: options.cwd,\n env: options.env,\n timeoutMs: hook.timeoutMs,\n stdin: payload,\n ...(options.signal ? { signal: options.signal } : {}),\n });\n return { hook, result };\n } catch (error) {\n return { hook, failure: (error as Error).message };\n }\n }),\n );\n\n for (const entry of results) {\n const label = `hook ${entry.hook.event} (${entry.hook.scope}): ${entry.hook.command}`;\n if ('failure' in entry) {\n outcome.problems.push(`${label} could not run: ${entry.failure}`);\n continue;\n }\n const { result } = entry;\n if (result.timedOut) {\n outcome.problems.push(`${label} timed out and was killed; it did not block anything`);\n continue;\n }\n\n // Exit 2 is the blocking convention. stderr is the reason, because that is\n // where a script that means to explain itself writes.\n if (result.code === 2) {\n outcome.decision = 'deny';\n outcome.reason = cap(result.stderr.trim() || `${label} blocked this`);\n continue;\n }\n if (result.code !== 0) {\n outcome.problems.push(\n `${label} exited ${result.code ?? 'on a signal'}: ${cap(result.stderr.trim(), 500)}`,\n );\n continue;\n }\n\n applyJson(entry.hook, result.stdout, outcome);\n }\n\n return outcome;\n}\n\n/**\n * Reads a hook's stdout.\n *\n * The deliberate deviation from Claude Code is here: a hook may deny, and it may\n * downgrade an allow to a prompt, but it may never grant. `\"decision\": \"approve\"`\n * and `permissionDecision: \"allow\"` are read and ignored, with a line saying so.\n * A hook command lives in a settings file, including a project's checked-in one,\n * so a hook that could approve would be a repository granting itself permissions\n * the user never gave - which is the thing deny-first exists to prevent.\n */\nfunction applyJson(hook: HookDefinition, stdout: string, outcome: HookOutcome): void {\n const text = stdout.trim();\n if (text === '') return;\n\n let json: Record<string, unknown> | undefined;\n if (text.startsWith('{')) {\n try {\n const parsed = JSON.parse(text) as unknown;\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n json = parsed as Record<string, unknown>;\n }\n } catch {\n // Left undefined: unparseable output is treated as the plain text below\n // rather than as a failure, since a hook printing a log line is normal.\n }\n }\n\n if (!json) {\n outcome.context.push(cap(text));\n return;\n }\n\n const specific = (json.hookSpecificOutput ?? {}) as Record<string, unknown>;\n const granted = json.decision === 'approve' || specific.permissionDecision === 'allow';\n if (granted) {\n outcome.problems.push(\n `${hook.command} tried to approve a call; hooks in earshot can block or ask, ` +\n 'never grant, so the decision was left to the permission rules',\n );\n }\n\n const blocked = json.decision === 'block' || specific.permissionDecision === 'deny';\n const asked = specific.permissionDecision === 'ask';\n if (blocked) {\n outcome.decision = 'deny';\n outcome.reason = cap(\n String(json.reason ?? specific.permissionDecisionReason ?? `${hook.command} blocked this`),\n );\n } else if (asked && outcome.decision !== 'deny') {\n outcome.decision = 'ask';\n outcome.reason ??= cap(String(specific.permissionDecisionReason ?? `${hook.command} asked`));\n }\n\n if (json.continue === false) {\n outcome.stop = cap(String(json.stopReason ?? `${hook.command} stopped the session`), 500);\n }\n if (typeof specific.additionalContext === 'string') {\n outcome.context.push(cap(specific.additionalContext));\n }\n if (typeof json.systemMessage === 'string') {\n outcome.problems.push(cap(json.systemMessage, 500));\n }\n}\n\nfunction cap(value: string, limit = MAX_HOOK_OUTPUT_CHARS): string {\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n[... truncated by earshot ...]`;\n}\n",
61
+ "import type { HookDefinition, HookEvent } from './config.ts';\nimport { type HookInput, type HookOutcome, matches, runHooks } from './run.ts';\n\nexport interface HookRunnerOptions {\n cwd: string;\n env: NodeJS.ProcessEnv;\n sessionId: string;\n transcriptPath?: string;\n}\n\nconst NOTHING: HookOutcome = { context: [], problems: [] };\n\n/**\n * The agent's view of hooks: one call per event, and an outcome that says what\n * to do.\n *\n * What each event may do is the contract, and it is not symmetric:\n *\n * - `PreToolUse` may block a call or force a prompt for it. It may not approve\n * one - see `applyJson` in run.ts for why.\n * - `UserPromptSubmit` may block the prompt, and may add context to it.\n * - `PostToolUse` may only observe and add context: the tool has already run,\n * and a hook pretending otherwise would be lying to the model about the state\n * of the world.\n * - `Stop` may ask for one more model call, once per turn, so a hook cannot loop\n * the agent forever.\n * - `SessionStart` and `SessionEnd` observe.\n */\nexport class HookRunner {\n private stopBlocked = false;\n\n constructor(\n private readonly hooks: HookDefinition[],\n private readonly options: HookRunnerOptions,\n ) {}\n\n get isEmpty(): boolean {\n return this.hooks.length === 0;\n }\n\n /** True when any hook is attached to this event, so callers can skip the work. */\n has(event: HookEvent): boolean {\n return this.hooks.some((hook) => hook.event === event);\n }\n\n beginTurn(): void {\n this.stopBlocked = false;\n }\n\n async preToolUse(toolName: string, input: unknown, signal?: AbortSignal): Promise<HookOutcome> {\n return this.run('PreToolUse', toolName, { tool_name: toolName, tool_input: input }, signal);\n }\n\n async postToolUse(\n toolName: string,\n input: unknown,\n response: unknown,\n signal?: AbortSignal,\n ): Promise<HookOutcome> {\n const outcome = await this.run(\n 'PostToolUse',\n toolName,\n { tool_name: toolName, tool_input: input, tool_response: response },\n signal,\n );\n // A PostToolUse block is downgraded to context: the call already happened,\n // and reporting it as blocked would tell the model something untrue.\n if (outcome.decision === 'deny') {\n const { decision: _blocked, reason: _reason, ...rest } = outcome;\n return {\n ...rest,\n context: [...outcome.context, outcome.reason ?? 'a hook objected to this result'],\n };\n }\n return outcome;\n }\n\n async userPromptSubmit(prompt: string, signal?: AbortSignal): Promise<HookOutcome> {\n return this.run('UserPromptSubmit', undefined, { prompt }, signal);\n }\n\n /**\n * Asks whether the turn may end. Answered at most once per turn: a hook that\n * could block every stop would keep the agent running - and spending - with no\n * way for the user to get a word in.\n */\n async stop(signal?: AbortSignal): Promise<HookOutcome> {\n if (this.stopBlocked) return NOTHING;\n const outcome = await this.run(\n 'Stop',\n undefined,\n { stop_hook_active: this.stopBlocked },\n signal,\n );\n if (outcome.decision === 'deny') this.stopBlocked = true;\n return outcome;\n }\n\n async sessionStart(signal?: AbortSignal): Promise<HookOutcome> {\n return this.run('SessionStart', undefined, {}, signal);\n }\n\n async sessionEnd(): Promise<HookOutcome> {\n return this.run('SessionEnd', undefined, {});\n }\n\n private run(\n event: HookEvent,\n toolName: string | undefined,\n extra: Partial<HookInput>,\n signal?: AbortSignal,\n ): Promise<HookOutcome> {\n const applicable = this.hooks.filter((hook) => hook.event === event && matches(hook, toolName));\n if (applicable.length === 0) return Promise.resolve(NOTHING);\n\n const input: HookInput = {\n session_id: this.options.sessionId,\n ...(this.options.transcriptPath ? { transcript_path: this.options.transcriptPath } : {}),\n cwd: this.options.cwd,\n hook_event_name: event,\n ...extra,\n };\n return runHooks(applicable, input, {\n cwd: this.options.cwd,\n env: this.options.env,\n ...(signal ? { signal } : {}),\n });\n }\n}\n",
62
+ "/**\n * Spots a correction in what the user just typed.\n *\n * Detection only proposes; nothing is remembered without the user pressing a\n * key. That asymmetry is deliberate - a false positive costs one dismissed\n * suggestion, while a silently stored wrong rule follows them into every future\n * session, and they would have no idea it was there.\n */\nexport interface MemoryCandidate {\n /** The rule, as it would be stored. */\n text: string;\n /** The sentence it was taken from, kept verbatim as provenance. */\n source: string;\n}\n\n/** Phrasings that state a standing preference rather than a one-off instruction. */\nconst RULES: RegExp[] = [\n /\\b(?:always|never)\\b[^.!?]*/i,\n /\\b(?:don'?t|do not|stop)\\s+[^.!?]*/i,\n /\\buse\\s+[^.!?]*?\\b(?:not|instead of|rather than)\\b[^.!?]*/i,\n /\\b(?:no more|prefer)\\s+[^.!?]*/i,\n /\\bi (?:already )?told you\\b[^.!?]*/i,\n];\n\n/**\n * Marks the instruction as being about this task, not about how to work in\n * general. \"Don't touch the tests in this PR\" is not a preference.\n */\nconst ONE_OFF =\n /\\b(?:this (?:time|once|file|function|test|case|pr|branch)|for now|just here|right now|in this)\\b/i;\n\nexport function detectPreference(prompt: string): MemoryCandidate | undefined {\n const text = prompt.trim();\n if (text === '' || text.length > 400) return undefined;\n\n for (const sentence of text.split(/(?<=[.!?\\n])\\s+/)) {\n const trimmed = sentence.trim();\n if (trimmed === '' || ONE_OFF.test(trimmed)) continue;\n for (const rule of RULES) {\n const match = rule.exec(trimmed);\n if (!match) continue;\n const captured = match[0].trim().replace(/[,;:]$/, '');\n // Two words is a fragment, not a rule worth carrying into every session.\n if (captured.split(/\\s+/).length < 3) continue;\n return { text: capitalise(captured), source: trimmed };\n }\n }\n return undefined;\n}\n\nfunction capitalise(text: string): string {\n const cleaned = text.replace(/^i (?:already )?told you (?:to |that )?/i, '');\n return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);\n}\n",
63
+ "import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { dataDir } from '@earshot/providers';\nimport { projectKey } from '../session/store.ts';\nimport { exec, hasExecutable } from '../tools/exec.ts';\nimport { displayPath } from '../tools/fs-paths.ts';\n\n/**\n * Per-batch snapshots of the files a turn is about to change, stored in a git\n * object database that lives outside the user's repository.\n *\n * The user's own repo is never touched: no commits, no stash, no index changes,\n * no reflog entries. An agent that commits to undo its own work is an agent that\n * has silently rewritten the user's history, and `git log` becomes unreadable.\n * `GIT_DIR` points at our own directory under the data dir instead, and the work\n * tree is the project, so `git hash-object` and `git cat-file` are all we need.\n *\n * Snapshots are of specific files, not of the whole tree: a turn touches a\n * handful of files and hashing the repository per batch would dominate the cost\n * of the batch itself.\n */\nexport interface Snapshot {\n id: string;\n timestamp: string;\n label: string;\n files: SnapshotFile[];\n /**\n * The session that took this snapshot.\n *\n * The store is keyed by working directory, so every session in a project\n * writes into the same one. Without this field `/undo` walked back through\n * whatever was most recent in the directory, which after a crash meant\n * reaching into a previous session's batches: a user who resumed and pressed\n * undo reverted work they had never seen this session do.\n *\n * Absent on snapshots written before this field existed. Those cannot be\n * attributed to any session, so they are unreachable rather than being\n * credited to the current one - crediting them would recreate exactly the\n * bug the field exists to close.\n */\n sessionId?: string;\n}\n\nexport interface SnapshotFile {\n /** Absolute path in the work tree. */\n path: string;\n /** Blob hash of the contents before the batch, or null when it did not exist. */\n before: string | null;\n}\n\n/**\n * Blobs are round-tripped as UTF-8 text, which is what every tool in this harness\n * writes. A binary file edited by a shell command would not survive a restore, so\n * snapshots are taken of the paths the file tools declare, not of arbitrary ones.\n */\nconst MAX_RESTORE_BYTES = 64 * 1024 * 1024;\n\nexport function shadowDir(cwd: string): string {\n return join(dataDir(), 'undo', projectKey(cwd));\n}\n\nexport class ShadowGit {\n private constructor(\n readonly gitDir: string,\n readonly cwd: string,\n /** Stamped onto new snapshots and used to filter `list()`. */\n readonly sessionId?: string,\n ) {}\n\n /**\n * Returns `undefined` when git is not installed rather than throwing: undo is\n * a convenience, and an agent that refuses to edit files because it cannot\n * snapshot them is worse than one that edits without an undo history. Callers\n * treat a missing store as \"no snapshots available\".\n */\n static async open(cwd: string, sessionId?: string): Promise<ShadowGit | undefined> {\n if (!(await hasExecutable('git', cwd))) return undefined;\n\n const gitDir = shadowDir(cwd);\n const initialised = await stat(join(gitDir, 'HEAD')).catch(() => undefined);\n if (!initialised) {\n await mkdir(gitDir, { recursive: true });\n const result = await exec('git', ['init', '--bare', '--quiet', gitDir], { cwd });\n if (result.code !== 0) return undefined;\n }\n await mkdir(join(gitDir, 'snapshots'), { recursive: true });\n return new ShadowGit(gitDir, cwd, sessionId);\n }\n\n private run(args: string[], maxBytes?: number) {\n // GIT_DIR and GIT_WORK_TREE are set per invocation rather than by running\n // inside the shadow directory: the object store is bare and elsewhere, while\n // the files being hashed are in the project.\n return exec('git', args, {\n cwd: this.cwd,\n env: { ...process.env, GIT_DIR: this.gitDir, GIT_WORK_TREE: this.cwd },\n ...(maxBytes !== undefined ? { maxBytes } : {}),\n });\n }\n\n /**\n * Stores one file's current contents and returns its blob hash, or null when\n * the file does not exist yet - which is how a creation is recorded.\n */\n async hashFile(path: string): Promise<string | null> {\n const info = await stat(path).catch(() => undefined);\n if (!info?.isFile()) return null;\n const result = await this.run(['hash-object', '-w', '--', path]);\n if (result.code !== 0) return null;\n return result.stdout.trim() || null;\n }\n\n /**\n * Snapshots the given paths as they are now, before a batch modifies them.\n * Must be called before the tools run, which is why the loop hands it the\n * `writes` from each permission request rather than discovering paths after.\n */\n async snapshot(paths: string[], label: string): Promise<Snapshot | undefined> {\n const unique = [...new Set(paths)];\n if (unique.length === 0) return undefined;\n\n const files: SnapshotFile[] = [];\n for (const path of unique) files.push({ path, before: await this.hashFile(path) });\n return this.record(files, label);\n }\n\n /**\n * Writes a snapshot record from hashes captured earlier. The loop hashes each\n * file immediately before the tool that changes it, then records the batch as\n * one unit at the end, so undo restores a whole batch rather than half of one.\n */\n async record(files: SnapshotFile[], label: string): Promise<Snapshot | undefined> {\n if (files.length === 0) return undefined;\n\n const snapshot: Snapshot = {\n id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: new Date().toISOString(),\n label,\n files,\n ...(this.sessionId !== undefined ? { sessionId: this.sessionId } : {}),\n };\n await writeFile(\n join(this.gitDir, 'snapshots', `${snapshot.id}.json`),\n `${JSON.stringify(snapshot, null, 2)}\\n`,\n 'utf8',\n );\n return snapshot;\n }\n\n /**\n * Snapshots this session may undo, oldest first.\n *\n * Scoped rather than unscoped by default, so the safe reading is the one a\n * caller gets without asking. A store opened without a session id sees\n * nothing: it cannot tell its own batches from another session's, and\n * guessing is what produced the bug.\n */\n async list(): Promise<Snapshot[]> {\n const all = await this.listAll();\n if (this.sessionId === undefined) return [];\n return all.filter((snapshot) => snapshot.sessionId === this.sessionId);\n }\n\n /** Every snapshot in the directory, whichever session wrote it. */\n async listAll(): Promise<Snapshot[]> {\n const dir = join(this.gitDir, 'snapshots');\n const names = await readdir(dir).catch(() => []);\n const snapshots: Snapshot[] = [];\n for (const name of names) {\n if (!name.endsWith('.json')) continue;\n const raw = await readFile(join(dir, name), 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n try {\n snapshots.push(JSON.parse(raw) as Snapshot);\n } catch {\n // A snapshot written during a crash; the rest are still usable.\n }\n }\n return snapshots.sort((a, b) => a.timestamp.localeCompare(b.timestamp));\n }\n\n /**\n * Reads a stored blob back. The output cap is raised well above the default,\n * which exists to stop a runaway tool from filling the context window - here it\n * would silently truncate the file being restored, which is data loss.\n */\n async contents(hash: string): Promise<string | undefined> {\n const result = await this.run(['cat-file', 'blob', hash], MAX_RESTORE_BYTES);\n return result.code === 0 ? result.stdout : undefined;\n }\n\n /**\n * Restores every file in a snapshot to its recorded contents. A file the batch\n * created is left in place rather than deleted - removing a path on the user's\n * behalf is not something an undo should do silently - and comes back in\n * `wasCreated` so the caller can say which files it did not touch.\n */\n async restore(snapshot: Snapshot): Promise<{ restored: string[]; wasCreated: string[] }> {\n const restored: string[] = [];\n const wasCreated: string[] = [];\n\n for (const file of snapshot.files) {\n if (file.before === null) {\n wasCreated.push(displayPath(this.cwd, file.path));\n continue;\n }\n const content = await this.contents(file.before);\n if (content === undefined) continue;\n await writeFile(file.path, content, 'utf8');\n restored.push(displayPath(this.cwd, file.path));\n }\n return { restored, wasCreated };\n }\n}\n",
64
+ "import { createHash, randomUUID } from 'node:crypto';\nimport { appendFile, mkdir, readdir, readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Message } from '@earshot/providers';\nimport { sessionsDir } from '@earshot/providers';\n\n/**\n * One line of a session transcript.\n *\n * Entries form a tree rather than a list: each carries its own `id` and the `id`\n * of the entry it follows. A linear session is the degenerate case where every\n * entry has exactly one child. `/fork` and `/rewind` then become navigation -\n * appending a new entry whose parent is somewhere other than the last entry -\n * rather than rewriting the file, which is what keeps the format append-only.\n */\nexport type SessionEntry =\n | {\n type: 'meta';\n id: string;\n parentId: string | null;\n timestamp: string;\n cwd: string;\n model: string;\n version: string;\n /** Set when this session continues another one. */\n forkedFrom?: { sessionId: string; entryId: string };\n }\n | {\n type: 'message';\n id: string;\n parentId: string | null;\n timestamp: string;\n message: Message;\n }\n | {\n type: 'summary';\n id: string;\n parentId: string | null;\n timestamp: string;\n /** Compaction writes a new entry rather than replacing what it summarises. */\n text: string;\n replaces: string[];\n };\n\n/** An entry as supplied by a caller; the store assigns id, parent and timestamp. */\nexport type NewEntry =\n | {\n type: 'meta';\n cwd: string;\n model: string;\n version: string;\n forkedFrom?: { sessionId: string; entryId: string };\n }\n | { type: 'message'; message: Message }\n | { type: 'summary'; text: string; replaces: string[] };\n\nexport interface SessionInfo {\n id: string;\n path: string;\n cwd: string;\n model: string;\n updatedAt: number;\n /** First user message, for showing the user which session is which. */\n preview: string;\n}\n\n/**\n * Sessions are grouped by a hash of the working directory so `--continue` finds\n * the last session for *this* project. The hash is truncated: it disambiguates\n * directories, and a full digest makes the path unreadable for no benefit.\n */\n/**\n * Session ids sort in creation order.\n *\n * A bare UUID does not, and file mtimes tie when two sessions are written in the\n * same millisecond - which makes `--continue` pick an arbitrary one of them. A\n * base36 timestamp plus a per-process counter gives a total order for sessions\n * started by one process, and the timestamp orders the rest.\n */\nlet created = 0;\n\nexport function newSessionId(): string {\n const stamp = Date.now().toString(36).padStart(9, '0');\n const seq = (created++ % 46_656).toString(36).padStart(3, '0');\n return `${stamp}${seq}-${randomUUID().slice(0, 8)}`;\n}\n\nexport function projectKey(cwd: string): string {\n return createHash('sha256').update(cwd).digest('hex').slice(0, 16);\n}\n\nexport function projectDir(cwd: string): string {\n return join(sessionsDir(), projectKey(cwd));\n}\n\n/**\n * Append-only JSONL writer. Every write is an `appendFile` of one line, so an\n * interrupted session leaves a truncated final line rather than a corrupt file,\n * and the reader drops exactly that line.\n */\nexport class SessionStore {\n /**\n * Ids of the message entries written so far, in order. Compaction needs them\n * to say which entries its summary stands in for, and only the store knows\n * the ids - the agent counts messages, not entries.\n */\n readonly messageIds: string[] = [];\n private tail: string | null = null;\n private queue: Promise<void> = Promise.resolve();\n\n private constructor(\n readonly id: string,\n readonly path: string,\n readonly cwd: string,\n ) {}\n\n static async create(\n cwd: string,\n meta: {\n model: string;\n version: string;\n forkedFrom?: { sessionId: string; entryId: string };\n },\n ): Promise<SessionStore> {\n const id = newSessionId();\n const dir = projectDir(cwd);\n await mkdir(dir, { recursive: true });\n\n const store = new SessionStore(id, join(dir, `${id}.jsonl`), cwd);\n await store.append({\n type: 'meta',\n cwd,\n model: meta.model,\n version: meta.version,\n ...(meta.forkedFrom ? { forkedFrom: meta.forkedFrom } : {}),\n });\n return store;\n }\n\n /** Reopens an existing session for appending, continuing from its last entry. */\n static async open(path: string): Promise<SessionStore> {\n const entries = await readEntries(path);\n const meta = entries.find((entry) => entry.type === 'meta');\n if (meta?.type !== 'meta') throw new Error(`${path} has no session header`);\n\n const id =\n path\n .split(/[/\\\\]/)\n .pop()\n ?.replace(/\\.jsonl$/, '') ?? randomUUID();\n const store = new SessionStore(id, path, meta.cwd);\n store.tail = entries.at(-1)?.id ?? null;\n return store;\n }\n\n /**\n * Appends one entry. Writes are serialised through a promise chain: two\n * concurrent appends could otherwise interleave partial lines, and both would\n * claim the same parent.\n */\n append(entry: NewEntry, parentId?: string | null): Promise<string> {\n const id = randomUUID();\n\n this.queue = this.queue.then(async () => {\n // The parent is read inside the queued task, not when append() was called.\n // Reading it eagerly would give every concurrent append the same parent, so\n // twenty writes would land as twenty siblings of one entry rather than as a\n // chain - and replaying the branch would recover only the last of them.\n const line = {\n ...entry,\n id,\n parentId: parentId !== undefined ? parentId : this.tail,\n timestamp: new Date().toISOString(),\n };\n await appendFile(this.path, `${JSON.stringify(line)}\\n`, 'utf8');\n this.tail = id;\n });\n return this.queue.then(() => id);\n }\n\n appendMessage(message: Message): Promise<string> {\n const id = this.append({ type: 'message', message });\n void id.then((value) => this.messageIds.push(value));\n return id;\n }\n\n /**\n * Points the next append at an earlier entry.\n *\n * This is all a rewind is at the storage layer: nothing is removed, and the\n * entries written after it become a second branch of the same file. The old\n * branch stays readable, which is what makes rewinding safe to do casually.\n */\n rewind(entryId: string): void {\n this.tail = entryId;\n }\n\n get tailId(): string | null {\n return this.tail;\n }\n\n /** Resolves once every queued write has landed. */\n flush(): Promise<void> {\n return this.queue;\n }\n}\n\n/**\n * Reads a transcript, skipping unparseable lines rather than failing.\n *\n * A truncated last line is the normal result of a session that was killed\n * mid-write, and refusing to open the file would lose the entire history over\n * one incomplete entry.\n */\nexport async function readEntries(path: string): Promise<SessionEntry[]> {\n const raw = await readFile(path, 'utf8');\n const entries: SessionEntry[] = [];\n for (const line of raw.split('\\n')) {\n if (line.trim() === '') continue;\n try {\n entries.push(JSON.parse(line) as SessionEntry);\n } catch {\n // A partial line: nothing after it can be read either, so stop here.\n break;\n }\n }\n return entries;\n}\n\n/**\n * Walks from `leaf` back to the root, so a forked session replays the branch it\n * actually descends from rather than every entry in the file.\n */\nexport function branchTo(entries: SessionEntry[], leafId?: string): SessionEntry[] {\n const byId = new Map(entries.map((entry) => [entry.id, entry]));\n let cursor = leafId ?? entries.at(-1)?.id;\n const branch: SessionEntry[] = [];\n const seen = new Set<string>();\n\n while (cursor !== undefined && cursor !== null) {\n const entry = byId.get(cursor);\n // A cycle can only come from a corrupted file, but walking one forever is a\n // hang rather than an error, so it is guarded explicitly.\n if (!entry || seen.has(entry.id)) break;\n seen.add(entry.id);\n branch.push(entry);\n cursor = entry.parentId ?? undefined;\n }\n return branch.reverse();\n}\n\n/** The messages of one branch, in order, ready to seed a resumed agent. */\nexport function messagesOf(entries: SessionEntry[]): Message[] {\n return entries\n .filter((entry): entry is SessionEntry & { type: 'message' } => entry.type === 'message')\n .map((entry) => entry.message);\n}\n\nexport async function listSessions(cwd: string): Promise<SessionInfo[]> {\n const dir = projectDir(cwd);\n const names = await readdir(dir).catch(() => []);\n const infos: SessionInfo[] = [];\n\n for (const name of names) {\n if (!name.endsWith('.jsonl')) continue;\n const path = join(dir, name);\n const [info, entries] = await Promise.all([\n stat(path).catch(() => undefined),\n readEntries(path).catch(() => []),\n ]);\n const meta = entries.find((entry) => entry.type === 'meta');\n if (!info || meta?.type !== 'meta') continue;\n\n infos.push({\n id: name.replace(/\\.jsonl$/, ''),\n path,\n cwd: meta.cwd,\n model: meta.model,\n updatedAt: info.mtimeMs,\n preview: firstUserText(entries),\n });\n }\n // Tie-broken by id, which encodes creation order, so two sessions written in\n // the same millisecond still resolve to a stable \"most recent\".\n return infos.sort((a, b) => b.updatedAt - a.updatedAt || b.id.localeCompare(a.id));\n}\n\nexport async function latestSession(cwd: string): Promise<SessionInfo | undefined> {\n return (await listSessions(cwd))[0];\n}\n\nfunction firstUserText(entries: SessionEntry[]): string {\n for (const entry of entries) {\n if (entry.type !== 'message' || entry.message.role !== 'user') continue;\n for (const part of entry.message.content) {\n if (part.type === 'text' && part.text.trim() !== '') {\n return part.text.split('\\n')[0]?.slice(0, 120) ?? '';\n }\n }\n }\n return '(no prompt)';\n}\n",
65
+ "/** Kept in its own module so anything can read it without importing the barrel. */\nexport const VERSION = '0.1.0';\n",
66
+ "import type { Message, ToolCallPart, ToolResultPart } from '@earshot/providers';\n\n/**\n * Repairing a transcript that a crash left mid-turn.\n *\n * The loop already covers the interruptions it can see: `runCalls` fills every\n * empty slot with an error result before the tool message is appended, so an\n * abort - Ctrl-C, a budget stop, a failed step - never reaches disk half-written.\n * What it cannot cover is the process not surviving to do that. Messages are\n * persisted as they are produced, so between the assistant message carrying the\n * tool calls and the tool message carrying their results there is a window in\n * which a SIGKILL, a power loss or an OOM leaves calls with no answer.\n *\n * That file is not corrupt and reads back fine. It is invalid as a *request*:\n * every tool call must have a result part or the next call fails at the\n * provider, so `--resume` on such a session breaks on the first turn, before\n * the user has done anything. Repair closes that.\n *\n * The repair is an append. History is append-only because Anthropic rejects\n * edited thinking blocks, and because a transcript that rewrites itself cannot\n * be trusted as a record of what happened - so the results synthesised here go\n * into a new entry with a normal parent, visible in `/tree` like any other. The\n * abandoned turn stays on disk exactly as the crash left it.\n */\nconst REPAIR_TEXT =\n 'No result was recorded for this call: earshot exited before the tool finished. ' +\n 'The call may or may not have run, so treat its effect as unknown and check ' +\n 'the current state rather than assuming either outcome.';\n\n/**\n * Tool calls in `messages` that no later message answers.\n *\n * The whole branch is scanned rather than only its last pair, because a result\n * may legitimately arrive in a message well after the call - and because a\n * session resumed twice must not re-repair calls the first repair answered.\n */\nexport function unresolvedToolCalls(messages: Message[]): ToolCallPart[] {\n const answered = new Set<string>();\n const calls: ToolCallPart[] = [];\n\n for (const message of messages) {\n for (const part of message.content) {\n if (part.type === 'tool_call') calls.push(part);\n else if (part.type === 'tool_result') answered.add(part.toolCallId);\n }\n }\n return calls.filter((call) => !answered.has(call.toolCallId));\n}\n\n/**\n * The message that answers `calls`, in the order they were emitted.\n *\n * Results are marked `isError` and say what is not known rather than claiming\n * the call failed: a process killed after a `write` completed leaves the file\n * written, and a repair that reported \"this did not run\" would be a lie the\n * model would then act on.\n */\nexport function repairMessage(calls: ToolCallPart[]): Message {\n const content: ToolResultPart[] = calls.map((call) => ({\n type: 'tool_result',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n output: { type: 'text', value: REPAIR_TEXT },\n isError: true,\n }));\n return { role: 'tool', content };\n}\n",
67
+ "import { buildRegistry, type ProviderRegistry } from '@earshot/providers';\nimport { Agent, type AgentOptions } from '../agent.ts';\nimport { buildSystemPrompt, type Curiosity } from '../context/system-prompt.ts';\nimport { loadHooks } from '../hooks/config.ts';\nimport { HookRunner } from '../hooks/runner.ts';\nimport { resolveModel } from '../model.ts';\nimport type { PermissionMode, PermissionPrompt } from '../permissions/engine.ts';\nimport { loadSettings } from '../permissions/settings.ts';\nimport {\n discoverExtensions,\n renderSkillIndex,\n type Skill,\n type SlashCommand,\n} from '../skills/discover.ts';\nimport { BUILTIN_TOOLS } from '../tools/index.ts';\nimport { skillTool } from '../tools/skill.ts';\nimport type { Tool } from '../tools/types.ts';\nimport { ShadowGit } from '../undo/shadow-git.ts';\nimport { VERSION } from '../version.ts';\nimport { repairMessage, unresolvedToolCalls } from './repair.ts';\nimport {\n branchTo,\n latestSession,\n messagesOf,\n readEntries,\n type SessionEntry,\n SessionStore,\n} from './store.ts';\n\nexport interface CreateSessionOptions {\n cwd: string;\n /** Model reference; falls back to the configured default. */\n model: string;\n mode?: PermissionMode;\n apiKey?: string;\n registry?: ProviderRegistry;\n prompt?: PermissionPrompt;\n ask?: (question: string, options?: string[]) => Promise<string>;\n /** Resume a specific transcript, or the most recent one for this directory. */\n resume?: { path: string } | { latest: true };\n /** Skips session persistence entirely, for one-shot runs. */\n ephemeral?: boolean;\n /** Disables undo snapshots. */\n noUndo?: boolean;\n maxSteps?: number;\n /** Overrides `curiosity` in settings. */\n curiosity?: Curiosity;\n /** Overrides `maxCostUsd` in settings. Zero or less removes the budget. */\n maxCostUsd?: number;\n /** Asked when the budget is reached; returns a higher limit, or stops. */\n confirmBudget?: (spentUsd: number, limitUsd: number) => Promise<number | undefined>;\n /**\n * Tools contributed from outside core - MCP servers today, subagents next.\n * They are appended to the built-ins and go through the same gate: core knows\n * nothing about where they came from, which is what keeps `packages/mcp`\n * depending on core rather than the other way round.\n */\n extraTools?: Tool<never>[];\n /** Additional problems to surface before the first turn, e.g. a server that failed. */\n problems?: string[];\n /** Torn down with the session, so a spawned server does not outlive it. */\n onDispose?: () => Promise<void> | void;\n /** Skips skill and slash-command discovery, for tests and one-shot runs. */\n noExtensions?: boolean;\n}\n\nexport interface CreatedSession {\n agent: Agent;\n store?: SessionStore;\n /** Settings problems worth showing the user before the first turn. */\n problems: string[];\n /** Number of messages replayed from a resumed transcript. */\n resumed: number;\n /** Discovered skills, for `/skills` and for explaining what is loaded. */\n skills: Skill[];\n /** User-defined slash commands, expanded into prompts by the TUI. */\n commands: SlashCommand[];\n /** Installs the approval callback; the TUI can only build one after it mounts. */\n installPrompt(prompt: PermissionPrompt): void;\n installAsk(ask: (question: string, options?: string[]) => Promise<string>): void;\n /** The current branch of the transcript, oldest first. */\n branch(): Promise<SessionEntry[]>;\n /**\n * Moves the session back to an earlier entry. Nothing is deleted: later\n * entries stay in the file as an abandoned branch.\n */\n rewindTo(entryId: string): Promise<number>;\n /** Continues in a new transcript that records where it branched from. */\n fork(entryId?: string): Promise<string | undefined>;\n /**\n * Reverts the most recent tool batch's file changes. Calling it again steps\n * back another batch; a file the batch created is reported rather than\n * deleted.\n */\n undo(): Promise<{ label: string; restored: string[]; wasCreated: string[] } | undefined>;\n dispose(): Promise<void>;\n}\n\nexport class NoSessionToResumeError extends Error {\n constructor(cwd: string) {\n super(`no previous session for ${cwd}`);\n this.name = 'NoSessionToResumeError';\n }\n}\n\n/**\n * One place that turns flags into a running agent, so the TUI and the headless\n * command cannot drift on which settings are honoured. Everything optional here\n * degrades rather than failing: a missing git binary means no undo, and an\n * unwritable data directory means no transcript, but the turn still runs.\n */\nexport async function createSession(options: CreateSessionOptions): Promise<CreatedSession> {\n const registry = options.registry ?? buildRegistry();\n const settings = await loadSettings(options.cwd);\n const mode = options.mode ?? settings.defaultMode ?? 'ask';\n const curiosity = options.curiosity ?? settings.curiosity ?? 'normal';\n // A flag of zero or less is how the CLI says \"no budget\", which has to beat a\n // settings file that sets one, or a limit would be impossible to turn off.\n const maxCostUsd =\n options.maxCostUsd !== undefined\n ? options.maxCostUsd > 0\n ? options.maxCostUsd\n : undefined\n : settings.maxCostUsd;\n\n const resolved = await resolveModel(registry, options.model, {\n ...(options.apiKey ? { apiKey: options.apiKey } : {}),\n });\n const modelRef = `${resolved.provider.id}/${resolved.model.id}`;\n\n const discovered = options.noExtensions\n ? { skills: [], commands: [], problems: [] }\n : await discoverExtensions(options.cwd);\n\n let store: SessionStore | undefined;\n let replayed: ReturnType<typeof messagesOf> = [];\n const repairProblems: string[] = [];\n\n if (!options.ephemeral) {\n const resumePath = await resolveResumePath(options);\n if (resumePath) {\n const entries = await readEntries(resumePath);\n // Only the branch the transcript actually ends on: a session that was\n // rewound has entries that are no longer part of its history.\n replayed = messagesOf(branchTo(entries));\n store = await SessionStore.open(resumePath).catch(() => undefined);\n\n // A crash between the assistant message and its tool results leaves calls\n // with no answer, which the provider rejects on the next request - so the\n // resumed session would fail before the user typed anything. The results\n // are appended as a new entry; nothing already written is touched.\n const orphaned = unresolvedToolCalls(replayed);\n if (orphaned.length > 0) {\n const repair = repairMessage(orphaned);\n replayed = [...replayed, repair];\n if (store) await store.appendMessage(repair);\n repairProblems.push(\n `repaired an interrupted turn: ${orphaned.length} tool ` +\n `${orphaned.length === 1 ? 'call' : 'calls'} ` +\n `(${orphaned.map((call) => call.toolName).join(', ')}) had no recorded result`,\n );\n }\n }\n store ??= await SessionStore.create(options.cwd, {\n model: modelRef,\n version: VERSION,\n }).catch(() => undefined);\n }\n\n const loadedHooks = options.noExtensions\n ? { hooks: [], problems: [] }\n : await loadHooks(options.cwd);\n const hooks = new HookRunner(loadedHooks.hooks, {\n cwd: options.cwd,\n env: process.env,\n sessionId: store?.id ?? 'ephemeral',\n ...(store ? { transcriptPath: store.path } : {}),\n });\n\n // Built after the session id exists, because a SessionStart hook is told which\n // session it is running for, and its context goes into the prompt it starts.\n const started = hooks.has('SessionStart') ? await hooks.sessionStart() : undefined;\n const system = await buildSystemPrompt({\n cwd: options.cwd,\n mode,\n curiosity,\n model: modelRef,\n skills: renderSkillIndex(discovered.skills),\n ...(started?.context.length\n ? { extra: `<session-start>\\n${started.context.join('\\n\\n')}\\n</session-start>` }\n : {}),\n });\n\n // Scoped to this session: the store is shared by every session in the\n // directory, and an unscoped `/undo` reached into batches the user never saw\n // this session make. An ephemeral run has no id and so has no undo history.\n const shadow = options.noUndo\n ? undefined\n : await ShadowGit.open(options.cwd, store?.id).catch(() => undefined);\n\n // The skill tool only exists when there is something to load: a tool whose\n // every argument is invalid is one the model wastes a call discovering.\n const sessionTools: Tool<never>[] = [\n ...(BUILTIN_TOOLS as Tool<never>[]),\n ...(discovered.skills.length ? [skillTool(discovered.skills) as unknown as Tool<never>] : []),\n ...(options.extraTools ?? []),\n ];\n\n const agentOptions: AgentOptions = {\n registry,\n model: resolved,\n cwd: options.cwd,\n system,\n mode,\n rules: settings.rules,\n ...(options.prompt ? { prompt: options.prompt } : {}),\n ...(options.ask ? { ask: options.ask } : {}),\n ...(options.maxSteps !== undefined ? { maxSteps: options.maxSteps } : {}),\n ...(maxCostUsd !== undefined ? { maxCostUsd } : {}),\n ...(options.confirmBudget ? { confirmBudget: options.confirmBudget } : {}),\n ...(sessionTools.length > BUILTIN_TOOLS.length ? { tools: sessionTools } : {}),\n ...(hooks.isEmpty ? {} : { hooks }),\n ...(shadow ? { shadow } : {}),\n ...(store ? { onMessage: (message) => void store?.appendMessage(message) } : {}),\n ...(store\n ? {\n // Appended, never substituted for what it summarises: the transcript\n // on disk stays complete, so a resumed session can replay the real\n // messages rather than a recollection of them.\n onCompaction: (summary: string, historyCut: number) => {\n void store?.append({\n type: 'summary',\n text: summary,\n replaces: store?.messageIds.slice(0, historyCut) ?? [],\n });\n },\n }\n : {}),\n };\n\n const agent = new Agent(agentOptions);\n // Replayed messages are pushed straight onto history rather than re-appended\n // through the store: they are already in the transcript, and writing them back\n // would duplicate every entry on each resume.\n agent.history.push(...replayed);\n\n const undone = new Set<string>();\n\n const branch = async (): Promise<SessionEntry[]> => {\n if (!store) return [];\n await store.flush();\n return branchTo(await readEntries(store.path), store.tailId ?? undefined);\n };\n\n return {\n agent,\n ...(store ? { store } : {}),\n problems: [\n ...settings.problems,\n ...discovered.problems,\n ...loadedHooks.problems,\n ...(started?.problems ?? []),\n ...repairProblems,\n ...(options.problems ?? []),\n ],\n resumed: replayed.length,\n skills: discovered.skills,\n commands: discovered.commands,\n installPrompt: (prompt) => agent.setPrompt(prompt),\n installAsk: (ask) => agent.setAsk(ask),\n branch,\n async rewindTo(entryId) {\n if (!store) return 0;\n await store.flush();\n const entries = await readEntries(store.path);\n const kept = messagesOf(branchTo(entries, entryId));\n store.rewind(entryId);\n agent.replaceHistory(kept);\n return kept.length;\n },\n async fork(entryId) {\n if (!store) return undefined;\n await store.flush();\n const from = entryId ?? store.tailId;\n const entries = await readEntries(store.path);\n const forked = await SessionStore.create(options.cwd, {\n model: modelRef,\n version: VERSION,\n ...(from ? { forkedFrom: { sessionId: store.id, entryId: from } } : {}),\n }).catch(() => undefined);\n if (!forked) return undefined;\n\n // The branch is replayed into the new file rather than referenced across\n // it: a transcript that cannot be read on its own is one that breaks as\n // soon as the file it points at is deleted.\n const kept = messagesOf(branchTo(entries, from ?? undefined));\n for (const message of kept) await forked.appendMessage(message);\n agent.replaceHistory(kept);\n store = forked;\n return forked.id;\n },\n async undo() {\n if (!shadow) return undefined;\n // Snapshots are not consumed by restoring them, so the ones already used\n // are tracked here; without this, a second /undo replays the first.\n const snapshots = (await shadow.list()).filter((snapshot) => !undone.has(snapshot.id));\n const last = snapshots.at(-1);\n if (!last) return undefined;\n undone.add(last.id);\n const { restored, wasCreated } = await shadow.restore(last);\n return { label: last.label, restored, wasCreated };\n },\n async dispose() {\n agent.dispose();\n // Best effort: a SessionEnd hook that fails must not stop the session from\n // closing, and nothing can act on its answer by this point anyway.\n if (hooks.has('SessionEnd')) await hooks.sessionEnd().catch(() => undefined);\n await store?.flush();\n await options.onDispose?.();\n },\n };\n}\n\n/**\n * Rebuilds the system prompt from what is currently on disk.\n *\n * Called after a memory is captured or deleted, so a preference takes effect on\n * the next model call rather than the next session.\n */\nexport async function refreshSystemPrompt(\n agent: Agent,\n model: string,\n skills: Skill[] = [],\n): Promise<void> {\n agent.setSystem(\n await buildSystemPrompt({\n cwd: agent.cwd,\n mode: agent.permissionMode,\n model,\n // Rebuilt from the same list rather than re-discovered: a skill added mid\n // session is not loaded until the next one, and a prompt that silently\n // gained an entry would be harder to explain than one that did not.\n skills: renderSkillIndex(skills),\n }),\n );\n}\n\nasync function resolveResumePath(options: CreateSessionOptions): Promise<string | undefined> {\n const { resume } = options;\n if (!resume) return undefined;\n if ('path' in resume) return resume.path;\n\n const latest = await latestSession(options.cwd);\n if (!latest) throw new NoSessionToResumeError(options.cwd);\n return latest.path;\n}\n",
68
+ "export interface ParsedArgs {\n command: string | undefined;\n flags: Record<string, string | boolean>;\n positionals: string[];\n}\n\n/** Minimal, dependency-free flag parsing: --key=value, --key value, --bool, -p. */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const flags: Record<string, string | boolean> = {};\n const positionals: string[] = [];\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i] as string;\n if (arg === '--') {\n positionals.push(...argv.slice(i + 1));\n break;\n }\n if (arg.startsWith('--')) {\n const eq = arg.indexOf('=');\n if (eq !== -1) {\n flags[arg.slice(2, eq)] = arg.slice(eq + 1);\n } else {\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith('-')) {\n flags[arg.slice(2)] = next;\n i++;\n } else {\n flags[arg.slice(2)] = true;\n }\n }\n } else if (arg.startsWith('-') && arg.length > 1) {\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith('-')) {\n flags[arg.slice(1)] = next;\n i++;\n } else {\n flags[arg.slice(1)] = true;\n }\n } else {\n positionals.push(arg);\n }\n }\n\n const known = new Set(['auth', 'mcp', 'extensions', 'config', 'models', 'acp', 'doctor']);\n const command =\n positionals[0] !== undefined && known.has(positionals[0]) ? positionals[0] : undefined;\n return { command, flags, positionals: command ? positionals.slice(1) : positionals };\n}\n",
69
+ "import type * as acp from '@agentclientprotocol/sdk';\nimport type { AgentEvent } from '@earshot/core';\n\nexport function updateFromEvent(\n event: AgentEvent,\n context: { tokens: number; window: number; costUsd: number },\n): acp.SessionUpdate | undefined {\n switch (event.type) {\n case 'text_delta':\n return {\n sessionUpdate: 'agent_message_chunk',\n content: { type: 'text', text: event.text },\n };\n case 'reasoning_delta':\n return {\n sessionUpdate: 'agent_thought_chunk',\n content: { type: 'text', text: event.text },\n };\n case 'tool_start':\n return {\n sessionUpdate: 'tool_call',\n toolCallId: event.call.toolCallId,\n title: event.call.toolName,\n kind: toolKind(event.call.toolName),\n status: 'in_progress',\n rawInput: event.call.input,\n };\n case 'tool_end':\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: event.toolCallId,\n status: event.result.isError ? 'failed' : 'completed',\n rawOutput: outputValue(event.result.output),\n content: [{ type: 'content', content: contentOf(event.result.output) }],\n };\n case 'usage':\n return {\n sessionUpdate: 'usage_update',\n used: context.tokens,\n size: context.window,\n cost: { amount: context.costUsd, currency: 'USD' },\n };\n default:\n return undefined;\n }\n}\n\nfunction toolKind(name: string): acp.ToolKind {\n if (name === 'read' || name === 'ls') return 'read';\n if (name === 'write' || name === 'edit' || name === 'multi_edit') return 'edit';\n if (name === 'grep' || name === 'glob') return 'search';\n if (name === 'bash' || name === 'bash_output') return 'execute';\n if (name === 'web_fetch') return 'fetch';\n if (name === 'todo' || name === 'declare_scope') return 'think';\n return 'other';\n}\n\nfunction outputValue(output: { type: string; value: unknown }): unknown {\n return output.value;\n}\n\nfunction contentOf(output: { type: string; value: unknown }): acp.ContentBlock {\n if (output.type === 'text') return { type: 'text', text: String(output.value) };\n return { type: 'text', text: JSON.stringify(output.value) ?? String(output.value) };\n}\n",
70
+ "import { randomUUID } from 'node:crypto';\nimport { isAbsolute } from 'node:path';\nimport { Readable, Writable } from 'node:stream';\nimport * as acp from '@agentclientprotocol/sdk';\nimport {\n type CreatedSession,\n createSession,\n listSessions,\n type PermissionMode,\n type PromptChoice,\n VERSION,\n} from '@earshot/core';\nimport { updateFromEvent } from './events.ts';\n\nexport interface AcpSessionRequest {\n cwd: string;\n resumeSessionId?: string;\n}\n\nexport type AcpSessionFactory = (request: AcpSessionRequest) => Promise<CreatedSession>;\n\nexport interface AcpServerOptions {\n model: string;\n mode?: PermissionMode;\n apiKey?: string;\n sessionFactory?: AcpSessionFactory;\n}\n\ninterface ActiveSession {\n session: CreatedSession;\n controller?: AbortController;\n activeToolCallId?: string;\n}\n\nexport function createAcpApp(options: AcpServerOptions): acp.AgentApp {\n const sessions = new Map<string, ActiveSession>();\n const factory = options.sessionFactory ?? defaultSessionFactory(options);\n\n const app = acp\n .agent({ name: 'earshot' })\n .onRequest(acp.methods.agent.initialize, () => ({\n protocolVersion: acp.PROTOCOL_VERSION,\n agentCapabilities: { loadSession: true, promptCapabilities: { image: true } },\n agentInfo: { name: 'earshot', version: VERSION },\n }))\n .onRequest(acp.methods.agent.session.new, async (ctx) => {\n assertWorkspace(ctx.params.cwd);\n rejectClientMcp(ctx.params.mcpServers);\n const session = await factory({ cwd: ctx.params.cwd });\n const id = session.store?.id ?? randomUUID();\n const active: ActiveSession = { session };\n installClientRequests(active, id, ctx.client);\n sessions.set(id, active);\n return { sessionId: id };\n })\n .onRequest(acp.methods.agent.session.load, async (ctx) => {\n assertWorkspace(ctx.params.cwd);\n rejectClientMcp(ctx.params.mcpServers);\n await sessions.get(ctx.params.sessionId)?.session.dispose();\n const session = await factory({\n cwd: ctx.params.cwd,\n resumeSessionId: ctx.params.sessionId,\n });\n const active: ActiveSession = { session };\n installClientRequests(active, ctx.params.sessionId, ctx.client);\n sessions.set(ctx.params.sessionId, active);\n await replayHistory(ctx.params.sessionId, session, ctx.client);\n return {};\n })\n .onRequest(acp.methods.agent.session.prompt, async (ctx) => {\n const active = sessions.get(ctx.params.sessionId);\n if (!active) throw new Error(`unknown ACP session \"${ctx.params.sessionId}\"`);\n\n active.controller?.abort();\n const controller = new AbortController();\n active.controller = controller;\n let stopReason: acp.StopReason = 'end_turn';\n let failure: Error | undefined;\n\n try {\n for await (const event of active.session.agent.runTurn(\n promptText(ctx.params.prompt),\n controller.signal,\n )) {\n if (event.type === 'tool_start') active.activeToolCallId = event.call.toolCallId;\n if (event.type === 'turn_end') stopReason = stopReasonOf(event.reason);\n if (event.type === 'error') failure = new Error(event.error.message);\n const update = updateFromEvent(event, {\n tokens: active.session.agent.contextUse.tokens,\n window: active.session.agent.contextUse.window,\n costUsd: active.session.agent.costUsd,\n });\n if (update) {\n await ctx.client.notify(acp.methods.client.session.update, {\n sessionId: ctx.params.sessionId,\n update,\n });\n }\n }\n } finally {\n if (active.controller === controller) delete active.controller;\n }\n if (failure) throw failure;\n return { stopReason: controller.signal.aborted ? 'cancelled' : stopReason };\n })\n .onNotification(acp.methods.agent.session.cancel, (ctx) => {\n sessions.get(ctx.params.sessionId)?.controller?.abort();\n });\n\n app.onConnect((connection) => {\n void connection.closed.finally(async () => {\n await Promise.all([...sessions.values()].map(({ session }) => session.dispose()));\n sessions.clear();\n });\n });\n return app;\n}\n\n/** Serves one ACP connection over the process-style NDJSON transport. */\nexport async function runAcpServer(\n options: AcpServerOptions,\n input: NodeJS.ReadableStream = process.stdin,\n output: NodeJS.WritableStream = process.stdout,\n): Promise<void> {\n const stream = acp.ndJsonStream(\n Writable.toWeb(output as NodeJS.WritableStream & import('node:stream').Writable),\n Readable.toWeb(input as NodeJS.ReadableStream & import('node:stream').Readable),\n );\n const connection = createAcpApp(options).connect(stream);\n await connection.closed;\n}\n\nfunction defaultSessionFactory(options: AcpServerOptions): AcpSessionFactory {\n return async ({ cwd, resumeSessionId }) => {\n let resume: { path: string } | undefined;\n if (resumeSessionId) {\n const found = (await listSessions(cwd)).find((session) => session.id === resumeSessionId);\n if (!found) throw new Error(`no session \"${resumeSessionId}\" for ${cwd}`);\n resume = { path: found.path };\n }\n return createSession({\n cwd,\n model: options.model,\n ...(options.mode ? { mode: options.mode } : {}),\n ...(options.apiKey ? { apiKey: options.apiKey } : {}),\n ...(resume ? { resume } : {}),\n });\n };\n}\n\nfunction installClientRequests(\n active: ActiveSession,\n sessionId: string,\n client: acp.AgentContext,\n): void {\n active.session.installPrompt(async (request, reason) => {\n const response = await client.request(\n acp.methods.client.session.requestPermission,\n {\n sessionId,\n toolCall: {\n toolCallId: active.activeToolCallId ?? `permission-${randomUUID()}`,\n title: request.title,\n status: 'pending',\n rawInput: {\n tool: request.tool,\n target: request.target,\n reason,\n detail: request.detail,\n },\n },\n options: [\n { optionId: 'allow_once', name: 'Allow once', kind: 'allow_once' },\n { optionId: 'allow_always', name: 'Always allow this action', kind: 'allow_always' },\n { optionId: 'reject_once', name: 'Reject', kind: 'reject_once' },\n ],\n },\n active.controller ? { cancellationSignal: active.controller.signal } : {},\n );\n if (response.outcome.outcome === 'cancelled') return { kind: 'deny', message: 'cancelled' };\n return promptChoice(response.outcome.optionId);\n });\n\n active.session.installAsk(async (question, options) => {\n const property = {\n type: 'string',\n title: question,\n ...(options?.length ? { enum: options } : {}),\n } as const;\n const response = await client.request(\n acp.methods.client.elicitation.create,\n {\n mode: 'form',\n sessionId,\n message: question,\n requestedSchema: {\n type: 'object',\n properties: { answer: property },\n required: ['answer'],\n },\n },\n active.controller ? { cancellationSignal: active.controller.signal } : {},\n );\n if (response.action !== 'accept') return 'The user declined to answer.';\n const content = response.content as Record<string, unknown> | null | undefined;\n return String(content?.answer ?? '');\n });\n}\n\nfunction promptChoice(optionId: string): PromptChoice {\n if (optionId === 'allow_once') return { kind: 'allow-once' };\n if (optionId === 'allow_always') return { kind: 'allow-always', scope: 'session' };\n return { kind: 'deny' };\n}\n\nfunction promptText(blocks: acp.ContentBlock[]): import('@earshot/core').UserPromptPart[] {\n return blocks.map((block) => {\n if (block.type === 'text') return { type: 'text' as const, text: block.text };\n if (block.type === 'image') {\n return { type: 'image' as const, data: block.data, mediaType: block.mimeType };\n }\n if (block.type === 'resource_link') {\n return { type: 'text' as const, text: `[${block.name}](${block.uri})` };\n }\n throw new Error(`ACP prompt content \"${block.type}\" is not supported yet`);\n });\n}\n\nasync function replayHistory(\n sessionId: string,\n session: CreatedSession,\n client: acp.AgentContext,\n): Promise<void> {\n for (const message of session.agent.history) {\n if (message.role !== 'user' && message.role !== 'assistant') continue;\n for (const part of message.content) {\n if (part.type !== 'text') continue;\n await client.notify(acp.methods.client.session.update, {\n sessionId,\n update: {\n sessionUpdate: message.role === 'user' ? 'user_message_chunk' : 'agent_message_chunk',\n content: { type: 'text', text: part.text },\n },\n });\n }\n }\n}\n\nfunction stopReasonOf(\n reason: 'stop' | 'aborted' | 'max_steps' | 'error' | 'budget',\n): acp.StopReason {\n if (reason === 'aborted') return 'cancelled';\n if (reason === 'max_steps') return 'max_turn_requests';\n // A budget stop is a configured limit, not the model declining: `refusal`\n // would tell the editor the wrong thing about who stopped and why.\n if (reason === 'budget') return 'max_turn_requests';\n return 'end_turn';\n}\n\nfunction assertWorkspace(cwd: string): void {\n if (!isAbsolute(cwd)) throw new Error(`ACP session cwd must be absolute: ${cwd}`);\n}\n\nfunction rejectClientMcp(servers: acp.McpServer[]): void {\n if (servers.length > 0) {\n // A RequestError rather than a plain Error: the JSON-RPC layer reports an\n // unrecognised throw as \"Internal error\" with no message, and a client told\n // only that would have no way to learn its servers were not taken - which is\n // the silent-ignore this rejection exists to avoid.\n throw acp.RequestError.invalidParams(\n undefined,\n 'client-provided MCP servers are not supported; configure them in earshot',\n );\n }\n}\n",
71
+ "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Tool } from '@earshot/core';\nimport { LOCAL_SETTINGS, McpManager } from '@earshot/mcp';\nimport { EXTENSION_TRUST_NOTE, loadExtensions } from './modules.ts';\n\nexport * from './modules.ts';\n\n/**\n * Above this many MCP tools, their schemas stop being offered in every request\n * and are found with `tool_search` instead. Under it, listing them outright is\n * cheaper than making the model search: one round trip beats two.\n */\nexport const TOOL_SEARCH_THRESHOLD = 25;\n\nexport interface Extensions {\n tools: Tool<never>[];\n /** Lines worth showing before the first turn: a server that failed, a bad config. */\n problems: string[];\n /** One line per configured server, shown on request rather than at every start. */\n summary: string[];\n close(): Promise<void>;\n}\n\n/**\n * Everything outside core that contributes tools to a session.\n *\n * Assembled in the CLI rather than in core: core must not know that MCP exists,\n * or the dependency arrow between the two packages reverses. A failure here is\n * reported and the session still starts - a broken server config should cost the\n * user that server, not their agent.\n */\nexport async function startExtensions(cwd: string): Promise<Extensions> {\n const local = await loadLocalExtensions(cwd);\n const manager = await McpManager.start({ cwd }).catch((error: Error) => {\n return { error } as const;\n });\n\n if ('error' in manager) {\n return {\n tools: local.tools,\n problems: [...local.problems, `mcp servers could not be started: ${manager.error.message}`],\n summary: local.summary,\n close: async () => {},\n };\n }\n\n const failures = manager.reports\n .filter((report) => report.status !== 'ready')\n .map((report) => `mcp server \"${report.name}\" ${report.detail ?? 'did not start'}`);\n\n const mcpTools = manager.tools();\n const deferred = mcpTools.length > TOOL_SEARCH_THRESHOLD;\n\n return {\n tools: [\n ...local.tools,\n ...(deferred ? mcpTools.map((tool) => ({ ...tool, deferred: true })) : mcpTools),\n ],\n problems: [...local.problems, ...manager.problems, ...failures],\n summary: [\n ...local.summary,\n ...manager.summary(),\n ...(deferred\n ? [`${mcpTools.length} mcp tools: found with tool_search rather than listed in full`]\n : []),\n ],\n close: () => manager.close(),\n };\n}\n\n/**\n * In-process extensions, kept separate from MCP tools: they are never deferred\n * behind `tool_search`. A user who wrote a tool into their own config directory\n * expects the model to see it, and there are never a hundred of them.\n */\nasync function loadLocalExtensions(\n cwd: string,\n): Promise<{ tools: Tool<never>[]; problems: string[]; summary: string[] }> {\n const { tools, reports } = await loadExtensions(cwd, await trustedExtensions(cwd));\n return {\n tools,\n problems: reports\n .filter((report) => report.status === 'failed')\n .map((report) => `extension \"${report.name}\" failed to load: ${report.detail ?? 'unknown'}`),\n summary: reports.map((report) => {\n if (report.status === 'untrusted') return `${report.name}: ${EXTENSION_TRUST_NOTE}`;\n if (report.status === 'failed') return `${report.name}: ${report.detail ?? 'failed'}`;\n return `${report.name}: ${report.toolCount} tool${report.toolCount === 1 ? '' : 's'}`;\n }),\n };\n}\n\nexport async function trustedExtensions(cwd: string): Promise<Set<string>> {\n const raw = await readFile(join(cwd, LOCAL_SETTINGS), 'utf8').catch(() => '{}');\n try {\n const parsed = JSON.parse(raw) as { extensionTrust?: unknown };\n return new Set(\n Array.isArray(parsed.extensionTrust)\n ? parsed.extensionTrust.filter((name): name is string => typeof name === 'string')\n : [],\n );\n } catch {\n return new Set();\n }\n}\n",
72
+ "import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { ServerConfig } from './config.ts';\n\nexport interface McpToolDescriptor {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nexport interface McpCallResult {\n text: string;\n isError: boolean;\n}\n\n/**\n * What the rest of earshot needs from a server. An interface rather than the\n * SDK's `Client` so the manager, the tool bridge and the permission path can be\n * tested against a server that hangs, dies or floods without spawning one.\n */\nexport interface McpClient {\n readonly name: string;\n listTools(signal?: AbortSignal): Promise<McpToolDescriptor[]>;\n callTool(tool: string, args: unknown, signal: AbortSignal): Promise<McpCallResult>;\n close(): Promise<void>;\n /** Recent stderr, for explaining a server that failed rather than guessing. */\n diagnostics(): string;\n}\n\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 30_000;\nexport const DEFAULT_CALL_TIMEOUT_MS = 60_000;\n/**\n * A server can return as much text as it likes, and a large one would blow the\n * context window before the shapers ever see it. Capped here, at the boundary,\n * with the middle dropped rather than the tail: the end of a result is usually\n * where the answer is.\n */\nexport const MAX_RESULT_CHARS = 40_000;\nconst STDERR_KEEP_CHARS = 4_000;\n\nexport interface ConnectOptions {\n connectTimeoutMs?: number;\n callTimeoutMs?: number;\n cwd: string;\n env: NodeJS.ProcessEnv;\n}\n\n/** Thrown when a server cannot be reached at all; the manager reports and skips it. */\nexport class McpConnectError extends Error {\n constructor(\n readonly server: string,\n message: string,\n ) {\n super(`mcp server \"${server}\" failed to start: ${message}`);\n this.name = 'McpConnectError';\n }\n}\n\nclass SdkClient implements McpClient {\n private closed = false;\n private stderr = '';\n\n constructor(\n readonly name: string,\n private readonly client: Client,\n private readonly callTimeoutMs: number,\n private readonly onStderr: (chunk: string) => void = () => {},\n ) {}\n\n record(chunk: string): void {\n this.stderr = `${this.stderr}${chunk}`.slice(-STDERR_KEEP_CHARS);\n this.onStderr(chunk);\n }\n\n diagnostics(): string {\n return this.stderr.trim();\n }\n\n async listTools(signal?: AbortSignal): Promise<McpToolDescriptor[]> {\n const result = await this.client.listTools(\n {},\n { timeout: this.callTimeoutMs, ...(signal ? { signal } : {}) },\n );\n return result.tools.map((tool) => ({\n name: tool.name,\n description: tool.description ?? '',\n inputSchema: (tool.inputSchema ?? { type: 'object' }) as Record<string, unknown>,\n }));\n }\n\n /**\n * A call never throws: a dead server, a timeout and a tool that reports its\n * own failure are all data the model reads and reacts to, exactly like a\n * failing built-in tool.\n */\n async callTool(tool: string, args: unknown, signal: AbortSignal): Promise<McpCallResult> {\n if (this.closed) {\n const why = this.diagnostics();\n return {\n isError: true,\n text:\n `the \"${this.name}\" server is no longer running, so ${tool} cannot be called` +\n (why ? `. Its last output was:\\n${why}` : '. Tell the user it needs restarting.'),\n };\n }\n try {\n const result = await this.client.callTool(\n { name: tool, arguments: asArguments(args) },\n undefined,\n { timeout: this.callTimeoutMs, signal },\n );\n return {\n text: renderContent(result.content),\n isError: result.isError === true,\n };\n } catch (error) {\n return { isError: true, text: describeFailure(this.name, tool, error, this.diagnostics()) };\n }\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n await this.client.close().catch(() => undefined);\n }\n\n markClosed(): void {\n this.closed = true;\n }\n}\n\n/**\n * Wraps an already-connected SDK client. Separate from `connectServer` so a test\n * can drive the same wrapper over an in-memory transport - the hang, the crash\n * and the flood are the cases worth testing, and none of them need a process.\n */\nexport function fromClient(name: string, client: Client, callTimeoutMs: number): McpClient {\n return new SdkClient(name, client, callTimeoutMs);\n}\n\n/** Starts one server and completes the MCP handshake. */\nexport async function connectServer(\n config: ServerConfig,\n options: ConnectOptions,\n): Promise<McpClient> {\n const client = new Client({ name: 'earshot', version: '0.0.1' }, { capabilities: {} });\n\n let transport: StdioClientTransport | StreamableHTTPClientTransport;\n if (config.transport.type === 'stdio') {\n transport = new StdioClientTransport({\n command: config.transport.command,\n args: config.transport.args,\n // The server's own environment, not the whole of ours: a server has no\n // business reading the user's API keys unless its config named them.\n env: { ...inheritedEnv(options.env), ...config.transport.env },\n cwd: config.transport.cwd ?? options.cwd,\n // Piped rather than inherited: a chatty server writing to our stderr would\n // scribble over the TUI's own output.\n stderr: 'pipe',\n });\n } else {\n transport = new StreamableHTTPClientTransport(new URL(config.transport.url), {\n requestInit: { headers: config.transport.headers },\n });\n }\n\n const wrapper = new SdkClient(\n config.name,\n client,\n config.timeoutMs ?? options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS,\n );\n\n try {\n // The SDK's transport classes declare `sessionId: string | undefined` against\n // an interface declaring `sessionId?: string`, which `exactOptionalPropertyTypes`\n // treats as a mismatch. The cast is to the SDK's own parameter type, so it\n // narrows nothing we rely on.\n await client.connect(transport as Parameters<Client['connect']>[0], {\n timeout: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,\n });\n } catch (error) {\n await client.close().catch(() => undefined);\n throw new McpConnectError(config.name, (error as Error).message);\n }\n\n if (transport instanceof StdioClientTransport) {\n transport.stderr?.on('data', (chunk: Buffer) => wrapper.record(chunk.toString('utf8')));\n }\n // A server that exits after a successful handshake must not leave calls\n // hanging until their timeout; the next call reports it plainly instead.\n transport.onclose = () => wrapper.markClosed();\n\n return wrapper;\n}\n\n/**\n * The variables a spawned server gets when its config names none. Deliberately\n * small: PATH and the platform's own variables, so the command resolves, and\n * nothing that carries a credential.\n */\nfunction inheritedEnv(env: NodeJS.ProcessEnv): Record<string, string> {\n const keep = [\n 'PATH',\n 'HOME',\n 'USER',\n 'SHELL',\n 'LANG',\n 'LC_ALL',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'APPDATA',\n 'LOCALAPPDATA',\n 'PROGRAMFILES',\n 'PROGRAMFILES(X86)',\n 'SYSTEMROOT',\n 'WINDIR',\n 'COMSPEC',\n 'PATHEXT',\n 'USERPROFILE',\n 'HOMEDRIVE',\n 'HOMEPATH',\n ];\n const out: Record<string, string> = {};\n for (const key of keep) {\n const value = env[key];\n if (typeof value === 'string') out[key] = value;\n }\n return out;\n}\n\nfunction asArguments(args: unknown): Record<string, unknown> {\n return typeof args === 'object' && args !== null && !Array.isArray(args)\n ? (args as Record<string, unknown>)\n : {};\n}\n\n/**\n * MCP content blocks reduced to text. Images and audio are named rather than\n * carried: earshot has no image input yet, and silently dropping a block would\n * leave the model reasoning about a result it cannot see.\n */\nexport function renderContent(content: unknown): string {\n if (!Array.isArray(content)) return '';\n const parts: string[] = [];\n for (const block of content) {\n if (typeof block !== 'object' || block === null) continue;\n const item = block as Record<string, unknown>;\n if (item.type === 'text' && typeof item.text === 'string') {\n parts.push(item.text);\n } else if (item.type === 'resource' && typeof item.resource === 'object') {\n const resource = item.resource as Record<string, unknown>;\n parts.push(\n typeof resource.text === 'string'\n ? `${resource.uri ?? 'resource'}:\\n${resource.text}`\n : `[resource ${String(resource.uri ?? '')} (${String(\n resource.mimeType ?? 'unknown',\n )}), not text]`,\n );\n } else if (item.type === 'resource_link') {\n parts.push(`[resource link ${String(item.uri ?? '')}]`);\n } else {\n parts.push(`[${String(item.type ?? 'unknown')} content, which earshot cannot show yet]`);\n }\n }\n return truncate(parts.join('\\n'));\n}\n\nexport function truncate(value: string, limit = MAX_RESULT_CHARS): string {\n if (value.length <= limit) return value;\n const head = Math.floor(limit * 0.6);\n const tail = limit - head;\n const dropped = value.length - limit;\n return `${value.slice(0, head)}\\n\\n[... ${dropped} characters dropped by earshot ...]\\n\\n${value.slice(-tail)}`;\n}\n\nfunction describeFailure(server: string, tool: string, error: unknown, stderr: string): string {\n const message = (error as Error).message ?? String(error);\n const timedOut = /timed out|timeout/i.test(message);\n const detail = stderr ? `\\n\\nThe server's last output was:\\n${truncate(stderr, 2_000)}` : '';\n return timedOut\n ? `${server}__${tool} did not answer in time and was abandoned. Do not retry it without ` +\n `saying so; tell the user the server is not responding.${detail}`\n : `${server}__${tool} failed: ${message}${detail}`;\n}\n",
73
+ "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { configDir } from '@earshot/providers';\n\n/** Where a server definition came from. Decides whether it starts on its own. */\nexport type ServerScope = 'global' | 'project' | 'local';\n\nexport interface StdioServerConfig {\n type: 'stdio';\n command: string;\n args: string[];\n env: Record<string, string>;\n cwd?: string;\n}\n\nexport interface HttpServerConfig {\n type: 'http';\n url: string;\n headers: Record<string, string>;\n}\n\nexport interface ServerConfig {\n name: string;\n scope: ServerScope;\n transport: StdioServerConfig | HttpServerConfig;\n /** Per-call timeout. A server that never answers must not wedge the turn. */\n timeoutMs?: number;\n /**\n * False for a project-scope server the user has not trusted. It is listed and\n * explained rather than started - see `TRUST_NOTE`.\n */\n enabled: boolean;\n}\n\nexport interface LoadedMcpConfig {\n servers: ServerConfig[];\n /** Malformed entries, reported rather than silently dropped. */\n problems: string[];\n}\n\nexport const PROJECT_SETTINGS = join('.earshot', 'settings.json');\nexport const LOCAL_SETTINGS = join('.earshot', 'settings.local.json');\n\nexport const TRUST_NOTE =\n \"defined in this project's checked-in settings and not started. Run \" +\n '`earshot mcp trust <name>` to allow it - a project settings file is code you ' +\n 'cloned, and starting a process it names is running that code.';\n\n/**\n * A server name becomes the prefix of every tool it contributes, so it is\n * validated rather than trusted: `__` is the namespace separator, and a name\n * containing one could otherwise be chosen to impersonate another server's\n * tools. The rest of the character set keeps a name usable in a permission rule.\n */\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;\n\nexport function isValidServerName(name: string): boolean {\n return NAME.test(name) && !name.includes('__');\n}\n\ninterface SettingsShape {\n mcpServers?: Record<string, unknown>;\n /** Names of project-scope servers the user has approved. Local scope only. */\n mcpTrust?: string[];\n}\n\nfunction settingsPath(scope: ServerScope, cwd: string): string {\n if (scope === 'global') return join(configDir(), 'settings.json');\n return join(cwd, scope === 'project' ? PROJECT_SETTINGS : LOCAL_SETTINGS);\n}\n\nasync function read(path: string, problems: string[]): Promise<SettingsShape | undefined> {\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) return undefined;\n try {\n return JSON.parse(raw) as SettingsShape;\n } catch (error) {\n problems.push(`${path} is not valid JSON: ${(error as Error).message}`);\n return undefined;\n }\n}\n\n/**\n * Loads server definitions from global, project and local settings.\n *\n * Unlike permission rules, which are concatenated so a project cannot remove a\n * user's deny, a server is a single named thing: the narrowest scope defining a\n * name wins, so a user can point a project's `github` server at their own\n * wrapper without editing a file the repository owns.\n */\nexport async function loadMcpConfig(cwd: string): Promise<LoadedMcpConfig> {\n const problems: string[] = [];\n const byName = new Map<string, ServerConfig>();\n let trusted = new Set<string>();\n\n for (const scope of ['global', 'project', 'local'] as ServerScope[]) {\n const path = settingsPath(scope, cwd);\n const file = await read(path, problems);\n if (!file) continue;\n if (scope === 'local' && Array.isArray(file.mcpTrust)) {\n trusted = new Set(file.mcpTrust.filter((name): name is string => typeof name === 'string'));\n }\n for (const [name, raw] of Object.entries(file.mcpServers ?? {})) {\n if (!isValidServerName(name)) {\n problems.push(`${path}: \"${name}\" is not a usable server name`);\n continue;\n }\n const transport = parseTransport(raw, `${path}: server \"${name}\"`, problems);\n if (!transport) continue;\n const timeoutMs = timeoutOf(raw);\n byName.set(name, {\n name,\n scope,\n transport,\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n enabled: true,\n });\n }\n }\n\n // Resolved after the merge, so a project server the user redefined locally is\n // theirs and needs no trust entry.\n const servers = [...byName.values()].map((server) =>\n server.scope === 'project' && !trusted.has(server.name)\n ? { ...server, enabled: false }\n : server,\n );\n servers.sort((a, b) => a.name.localeCompare(b.name));\n return { servers, problems };\n}\n\nfunction timeoutOf(raw: unknown): number | undefined {\n const value = (raw as { timeoutMs?: unknown }).timeoutMs;\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nfunction parseTransport(\n raw: unknown,\n where: string,\n problems: string[],\n): StdioServerConfig | HttpServerConfig | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n problems.push(`${where} is not an object`);\n return undefined;\n }\n const entry = raw as Record<string, unknown>;\n const declared = typeof entry.type === 'string' ? entry.type : undefined;\n\n // `sse` is the pre-2025 transport. Named rather than ignored so a user\n // pasting an older config is told what happened instead of seeing nothing.\n if (declared === 'sse') {\n problems.push(`${where}: the sse transport is not supported; use \"type\": \"http\"`);\n return undefined;\n }\n\n if (declared === 'http' || (declared === undefined && typeof entry.url === 'string')) {\n if (typeof entry.url !== 'string') {\n problems.push(`${where} declares http but has no \"url\"`);\n return undefined;\n }\n try {\n const url = new URL(entry.url);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('not http');\n } catch {\n problems.push(`${where}: \"${String(entry.url)}\" is not an http(s) URL`);\n return undefined;\n }\n return { type: 'http', url: entry.url, headers: stringMap(entry.headers) };\n }\n\n if (typeof entry.command !== 'string' || entry.command.trim() === '') {\n problems.push(`${where} has neither a \"command\" nor a \"url\"`);\n return undefined;\n }\n const args = Array.isArray(entry.args) ? entry.args.map(String) : [];\n return {\n type: 'stdio',\n command: entry.command,\n args,\n env: stringMap(entry.env),\n ...(typeof entry.cwd === 'string' ? { cwd: entry.cwd } : {}),\n };\n}\n\nfunction stringMap(value: unknown): Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return {};\n const out: Record<string, string> = {};\n for (const [key, item] of Object.entries(value)) {\n if (typeof item === 'string') out[key] = item;\n }\n return out;\n}\n",
74
+ "import { createHash } from 'node:crypto';\nimport { defineTool, type Tool, ToolInputError, text } from '@earshot/core';\nimport type { McpClient, McpToolDescriptor } from './client.ts';\n\n/**\n * Providers reject a tool name longer than this, so a server with long names\n * would otherwise break every request rather than just its own tools.\n */\nexport const MAX_TOOL_NAME = 64;\n\n/** The separator between a server and its tool. Server names may not contain it. */\nexport const NAMESPACE = '__';\n\n/**\n * `server__tool`, shortened deterministically when the pair is too long for a\n * provider to accept. The hash keeps two long names on the same server distinct;\n * being deterministic keeps a permission rule the user saved yesterday matching\n * the same tool today.\n */\nexport function namespacedName(server: string, tool: string): string {\n const full = `${server}${NAMESPACE}${tool}`;\n if (full.length <= MAX_TOOL_NAME) return full;\n const digest = createHash('sha256').update(full).digest('hex').slice(0, 6);\n const room = MAX_TOOL_NAME - server.length - NAMESPACE.length - digest.length - 1;\n return `${server}${NAMESPACE}${tool.slice(0, Math.max(1, room))}_${digest}`;\n}\n\n/**\n * Wraps one server-supplied tool as an earshot tool.\n *\n * Two properties are not negotiable. It is never `readOnly`, whatever the server\n * says about itself: `readOnlyHint` is an assertion by the same party that wrote\n * the tool, and believing it would mean a server could run in parallel and\n * without a prompt by claiming to be harmless. And it declares a\n * `permission()`, so a server-supplied tool goes through exactly the gate a\n * built-in does - the gate that would otherwise be decorative the moment anyone\n * configured a server.\n */\nexport function mcpTool(\n client: McpClient,\n descriptor: McpToolDescriptor,\n name = namespacedName(client.name, descriptor.name),\n): Tool<Record<string, unknown>> {\n return defineTool<Record<string, unknown>>({\n name,\n description:\n `${descriptor.description || descriptor.name} ` +\n `(provided by the \"${client.name}\" MCP server)`.trim(),\n readOnly: false,\n inputSchema: schemaOf(descriptor),\n parse: (input) => {\n if (input === undefined || input === null) return {};\n if (typeof input !== 'object' || Array.isArray(input)) {\n throw new ToolInputError('expected an object of arguments');\n }\n return input as Record<string, unknown>;\n },\n // The rule name is `Mcp` for every server, so \"always allow\" persists as\n // `Mcp(github__create_issue)` - one tool, not one server. A server that adds\n // a tool after the user approved a different one is not covered by it.\n permission: (input) => ({\n tool: 'Mcp',\n target: name,\n title: `${descriptor.name} on the \"${client.name}\" MCP server`,\n // The arguments verbatim, because that is the thing being judged. A\n // summary here is where a create_issue that posts your source code hides.\n detail: `${name}(${JSON.stringify(input, null, 2)})`,\n }),\n async execute(input, ctx) {\n const result = await client.callTool(descriptor.name, input, ctx.signal);\n return {\n output: text(result.text || '(the server returned no content)'),\n ...(result.isError ? { isError: true } : {}),\n title: name,\n };\n },\n });\n}\n\n/**\n * The server's own schema, passed through. It describes arguments the server\n * will validate itself, so rewriting it here would only add a second opinion -\n * but it must at least be an object schema, or providers reject the request.\n */\nfunction schemaOf(descriptor: McpToolDescriptor): Record<string, unknown> {\n const schema = descriptor.inputSchema;\n if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) {\n return { type: 'object', properties: {} };\n }\n if (schema.type !== 'object') return { ...schema, type: 'object' };\n return schema;\n}\n",
75
+ "import type { Tool } from '@earshot/core';\nimport { type ConnectOptions, connectServer, type McpClient } from './client.ts';\nimport { loadMcpConfig, type ServerConfig, TRUST_NOTE } from './config.ts';\nimport { mcpTool, namespacedName } from './tool.ts';\n\nexport type ServerStatus = 'ready' | 'failed' | 'untrusted';\n\nexport interface ServerReport {\n name: string;\n scope: ServerConfig['scope'];\n status: ServerStatus;\n toolCount: number;\n detail?: string;\n}\n\nexport interface ManagerOptions {\n cwd: string;\n env?: NodeJS.ProcessEnv;\n connectTimeoutMs?: number;\n callTimeoutMs?: number;\n /** Substituted in tests, so no test spawns a process or opens a socket. */\n connect?: (config: ServerConfig, options: ConnectOptions) => Promise<McpClient>;\n}\n\n/**\n * Every configured MCP server, and the tools they contribute.\n *\n * One server failing is the normal case, not an exception: a missing binary, a\n * bad token, a server that hangs on start. Each is reported and skipped, and the\n * session runs with the tools it does have - a config typo should not be the\n * difference between having a coding agent and not having one.\n */\nexport class McpManager {\n private constructor(\n private readonly clients: McpClient[],\n private readonly registered: Tool<never>[],\n readonly reports: ServerReport[],\n readonly problems: string[],\n ) {}\n\n static async start(options: ManagerOptions): Promise<McpManager> {\n const { servers, problems } = await loadMcpConfig(options.cwd);\n const connect = options.connect ?? connectServer;\n const connectOptions: ConnectOptions = {\n cwd: options.cwd,\n env: options.env ?? process.env,\n ...(options.connectTimeoutMs !== undefined\n ? { connectTimeoutMs: options.connectTimeoutMs }\n : {}),\n ...(options.callTimeoutMs !== undefined ? { callTimeoutMs: options.callTimeoutMs } : {}),\n };\n\n const clients: McpClient[] = [];\n const tools: Tool<never>[] = [];\n const reports: ServerReport[] = [];\n const taken = new Set<string>();\n\n // Started concurrently: a dozen servers each taking a second to hand shake\n // is a dozen seconds of staring at nothing when it could be one.\n const started = await Promise.all(\n servers.map(async (config) => {\n if (!config.enabled) return { config, error: TRUST_NOTE };\n try {\n const client = await connect(config, connectOptions);\n return { config, client };\n } catch (error) {\n return { config, error: (error as Error).message };\n }\n }),\n );\n\n for (const outcome of started) {\n const { config } = outcome;\n if (!('client' in outcome) || !outcome.client) {\n reports.push({\n name: config.name,\n scope: config.scope,\n status: config.enabled ? 'failed' : 'untrusted',\n toolCount: 0,\n ...(outcome.error ? { detail: outcome.error } : {}),\n });\n continue;\n }\n\n const client = outcome.client;\n clients.push(client);\n let descriptors: Awaited<ReturnType<McpClient['listTools']>>;\n try {\n descriptors = await client.listTools();\n } catch (error) {\n await client.close().catch(() => undefined);\n reports.push({\n name: config.name,\n scope: config.scope,\n status: 'failed',\n toolCount: 0,\n detail: `listing its tools failed: ${(error as Error).message}`,\n });\n continue;\n }\n\n let added = 0;\n for (const descriptor of descriptors) {\n const name = namespacedName(config.name, descriptor.name);\n // Two tools can only collide here by a server declaring the same name\n // twice, or by a hashed shortening meeting itself. Skipped rather than\n // thrown: one malformed tool must not cost the session the other forty.\n if (taken.has(name)) continue;\n taken.add(name);\n tools.push(mcpTool(client, descriptor, name) as unknown as Tool<never>);\n added++;\n }\n reports.push({ name: config.name, scope: config.scope, status: 'ready', toolCount: added });\n }\n\n return new McpManager(clients, tools, reports, problems);\n }\n\n tools(): Tool<never>[] {\n return [...this.registered];\n }\n\n /** One line per server, for the CLI and for the startup notice in the TUI. */\n summary(): string[] {\n return this.reports.map((report) => {\n if (report.status === 'ready') {\n return `${report.name}: ${report.toolCount} tool${report.toolCount === 1 ? '' : 's'}`;\n }\n if (report.status === 'untrusted') return `${report.name}: ${TRUST_NOTE}`;\n return `${report.name}: ${report.detail ?? 'failed to start'}`;\n });\n }\n\n async close(): Promise<void> {\n await Promise.all(this.clients.map((client) => client.close().catch(() => undefined)));\n }\n}\n",
76
+ "import { readdir } from 'node:fs/promises';\nimport { basename, extname, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { defineTool, type PermissionRequest, type Tool, type ToolContext } from '@earshot/core';\nimport { LOCAL_SETTINGS, namespacedName } from '@earshot/mcp';\nimport { configDir } from '@earshot/providers';\n\n/** Where extensions live, under the project and under the config directory. */\nexport const PROJECT_EXTENSIONS = join('.earshot', 'extensions');\n\nconst LOADABLE = new Set(['.ts', '.mts', '.js', '.mjs']);\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;\n\nexport const EXTENSION_TRUST_NOTE =\n 'checked in under this project and not loaded. Run `earshot extensions trust <name>` ' +\n 'to allow it - an extension runs inside earshot, with everything earshot can reach, ' +\n 'from the moment it is imported.';\n\nexport type ExtensionStatus = 'ready' | 'failed' | 'untrusted';\n\nexport interface ExtensionReport {\n name: string;\n scope: 'global' | 'project';\n status: ExtensionStatus;\n toolCount: number;\n detail?: string;\n}\n\nexport interface LoadedExtensions {\n tools: Tool<never>[];\n reports: ExtensionReport[];\n}\n\n/**\n * The shape an extension module default-exports.\n *\n * Deliberately importable from nowhere: earshot ships as a bundled binary, not\n * as a library, so requiring `import { defineExtension } from 'earshot'` would\n * mean an extension only works when earshot happens to be resolvable from the\n * project. The shape is structural and validated on load instead.\n */\nexport interface ExtensionModule {\n name?: string;\n tools?: ExtensionTool[];\n}\n\nexport interface ExtensionTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n readOnly?: boolean;\n permission?(input: Record<string, unknown>, ctx: ToolContext): PermissionRequest;\n execute(input: Record<string, unknown>, ctx: ToolContext): Promise<unknown>;\n}\n\n/**\n * Loads every extension module in scope.\n *\n * An extension is not sandboxed and cannot be: it is user TypeScript running in\n * earshot's own process, which is the whole point of it being in-process rather\n * than an MCP server. So the boundary is not what it may do once loaded, but\n * whether it is loaded at all - a module checked into a repository the user\n * cloned stays inert until `earshot extensions trust` names it, exactly as a\n * project-defined stdio MCP server does.\n */\nexport async function loadExtensions(cwd: string, trusted: Set<string>): Promise<LoadedExtensions> {\n const tools: Tool<never>[] = [];\n const reports: ExtensionReport[] = [];\n const taken = new Set<string>();\n\n const sources = [\n { scope: 'global' as const, dir: join(configDir(), 'extensions') },\n { scope: 'project' as const, dir: resolve(cwd, PROJECT_EXTENSIONS) },\n ];\n\n for (const { scope, dir } of sources) {\n for (const file of await modulesIn(dir)) {\n const name = basename(file, extname(file));\n if (!NAME.test(name) || name.includes('__')) {\n reports.push({ name, scope, status: 'failed', toolCount: 0, detail: 'unusable name' });\n continue;\n }\n // Global extensions are the user's own files in their own config\n // directory; a project one arrived with the repository.\n if (scope === 'project' && !trusted.has(name)) {\n reports.push({\n name,\n scope,\n status: 'untrusted',\n toolCount: 0,\n detail: EXTENSION_TRUST_NOTE,\n });\n continue;\n }\n\n let module: ExtensionModule;\n try {\n module = await importExtension(join(dir, file));\n } catch (error) {\n reports.push({ name, scope, status: 'failed', toolCount: 0, detail: describe(error) });\n continue;\n }\n\n const declared = module.tools ?? [];\n let added = 0;\n let problem: string | undefined;\n for (const tool of declared) {\n try {\n const wrapped = extensionTool(name, tool, taken);\n if (!wrapped) continue;\n tools.push(wrapped);\n added++;\n } catch (error) {\n problem = describe(error);\n break;\n }\n }\n\n reports.push({\n name,\n scope,\n status: problem ? 'failed' : 'ready',\n toolCount: added,\n ...(problem ? { detail: problem } : {}),\n });\n }\n }\n\n return { tools, reports };\n}\n\n/**\n * One extension-supplied tool, namespaced and put behind the same gate a\n * built-in goes through.\n *\n * Its `readOnly` claim is honoured, unlike an MCP server's: a server is a\n * different party asserting something about itself, whereas an extension is\n * code the user trusted into their own process, where a false claim here is the\n * least of what it could have done at import time.\n */\nfunction extensionTool(\n extension: string,\n tool: ExtensionTool,\n taken: Set<string>,\n): Tool<never> | undefined {\n if (typeof tool?.name !== 'string' || !NAME.test(tool.name)) {\n throw new Error(`declared a tool with an unusable name`);\n }\n if (typeof tool.execute !== 'function') {\n throw new Error(`tool \"${tool.name}\" has no execute()`);\n }\n\n const name = namespacedName(extension, tool.name);\n if (taken.has(name)) return undefined;\n taken.add(name);\n\n const readOnly = tool.readOnly === true;\n return defineTool<Record<string, unknown>>({\n name,\n description: `${tool.description || tool.name} (from the \"${extension}\" extension)`,\n inputSchema: objectSchema(tool.inputSchema),\n readOnly,\n parse: (input) => (typeof input === 'object' && input !== null ? { ...input } : {}),\n ...(readOnly\n ? {}\n : {\n permission: (input, ctx) => ({\n ...(tool.permission?.(input, ctx) ?? {\n tool: 'Extension',\n target: name,\n title: `${tool.name} from the \"${extension}\" extension`,\n detail: `${name}(${JSON.stringify(input, null, 2)})`,\n }),\n // The rule name and target are earshot's to decide: an extension\n // choosing its own would let it match a rule the user wrote for\n // something else.\n tool: 'Extension',\n target: name,\n }),\n }),\n async execute(input, ctx) {\n const result = (await tool.execute(input, ctx)) as\n | { output?: unknown; isError?: boolean; title?: string }\n | string\n | undefined;\n if (typeof result === 'string') {\n return { output: { type: 'text', value: result }, title: name };\n }\n const output = result?.output;\n return {\n output:\n typeof output === 'object' && output !== null && 'type' in output\n ? (output as { type: 'text'; value: string })\n : { type: 'text', value: String(output ?? '') },\n ...(result?.isError ? { isError: true } : {}),\n title: typeof result?.title === 'string' ? result.title : name,\n };\n },\n }) as unknown as Tool<never>;\n}\n\nfunction objectSchema(schema: unknown): Record<string, unknown> {\n if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) {\n return { type: 'object', properties: {} };\n }\n return { ...(schema as Record<string, unknown>), type: 'object' };\n}\n\nasync function modulesIn(dir: string): Promise<string[]> {\n const entries = await readdir(dir).catch(() => []);\n return entries.filter((entry) => LOADABLE.has(extname(entry))).sort();\n}\n\nasync function importExtension(path: string): Promise<ExtensionModule> {\n const imported = (await import(pathToFileURL(path).href)) as { default?: unknown };\n const module = imported.default;\n if (typeof module !== 'object' || module === null || Array.isArray(module)) {\n throw new Error('does not default-export an object');\n }\n const tools = (module as ExtensionModule).tools;\n if (tools !== undefined && !Array.isArray(tools)) throw new Error('\"tools\" is not an array');\n return module as ExtensionModule;\n}\n\n/**\n * Node cannot import TypeScript on every supported version, and the failure it\n * gives is about file extensions rather than about the thing the user did. Said\n * plainly here rather than left for them to decode.\n */\nfunction describe(error: unknown): string {\n const message = (error as Error)?.message ?? String(error);\n if (/Unknown file extension|Cannot find module .*\\.ts/.test(message)) {\n return `this runtime cannot import TypeScript directly: ${message}`;\n }\n return message;\n}\n\nexport { LOCAL_SETTINGS };\n",
77
+ "import { type AcpSessionFactory, runAcpServer } from '@earshot/acp';\nimport { createSession, isPermissionMode, listSessions, type PermissionMode } from '@earshot/core';\nimport type { ParsedArgs } from '../args.ts';\nimport { startExtensions } from '../extensions/index.ts';\n\nconst DEFAULT_MODEL = 'anthropic/claude-opus-5';\n\nexport async function acpCommand(args: ParsedArgs): Promise<number> {\n const requested = args.flags['permission-mode'];\n let mode: PermissionMode | undefined;\n if (typeof requested === 'string') {\n if (!isPermissionMode(requested)) {\n process.stderr.write(`\"${requested}\" is not a permission mode\\n`);\n return 2;\n }\n mode = requested;\n }\n\n const model = typeof args.flags.model === 'string' ? args.flags.model : DEFAULT_MODEL;\n const apiKey = typeof args.flags['api-key'] === 'string' ? args.flags['api-key'] : undefined;\n const sessionFactory: AcpSessionFactory = async ({ cwd, resumeSessionId }) => {\n const extensions = await startExtensions(cwd);\n let resume: { path: string } | undefined;\n if (resumeSessionId) {\n const found = (await listSessions(cwd)).find((session) => session.id === resumeSessionId);\n if (!found) {\n await extensions.close();\n throw new Error(`no session \"${resumeSessionId}\" for ${cwd}`);\n }\n resume = { path: found.path };\n }\n try {\n return await createSession({\n cwd,\n model,\n extraTools: extensions.tools,\n problems: extensions.problems,\n onDispose: () => extensions.close(),\n ...(mode ? { mode } : {}),\n ...(apiKey ? { apiKey } : {}),\n ...(resume ? { resume } : {}),\n });\n } catch (error) {\n await extensions.close();\n throw error;\n }\n };\n\n await runAcpServer({ model, sessionFactory });\n return 0;\n}\n",
78
+ "import {\n AuthStore,\n buildRegistry,\n loginToOpenRouter,\n OAuthError,\n resolveCredentials,\n} from '@earshot/providers';\nimport type { ParsedArgs } from '../args.ts';\n\n/**\n * `earshot auth login|list|logout`.\n *\n * `login` prompts for a key by default; a provider with a published OAuth flow\n * for third-party apps can be signed into instead. Nothing here uses a\n * consumer subscription's credentials outside the client it was issued for -\n * see docs/providers.md, \"Deliberately not supported\".\n */\nexport async function authCommand(args: ParsedArgs): Promise<number> {\n const [action = 'list', providerId] = args.positionals;\n\n if (action === 'list') return list();\n if (action === 'login') return login(providerId, args);\n if (action === 'logout') return logout(providerId);\n\n process.stderr.write(`earshot auth: unknown action \"${action}\"\\n`);\n return 2;\n}\n\nasync function list(): Promise<number> {\n const registry = buildRegistry();\n const rows: string[] = [];\n\n for (const provider of registry.list()) {\n const credentials = await resolveCredentials(provider).catch(() => undefined);\n const how =\n credentials === undefined\n ? 'not configured'\n : credentials.type === 'ambient'\n ? 'ambient credentials'\n : credentials.type === 'oauth'\n ? 'signed in'\n : 'api key';\n rows.push(`${provider.id.padEnd(14)} ${how}`);\n }\n\n process.stdout.write(`${rows.join('\\n')}\\n`);\n return 0;\n}\n\nasync function login(providerId: string | undefined, args: ParsedArgs): Promise<number> {\n if (!providerId) {\n process.stderr.write('usage: earshot auth login <provider> [--api-key <key>]\\n');\n return 2;\n }\n\n const store = new AuthStore();\n const key = args.flags['api-key'];\n if (typeof key === 'string' && key !== '') {\n await store.set(providerId, { type: 'api-key', apiKey: key });\n process.stdout.write(`stored an api key for ${providerId}\\n`);\n return 0;\n }\n\n if (providerId !== 'openrouter') {\n process.stderr.write(\n `earshot has no sign-in flow for \"${providerId}\". Pass --api-key, or set its ` +\n 'environment variable - `earshot models` names it.\\n',\n );\n return 2;\n }\n\n try {\n const credentials = await loginToOpenRouter({\n onUrl: (url) => {\n // Printed as well as opened: over SSH or in a container there is no\n // browser to open, and a flow that only opens one leaves nothing to do.\n process.stdout.write(`opening your browser to sign in to OpenRouter.\\n\\n${url}\\n\\n`);\n },\n });\n await store.set(providerId, credentials);\n process.stdout.write('signed in to OpenRouter.\\n');\n return 0;\n } catch (error) {\n if (error instanceof OAuthError) {\n process.stderr.write(`${error.message}\\n`);\n return 3;\n }\n process.stderr.write(`sign-in failed: ${(error as Error).message}\\n`);\n return 3;\n }\n}\n\nasync function logout(providerId: string | undefined): Promise<number> {\n if (!providerId) {\n process.stderr.write('usage: earshot auth logout <provider>\\n');\n return 2;\n }\n await new AuthStore().remove(providerId);\n // Says what it did not do: a key in the environment outlives this, and a user\n // who thinks they logged out and did not is worse off than one who knows.\n process.stdout.write(\n `removed stored credentials for ${providerId}. An environment variable, if you have ` +\n 'one set, still applies.\\n',\n );\n return 0;\n}\n",
79
+ "import { spawnSync } from 'node:child_process';\nimport { access, constants, readFile, stat } from 'node:fs/promises';\nimport { homedir, platform, release } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { resolveShell, ShellNotFoundError, VERSION } from '@earshot/core';\nimport type { ParsedArgs } from '../args.ts';\n\nexport type DoctorStatus = 'pass' | 'warn' | 'fail';\n\nexport interface DoctorCheck {\n name: string;\n status: DoctorStatus;\n detail: string;\n}\n\ninterface DoctorOptions {\n env?: NodeJS.ProcessEnv;\n cwd?: string;\n platform?: NodeJS.Platform;\n nodeVersion?: string;\n run?: (command: string, args: string[]) => { status: number | null; stdout: string };\n}\n\nconst runCommand = (command: string, args: string[]) => {\n const result = spawnSync(command, args, { encoding: 'utf8', windowsHide: true });\n return { status: result.status, stdout: result.stdout.trim() };\n};\n\nasync function writableLocation(path: string): Promise<boolean> {\n let candidate = path;\n while (true) {\n try {\n const info = await stat(candidate);\n if (!info.isDirectory()) candidate = dirname(candidate);\n await access(candidate, constants.W_OK);\n return true;\n } catch {\n const parent = dirname(candidate);\n if (parent === candidate) return false;\n candidate = parent;\n }\n }\n}\n\nasync function jsonCheck(name: string, path: string): Promise<DoctorCheck | undefined> {\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) return undefined;\n try {\n JSON.parse(raw);\n return { name, status: 'pass', detail: path };\n } catch (error) {\n return { name, status: 'fail', detail: `${path}: ${(error as Error).message}` };\n }\n}\n\nexport async function runDoctor(options: DoctorOptions = {}): Promise<DoctorCheck[]> {\n const env = options.env ?? process.env;\n const cwd = options.cwd ?? process.cwd();\n const hostPlatform = options.platform ?? platform();\n const nodeVersion = options.nodeVersion ?? process.versions.node;\n const run = options.run ?? runCommand;\n const configPath =\n env.EARSHOT_CONFIG_DIR ??\n (hostPlatform === 'win32'\n ? join(env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), 'earshot')\n : join(env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'earshot'));\n const dataPath =\n env.EARSHOT_DATA_DIR ??\n (hostPlatform === 'win32'\n ? join(env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'earshot')\n : join(env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'earshot'));\n const authPath = join(configPath, 'auth.json');\n const checks: DoctorCheck[] = [];\n\n const nodeMajor = Number.parseInt(nodeVersion.split('.')[0] ?? '0', 10);\n checks.push({\n name: 'runtime',\n status: nodeMajor >= 22 ? 'pass' : 'fail',\n detail: `Node ${nodeVersion}${process.versions.bun ? ` (Bun ${process.versions.bun})` : ''}`,\n });\n checks.push({ name: 'platform', status: 'pass', detail: `${hostPlatform} ${release()}` });\n\n const git = run('git', ['--version']);\n checks.push({\n name: 'git',\n status: git.status === 0 ? 'pass' : 'warn',\n detail: git.status === 0 ? git.stdout : 'not found; sessions work, but /undo is unavailable',\n });\n\n try {\n const shell = resolveShell(env, hostPlatform);\n checks.push({ name: 'shell', status: 'pass', detail: shell.file });\n } catch (error) {\n checks.push({\n name: 'shell',\n status: error instanceof ShellNotFoundError ? 'fail' : 'warn',\n detail: (error as Error).message,\n });\n }\n\n for (const [name, path] of [\n ['config directory', configPath],\n ['data directory', dataPath],\n ] as const) {\n checks.push({\n name,\n status: (await writableLocation(path)) ? 'pass' : 'fail',\n detail: path,\n });\n }\n\n const auth = await jsonCheck('auth file', authPath);\n if (auth) {\n if (hostPlatform !== 'win32' && auth.status === 'pass') {\n const mode = (await stat(authPath)).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n auth.status = 'fail';\n auth.detail += ` (permissions ${mode.toString(8)}; expected 600)`;\n }\n }\n checks.push(auth);\n }\n\n for (const [name, path] of [\n ['project settings', join(cwd, '.earshot', 'settings.json')],\n ['local settings', join(cwd, '.earshot', 'settings.local.json')],\n ['global settings', join(configPath, 'settings.json')],\n ] as const) {\n const check = await jsonCheck(name, path);\n if (check) checks.push(check);\n }\n\n checks.unshift({ name: 'earshot', status: 'pass', detail: VERSION });\n return checks;\n}\n\nexport async function doctorCommand(_args: ParsedArgs): Promise<number> {\n const checks = await runDoctor();\n for (const check of checks) {\n process.stdout.write(\n `${check.status.toUpperCase().padEnd(4)} ${check.name.padEnd(18)} ${check.detail}\\n`,\n );\n }\n const failed = checks.filter((check) => check.status === 'fail').length;\n const warnings = checks.filter((check) => check.status === 'warn').length;\n process.stdout.write(\n `\\n${failed === 0 ? 'ready' : 'not ready'}: ${failed} failed, ${warnings} warnings\\n`,\n );\n return failed === 0 ? 0 : 1;\n}\n",
80
+ "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { LOCAL_SETTINGS } from '@earshot/mcp';\nimport { configDir } from '@earshot/providers';\nimport type { ParsedArgs } from '../args.ts';\nimport {\n EXTENSION_TRUST_NOTE,\n loadExtensions,\n PROJECT_EXTENSIONS,\n trustedExtensions,\n} from '../extensions/index.ts';\n\n/**\n * `earshot extensions list|trust|untrust`.\n *\n * `list` names what is there without importing anything untrusted: an extension\n * runs the moment it is imported, so listing must not be the thing that runs it.\n */\nexport async function extensionsCommand(args: ParsedArgs): Promise<number> {\n const [action = 'list', name] = args.positionals;\n const cwd = process.cwd();\n\n if (action === 'list') return list(cwd);\n if (action === 'trust' || action === 'untrust') {\n if (!name) {\n process.stderr.write(`usage: earshot extensions ${action} <name>\\n`);\n return 2;\n }\n return setTrust(cwd, name, action === 'trust');\n }\n\n process.stderr.write(`earshot extensions: unknown action \"${action}\"\\n`);\n return 2;\n}\n\nasync function list(cwd: string): Promise<number> {\n const { reports } = await loadExtensions(cwd, await trustedExtensions(cwd));\n if (reports.length === 0) {\n process.stdout.write(\n 'no extensions found\\n\\n' +\n `add a module to ${PROJECT_EXTENSIONS} for this project, ` +\n `or to ${join(configDir(), 'extensions')} for every project\\n`,\n );\n return 0;\n }\n\n for (const report of reports) {\n const state =\n report.status === 'ready'\n ? `${report.toolCount} tool${report.toolCount === 1 ? '' : 's'}`\n : `${report.status}: ${report.detail ?? EXTENSION_TRUST_NOTE}`;\n process.stdout.write(`${report.name} [${report.scope}] ${state}\\n`);\n }\n return 0;\n}\n\n/** Recorded in local settings, which are not committed: see `earshot mcp trust`. */\nasync function setTrust(cwd: string, name: string, trust: boolean): Promise<number> {\n const { reports } = await loadExtensions(cwd, new Set());\n if (!reports.some((report) => report.name === name && report.scope === 'project')) {\n process.stderr.write(`no project extension named \"${name}\" was found\\n`);\n return 2;\n }\n\n const path = join(cwd, LOCAL_SETTINGS);\n const raw = await readFile(path, 'utf8').catch(() => '{}');\n let settings: { extensionTrust?: string[] };\n try {\n settings = JSON.parse(raw) as { extensionTrust?: string[] };\n } catch (error) {\n process.stderr.write(`${path} is not valid JSON: ${(error as Error).message}\\n`);\n return 2;\n }\n\n const current = new Set(settings.extensionTrust ?? []);\n if (trust) current.add(name);\n else current.delete(name);\n\n await mkdir(dirname(path), { recursive: true });\n await writeFile(\n path,\n `${JSON.stringify({ ...settings, extensionTrust: [...current].sort() }, null, 2)}\\n`,\n 'utf8',\n );\n process.stdout.write(`${trust ? 'trusted' : 'no longer trusting'} \"${name}\" (${path})\\n`);\n return 0;\n}\n",
81
+ "import { type Curiosity, isCuriosity } from '@earshot/core';\n\n/**\n * `--curiosity` and `--max-cost`, shared by the interactive and headless paths\n * so the two cannot drift on what a flag means. Both refuse a bad value rather\n * than falling back to a default: a script that asked for a $2 ceiling and\n * silently got none is the failure the flag exists to prevent.\n */\nexport function parseCuriosity(value: unknown): Curiosity | undefined | 'invalid' {\n if (value === undefined) return undefined;\n return isCuriosity(value) ? value : 'invalid';\n}\n\nexport function parseMaxCost(value: unknown): number | undefined | 'invalid' {\n if (value === undefined) return undefined;\n const usd = typeof value === 'string' ? Number(value.replace(/^\\$/, '')) : Number.NaN;\n if (!Number.isFinite(usd) || usd < 0) return 'invalid';\n return usd;\n}\n",
82
+ "import { readFile, stat } from 'node:fs/promises';\nimport { extname, resolve } from 'node:path';\nimport type { ImagePart } from '@earshot/providers';\n\nconst MAX_IMAGE_BYTES = 20 * 1024 * 1024;\nconst MEDIA_TYPES: Record<string, string> = {\n '.gif': 'image/gif',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.png': 'image/png',\n '.webp': 'image/webp',\n};\n\nexport async function loadImage(input: string, cwd: string): Promise<ImagePart> {\n const remote = input.startsWith('https://');\n const pathname = remote ? new URL(input).pathname : input;\n const mediaType = MEDIA_TYPES[extname(pathname).toLowerCase()];\n if (!mediaType) {\n throw new Error('supported image formats are PNG, JPEG, GIF and WebP');\n }\n if (remote) return { type: 'image', data: input, mediaType };\n if (input.includes('://')) throw new Error('image URLs must use https');\n\n const path = resolve(cwd, input);\n const info = await stat(path);\n if (!info.isFile()) throw new Error(`${path} is not a file`);\n if (info.size > MAX_IMAGE_BYTES) throw new Error(`${path} is larger than 20 MB`);\n return { type: 'image', data: (await readFile(path)).toString('base64'), mediaType };\n}\n",
83
+ "import type { AgentEvent } from '@earshot/core';\n\n/**\n * The version of the headless output contract.\n *\n * What `earshot.v1` promises, and what it does not:\n *\n * - Every object earshot writes to stdout in a JSON format carries this string,\n * so a consumer can tell which contract it is reading without knowing which\n * binary produced it.\n * - Within v1, fields and record types may be **added**. A consumer must ignore\n * records whose `type` it does not know and fields it did not expect. That is\n * the whole compatibility rule, and it is what lets earshot report new things\n * without breaking anything already parsing the stream.\n * - Renaming a field, removing one, or changing what one means requires v2. v2\n * would be requested explicitly - `--output-format json@v2` - and v1 would\n * keep working alongside it, so an upgrade is never the thing that breaks a\n * script.\n *\n * The internal `AgentEvent` union is deliberately not what gets written: it is\n * ours to rename, and a consumer should not be able to notice when we do.\n */\nexport const SCHEMA = 'earshot.v1';\n\nexport type OutputFormat = 'text' | 'json' | 'stream-json';\n\n/** `json`, `stream-json`, and the pinned forms `json@v1` / `stream-json@v1`. */\nexport function parseFormat(value: string): OutputFormat | undefined {\n const [name, version] = value.split('@');\n if (version !== undefined && version !== 'v1') return undefined;\n if (name === 'text' && version === undefined) return 'text';\n if (name === 'json' || name === 'stream-json') return name;\n return undefined;\n}\n\nexport interface ResultRecord {\n schema: string;\n type: 'result';\n /** `success` unless something stopped the turn; `isError` is the short form. */\n subtype: 'success' | 'error' | 'interrupted' | 'max_steps' | 'budget';\n isError: boolean;\n text: string;\n costUsd: number;\n durationMs: number;\n numMessages: number;\n model: string;\n permissionMode: string;\n sessionId?: string;\n error?: { kind: string; message: string };\n}\n\nexport type StreamRecord = { schema: string; type: string } & Record<string, unknown>;\n\n/**\n * One agent event as a stream record.\n *\n * Events with nothing a consumer can act on return undefined rather than an\n * empty record. Text deltas are passed through as they arrive: a program\n * consuming the stream wants the same incremental output a person watching the\n * terminal gets, or there is no reason to stream at all.\n */\nexport function toStreamRecord(event: AgentEvent): StreamRecord | undefined {\n const base = { schema: SCHEMA };\n switch (event.type) {\n case 'model_start':\n return { ...base, type: 'model_start', model: event.model };\n case 'text_delta':\n return { ...base, type: 'text', text: event.text };\n case 'reasoning_delta':\n return { ...base, type: 'reasoning', text: event.text };\n case 'tool_start':\n return {\n ...base,\n type: 'tool_use',\n toolCallId: event.call.toolCallId,\n toolName: event.call.toolName,\n input: event.call.input,\n };\n case 'tool_end':\n return {\n ...base,\n type: 'tool_result',\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n isError: event.result.isError === true,\n output: event.result.output,\n };\n case 'permission':\n return {\n ...base,\n type: 'permission',\n tool: event.request.tool,\n target: event.request.target,\n title: event.request.title,\n reason: event.reason,\n };\n case 'intent':\n return {\n ...base,\n type: 'intent',\n calls: event.calls,\n ...(event.text !== undefined ? { text: event.text } : {}),\n };\n case 'usage':\n return { ...base, type: 'usage', usage: event.usage, costUsd: event.costUsd };\n case 'budget':\n return {\n ...base,\n type: 'budget',\n spentUsd: event.spentUsd,\n limitUsd: event.limitUsd,\n ...(event.raisedTo !== undefined ? { raisedTo: event.raisedTo } : {}),\n };\n case 'compacted':\n return { ...base, type: 'compacted', replaced: event.replaced };\n case 'scope_concern':\n return {\n ...base,\n type: 'scope',\n kind: event.concern.kind,\n summary: event.concern.summary,\n accepted: event.accepted,\n };\n case 'verification':\n return {\n ...base,\n type: 'verification',\n command: event.result.command,\n exitCode: event.result.exitCode,\n output: event.result.output,\n };\n case 'hook':\n return {\n ...base,\n type: 'hook',\n event: event.event,\n ...(event.blocked !== undefined ? { blocked: event.blocked } : {}),\n problems: event.problems,\n };\n case 'subagent':\n return {\n ...base,\n type: 'subagent',\n description: event.description,\n steps: event.steps,\n costUsd: event.costUsd,\n };\n case 'error':\n return {\n ...base,\n type: 'error',\n kind: event.error.kind,\n message: event.error.message,\n retryable: event.error.retryable,\n };\n // `message` and `turn_end` are covered by the records above and by the final\n // result record; emitting the raw assistant message as well would put the\n // same text in the stream twice.\n default:\n return undefined;\n }\n}\n",
84
+ "import {\n type AgentEvent,\n createSession,\n isPermissionMode,\n MissingCredentialsError,\n NoSessionToResumeError,\n type PermissionMode,\n ShellNotFoundError,\n UnknownModelError,\n} from '@earshot/core';\nimport type { ParsedArgs } from '../args.ts';\nimport { parseCuriosity, parseMaxCost } from '../budget.ts';\nimport { startExtensions } from '../extensions/index.ts';\nimport { loadImage } from '../image.ts';\nimport {\n type OutputFormat,\n parseFormat,\n type ResultRecord,\n SCHEMA,\n toStreamRecord,\n} from '../output.ts';\n\nconst DEFAULT_MODEL = 'anthropic/claude-opus-5';\n\n/**\n * `earshot -p \"<prompt>\"` - one non-interactive turn, with tools.\n *\n * Headless runs default to `ask` like everywhere else, which with no terminal to\n * prompt at means mutating tools are refused with an explanation the model can\n * act on. Scripted use passes `--permission-mode`; that is a deliberate choice\n * the caller makes, not a default they fall into.\n */\nexport async function headlessCommand(prompt: string, args: ParsedArgs): Promise<number> {\n const flags = args.flags;\n const requestedFormat =\n typeof flags['output-format'] === 'string' ? flags['output-format'] : 'text';\n const format = parseFormat(requestedFormat);\n if (!format) {\n // Refused rather than falling back to text: a script asking for a format\n // earshot does not have wants to know that, not to be handed prose.\n process.stderr.write(\n `\"${requestedFormat}\" is not an output format. Use text, json or stream-json ` +\n `(optionally pinned as json@v1).\\n`,\n );\n return 2;\n }\n const emit = makeEmitter(format);\n const startedAt = Date.now();\n\n let mode: PermissionMode | undefined;\n const requested = flags['permission-mode'];\n if (typeof requested === 'string') {\n if (!isPermissionMode(requested)) {\n process.stderr.write(`\"${requested}\" is not a permission mode\\n`);\n return 2;\n }\n mode = requested;\n }\n\n const curiosity = parseCuriosity(flags.curiosity);\n if (curiosity === 'invalid') {\n process.stderr.write(`\"${flags.curiosity}\" is not a curiosity level: low, normal or high\\n`);\n return 2;\n }\n const maxCostUsd = parseMaxCost(flags['max-cost']);\n if (maxCostUsd === 'invalid') {\n process.stderr.write(`\"${flags['max-cost']}\" is not an amount in dollars\\n`);\n return 2;\n }\n\n const extensions = await startExtensions(process.cwd());\n\n let session: Awaited<ReturnType<typeof createSession>>;\n try {\n session = await createSession({\n cwd: process.cwd(),\n extraTools: extensions.tools,\n problems: extensions.problems,\n onDispose: () => extensions.close(),\n model: typeof flags.model === 'string' ? flags.model : DEFAULT_MODEL,\n ...(mode ? { mode } : {}),\n ...(typeof flags['api-key'] === 'string' ? { apiKey: flags['api-key'] } : {}),\n ...(curiosity ? { curiosity } : {}),\n ...(maxCostUsd !== undefined ? { maxCostUsd } : {}),\n ...resumeFrom(flags),\n });\n } catch (error) {\n await extensions.close();\n return reportStartupFailure(error);\n }\n\n for (const problem of session.problems) process.stderr.write(`warning: ${problem}\\n`);\n\n const controller = new AbortController();\n // A second interrupt exits rather than waiting: the first asks the turn to\n // stop, and a turn wedged in a subprocess should not trap the user.\n let interrupts = 0;\n const onSigint = () => {\n interrupts += 1;\n if (interrupts === 1) controller.abort();\n else process.exit(130);\n };\n process.on('SIGINT', onSigint);\n\n let exitCode = 0;\n let subtype: ResultRecord['subtype'] = 'success';\n let failure: { kind: string; message: string } | undefined;\n\n try {\n let image: Awaited<ReturnType<typeof loadImage>> | undefined;\n if (typeof flags.image === 'string') {\n try {\n image = await loadImage(flags.image, process.cwd());\n } catch (error) {\n process.stderr.write(`image: ${(error as Error).message}\\n`);\n exitCode = 2;\n subtype = 'error';\n failure = { kind: 'invalid_image', message: (error as Error).message };\n }\n }\n const input = image ? [{ type: 'text' as const, text: prompt }, image] : prompt;\n for await (const event of failure\n ? ([] as AgentEvent[])\n : session.agent.runTurn(input, controller.signal)) {\n emit(event);\n if (event.type === 'error') {\n exitCode = 1;\n subtype = 'error';\n failure = { kind: event.error.kind, message: event.error.message };\n }\n if (event.type === 'turn_end' && event.reason === 'aborted') {\n exitCode = 130;\n subtype = 'interrupted';\n }\n if (event.type === 'turn_end' && event.reason === 'max_steps') {\n exitCode = 1;\n subtype = 'max_steps';\n }\n // Its own exit code: a script that set a ceiling needs to tell \"stopped\n // because it ran out of budget\" from \"stopped because it failed\".\n if (event.type === 'turn_end' && event.reason === 'budget') {\n exitCode = 3;\n subtype = 'budget';\n }\n }\n } finally {\n process.off('SIGINT', onSigint);\n await session.dispose();\n }\n\n if (format === 'text') {\n process.stdout.write('\\n');\n return exitCode;\n }\n\n // The same record ends a stream and stands alone as the whole of `json`, so a\n // consumer that reads only the last line of a stream and one that parses a\n // single object are reading the same thing.\n const result: ResultRecord = {\n schema: SCHEMA,\n type: 'result',\n subtype,\n isError: subtype !== 'success',\n text: emit.text(),\n costUsd: session.agent.costUsd,\n durationMs: Date.now() - startedAt,\n numMessages: session.agent.history.length,\n model: typeof flags.model === 'string' ? flags.model : DEFAULT_MODEL,\n permissionMode: session.agent.permissionMode,\n ...(session.store ? { sessionId: session.store.id } : {}),\n ...(failure ? { error: failure } : {}),\n };\n process.stdout.write(\n format === 'json' ? `${JSON.stringify(result, null, 2)}\\n` : `${JSON.stringify(result)}\\n`,\n );\n\n return exitCode;\n}\n\nfunction resumeFrom(flags: ParsedArgs['flags']) {\n if (typeof flags.resume === 'string') return { resume: { path: flags.resume } } as const;\n if (flags.continue === true || flags.resume === true)\n return { resume: { latest: true } } as const;\n return {};\n}\n\n/**\n * Renders events for one of three consumers: a person reading a terminal, a\n * script parsing one JSON object, or a program reading a JSON stream. All three\n * see tool activity - a headless run that printed only prose would hide the fact\n * that the agent edited files.\n */\nfunction makeEmitter(format: OutputFormat) {\n let text = '';\n\n const emit = (event: AgentEvent): void => {\n if (event.type === 'text_delta') text += event.text;\n\n if (format === 'stream-json') {\n const record = toStreamRecord(event);\n if (record) process.stdout.write(`${JSON.stringify(record)}\\n`);\n return;\n }\n if (format !== 'text') return;\n\n switch (event.type) {\n case 'text_delta':\n process.stdout.write(event.text);\n break;\n case 'tool_start':\n process.stderr.write(`\\n· ${event.call.toolName}\\n`);\n break;\n case 'tool_end':\n if (event.result.isError) {\n process.stderr.write(` ! ${describe(event.result.output)}\\n`);\n }\n break;\n case 'hook':\n // A hook that stopped something is why the run did what it did; leaving\n // it out would make the transcript unexplainable.\n if (event.blocked)\n process.stderr.write(`\\n${event.event} hook blocked: ${event.blocked}\\n`);\n for (const problem of event.problems) process.stderr.write(` ! ${problem}\\n`);\n break;\n case 'subagent':\n process.stderr.write(`\\n· subagent \"${event.description}\" (${event.steps} steps)\\n`);\n break;\n case 'error':\n process.stderr.write(`\\nerror: ${event.error.message}\\n`);\n break;\n case 'turn_end':\n if (event.reason === 'aborted') process.stderr.write('\\ninterrupted\\n');\n if (event.reason === 'max_steps') process.stderr.write('\\nstopped: step limit reached\\n');\n if (event.reason === 'budget') process.stderr.write('\\nstopped: cost budget reached\\n');\n break;\n default:\n break;\n }\n };\n\n emit.text = () => text;\n return emit;\n}\n\nfunction describe(output: { type: string; value: unknown }): string {\n return output.type === 'text' ? (String(output.value).split('\\n')[0] ?? '') : output.type;\n}\n\nfunction reportStartupFailure(error: unknown): number {\n if (error instanceof UnknownModelError) {\n process.stderr.write(`${error.message}\\n\\nrun \\`earshot models\\` to see what is available\\n`);\n return 2;\n }\n if (error instanceof MissingCredentialsError) {\n process.stderr.write(`${error.message}\\n`);\n return 3;\n }\n if (error instanceof NoSessionToResumeError) {\n process.stderr.write(`${error.message}\\n`);\n return 2;\n }\n if (error instanceof ShellNotFoundError) {\n process.stderr.write(`${error.message}\\n`);\n return 4;\n }\n throw error;\n}\n",
85
+ "import type {\n Agent,\n CreatedSession,\n MemoryCandidate,\n MemoryScope,\n PermissionMode,\n PermissionRequest,\n PromptChoice,\n TodoItem,\n UserPrompt,\n} from '@earshot/core';\nimport {\n deleteMemory,\n detectPreference,\n expandCommand,\n isPermissionMode,\n loadMemories,\n openInEditor,\n PERMISSION_MODES,\n PLAN_PROMPT,\n planPath,\n readPlan,\n refreshSystemPrompt,\n saveMemory,\n savePlan,\n} from '@earshot/core';\nimport { Box, Static, Text, useApp, useInput } from 'ink';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { Markdown } from './components/markdown.tsx';\nimport { MemoryCapture } from './components/memory-capture.tsx';\nimport { PermissionPrompt } from './components/permission.tsx';\nimport { QuestionPrompt } from './components/question.tsx';\nimport { StatusLine } from './components/status.tsx';\nimport { TextInput } from './components/text-input.tsx';\nimport { ToolBlock } from './components/tool-block.tsx';\nimport { theme } from './theme.ts';\n\n/**\n * A finished piece of scrollback.\n *\n * Once an item is here it never changes, which is the contract `Static` needs:\n * Ink writes those rows to the terminal once and then leaves them alone, so they\n * become real scrollback the user can select and scroll with their own terminal.\n * Only the live region below is re-rendered, which is what keeps a long session\n * from repainting thousands of rows on every token.\n */\nexport type ScrollItem =\n | { kind: 'user'; id: string; text: string }\n | { kind: 'assistant'; id: string; text: string }\n | { kind: 'tool'; id: string; name: string; title?: string; output?: string; isError?: boolean }\n | { kind: 'notice'; id: string; text: string; color?: string };\n\nexport interface AppProps {\n session: CreatedSession;\n model: string;\n /** Run immediately on start, for `earshot \"do the thing\"`. */\n initialPrompt?: UserPrompt;\n}\n\nlet sequence = 0;\nconst nextId = () => `item_${sequence++}`;\n\nfunction promptLabel(prompt: UserPrompt): string {\n if (typeof prompt === 'string') return prompt;\n return prompt\n .map((part) => (part.type === 'text' ? part.text : `[attached ${part.mediaType} image]`))\n .join('\\n');\n}\n\nexport function App({ session, model, initialPrompt }: AppProps) {\n const { exit } = useApp();\n const agent: Agent = session.agent;\n\n const [items, setItems] = useState<ScrollItem[]>(() =>\n session.problems.map((problem) => ({\n kind: 'notice' as const,\n id: nextId(),\n text: `warning: ${problem}`,\n color: theme.warning,\n })),\n );\n const [live, setLive] = useState('');\n const [runningTool, setRunningTool] = useState<string | undefined>();\n const [input, setInput] = useState('');\n const [busy, setBusy] = useState(false);\n const [mode, setMode] = useState<PermissionMode>(agent.permissionMode);\n const [cost, setCost] = useState(0);\n const [todos, setTodos] = useState<TodoItem[]>([]);\n const [queued, setQueued] = useState(0);\n const [candidate, setCandidate] = useState<MemoryCandidate | undefined>();\n const [context, setContext] = useState(() => agent.contextUse);\n const [compacted, setCompacted] = useState(0);\n\n const [pending, setPending] = useState<\n | { request: PermissionRequest; reason: string; resolve: (choice: PromptChoice) => void }\n | undefined\n >();\n const [question, setQuestion] = useState<\n { question: string; options?: string[]; resolve: (answer: string) => void } | undefined\n >();\n\n const controller = useRef<AbortController | undefined>(undefined);\n const push = useCallback((item: ScrollItem) => setItems((current) => [...current, item]), []);\n\n // The prompt and ask callbacks are installed once and read through refs, so a\n // re-render never leaves the agent holding a stale closure over old state.\n const pendingRef = useRef(setPending);\n pendingRef.current = setPending;\n const questionRef = useRef(setQuestion);\n questionRef.current = setQuestion;\n\n useEffect(() => {\n session.installPrompt(\n (request, reason) =>\n new Promise<PromptChoice>((resolve) => {\n pendingRef.current({ request, reason, resolve });\n }),\n );\n session.installAsk(\n (q, options) =>\n new Promise<string>((resolve) => {\n questionRef.current({ question: q, ...(options ? { options } : {}), resolve });\n }),\n );\n }, [session]);\n\n /** The mode to go back to once a plan is approved or abandoned. */\n const modeBeforePlan = useRef<PermissionMode | undefined>(undefined);\n /** The last thing the model said, which in plan mode is the plan itself. */\n const lastAssistantText = useRef('');\n\n const runTurn = useCallback(\n async (prompt: UserPrompt) => {\n setBusy(true);\n // Cleared per turn: a stale answer read back as this turn's plan is worse\n // than no plan at all.\n lastAssistantText.current = '';\n push({ kind: 'user', id: nextId(), text: promptLabel(prompt) });\n\n const abort = new AbortController();\n controller.current = abort;\n let assistantText = '';\n\n try {\n for await (const event of agent.runTurn(prompt, abort.signal)) {\n switch (event.type) {\n case 'text_delta':\n assistantText += event.text;\n setLive(assistantText);\n break;\n case 'intent':\n // The intent itself is the assistant text already on screen just\n // above the tool block, so only its absence is worth a line: a\n // batch that arrived without a reason is what this exists to show.\n if (event.text === undefined) {\n push({\n kind: 'notice',\n id: nextId(),\n text: `about to run ${event.calls} tool call${\n event.calls === 1 ? '' : 's'\n } without saying why`,\n color: theme.warning,\n });\n }\n break;\n case 'tool_start':\n // The assistant's prose is flushed to scrollback before the tool\n // block, so the two never re-order once the tool finishes.\n if (assistantText.trim() !== '') {\n push({ kind: 'assistant', id: nextId(), text: assistantText.trimEnd() });\n assistantText = '';\n setLive('');\n }\n setRunningTool(event.call.toolName);\n break;\n case 'tool_end': {\n setRunningTool(undefined);\n const output = event.result.output.type === 'text' ? event.result.output.value : '';\n push({\n kind: 'tool',\n id: nextId(),\n name: event.toolName,\n ...(event.result.title ? { title: event.result.title } : {}),\n output,\n ...(event.result.isError ? { isError: true } : {}),\n });\n setTodos(agent.todos.list());\n break;\n }\n case 'usage':\n setCost(agent.costUsd);\n setContext(agent.contextUse);\n break;\n case 'budget':\n push({\n kind: 'notice',\n id: nextId(),\n text:\n event.raisedTo === undefined\n ? `stopped: $${event.spentUsd.toFixed(2)} spent against a ` +\n `$${event.limitUsd.toFixed(2)} budget`\n : `budget raised to $${event.raisedTo.toFixed(2)} after ` +\n `$${event.spentUsd.toFixed(2)} spent`,\n color: theme.warning,\n });\n break;\n case 'verification':\n // Shown to the user as it was shown to the model: the command, the\n // exit code and the output, none of it summarised.\n push({\n kind: 'tool',\n id: nextId(),\n name: event.result.command,\n title: `${event.result.command} - exit ${event.result.exitCode ?? 'killed'}`,\n output: event.result.output,\n ...(event.result.exitCode === 0 ? {} : { isError: true }),\n });\n break;\n case 'subagent':\n push({\n kind: 'notice',\n id: nextId(),\n text: `subagent \"${event.description}\": ${event.steps} step${\n event.steps === 1 ? '' : 's'\n }, $${event.costUsd.toFixed(4)}`,\n });\n break;\n case 'hook':\n // A hook that blocked something is the reason the agent did not do\n // it, so it is said out loud rather than left for the model to\n // paraphrase. Problems are shown too: a hook that failed silently\n // is one the user goes on believing is protecting them.\n if (event.blocked) {\n push({\n kind: 'notice',\n id: nextId(),\n text: `${event.event} hook blocked this: ${event.blocked}`,\n color: theme.warning,\n });\n }\n for (const problem of event.problems) {\n push({ kind: 'notice', id: nextId(), text: problem, color: theme.warning });\n }\n break;\n case 'compacted':\n setCompacted((count) => count + event.replaced);\n push({\n kind: 'notice',\n id: nextId(),\n text: `compacted: ${event.replaced} earlier messages are now a summary`,\n });\n break;\n case 'error':\n push({\n kind: 'notice',\n id: nextId(),\n text: `error: ${event.error.message}`,\n color: theme.danger,\n });\n break;\n case 'turn_end':\n if (event.reason === 'aborted') {\n push({\n kind: 'notice',\n id: nextId(),\n text: 'interrupted',\n color: theme.warning,\n });\n }\n if (event.reason === 'max_steps') {\n push({\n kind: 'notice',\n id: nextId(),\n text: 'stopped: step limit reached',\n color: theme.warning,\n });\n }\n break;\n default:\n break;\n }\n setQueued(agent.pendingSteers);\n }\n } finally {\n if (assistantText.trim() !== '') {\n lastAssistantText.current = assistantText;\n push({ kind: 'assistant', id: nextId(), text: assistantText.trimEnd() });\n }\n setLive('');\n setRunningTool(undefined);\n setBusy(false);\n setQueued(agent.pendingSteers);\n controller.current = undefined;\n }\n },\n [agent, push],\n );\n\n const started = useRef(false);\n useEffect(() => {\n if (started.current || !initialPrompt) return;\n started.current = true;\n void runTurn(initialPrompt);\n }, [initialPrompt, runTurn]);\n\n /**\n * Lists what is remembered, with the sentence each rule came from. Memory the\n * user cannot inspect is memory they cannot trust, so provenance is shown\n * here rather than hidden in the file.\n */\n const showMemories = useCallback(\n async (argument?: string) => {\n const [verb, ...rest] = (argument ?? '').split(/\\s+/);\n const id = rest.join(' ').trim();\n if (verb === 'forget' && id) {\n const gone = await deleteMemory(id, agent.cwd);\n if (gone) await refreshSystemPrompt(agent, model, session.skills);\n push({\n kind: 'notice',\n id: nextId(),\n text: gone ? `forgot ${id}` : `no memory called \"${id}\"`,\n ...(gone ? {} : { color: theme.warning }),\n });\n return;\n }\n\n const memories = await loadMemories(agent.cwd);\n if (memories.length === 0) {\n push({ kind: 'notice', id: nextId(), text: 'nothing remembered yet' });\n return;\n }\n const lines = memories.map((memory) => {\n const when = memory.created.slice(0, 10);\n const why = memory.source ? `\\n from \"${memory.source}\" on ${when}` : '';\n return ` [${memory.id}] (${memory.scope}) ${memory.text}${why}`;\n });\n push({\n kind: 'notice',\n id: nextId(),\n text: `${lines.join('\\n')}\\n\\n /memory forget <id> removes one`,\n });\n },\n [agent, model, push, session.skills],\n );\n\n const remember = useCallback(\n async (scope: MemoryScope) => {\n if (!candidate) return;\n setCandidate(undefined);\n const saved = await saveMemory({ ...candidate, scope }, agent.cwd).catch(() => undefined);\n if (!saved) {\n push({ kind: 'notice', id: nextId(), text: 'could not save that', color: theme.warning });\n return;\n }\n // Applied from the next model call, not the next session.\n await refreshSystemPrompt(agent, model, session.skills);\n push({\n kind: 'notice',\n id: nextId(),\n text: `remembered [${saved.id}] (${scope}) - /memory to review or forget it`,\n });\n },\n [agent, candidate, model, push, session.skills],\n );\n\n /**\n * `/tree`, `/rewind`, `/fork` and `/undo`.\n *\n * The numbering is over the user's own prompts rather than over every entry:\n * \"go back to before I asked for the refactor\" is how people think about a\n * session, and an entry id is not something anyone can pick out of a list.\n */\n const sessionTree = useCallback(\n async (name: string, argument?: string) => {\n const entries = await session.branch();\n const prompts = entries.filter(\n (entry) =>\n entry.type === 'message' &&\n entry.message.role === 'user' &&\n entry.message.content.some(\n (part) => part.type === 'text' && !part.text.startsWith('<self-check>'),\n ),\n );\n\n if (name === 'tree' || !argument) {\n if (prompts.length === 0) {\n push({ kind: 'notice', id: nextId(), text: 'nothing in this session yet' });\n return;\n }\n const lines = prompts.map((entry, index) => {\n const text =\n entry.type === 'message'\n ? (entry.message.content.find((part) => part.type === 'text')?.text ?? '')\n : '';\n return ` ${index + 1}. ${text.split('\\n')[0]?.slice(0, 70) ?? ''}`;\n });\n push({\n kind: 'notice',\n id: nextId(),\n text: `${lines.join('\\n')}\\n\\n /rewind <n> goes back to one · /fork <n> branches from it`,\n });\n return;\n }\n\n const index = Number.parseInt(argument, 10) - 1;\n const target = prompts[index];\n if (!target) {\n push({\n kind: 'notice',\n id: nextId(),\n text: `no prompt ${argument} in this session - /tree lists them`,\n color: theme.warning,\n });\n return;\n }\n // The entry before the chosen prompt: rewinding \"to\" a prompt means the\n // state the session was in when it was typed, not after it ran.\n const previous = entries[entries.indexOf(target) - 1] ?? target;\n\n if (name === 'rewind') {\n const kept = await session.rewindTo(previous.id);\n push({\n kind: 'notice',\n id: nextId(),\n text: `rewound to before prompt ${index + 1}; ${kept} message${kept === 1 ? '' : 's'} kept. Nothing was deleted - the rest is still in the transcript as another branch.`,\n });\n return;\n }\n\n const forked = await session.fork(previous.id);\n push({\n kind: 'notice',\n id: nextId(),\n text: forked\n ? `forked from prompt ${index + 1} into ${forked}; this session continues there and the original is untouched`\n : 'could not fork this session',\n ...(forked ? {} : { color: theme.warning }),\n });\n },\n [push, session],\n );\n\n const undoLast = useCallback(async () => {\n const result = await session.undo();\n if (!result) {\n push({ kind: 'notice', id: nextId(), text: 'nothing to undo', color: theme.warning });\n return;\n }\n const created = result.wasCreated.length\n ? ` Left in place because the batch created them: ${result.wasCreated.join(', ')}.`\n : '';\n push({\n kind: 'notice',\n id: nextId(),\n text: result.restored.length\n ? `undid ${result.label}: restored ${result.restored.join(', ')}.${created}`\n : `nothing to restore from ${result.label}.${created}`,\n });\n }, [push, session]);\n\n /**\n * `/plan` - draft, edit, approve.\n *\n * The plan is a file, and approving reads it back from disk rather than using\n * what the model wrote. That is the difference between a plan and a prompt:\n * whatever the user changed is what gets pinned, and if they changed nothing\n * it is still their decision that it stands.\n */\n const plan = useCallback(\n async (argument?: string) => {\n const path = planPath(session.store?.id ?? 'scratch');\n const [verb = '', ...rest] = (argument ?? '').split(/\\s+/);\n const task = [verb, ...rest].join(' ').trim();\n\n if (verb === 'show') {\n const text = await readPlan(path);\n push({\n kind: 'notice',\n id: nextId(),\n text: text ? `${path}\\n\\n${text}` : `no plan yet at ${path}`,\n });\n return;\n }\n if (verb === 'edit') {\n const result = await openInEditor(path);\n push({\n kind: 'notice',\n id: nextId(),\n text: result.message,\n ...(result.edited ? {} : { color: theme.warning }),\n });\n return;\n }\n if (verb === 'approve') {\n const text = await readPlan(path);\n if (!text) {\n push({\n kind: 'notice',\n id: nextId(),\n text: `there is no plan at ${path} to approve`,\n color: theme.warning,\n });\n return;\n }\n agent.setPlan(text);\n // Back to whatever the session was in before planning: staying in plan\n // mode after approving one is the one thing the user certainly did not\n // ask for.\n const restored = modeBeforePlan.current ?? 'ask';\n agent.setPermissionMode(restored);\n setMode(restored);\n modeBeforePlan.current = undefined;\n push({\n kind: 'notice',\n id: nextId(),\n text: `plan approved and pinned for this run; permission mode: ${restored}`,\n });\n return;\n }\n if (verb === 'clear') {\n agent.setPlan(undefined);\n push({ kind: 'notice', id: nextId(), text: 'plan unpinned' });\n return;\n }\n if (task === '') {\n push({\n kind: 'notice',\n id: nextId(),\n text: 'usage: /plan <what you want planned>, then /plan edit, /plan approve',\n color: theme.warning,\n });\n return;\n }\n\n modeBeforePlan.current = agent.permissionMode;\n agent.setPermissionMode('plan');\n setMode('plan');\n await runTurn(`${task}\\n\\n${PLAN_PROMPT}`);\n\n // Written from the last thing the model said, which in plan mode is the\n // plan, because every mutating tool was refused.\n const drafted = lastAssistantText.current.trim();\n if (drafted === '') {\n push({\n kind: 'notice',\n id: nextId(),\n text: 'the model produced no plan to write',\n color: theme.warning,\n });\n return;\n }\n await savePlan(path, drafted);\n push({\n kind: 'notice',\n id: nextId(),\n text: `plan written to ${path}\\n/plan edit to change it, /plan approve to pin it`,\n });\n },\n [agent, push, runTurn, session.store],\n );\n\n const handleCommand = useCallback(\n (command: string) => {\n // Split once, keeping the remainder: `split(/\\s+/, 2)` discards everything\n // after the second field, which silently drops the argument of any command\n // that takes more than one word.\n const body = command.slice(1).trim();\n const space = body.search(/\\s/);\n const name = space === -1 ? body : body.slice(0, space);\n const argument = space === -1 ? undefined : body.slice(space + 1).trim();\n\n if (name === 'exit' || name === 'quit') {\n exit();\n return;\n }\n if (name === 'mode') {\n if (argument && isPermissionMode(argument)) {\n agent.setPermissionMode(argument);\n setMode(argument);\n push({ kind: 'notice', id: nextId(), text: `permission mode: ${argument}` });\n } else {\n push({\n kind: 'notice',\n id: nextId(),\n text: `usage: /mode <${PERMISSION_MODES.join('|')}>`,\n color: theme.warning,\n });\n }\n return;\n }\n if (name === 'memory') {\n void showMemories(argument);\n return;\n }\n if (name === 'tree' || name === 'rewind' || name === 'fork') {\n if (busy) {\n push({\n kind: 'notice',\n id: nextId(),\n text: 'finish or interrupt the current turn first (esc)',\n color: theme.warning,\n });\n return;\n }\n void sessionTree(name, argument);\n return;\n }\n if (name === 'undo') {\n void undoLast();\n return;\n }\n if (name === 'plan') {\n if (busy) {\n push({\n kind: 'notice',\n id: nextId(),\n text: 'finish or interrupt the current turn first (esc)',\n color: theme.warning,\n });\n return;\n }\n void plan(argument);\n return;\n }\n if (name === 'skills') {\n push({\n kind: 'notice',\n id: nextId(),\n text: describeExtensions(session),\n });\n return;\n }\n\n // A user-defined command is expanded into a prompt and run as one. It is\n // not a second way to reach the tools: whatever the file asks for goes\n // through the same turn, and the same gate, as anything typed by hand.\n const custom = session.commands.find((entry) => entry.name === name);\n if (custom) {\n const prompt = expandCommand(custom, argument ?? '');\n if (prompt.trim() === '') {\n push({\n kind: 'notice',\n id: nextId(),\n text: `/${name} expanded to nothing`,\n color: theme.warning,\n });\n return;\n }\n if (busy) {\n agent.steer(prompt);\n setQueued(agent.pendingSteers);\n push({ kind: 'user', id: nextId(), text: command });\n return;\n }\n void runTurn(prompt);\n return;\n }\n\n push({\n kind: 'notice',\n id: nextId(),\n text: `unknown command \"${name}\"`,\n color: theme.warning,\n });\n },\n [agent, busy, exit, plan, push, runTurn, session, sessionTree, showMemories, undoLast],\n );\n\n const submit = useCallback(\n (text: string) => {\n const trimmed = text.trim();\n setInput('');\n if (trimmed === '') return;\n\n if (trimmed.startsWith('/')) {\n handleCommand(trimmed);\n return;\n }\n // Offered, never stored: a wrong rule saved silently would follow the user\n // into every future session with no sign of where it came from.\n setCandidate(detectPreference(trimmed));\n if (busy) {\n // Steering, not queueing a second turn: the agent injects it at the next\n // model call so the user redirects without losing work in flight.\n agent.steer(trimmed);\n setQueued(agent.pendingSteers);\n push({ kind: 'user', id: nextId(), text: trimmed });\n return;\n }\n void runTurn(trimmed);\n },\n [agent, busy, push, runTurn, handleCommand],\n );\n\n // Input is disabled while a prompt is open so the two do not both consume keys.\n const inputActive = !pending && !question;\n\n useInput(\n (input_, key) => {\n if (key.escape) {\n setCandidate(undefined);\n if (busy) controller.current?.abort();\n return;\n }\n // Bound rather than modal: taking the offer must not stop the user typing.\n if (key.ctrl && candidate && (input_ === 'r' || input_ === 'g')) {\n void remember(input_ === 'r' ? 'project' : 'user');\n }\n },\n { isActive: inputActive },\n );\n\n return (\n <Box flexDirection=\"column\">\n <Static items={items}>{(item) => <ScrollRow key={item.id} item={item} />}</Static>\n\n {live !== '' && (\n <Box marginTop={1}>\n <Markdown text={live} />\n </Box>\n )}\n {runningTool && <ToolBlock name={runningTool} running />}\n\n {pending && (\n <PermissionPrompt\n request={pending.request}\n reason={pending.reason}\n onChoice={(choice) => {\n setPending(undefined);\n pending.resolve(choice);\n }}\n />\n )}\n\n {question && (\n <QuestionPrompt\n question={question.question}\n {...(question.options ? { options: question.options } : {})}\n onAnswer={(answer) => {\n setQuestion(undefined);\n question.resolve(answer);\n }}\n />\n )}\n\n {candidate && inputActive && <MemoryCapture candidate={candidate} />}\n\n {inputActive && (\n <Box marginTop={1}>\n <Text color={theme.user}>{'> '}</Text>\n <TextInput\n value={input}\n onChange={setInput}\n onSubmit={submit}\n placeholder={busy ? 'steer the agent, or esc to interrupt' : 'what should I do?'}\n />\n </Box>\n )}\n\n <StatusLine\n model={model}\n mode={mode}\n costUsd={cost}\n todos={todos}\n busy={busy}\n queued={queued}\n context={context}\n compacted={compacted}\n />\n </Box>\n );\n}\n\nfunction ScrollRow({ item }: { item: ScrollItem }) {\n if (item.kind === 'user') {\n return (\n <Box marginTop={1}>\n <Text color={theme.user}>{'> '}</Text>\n <Text>{item.text}</Text>\n </Box>\n );\n }\n if (item.kind === 'assistant') {\n return (\n <Box marginTop={1}>\n <Markdown text={item.text} />\n </Box>\n );\n }\n if (item.kind === 'tool') {\n return (\n <ToolBlock\n name={item.name}\n {...(item.title ? { title: item.title } : {})}\n {...(item.output ? { output: item.output } : {})}\n {...(item.isError ? { isError: true } : {})}\n />\n );\n }\n return (\n <Box marginTop={1}>\n <Text color={item.color ?? theme.muted}>{item.text}</Text>\n </Box>\n );\n}\n\n/**\n * What `/skills` shows. Skills and commands are listed together because from the\n * user's side they are the same question - what extra behaviour is loaded in\n * this directory, and where did it come from.\n */\nfunction describeExtensions(session: CreatedSession): string {\n const lines: string[] = [];\n if (session.skills.length > 0) {\n lines.push('skills (the agent loads these itself when they fit):');\n for (const skill of session.skills) {\n lines.push(` ${skill.name} [${skill.scope}] ${skill.description}`);\n }\n }\n if (session.commands.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('commands you can type:');\n for (const command of session.commands) {\n lines.push(` /${command.name} [${command.scope}] ${command.description}`);\n }\n }\n return lines.length === 0\n ? 'no skills or commands found in .earshot/skills, .earshot/commands or your config directory'\n : lines.join('\\n');\n}\n",
86
+ "import { Box, Text } from 'ink';\nimport { theme } from '../theme.ts';\n\n/**\n * Renders a model's markdown as styled terminal text.\n *\n * Not a spec-complete parser - just the subset a model actually produces in\n * conversation: headers, bold/italic, inline and fenced code, lists, block\n * quotes and rules. Anything else falls through as plain text rather than\n * failing, since a raw line is still more readable than a crash.\n */\nexport function Markdown({ text }: { text: string }) {\n const blocks = splitBlocks(text);\n return (\n <Box flexDirection=\"column\">\n {blocks.map((block, index) => (\n // Blocks have no identity beyond position: the whole text is replaced\n // wholesale on every render, never reordered in place.\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Block key={index} block={block} />\n ))}\n </Box>\n );\n}\n\ntype ParsedBlock =\n | { kind: 'code'; lang: string; lines: string[] }\n | { kind: 'heading'; level: number; text: string }\n | { kind: 'rule' }\n | { kind: 'list'; ordered: boolean; items: string[] }\n | { kind: 'quote'; lines: string[] }\n | { kind: 'paragraph'; text: string };\n\nfunction splitBlocks(text: string): ParsedBlock[] {\n const lines = text.split('\\n');\n const blocks: ParsedBlock[] = [];\n let index = 0;\n\n while (index < lines.length) {\n const line = lines[index] ?? '';\n\n if (line.trim() === '') {\n index++;\n continue;\n }\n\n const fence = line.match(/^```(\\w*)\\s*$/);\n if (fence) {\n const lang = fence[1] ?? '';\n const codeLines: string[] = [];\n index++;\n while (index < lines.length && !/^```\\s*$/.test(lines[index] ?? '')) {\n codeLines.push(lines[index] ?? '');\n index++;\n }\n index++; // closing fence\n blocks.push({ kind: 'code', lang, lines: codeLines });\n continue;\n }\n\n const heading = line.match(/^(#{1,6})\\s+(.*)$/);\n if (heading) {\n blocks.push({ kind: 'heading', level: heading[1]?.length ?? 1, text: heading[2] ?? '' });\n index++;\n continue;\n }\n\n if (/^(-{3,}|\\*{3,}|_{3,})\\s*$/.test(line.trim())) {\n blocks.push({ kind: 'rule' });\n index++;\n continue;\n }\n\n const listItem = line.match(/^\\s*([-*]|\\d+[.)])\\s+(.*)$/);\n if (listItem) {\n const ordered = /\\d/.test(listItem[1] ?? '');\n const items: string[] = [];\n while (index < lines.length) {\n const match = (lines[index] ?? '').match(/^\\s*(?:[-*]|\\d+[.)])\\s+(.*)$/);\n if (!match) break;\n items.push(match[1] ?? '');\n index++;\n }\n blocks.push({ kind: 'list', ordered, items });\n continue;\n }\n\n if (line.trimStart().startsWith('>')) {\n const quoteLines: string[] = [];\n while (index < lines.length && (lines[index] ?? '').trimStart().startsWith('>')) {\n quoteLines.push((lines[index] ?? '').trimStart().replace(/^>\\s?/, ''));\n index++;\n }\n blocks.push({ kind: 'quote', lines: quoteLines });\n continue;\n }\n\n const paragraphLines: string[] = [];\n while (index < lines.length && (lines[index] ?? '').trim() !== '') {\n const current = lines[index] ?? '';\n if (\n /^```/.test(current) ||\n /^(#{1,6})\\s+/.test(current) ||\n /^\\s*([-*]|\\d+[.)])\\s+/.test(current) ||\n current.trimStart().startsWith('>')\n ) {\n break;\n }\n paragraphLines.push(current);\n index++;\n }\n blocks.push({ kind: 'paragraph', text: paragraphLines.join(' ') });\n }\n\n return blocks;\n}\n\nfunction Block({ block }: { block: ParsedBlock }) {\n switch (block.kind) {\n case 'code':\n return (\n <Box flexDirection=\"column\" marginY={1} paddingLeft={2}>\n {block.lines.map((line, index) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} color={theme.tool}>\n {line}\n </Text>\n ))}\n </Box>\n );\n case 'heading':\n return (\n <Box marginTop={block.level <= 2 ? 1 : 0}>\n <Text bold underline={block.level === 1} color={theme.assistant}>\n {inlineToText(block.text)}\n </Text>\n </Box>\n );\n case 'rule':\n return <Text color={theme.muted}>{'─'.repeat(40)}</Text>;\n case 'list':\n return (\n <Box flexDirection=\"column\">\n {block.items.map((item, index) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index}>\n {' '}\n {block.ordered ? `${index + 1}.` : '-'} <Inline text={item} />\n </Text>\n ))}\n </Box>\n );\n case 'quote':\n return (\n <Box flexDirection=\"column\" paddingLeft={1}>\n {block.lines.map((line, index) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} color={theme.muted} italic>\n │ {inlineToText(line)}\n </Text>\n ))}\n </Box>\n );\n default:\n return (\n <Text>\n <Inline text={block.text} />\n </Text>\n );\n }\n}\n\n/** Strips inline markers for contexts (headings, quotes) that render as one line. */\nfunction inlineToText(text: string): string {\n return text\n .replace(/\\*\\*(.+?)\\*\\*/g, '$1')\n .replace(/__(.+?)__/g, '$1')\n .replace(/\\*(.+?)\\*/g, '$1')\n .replace(/_(.+?)_/g, '$1')\n .replace(/`(.+?)`/g, '$1');\n}\n\n/**\n * Splits one line into bold/italic/code spans and renders each with its own\n * styling, in order - the only way Ink can mix styles within a single line.\n */\nfunction Inline({ text }: { text: string }) {\n const pattern = /(\\*\\*.+?\\*\\*|__.+?__|`.+?`|\\*.+?\\*|_.+?_)/g;\n const parts = text.split(pattern);\n\n return (\n <>\n {parts.map((part, index) => {\n if (part === '') return null;\n if (part.startsWith('**') && part.endsWith('**')) {\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} bold>\n {part.slice(2, -2)}\n </Text>\n );\n }\n if (part.startsWith('__') && part.endsWith('__')) {\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} bold>\n {part.slice(2, -2)}\n </Text>\n );\n }\n if (part.startsWith('`') && part.endsWith('`')) {\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} color={theme.tool}>\n {part.slice(1, -1)}\n </Text>\n );\n }\n if (part.startsWith('*') && part.endsWith('*')) {\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} italic>\n {part.slice(1, -1)}\n </Text>\n );\n }\n if (part.startsWith('_') && part.endsWith('_')) {\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} italic>\n {part.slice(1, -1)}\n </Text>\n );\n }\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index}>{part}</Text>\n );\n })}\n </>\n );\n}\n",
87
+ "/**\n * Colours are named by role rather than by hue so a future theme can be swapped\n * in one place. Only the sixteen ANSI names are used: a 24-bit palette looks\n * better on the terminals that support it and unreadable on the ones that map it\n * badly, and a coding agent has to be legible on a stranger's machine.\n */\nexport const theme = {\n user: 'cyan',\n assistant: 'white',\n reasoning: 'gray',\n tool: 'blue',\n toolError: 'red',\n added: 'green',\n removed: 'red',\n hunk: 'cyan',\n muted: 'gray',\n warning: 'yellow',\n danger: 'red',\n accent: 'magenta',\n} as const;\n\n/** Mode indicators for the status line, shortest first - the line is one row. */\nexport const MODE_LABEL: Record<string, string> = {\n plan: 'plan',\n ask: 'ask',\n 'accept-edits': 'edits',\n auto: 'auto',\n yolo: 'yolo',\n};\n\nexport const MODE_COLOR: Record<string, string> = {\n plan: theme.accent,\n ask: theme.muted,\n 'accept-edits': theme.added,\n auto: theme.warning,\n yolo: theme.danger,\n};\n",
88
+ "import type { MemoryCandidate } from '@earshot/core';\nimport { Box, Text } from 'ink';\nimport { theme } from '../theme.ts';\n\nexport interface MemoryCaptureProps {\n candidate: MemoryCandidate;\n}\n\n/**\n * A one-line offer, not a modal.\n *\n * Capturing a preference must never interrupt the turn the user just started:\n * a dialog here would make correcting the agent more expensive than letting the\n * mistake stand, which is the opposite of the point. Two keystrokes take it,\n * ignoring it costs nothing, and it disappears with the next prompt.\n */\nexport function MemoryCapture({ candidate }: MemoryCaptureProps) {\n return (\n <Box marginTop={1}>\n <Text color={theme.accent}>remember </Text>\n <Text>“{candidate.text}”</Text>\n <Text color={theme.muted}>? ctrl+r for this project · ctrl+g everywhere</Text>\n </Box>\n );\n}\n",
89
+ "import type { PermissionRequest, PromptChoice } from '@earshot/core';\nimport { Box, Text, useInput } from 'ink';\nimport { useState } from 'react';\nimport { theme } from '../theme.ts';\nimport { DiffView } from './diff.tsx';\n\nexport interface PermissionPromptProps {\n request: PermissionRequest;\n reason: string;\n onChoice: (choice: PromptChoice) => void;\n}\n\ninterface Option {\n label: string;\n choice: PromptChoice;\n color: string;\n}\n\n/**\n * The approval prompt.\n *\n * It renders `request.detail` in full - the actual command, or the actual diff.\n * A prompt that shows a summary is one people learn to approve without reading,\n * which makes the whole gate theatre. Nothing here paraphrases.\n *\n * \"Allow once\" is first and selected by default. The safe choice being the\n * default matters more than the convenient one, and a user who wants the\n * standing rule has to move to it deliberately.\n */\nexport function PermissionPrompt({ request, reason, onChoice }: PermissionPromptProps) {\n const [selected, setSelected] = useState(0);\n\n const options: Option[] = [\n { label: 'Allow once', choice: { kind: 'allow-once' }, color: theme.assistant },\n {\n label: `Always allow ${request.tool}(${truncate(request.target, 40)}) in this project`,\n choice: { kind: 'allow-always', scope: 'project' },\n color: theme.assistant,\n },\n {\n label: 'Deny and tell the agent why',\n choice: { kind: 'deny' },\n color: theme.danger,\n },\n ];\n\n useInput((input, key) => {\n if (key.upArrow || input === 'k') setSelected((n) => (n + options.length - 1) % options.length);\n else if (key.downArrow || input === 'j') setSelected((n) => (n + 1) % options.length);\n else if (key.return) onChoice(options[selected]?.choice ?? { kind: 'deny' });\n // Escape is a denial, not a dismissal: a prompt that can be closed without\n // answering would leave the turn waiting on a promise nothing will resolve.\n else if (key.escape) onChoice({ kind: 'deny', message: 'the user dismissed the prompt' });\n });\n\n const isDiff = request.detail.includes('\\n@@') || request.detail.startsWith('---');\n\n return (\n <Box flexDirection=\"column\" borderStyle=\"round\" borderColor={theme.warning} paddingX={1}>\n <Text bold color={theme.warning}>\n {request.title}\n </Text>\n <Text color={theme.muted}>{reason}</Text>\n <Box marginY={1} flexDirection=\"column\">\n {isDiff ? <DiffView diff={request.detail} /> : <Text wrap=\"wrap\">{request.detail}</Text>}\n </Box>\n {options.map((option, index) => (\n <Text key={option.label} color={index === selected ? theme.accent : option.color}>\n {index === selected ? '❯ ' : ' '}\n {option.label}\n </Text>\n ))}\n </Box>\n );\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length <= max ? value : `${value.slice(0, max - 1)}…`;\n}\n",
90
+ "import { Box, Text } from 'ink';\nimport { theme } from '../theme.ts';\n\n/** Beyond this a diff is summarised; a 900-line hunk is not read, it is scrolled past. */\nconst MAX_LINES = 60;\n\nexport function DiffView({ diff, maxLines = MAX_LINES }: { diff: string; maxLines?: number }) {\n const lines = diff.split('\\n');\n // The `---`/`+++` header repeats the filename the caller has already shown.\n const body = lines.filter((line) => !line.startsWith('---') && !line.startsWith('+++'));\n const shown = body.slice(0, maxLines);\n const hidden = body.length - shown.length;\n\n return (\n <Box flexDirection=\"column\">\n {shown.map((line, index) => (\n // A diff line has no identity beyond its position, and duplicate lines in\n // one hunk are ordinary. The list is only ever replaced wholesale - never\n // reordered or spliced - so a positional key is the correct one here.\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} color={colorFor(line)} wrap=\"truncate-end\">\n {line === '' ? ' ' : line}\n </Text>\n ))}\n {hidden > 0 && (\n <Text color={theme.muted}>\n {' '}\n ... {hidden} more lines\n </Text>\n )}\n </Box>\n );\n}\n\nfunction colorFor(line: string): string {\n if (line.startsWith('+')) return theme.added;\n if (line.startsWith('-')) return theme.removed;\n if (line.startsWith('@@')) return theme.hunk;\n return theme.muted;\n}\n\n/** One line of counts, for a collapsed edit. */\nexport function diffStat(diff: string): string {\n let added = 0;\n let removed = 0;\n for (const line of diff.split('\\n')) {\n if (line.startsWith('+') && !line.startsWith('+++')) added++;\n if (line.startsWith('-') && !line.startsWith('---')) removed++;\n }\n return `+${added} -${removed}`;\n}\n",
91
+ "import { Box, Text, useInput } from 'ink';\nimport { useState } from 'react';\nimport { theme } from '../theme.ts';\nimport { TextInput } from './text-input.tsx';\n\nexport interface QuestionPromptProps {\n question: string;\n options?: string[];\n onAnswer: (answer: string) => void;\n}\n\n/**\n * What `ask_user` renders. Offered options are selectable, but a free-text answer\n * is always available: the model's suggestions are guesses, and forcing the user\n * into one of them is exactly the not-listening this project exists to avoid.\n */\nexport function QuestionPrompt({ question, options = [], onAnswer }: QuestionPromptProps) {\n const [selected, setSelected] = useState(0);\n const [typing, setTyping] = useState(options.length === 0);\n const [value, setValue] = useState('');\n\n useInput(\n (input, key) => {\n if (key.upArrow) setSelected((n) => (n + options.length - 1) % options.length);\n else if (key.downArrow) setSelected((n) => (n + 1) % options.length);\n else if (key.return) onAnswer(options[selected] ?? '');\n else if (input && !key.ctrl && !key.meta) {\n // Typing a printable character switches to free text and keeps it, so the\n // first keystroke of an answer is never swallowed by the option list.\n setTyping(true);\n setValue(input);\n }\n },\n { isActive: !typing },\n );\n\n return (\n <Box flexDirection=\"column\" borderStyle=\"round\" borderColor={theme.accent} paddingX={1}>\n <Text bold color={theme.accent}>\n {question}\n </Text>\n {!typing &&\n options.map((option, index) => (\n <Text key={option} color={index === selected ? theme.accent : theme.muted}>\n {index === selected ? '❯ ' : ' '}\n {option}\n </Text>\n ))}\n {!typing && <Text color={theme.muted}>or start typing to answer in your own words</Text>}\n {typing && (\n <TextInput\n value={value}\n onChange={setValue}\n onSubmit={(answer) => onAnswer(answer.trim())}\n placeholder=\"your answer\"\n />\n )}\n </Box>\n );\n}\n",
92
+ "import { Text, useInput } from 'ink';\nimport { useEffect, useRef } from 'react';\nimport { theme } from '../theme.ts';\n\nexport interface TextInputProps {\n value: string;\n onChange: (value: string) => void;\n onSubmit?: (value: string) => void;\n placeholder?: string;\n isActive?: boolean;\n}\n\n/**\n * A single-line controlled input.\n *\n * Hand-written rather than pulled from `ink-text-input`, which has not kept pace\n * with Ink's major versions and would add a dependency for about thirty lines.\n * The cursor is rendered as an inverted character rather than moved with an\n * escape sequence, so nothing here writes cursor-control codes that ConPTY\n * handles differently from a POSIX terminal.\n */\nexport function TextInput({\n value,\n onChange,\n onSubmit,\n placeholder = '',\n isActive = true,\n}: TextInputProps) {\n /**\n * The edit buffer is tracked in a ref as well as in the parent's state.\n *\n * Several keystrokes can arrive in one tick - fast typing, and every paste -\n * and each handler would then read the same pre-render `value` prop, so all\n * but the last character would be silently dropped and a Return arriving in\n * the same tick would submit a stale string. The ref carries the edit forward\n * within a tick; the effect resyncs it whenever the parent changes the value\n * itself, such as clearing the line after a submit.\n */\n const buffer = useRef(value);\n useEffect(() => {\n buffer.current = value;\n }, [value]);\n\n useInput(\n (input, key) => {\n if (key.return) {\n const submitted = buffer.current;\n buffer.current = '';\n onSubmit?.(submitted);\n return;\n }\n if (key.backspace || key.delete) {\n buffer.current = buffer.current.slice(0, -1);\n onChange(buffer.current);\n return;\n }\n // Control sequences arrive as `input` too; only printable text is appended.\n if (key.ctrl || key.meta || key.escape || key.tab) return;\n if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) return;\n if (input) {\n buffer.current += input;\n onChange(buffer.current);\n }\n },\n { isActive },\n );\n\n if (value === '') {\n return (\n <Text>\n <Text inverse> </Text>\n <Text color={theme.muted}>{placeholder}</Text>\n </Text>\n );\n }\n\n return (\n <Text>\n {value}\n <Text inverse> </Text>\n </Text>\n );\n}\n",
93
+ "import type { PermissionMode, TodoItem } from '@earshot/core';\nimport { Box, Text } from 'ink';\nimport { MODE_COLOR, MODE_LABEL, theme } from '../theme.ts';\n\nexport interface StatusLineProps {\n model: string;\n mode: PermissionMode;\n costUsd: number;\n todos: TodoItem[];\n busy: boolean;\n queued: number;\n /** Estimated tokens in the last request, and the model's window. */\n context: { tokens: number; window: number };\n /** How many messages compaction has replaced with a summary this session. */\n compacted: number;\n}\n\n/**\n * One row, always present. Everything on it answers a question the user would\n * otherwise have to interrupt to ask: which model is spending their money, how\n * much it has spent, what the agent thinks it is doing, and whether the thing\n * they just typed was received.\n */\nexport function StatusLine({\n model,\n mode,\n costUsd,\n todos,\n busy,\n queued,\n context,\n compacted,\n}: StatusLineProps) {\n const done = todos.filter((todo) => todo.status === 'done').length;\n const current = todos.find((todo) => todo.status === 'in_progress');\n const used = context.window > 0 ? Math.min(100, (context.tokens / context.window) * 100) : 0;\n\n return (\n <Box>\n <Text color={MODE_COLOR[mode] ?? theme.muted}>{MODE_LABEL[mode] ?? mode}</Text>\n <Text color={theme.muted}> · {model}</Text>\n <Text color={theme.muted}> · ${costUsd.toFixed(4)}</Text>\n {context.window > 0 && (\n // Coloured only when it is close enough to matter: a percentage that is\n // always yellow stops being a warning.\n <Text color={used >= 80 ? theme.warning : theme.muted}> · {used.toFixed(0)}% ctx</Text>\n )}\n {compacted > 0 && (\n // What was dropped, not just that something was: a summarised session\n // answers from a recollection, and the user should know which part.\n <Text color={theme.muted}> · {compacted} summarised</Text>\n )}\n {todos.length > 0 && (\n <Text color={theme.muted}>\n {' '}\n · {done}/{todos.length}\n {current ? ` ${truncate(current.text, 40)}` : ''}\n </Text>\n )}\n {busy && <Text color={theme.warning}> · working (esc to interrupt)</Text>}\n {queued > 0 && <Text color={theme.accent}> · {queued} queued</Text>}\n </Box>\n );\n}\n\nfunction truncate(value: string, max: number): string {\n return value.length <= max ? value : `${value.slice(0, max - 1)}…`;\n}\n",
94
+ "import { Box, Text } from 'ink';\nimport { theme } from '../theme.ts';\nimport { DiffView, diffStat } from './diff.tsx';\n\nexport interface ToolBlockProps {\n name: string;\n title?: string;\n output?: string;\n isError?: boolean;\n running?: boolean;\n /** Expanded blocks show full output; collapsed ones show a line of summary. */\n expanded?: boolean;\n}\n\n/** Output beyond this collapses to a count; the full text is in the transcript. */\nconst PREVIEW_LINES = 8;\n\n/**\n * One tool call, collapsed by default.\n *\n * A long tool result pushes the conversation off the screen, and the reason\n * someone is reading a coding agent's scrollback is almost never to re-read the\n * contents of a file it opened. What matters is which tool ran, on what, and\n * whether it failed - so that is what a collapsed block shows, and errors are\n * never collapsed.\n */\nexport function ToolBlock({\n name,\n title,\n output = '',\n isError,\n running,\n expanded,\n}: ToolBlockProps) {\n const marker = running ? '·' : isError ? '✗' : '✓';\n const color = isError ? theme.toolError : theme.tool;\n const isDiff = output.includes('\\n@@') || output.startsWith('---');\n\n const lines = output === '' ? [] : output.split('\\n');\n // An error is always shown in full: it is the one output the user has to read,\n // and it is the thing the model is about to react to.\n const showAll = expanded || isError;\n const shown = showAll ? lines : lines.slice(0, PREVIEW_LINES);\n const hidden = lines.length - shown.length;\n\n return (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text color={color}>\n {marker} <Text bold>{name}</Text>\n {title ? <Text color={theme.muted}> {title}</Text> : null}\n {isDiff && !showAll ? <Text color={theme.muted}> {diffStat(output)}</Text> : null}\n </Text>\n {isDiff && showAll ? (\n <Box marginLeft={2}>\n <DiffView diff={output} />\n </Box>\n ) : (\n shown.map((line, index) => (\n // Output lines have no identity beyond position, and this block is\n // replaced wholesale rather than reordered. See DiffView for the same.\n // biome-ignore lint/suspicious/noArrayIndexKey: position is the identity\n <Text key={index} color={theme.muted} wrap=\"truncate-end\">\n {' '}\n {line}\n </Text>\n ))\n )}\n {hidden > 0 && !isDiff && (\n <Text color={theme.muted}>\n {' '}\n ... {hidden} more lines\n </Text>\n )}\n </Box>\n );\n}\n",
95
+ "import { platform } from 'node:os';\nimport type { CreatedSession, UserPrompt } from '@earshot/core';\nimport { render } from 'ink';\nimport { App } from './app.tsx';\n\nexport interface RunTuiOptions {\n session: CreatedSession;\n model: string;\n initialPrompt?: UserPrompt;\n}\n\n/**\n * Windows renders more slowly and repaints more visibly than a POSIX terminal,\n * so the frame rate is capped rather than left at Ink's default. 30 is not a\n * performance tuning number: above it, ConPTY's repaint of the live region\n * flickers badly enough to be unpleasant to watch during a long turn.\n */\nconst WINDOWS_MAX_FPS = 30;\n\n/**\n * Starts the interactive app.\n *\n * Nothing in this package writes a DA1 (`CSI c`) or DCS terminal query. ConPTY\n * does not answer them and does not fail either: the query is swallowed and the\n * process sits waiting for a reply that never arrives, which presents to the\n * user as earshot hanging for a minute on startup. Any future capability\n * detection has to be feature-flagged off on Windows for the same reason, which\n * is why colour support is assumed from Ink's own detection rather than probed.\n */\nexport async function runTui(options: RunTuiOptions): Promise<number> {\n const isWindows = platform() === 'win32';\n\n const instance = render(\n <App\n session={options.session}\n model={options.model}\n {...(options.initialPrompt ? { initialPrompt: options.initialPrompt } : {})}\n />,\n {\n // Ctrl-C is handled by the app so a running turn can be interrupted without\n // tearing down the terminal mid-render and leaving it in a raw mode.\n exitOnCtrlC: false,\n // Console output from a dependency would otherwise be interleaved into the\n // live region and corrupt the frame Ink believes it has drawn.\n patchConsole: true,\n ...(isWindows ? { maxFps: WINDOWS_MAX_FPS } : {}),\n },\n );\n\n try {\n await instance.waitUntilExit();\n } finally {\n await options.session.dispose();\n }\n return 0;\n}\n",
96
+ "import {\n createSession,\n isPermissionMode,\n MissingCredentialsError,\n NoSessionToResumeError,\n type PermissionMode,\n UnknownModelError,\n} from '@earshot/core';\nimport { runTui } from '@earshot/tui';\nimport type { ParsedArgs } from '../args.ts';\nimport { parseCuriosity, parseMaxCost } from '../budget.ts';\nimport { startExtensions } from '../extensions/index.ts';\nimport { loadImage } from '../image.ts';\n\nconst DEFAULT_MODEL = 'anthropic/claude-opus-5';\n\n/**\n * The default command: the interactive TUI.\n *\n * Refuses to start without a TTY rather than rendering into a pipe. Ink would\n * happily draw frames into a redirect and produce a file full of escape\n * sequences; someone piping earshot almost certainly wanted `-p`, and the error\n * says so.\n */\nexport async function interactiveCommand(args: ParsedArgs): Promise<number> {\n const flags = args.flags;\n\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n process.stderr.write(\n 'earshot needs an interactive terminal. For scripted use, run `earshot -p \"<prompt>\"`.\\n',\n );\n return 2;\n }\n\n let mode: PermissionMode | undefined;\n const requested = flags['permission-mode'];\n if (typeof requested === 'string') {\n if (!isPermissionMode(requested)) {\n process.stderr.write(`\"${requested}\" is not a permission mode\\n`);\n return 2;\n }\n mode = requested;\n }\n\n // A bare `earshot \"do the thing\"` starts the TUI with that first turn already\n // running, which is how most sessions actually begin.\n const initialPrompt = args.positionals.join(' ').trim();\n let image: Awaited<ReturnType<typeof loadImage>> | undefined;\n if (typeof flags.image === 'string') {\n try {\n image = await loadImage(flags.image, process.cwd());\n } catch (error) {\n process.stderr.write(`image: ${(error as Error).message}\\n`);\n return 2;\n }\n }\n\n const curiosity = parseCuriosity(flags.curiosity);\n if (curiosity === 'invalid') {\n process.stderr.write(`\"${flags.curiosity}\" is not a curiosity level: low, normal or high\\n`);\n return 2;\n }\n const maxCostUsd = parseMaxCost(flags['max-cost']);\n if (maxCostUsd === 'invalid') {\n process.stderr.write(`\"${flags['max-cost']}\" is not an amount in dollars\\n`);\n return 2;\n }\n\n const extensions = await startExtensions(process.cwd());\n\n try {\n const session = await createSession({\n cwd: process.cwd(),\n extraTools: extensions.tools,\n problems: extensions.problems,\n onDispose: () => extensions.close(),\n model: typeof flags.model === 'string' ? flags.model : DEFAULT_MODEL,\n ...(mode ? { mode } : {}),\n ...(typeof flags['api-key'] === 'string' ? { apiKey: flags['api-key'] } : {}),\n ...(curiosity ? { curiosity } : {}),\n ...(maxCostUsd !== undefined ? { maxCostUsd } : {}),\n ...resumeFrom(flags),\n });\n\n return await runTui({\n session,\n model: typeof flags.model === 'string' ? flags.model : DEFAULT_MODEL,\n ...(initialPrompt !== '' || image\n ? {\n initialPrompt: image\n ? [...(initialPrompt ? [{ type: 'text' as const, text: initialPrompt }] : []), image]\n : initialPrompt,\n }\n : {}),\n });\n } catch (error) {\n // The session never reached dispose(), so anything already spawned is ours\n // to clean up here or it outlives the process that started it.\n await extensions.close();\n if (error instanceof UnknownModelError) {\n process.stderr.write(`${error.message}\\n\\nrun \\`earshot models\\` to see what is available\\n`);\n return 2;\n }\n if (error instanceof MissingCredentialsError) {\n process.stderr.write(`${error.message}\\n`);\n return 3;\n }\n if (error instanceof NoSessionToResumeError) {\n process.stderr.write(`${error.message}\\n`);\n return 2;\n }\n throw error;\n }\n}\n\nfunction resumeFrom(flags: ParsedArgs['flags']) {\n if (typeof flags.resume === 'string') return { resume: { path: flags.resume } } as const;\n if (flags.continue === true || flags.resume === true)\n return { resume: { latest: true } } as const;\n return {};\n}\n",
97
+ "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { LOCAL_SETTINGS, loadMcpConfig, TRUST_NOTE } from '@earshot/mcp';\nimport type { ParsedArgs } from '../args.ts';\n\n/**\n * `earshot mcp list|trust|untrust`.\n *\n * `list` deliberately does not start anything: seeing what is configured should\n * not be the thing that runs it.\n */\nexport async function mcpCommand(args: ParsedArgs): Promise<number> {\n const [action = 'list', name] = args.positionals;\n const cwd = process.cwd();\n\n if (action === 'list') return list(cwd);\n if (action === 'trust' || action === 'untrust') {\n if (!name) {\n process.stderr.write(`usage: earshot mcp ${action} <server>\\n`);\n return 2;\n }\n return setTrust(cwd, name, action === 'trust');\n }\n\n process.stderr.write(`earshot mcp: unknown action \"${action}\"\\n`);\n return 2;\n}\n\nasync function list(cwd: string): Promise<number> {\n const { servers, problems } = await loadMcpConfig(cwd);\n for (const problem of problems) process.stderr.write(`warning: ${problem}\\n`);\n\n if (servers.length === 0) {\n process.stdout.write(\n 'no mcp servers configured\\n\\n' +\n `add one under \"mcpServers\" in ${join('.earshot', 'settings.local.json')}\\n`,\n );\n return 0;\n }\n\n for (const server of servers) {\n const where =\n server.transport.type === 'stdio'\n ? [server.transport.command, ...server.transport.args].join(' ')\n : server.transport.url;\n const state = server.enabled ? '' : ` (not started: ${TRUST_NOTE})`;\n process.stdout.write(`${server.name} [${server.scope}] ${where}${state}\\n`);\n }\n return 0;\n}\n\n/**\n * Trust is recorded in local settings, which are not committed. Writing it to\n * project settings would let a repository trust itself in the next clone.\n */\nasync function setTrust(cwd: string, name: string, trust: boolean): Promise<number> {\n const { servers } = await loadMcpConfig(cwd);\n if (!servers.some((server) => server.name === name)) {\n process.stderr.write(`no mcp server named \"${name}\" is configured\\n`);\n return 2;\n }\n\n const path = join(cwd, LOCAL_SETTINGS);\n const raw = await readFile(path, 'utf8').catch(() => '{}');\n let settings: { mcpTrust?: string[] };\n try {\n settings = JSON.parse(raw) as { mcpTrust?: string[] };\n } catch (error) {\n process.stderr.write(`${path} is not valid JSON: ${(error as Error).message}\\n`);\n return 2;\n }\n\n const current = new Set(settings.mcpTrust ?? []);\n if (trust) current.add(name);\n else current.delete(name);\n\n await mkdir(dirname(path), { recursive: true });\n await writeFile(\n path,\n `${JSON.stringify({ ...settings, mcpTrust: [...current].sort() }, null, 2)}\\n`,\n 'utf8',\n );\n process.stdout.write(`${trust ? 'trusted' : 'no longer trusting'} \"${name}\" (${path})\\n`);\n return 0;\n}\n",
98
+ "import { buildRegistry, fetchCatalog, ModelCatalog } from '@earshot/providers';\nimport type { ParsedArgs } from '../args.ts';\n\n/** `earshot models [filter] [--refresh] [--json]` */\nexport async function modelsCommand(args: ParsedArgs): Promise<number> {\n const catalog = args.flags.refresh ? new ModelCatalog(await fetchCatalog()) : new ModelCatalog();\n const registry = buildRegistry({ catalog });\n\n const filter = args.positionals[0]?.toLowerCase();\n const models = registry\n .models()\n .filter(\n (m) =>\n !filter ||\n m.id.toLowerCase().includes(filter) ||\n m.providerId.toLowerCase().includes(filter) ||\n m.name.toLowerCase().includes(filter),\n );\n\n if (args.flags.json) {\n process.stdout.write(`${JSON.stringify(models, null, 2)}\\n`);\n return 0;\n }\n\n if (models.length === 0) {\n process.stderr.write(`no models match \"${filter}\"\\n`);\n return 1;\n }\n\n const rows = models.map((m) => ({\n ref: `${m.providerId}/${m.id}`,\n context: `${Math.round(m.contextWindow / 1000)}k`,\n price: m.cost ? `$${m.cost.input}/$${m.cost.output}` : '-',\n tags: [\n m.capabilities.reasoning ? 'reasoning' : '',\n m.capabilities.vision ? 'vision' : '',\n m.capabilities.tools ? '' : 'no-tools',\n ]\n .filter(Boolean)\n .join(' '),\n }));\n\n const width = Math.max(...rows.map((r) => r.ref.length));\n const priceWidth = Math.max(...rows.map((r) => r.price.length));\n for (const row of rows) {\n process.stdout.write(\n `${row.ref.padEnd(width)} ${row.context.padStart(6)} ${row.price.padStart(priceWidth)} ${row.tags}\\n`,\n );\n }\n process.stdout.write(\n `\\n${models.length} models across ${new Set(models.map((m) => m.providerId)).size} providers`,\n );\n process.stdout.write(` (catalog ${catalog.generatedAt.slice(0, 10)})\\n`);\n process.stdout.write('prices are USD per million tokens, input/output\\n');\n return 0;\n}\n",
99
+ "import { VERSION } from '@earshot/core';\nimport { parseArgs } from './args.ts';\nimport { acpCommand } from './commands/acp.ts';\nimport { authCommand } from './commands/auth.ts';\nimport { doctorCommand } from './commands/doctor.ts';\nimport { extensionsCommand } from './commands/extensions.ts';\nimport { headlessCommand } from './commands/headless.ts';\nimport { interactiveCommand } from './commands/interactive.ts';\nimport { mcpCommand } from './commands/mcp.ts';\nimport { modelsCommand } from './commands/models.ts';\n\nconst HELP = `earshot ${VERSION} - a terminal coding agent that actually listens\n\nUsage\n earshot start the interactive TUI\n earshot -p \"<prompt>\" headless: print the final response\n earshot auth <cmd> login, list or logout provider credentials\n earshot models [--refresh] list or refresh the model catalog\n earshot mcp <cmd> list, trust or untrust MCP servers\n earshot extensions <cmd> list, trust or untrust in-process extensions\n earshot acp serve editor clients over ACP v1 on stdio\n earshot doctor diagnose the local setup\n\nFlags\n --model <provider/model> model for this session\n --permission-mode <mode> plan | ask | accept-edits | auto | yolo\n --output-format <fmt> text | json | stream-json | json@v1 (with -p)\n --continue resume the most recent session here\n --resume [<path>] resume a specific session transcript\n --api-key <key> credentials for this run only\n --image <path|https-url> attach one PNG, JPEG, GIF or WebP image\n --max-cost <usd> stop and ask before spending past this\n --curiosity <level> low, normal or high: how readily it asks\n --version, -v print the version\n --help, -h print this help\n`;\n\nexport async function main(argv = process.argv.slice(2)): Promise<number> {\n const args = parseArgs(argv);\n const { command, flags } = args;\n\n if (flags.version || flags.v) {\n process.stdout.write(`${VERSION}\\n`);\n return 0;\n }\n if (flags.help || flags.h) {\n process.stdout.write(HELP);\n return 0;\n }\n\n const prompt = typeof flags.p === 'string' ? flags.p : undefined;\n if (prompt) return headlessCommand(prompt, args);\n\n if (command === 'models') return modelsCommand(args);\n if (command === 'mcp') return mcpCommand(args);\n if (command === 'extensions') return extensionsCommand(args);\n if (command === 'auth') return authCommand(args);\n if (command === 'doctor') return doctorCommand(args);\n if (command === 'acp') return acpCommand(args);\n if (command) {\n process.stderr.write(`earshot: \"${command}\" is not implemented yet\\n`);\n return 1;\n }\n\n return interactiveCommand(args);\n}\n",
100
+ "import { main } from './index.ts';\n\nconst code = await main();\nprocess.exitCode = code;\n"
101
+ ],
102
+ "mappings": ";AAAA,qBAAS;AACT,oBAAS;AACT,oBAAS,kBAAS;;;ACFlB;AACA;;;ACDA;AACA;AAGO,SAA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