@pruddiman/dispatch 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/helpers/file-logger.ts","../src/helpers/logger.ts","../src/helpers/guards.ts","../src/providers/opencode.ts","../src/helpers/timeout.ts","../src/providers/copilot.ts","../src/providers/claude.ts","../src/providers/codex.ts","../src/providers/detect.ts","../src/providers/index.ts","../src/helpers/cleanup.ts","../src/helpers/environment.ts","../src/orchestrator/fix-tests-pipeline.ts","../src/cli.ts","../src/spec-generator.ts","../src/datasources/index.ts","../src/datasources/github.ts","../src/helpers/slugify.ts","../src/helpers/branch-validation.ts","../src/datasources/azdevops.ts","../src/datasources/md.ts","../src/config.ts","../src/config-prompts.ts","../src/orchestrator/datasource-helpers.ts","../src/helpers/worktree.ts","../src/orchestrator/runner.ts","../src/helpers/confirm-large-batch.ts","../src/helpers/prereqs.ts","../src/helpers/gitignore.ts","../src/orchestrator/cli-config.ts","../src/orchestrator/spec-pipeline.ts","../src/agents/spec.ts","../src/helpers/format.ts","../src/helpers/retry.ts","../src/orchestrator/dispatch-pipeline.ts","../src/parser.ts","../src/agents/planner.ts","../src/dispatcher.ts","../src/agents/executor.ts","../src/agents/commit.ts","../src/tui.ts"],"sourcesContent":["/**\n * Per-issue file logger for detailed, structured log output.\n *\n * Writes timestamped, plain-text log entries to `.dispatch/logs/issue-{id}.log`.\n * Each log line is prefixed with an ISO 8601 timestamp. The logger provides\n * standard level methods (`info`, `debug`, `warn`, `error`) plus structured\n * methods for prompts, responses, phase transitions, and agent lifecycle events.\n *\n * An `AsyncLocalStorage<FileLogger>` instance is exported for scoping file\n * loggers to async contexts, allowing each issue processed in parallel to\n * maintain its own log file without threading parameters through call stacks.\n */\n\nimport { mkdirSync, writeFileSync, appendFileSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport const fileLoggerStorage = new AsyncLocalStorage<FileLogger>();\n\nexport class FileLogger {\n readonly filePath: string;\n\n private static sanitizeIssueId(issueId: string | number): string {\n const raw = String(issueId);\n return raw.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n }\n\n constructor(issueId: string | number, cwd: string) {\n const safeIssueId = FileLogger.sanitizeIssueId(issueId);\n this.filePath = join(cwd, \".dispatch\", \"logs\", `issue-${safeIssueId}.log`);\n mkdirSync(dirname(this.filePath), { recursive: true });\n writeFileSync(this.filePath, \"\", \"utf-8\");\n }\n\n private write(level: string, message: string): void {\n const timestamp = new Date().toISOString();\n const line = `[${timestamp}] [${level}] ${message}\\n`;\n appendFileSync(this.filePath, line, \"utf-8\");\n }\n\n info(message: string): void {\n this.write(\"INFO\", message);\n }\n\n debug(message: string): void {\n this.write(\"DEBUG\", message);\n }\n\n warn(message: string): void {\n this.write(\"WARN\", message);\n }\n\n error(message: string): void {\n this.write(\"ERROR\", message);\n }\n\n success(message: string): void {\n this.write(\"SUCCESS\", message);\n }\n\n task(message: string): void {\n this.write(\"TASK\", message);\n }\n\n dim(message: string): void {\n this.write(\"DIM\", message);\n }\n\n prompt(label: string, content: string): void {\n const separator = \"─\".repeat(40);\n this.write(\"PROMPT\", `${label}\\n${separator}\\n${content}\\n${separator}`);\n }\n\n response(label: string, content: string): void {\n const separator = \"─\".repeat(40);\n this.write(\"RESPONSE\", `${label}\\n${separator}\\n${content}\\n${separator}`);\n }\n\n phase(name: string): void {\n const banner = \"═\".repeat(40);\n this.write(\"PHASE\", `${banner}\\n${name}\\n${banner}`);\n }\n\n agentEvent(agent: string, event: string, detail?: string): void {\n const msg = detail ? `[${agent}] ${event}: ${detail}` : `[${agent}] ${event}`;\n this.write(\"AGENT\", msg);\n }\n\n close(): void {\n // no-op for sync writes; provides a cleanup hook for future use\n }\n}\n","/**\n * Minimal structured logger for CLI output.\n *\n * The initial log level is resolved at module load from environment variables:\n * 1. `LOG_LEVEL` env var — one of `\"debug\"`, `\"info\"`, `\"warn\"`, `\"error\"`\n * 2. `DEBUG` env var — any truthy value sets the level to `\"debug\"`\n * 3. Default: `\"info\"`\n *\n * At runtime, `log.verbose` (or the `--verbose` CLI flag) can override the\n * env-resolved level — setting it to `true` forces `\"debug\"`, and `false`\n * resets to `\"info\"` regardless of the original env value.\n */\n\nimport chalk from \"chalk\";\nimport { fileLoggerStorage } from \"./file-logger.js\";\n\n/** Supported log levels, ordered from most to least verbose. */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVEL_SEVERITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Resolve the effective log level from environment variables.\n * Priority: LOG_LEVEL > DEBUG > default (\"info\").\n */\nfunction resolveLogLevel(): LogLevel {\n const envLevel = process.env.LOG_LEVEL?.toLowerCase();\n if (envLevel && Object.hasOwn(LOG_LEVEL_SEVERITY, envLevel)) {\n return envLevel as LogLevel;\n }\n if (process.env.DEBUG) {\n return \"debug\";\n }\n return \"info\";\n}\n\n/** Current effective log level. */\nlet currentLevel: LogLevel = resolveLogLevel();\n\n/** Returns the current effective log level. */\nexport function getLogLevel(): LogLevel {\n return currentLevel;\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_SEVERITY[level] >= LOG_LEVEL_SEVERITY[currentLevel];\n}\n\n/** Strip ANSI escape codes from a string for plain-text file logging. */\nfunction stripAnsi(str: string): string {\n return str.replace(/\\x1B\\[[0-9;]*m/g, \"\");\n}\n\n/** Maximum depth to traverse when unwinding nested error `.cause` chains. */\nconst MAX_CAUSE_CHAIN_DEPTH = 5;\n\nexport const log = {\n verbose: false as boolean,\n\n info(msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.blue(\"ℹ\"), msg);\n fileLoggerStorage.getStore()?.info(stripAnsi(msg));\n },\n success(msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.green(\"✔\"), msg);\n fileLoggerStorage.getStore()?.success(stripAnsi(msg));\n },\n warn(msg: string) {\n if (!shouldLog(\"warn\")) return;\n console.error(chalk.yellow(\"⚠\"), msg);\n fileLoggerStorage.getStore()?.warn(stripAnsi(msg));\n },\n error(msg: string) {\n if (!shouldLog(\"error\")) return;\n console.error(chalk.red(\"✖\"), msg);\n fileLoggerStorage.getStore()?.error(stripAnsi(msg));\n },\n task(index: number, total: number, msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.cyan(`[${index + 1}/${total}]`), msg);\n fileLoggerStorage.getStore()?.task(stripAnsi(`[${index + 1}/${total}] ${msg}`));\n },\n dim(msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.dim(msg));\n fileLoggerStorage.getStore()?.dim(stripAnsi(msg));\n },\n\n /**\n * Print a debug/verbose message. Only visible when the log level is\n * `\"debug\"`. Messages are prefixed with a dim arrow to visually nest\n * them under the preceding info/error line.\n */\n debug(msg: string) {\n if (!shouldLog(\"debug\")) return;\n console.log(chalk.dim(` ⤷ ${msg}`));\n fileLoggerStorage.getStore()?.debug(stripAnsi(msg));\n },\n\n /**\n * Extract and format the full error cause chain. Node.js network errors\n * (e.g. `TypeError: fetch failed`) bury the real reason in nested `.cause`\n * properties — this helper surfaces them all.\n */\n formatErrorChain(err: unknown): string {\n const parts: string[] = [];\n let current: unknown = err;\n let depth = 0;\n\n while (current && depth < MAX_CAUSE_CHAIN_DEPTH) {\n if (current instanceof Error) {\n const prefix = depth === 0 ? \"Error\" : \"Cause\";\n parts.push(`${prefix}: ${current.message}`);\n if (current.cause) {\n current = current.cause;\n } else {\n break;\n }\n } else {\n parts.push(`${depth === 0 ? \"Error\" : \"Cause\"}: ${String(current)}`);\n break;\n }\n depth++;\n }\n\n return parts.join(\"\\n ⤷ \");\n },\n\n /**\n * Extract the raw error message string from an unknown thrown value.\n * Returns `err.message` for Error instances, `String(err)` for other\n * truthy values, and `\"\"` for null/undefined.\n */\n extractMessage(err: unknown): string {\n if (err instanceof Error) return err.message;\n if (err != null) return String(err);\n return \"\";\n },\n};\n\nObject.defineProperty(log, \"verbose\", {\n get(): boolean {\n return currentLevel === \"debug\";\n },\n set(value: boolean) {\n currentLevel = value ? \"debug\" : \"info\";\n },\n enumerable: true,\n configurable: true,\n});\n","/**\n * Runtime type guard utilities.\n *\n * Provides small, reusable type predicates that validate unknown values\n * at runtime, enabling safe property access without unsafe `as` casts.\n */\n\n/**\n * Check whether an unknown value is a non-null object that contains\n * the specified key.\n *\n * Narrows the value to `Record<K, unknown>` so the caller can safely\n * access `value[key]` without an `as` cast.\n *\n * @param value - The value to inspect (may be any type).\n * @param key - The property name to look for.\n * @returns `true` when `value` is an object with the given key.\n */\nexport function hasProperty<K extends string>(\n value: unknown,\n key: K,\n): value is Record<K, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n","/**\n * OpenCode provider — wraps the @opencode-ai/sdk to conform to the\n * generic ProviderInstance interface.\n *\n * Uses the asynchronous prompt API (`promptAsync`) combined with SSE\n * event streaming to avoid HTTP timeout issues. The blocking `prompt()`\n * SDK method sends a single long-lived HTTP request that can exceed\n * Node.js/undici's default headers timeout for slow LLM responses.\n *\n * Flow:\n * 1. `promptAsync()` — fire-and-forget POST that returns 204 immediately\n * 2. `event.subscribe()` — SSE stream that yields session lifecycle events\n * 3. Wait for `session.idle` (success) or `session.error` (failure)\n * 4. `session.messages()` — fetch the completed response\n */\n\nimport {\n createOpencode,\n createOpencodeClient,\n type OpencodeClient,\n type Part,\n type TextPart,\n type Event as SdkEvent,\n} from \"@opencode-ai/sdk\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { hasProperty } from \"../helpers/guards.js\";\n\n/**\n * List available OpenCode models for configured providers.\n *\n * Starts a temporary server (or connects to an existing one), fetches\n * providers that have an API key configured, and returns their models\n * in \"providerId/modelId\" format (e.g. \"anthropic/claude-sonnet-4\").\n */\nexport async function listModels(opts?: ProviderBootOptions): Promise<string[]> {\n let client: OpencodeClient;\n let stopServer: (() => void) | undefined;\n\n if (opts?.url) {\n client = createOpencodeClient({ baseUrl: opts.url });\n } else {\n // See boot() for details on the SDK cwd limitation.\n if (opts?.cwd) {\n log.debug(`listModels: requested cwd \"${opts.cwd}\" — OpenCode SDK does not support spawn-level cwd`);\n }\n try {\n const oc = await createOpencode({ port: 0 });\n client = oc.client;\n stopServer = () => oc.server.close();\n } catch (err) {\n log.debug(`listModels: failed to start OpenCode server: ${log.formatErrorChain(err)}`);\n throw err;\n }\n }\n\n try {\n const { data } = await client.config.providers();\n if (!data) return [];\n return data.providers\n .filter((p) => p.source === \"env\" || p.source === \"config\" || p.source === \"custom\")\n .flatMap((p) => Object.keys(p.models).map((modelId) => `${p.id}/${modelId}`))\n .sort();\n } finally {\n stopServer?.();\n }\n}\n\n/**\n * Boot an OpenCode instance — either connect to a running server\n * or start a new one.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n let client: OpencodeClient;\n let stopServer: (() => void) | undefined;\n let cleaned = false;\n\n if (opts?.url) {\n log.debug(`Connecting to existing OpenCode server at ${opts.url}`);\n client = createOpencodeClient({ baseUrl: opts.url });\n } else {\n log.debug(\"No --server-url provided, spawning local OpenCode server...\");\n // NOTE: The @opencode-ai/sdk `createOpencodeServer` spawns the `opencode`\n // process via `child_process.spawn()` without a `cwd` option — the server\n // inherits `process.cwd()`. There is no `ServerOptions.cwd` or `Config`\n // field to control the working directory. When a worktree `cwd` is needed,\n // the prompt-level cwd (set by the executor/dispatcher) ensures the agent\n // operates in the correct directory.\n if (opts?.cwd) {\n log.debug(`Requested cwd \"${opts.cwd}\" — OpenCode SDK does not support spawn-level cwd; relying on prompt-level cwd`);\n }\n try {\n const oc = await createOpencode({ port: 0 });\n client = oc.client;\n stopServer = () => oc.server.close();\n log.debug(\"OpenCode server started successfully\");\n } catch (err) {\n log.debug(`Failed to start OpenCode server: ${log.formatErrorChain(err)}`);\n throw err;\n }\n }\n\n // ── Parse model override from boot options ────────────────────\n // Format: \"providerID/modelID\" (e.g. \"anthropic/claude-sonnet-4\")\n let modelOverride: { providerID: string; modelID: string } | undefined;\n if (opts?.model) {\n const slash = opts.model.indexOf(\"/\");\n if (slash > 0) {\n modelOverride = {\n providerID: opts.model.slice(0, slash),\n modelID: opts.model.slice(slash + 1),\n };\n log.debug(`Model override: ${opts.model}`);\n } else {\n log.debug(`Ignoring model override \"${opts.model}\": must be in \"provider/model\" format`);\n }\n }\n\n // ── Retrieve the active model (best-effort) ──────────────────\n let model: string | undefined = opts?.model;\n if (!model) {\n try {\n const { data: config } = await client.config.get();\n if (config?.model) {\n // model is in \"provider/model\" format (e.g. \"anthropic/claude-sonnet-4\")\n model = config.model;\n log.debug(`Detected model: ${model}`);\n }\n } catch (err) {\n log.debug(`Failed to retrieve model from config: ${log.formatErrorChain(err)}`);\n }\n }\n\n return {\n name: \"opencode\",\n model,\n\n async createSession(): Promise<string> {\n log.debug(\"Creating OpenCode session...\");\n try {\n const { data: session } = await client.session.create();\n if (!session) {\n throw new Error(\"Failed to create OpenCode session\");\n }\n log.debug(`Session created: ${session.id}`);\n return session.id;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n log.debug(`Sending async prompt to session ${sessionId} (${text.length} chars)...`);\n\n let controller: AbortController | undefined;\n\n try {\n // ── 1. Fire-and-forget: start the LLM processing ──────────\n const { error: promptError } = await client.session.promptAsync({\n path: { id: sessionId },\n body: {\n parts: [{ type: \"text\", text }],\n ...(modelOverride ? { model: modelOverride } : {}),\n },\n });\n\n if (promptError) {\n throw new Error(`OpenCode promptAsync failed: ${JSON.stringify(promptError)}`);\n }\n\n log.debug(\"Async prompt accepted, subscribing to events...\");\n\n // ── 2. Subscribe to SSE events ────────────────────────────\n controller = new AbortController();\n try {\n const { stream } = await client.event.subscribe({\n signal: controller.signal,\n });\n\n // ── 3. Wait for session to become idle or error ───────────\n for await (const event of stream) {\n if (!isSessionEvent(event, sessionId)) continue;\n\n if (\n event.type === \"message.part.updated\" &&\n event.properties.part.type === \"text\"\n ) {\n const delta = event.properties.delta;\n if (delta) {\n log.debug(`Streaming text (+${delta.length} chars)...`);\n }\n continue;\n }\n\n if (event.type === \"session.error\") {\n const err = event.properties.error;\n throw new Error(\n `OpenCode session error: ${err ? JSON.stringify(err) : \"unknown error\"}`\n );\n }\n\n if (event.type === \"session.idle\") {\n log.debug(\"Session went idle, fetching result...\");\n break;\n }\n }\n } finally {\n if (controller && !controller.signal.aborted) controller.abort();\n }\n\n // ── 4. Fetch the completed message ────────────────────────\n const { data: messages } = await client.session.messages({\n path: { id: sessionId },\n });\n\n if (!messages || messages.length === 0) {\n log.debug(\"No messages found in session\");\n return null;\n }\n\n const lastAssistant = [...messages]\n .reverse()\n .find((m) => m.info.role === \"assistant\");\n\n if (!lastAssistant) {\n log.debug(\"No assistant message found in session\");\n return null;\n }\n\n // Check for errors on the assistant message\n if (hasProperty(lastAssistant.info, \"error\") && lastAssistant.info.error) {\n throw new Error(\n `OpenCode assistant error: ${JSON.stringify(lastAssistant.info.error)}`\n );\n }\n\n // ── 5. Extract text parts ─────────────────────────────────\n const textParts = lastAssistant.parts.filter(\n (p: Part): p is TextPart => p.type === \"text\" && \"text\" in p\n );\n const result = textParts.map((p: TextPart) => p.text).join(\"\\n\") || null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n if (cleaned) return;\n cleaned = true;\n log.debug(\"Cleaning up OpenCode provider...\");\n try {\n stopServer?.();\n } catch (err) {\n log.debug(`Failed to stop OpenCode server: ${log.formatErrorChain(err)}`);\n }\n },\n };\n}\n\n/**\n * Check whether an SSE event belongs to the given session.\n *\n * Different event types store the session ID in different places:\n * - `session.*` events → `properties.sessionID`\n * - `message.*` events → `properties.info.sessionID` or `properties.part.sessionID`\n */\nfunction isSessionEvent(event: SdkEvent, sessionId: string): boolean {\n const props: unknown = event.properties;\n\n if (!hasProperty(props, \"sessionID\") && !hasProperty(props, \"info\") && !hasProperty(props, \"part\")) {\n return false;\n }\n\n // Direct sessionID on the event (session.idle, session.error, session.status, etc.)\n if (hasProperty(props, \"sessionID\") && props.sessionID === sessionId) return true;\n\n // Nested in .info (message.updated)\n if (hasProperty(props, \"info\") && hasProperty(props.info, \"sessionID\") && props.info.sessionID === sessionId) {\n return true;\n }\n\n // Nested in .part (message.part.updated)\n if (hasProperty(props, \"part\") && hasProperty(props.part, \"sessionID\") && props.part.sessionID === sessionId) {\n return true;\n }\n\n return false;\n}\n","/**\n * Generic promise timeout utility.\n *\n * Provides a reusable `withTimeout` wrapper that races a promise against\n * a `setTimeout` rejection. Used by the dispatch pipeline to bound\n * planning and execution durations. Timeout failures are distinguished\n * from other errors via the custom `TimeoutError` class.\n */\n\n/**\n * Thrown when a `withTimeout` call exceeds the specified duration.\n *\n * The `label` property (if set) identifies which operation timed out,\n * making log output and error messages more diagnosable.\n */\nexport class TimeoutError extends Error {\n /** Optional label identifying the operation that timed out. */\n readonly label?: string;\n\n constructor(ms: number, label?: string) {\n const suffix = label ? ` [${label}]` : \"\";\n super(`Timed out after ${ms}ms${suffix}`);\n this.name = \"TimeoutError\";\n this.label = label;\n }\n}\n\n/**\n * Race a promise against a timeout.\n *\n * If the promise resolves or rejects before `ms` milliseconds, its\n * result is returned (or its error re-thrown). If the timeout fires\n * first, a `TimeoutError` is thrown.\n *\n * The timer is always cleaned up to avoid leaking handles, regardless\n * of which branch wins the race.\n *\n * @param promise - The async operation to time-bound\n * @param ms - Timeout duration in milliseconds\n * @param label - Optional label included in the `TimeoutError` message\n * @returns The resolved value of `promise`\n * @throws {TimeoutError} If the timeout fires before the promise settles\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n label?: string,\n): Promise<T> {\n const p = new Promise<T>((resolve, reject) => {\n let settled = false;\n\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n reject(new TimeoutError(ms, label));\n }, ms);\n\n promise.then(\n (value) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n\n // Attach a no-op handler so the rejection is never briefly \"unhandled\"\n // when the losing side of the race fires during fake-timer advancement.\n p.catch(() => {});\n\n return p;\n}\n","/**\n * GitHub Copilot provider — wraps the @github/copilot-sdk to conform\n * to the generic ProviderInstance interface.\n *\n * Requires the `copilot` CLI to be installed and available on PATH\n * (or specify the path via COPILOT_CLI_PATH).\n *\n * Authentication options:\n * - Logged-in Copilot CLI user (default)\n * - COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN env vars\n */\n\nimport { CopilotClient, approveAll, type AssistantMessageEvent, type CopilotSession } from \"@github/copilot-sdk\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { withTimeout } from \"../helpers/timeout.js\";\n\n/**\n * List available Copilot models.\n *\n * Starts a temporary client, fetches the model list, then stops it.\n * Returns bare model IDs (e.g. \"claude-sonnet-4-5\").\n */\nexport async function listModels(opts?: ProviderBootOptions): Promise<string[]> {\n const client = new CopilotClient({\n ...(opts?.url ? { cliUrl: opts.url } : {}),\n });\n try {\n await client.start();\n const models = await client.listModels();\n return models.map((m) => m.id).sort();\n } finally {\n await client.stop().catch(() => {});\n }\n}\n\n/**\n * Boot a Copilot provider instance — starts or connects to a Copilot CLI server.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n log.debug(opts?.url ? `Connecting to Copilot CLI at ${opts.url}` : \"Starting Copilot CLI...\");\n\n const client = new CopilotClient({\n ...(opts?.url ? { cliUrl: opts.url } : {}),\n ...(opts?.cwd ? { cwd: opts.cwd } : {}),\n });\n\n try {\n await client.start();\n log.debug(\"Copilot CLI started successfully\");\n } catch (err) {\n log.debug(`Failed to start Copilot CLI: ${log.formatErrorChain(err)}`);\n throw err;\n }\n\n // Model is detected lazily after the first session is created\n let model: string | undefined;\n let modelDetected = false;\n\n // Track live sessions for prompt routing and cleanup\n const sessions = new Map<string, CopilotSession>();\n\n return {\n name: \"copilot\",\n get model() {\n return model;\n },\n\n async createSession(): Promise<string> {\n log.debug(\"Creating Copilot session...\");\n try {\n const session = await client.createSession({\n ...(opts?.model ? { model: opts.model } : {}),\n ...(opts?.cwd ? { workingDirectory: opts.cwd } : {}),\n onPermissionRequest: approveAll,\n });\n sessions.set(session.sessionId, session);\n log.debug(`Session created: ${session.sessionId}`);\n\n // Detect actual default model from the first session (best-effort, once only)\n if (!modelDetected) {\n modelDetected = true;\n try {\n const result = await session.rpc.model.getCurrent();\n if (result.modelId) {\n model = result.modelId;\n log.debug(`Detected model: ${model}`);\n }\n } catch (err) {\n log.debug(`Failed to detect model from session: ${log.formatErrorChain(err)}`);\n }\n }\n\n return session.sessionId;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n const session = sessions.get(sessionId);\n if (!session) {\n throw new Error(`Copilot session ${sessionId} not found`);\n }\n\n log.debug(`Sending prompt to session ${sessionId} (${text.length} chars)...`);\n try {\n // ── 1. Fire-and-forget: start LLM processing ──────────────\n await session.send({ prompt: text });\n log.debug(\"Async prompt accepted, waiting for session to become idle...\");\n\n // ── 2. Wait for session.idle or session.error ─────────────\n let unsubIdle: (() => void) | undefined;\n let unsubErr: (() => void) | undefined;\n try {\n await withTimeout(\n new Promise<void>((resolve, reject) => {\n unsubIdle = session.on(\"session.idle\", () => {\n resolve();\n });\n\n unsubErr = session.on(\"session.error\", (event) => {\n reject(new Error(`Copilot session error: ${event.data.message}`));\n });\n }),\n 300_000,\n \"copilot session ready\",\n );\n } finally {\n unsubIdle?.();\n unsubErr?.();\n }\n\n log.debug(\"Session went idle, fetching result...\");\n\n // ── 3. Fetch the completed messages ───────────────────────\n const events = await session.getMessages();\n const last = [...events]\n .reverse()\n .find((e): e is AssistantMessageEvent => e.type === \"assistant.message\");\n\n const result = last?.data?.content ?? null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n log.debug(\"Cleaning up Copilot provider...\");\n // Destroy all active sessions before stopping the server\n const destroyOps = [...sessions.values()].map((s) =>\n s.destroy().catch((err) => {\n log.debug(`Failed to destroy Copilot session: ${log.formatErrorChain(err)}`);\n })\n );\n await Promise.all(destroyOps);\n sessions.clear();\n\n await client.stop().catch((err) => {\n log.debug(`Failed to stop Copilot client: ${log.formatErrorChain(err)}`);\n });\n },\n };\n}\n","/**\n * Claude provider — wraps the @anthropic-ai/claude-agent-sdk V2 preview\n * to conform to the generic ProviderInstance interface.\n *\n * Uses the V2 session-based API: `unstable_v2_createSession` for session\n * creation, `session.send()`/`session.stream()` for prompting, and manual\n * `session.close()` for cleanup (the project targets ES2022 which does not\n * include the Disposable lib required for `await using`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { unstable_v2_createSession, type SDKSession, type SDKMessage } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\n\n/**\n * List available Claude models.\n *\n * The Claude Agent SDK does not expose a model listing API, so this returns\n * a hardcoded list of known Claude model identifiers.\n */\nexport async function listModels(_opts?: ProviderBootOptions): Promise<string[]> {\n return [\n \"claude-haiku-3-5\",\n \"claude-opus-4-6\",\n \"claude-sonnet-4\",\n \"claude-sonnet-4-5\",\n ];\n}\n\n/**\n * Boot a Claude provider instance using the V2 preview API.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n const model = opts?.model ?? \"claude-sonnet-4\";\n const cwd = opts?.cwd;\n log.debug(`Booting Claude provider with model ${model}`);\n\n const sessions = new Map<string, SDKSession>();\n\n return {\n name: \"claude\",\n model,\n\n async createSession(): Promise<string> {\n log.debug(\"Creating Claude session...\");\n try {\n const sessionOpts = { model, permissionMode: 'acceptEdits' as const, ...(cwd ? { cwd } : {}) };\n const session = unstable_v2_createSession(sessionOpts);\n const sessionId = randomUUID();\n sessions.set(sessionId, session);\n log.debug(`Session created: ${sessionId}`);\n return sessionId;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n const session = sessions.get(sessionId);\n if (!session) {\n throw new Error(`Claude session ${sessionId} not found`);\n }\n\n log.debug(`Sending prompt to session ${sessionId} (${text.length} chars)...`);\n try {\n await session.send(text);\n\n const parts: string[] = [];\n for await (const msg of session.stream()) {\n if (msg.type === \"assistant\") {\n const msgText = msg.message.content\n .filter((block: { type: string }) => block.type === \"text\")\n .map((block: { type: string; text: string }) => block.text)\n .join(\"\");\n if (msgText) parts.push(msgText);\n }\n }\n\n const result = parts.join(\"\") || null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n log.debug(\"Cleaning up Claude provider...\");\n for (const session of sessions.values()) {\n try { session.close(); } catch {}\n }\n sessions.clear();\n },\n };\n}\n","/**\n * Codex provider — wraps the @openai/codex SDK to conform to the\n * generic ProviderInstance interface.\n *\n * Uses the AgentLoop class for session management. Each session creates\n * its own AgentLoop instance with \"full-auto\" approval policy so that\n * file edits and shell commands are auto-approved.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\n\n/**\n * Lazily load the @openai/codex SDK.\n *\n * The package ships as a CLI bundle without a proper library entry-point\n * (no `main` / `module` / `exports` in its package.json). A top-level\n * static `import` would cause Vite's import analysis to fail at test time\n * for every test file that transitively touches the provider registry.\n * Using a dynamic import defers resolution to runtime so that only code\n * paths that actually exercise the Codex provider pay the cost.\n */\nasync function loadAgentLoop(): Promise<typeof import(\"@openai/codex\")> {\n return import(\"@openai/codex\");\n}\n\n/**\n * List available Codex models.\n *\n * The Codex SDK does not expose a model listing API, so this returns\n * a hardcoded list of known compatible model identifiers.\n */\nexport async function listModels(_opts?: ProviderBootOptions): Promise<string[]> {\n return [\n \"codex-mini-latest\",\n \"o3-mini\",\n \"o4-mini\",\n ];\n}\n\n/**\n * Boot a Codex provider instance.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n const model = opts?.model ?? \"o4-mini\";\n log.debug(`Booting Codex provider with model ${model}`);\n\n const { AgentLoop } = await loadAgentLoop();\n\n type AgentLoopInstance = InstanceType<typeof AgentLoop>;\n const sessions = new Map<string, AgentLoopInstance>();\n\n return {\n name: \"codex\",\n model,\n\n async createSession(): Promise<string> {\n log.debug(\"Creating Codex session...\");\n try {\n const sessionId = randomUUID();\n const agent = new AgentLoop({\n model,\n config: { model, instructions: \"\" },\n approvalPolicy: \"full-auto\",\n ...(opts?.cwd ? { rootDir: opts.cwd } : {}),\n additionalWritableRoots: [],\n getCommandConfirmation: async () => ({ approved: true }),\n onItem: () => {},\n onLoading: () => {},\n onLastResponseId: () => {},\n });\n sessions.set(sessionId, agent);\n log.debug(`Session created: ${sessionId}`);\n return sessionId;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n const agent = sessions.get(sessionId);\n if (!agent) {\n throw new Error(`Codex session ${sessionId} not found`);\n }\n\n log.debug(`Sending prompt to session ${sessionId} (${text.length} chars)...`);\n try {\n const items = await agent.run([text]);\n\n const parts: string[] = [];\n for (const item of items) {\n if (item.type === \"message\" && \"content\" in item) {\n const content = (item as { type: string; content: Array<{ type: string; text?: string }> }).content;\n const itemText = content\n .filter((block: { type: string }) => block.type === \"output_text\")\n .map((block: { type: string; text?: string }) => block.text ?? \"\")\n .join(\"\");\n if (itemText) parts.push(itemText);\n }\n }\n\n const result = parts.join(\"\") || null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n log.debug(\"Cleaning up Codex provider...\");\n for (const agent of sessions.values()) {\n try { agent.terminate(); } catch {}\n }\n sessions.clear();\n },\n };\n}\n","/**\n * Provider binary detection — checks whether each provider's CLI binary\n * is available on PATH.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport type { ProviderName } from \"./interface.js\";\n\nconst exec = promisify(execFile);\n\n/** Kill provider binary detection after this many milliseconds. */\nconst DETECTION_TIMEOUT_MS = 5000;\n\n/**\n * Maps each provider name to its expected CLI binary.\n */\nexport const PROVIDER_BINARIES: Record<ProviderName, string> = {\n opencode: \"opencode\",\n copilot: \"copilot\",\n claude: \"claude\",\n codex: \"codex\",\n};\n\n/**\n * Check whether a provider's CLI binary is available on PATH.\n *\n * Attempts to execute the binary with `--version`. Resolves `true` if the\n * binary is found, `false` otherwise. Never rejects.\n */\nexport async function checkProviderInstalled(\n name: ProviderName,\n): Promise<boolean> {\n try {\n await exec(PROVIDER_BINARIES[name], [\"--version\"], {\n shell: process.platform === \"win32\",\n timeout: DETECTION_TIMEOUT_MS,\n });\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Provider registry — maps provider names to their boot functions.\n *\n * To add a new agent backend:\n * 1. Create `src/providers/<name>.ts` exporting an async `boot()` function\n * 2. Import and register it in the `PROVIDERS` map below\n * 3. Add the name to the `ProviderName` union in `src/providers/interface.ts`\n */\n\nimport type { ProviderName, ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { boot as bootOpencode, listModels as listOpencodeModels } from \"./opencode.js\";\nimport { boot as bootCopilot, listModels as listCopilotModels } from \"./copilot.js\";\nimport { boot as bootClaude, listModels as listClaudeModels } from \"./claude.js\";\nimport { boot as bootCodex, listModels as listCodexModels } from \"./codex.js\";\n\ntype BootFn = (opts?: ProviderBootOptions) => Promise<ProviderInstance>;\ntype ListModelsFn = (opts?: ProviderBootOptions) => Promise<string[]>;\n\nconst PROVIDERS: Record<ProviderName, BootFn> = {\n opencode: bootOpencode,\n copilot: bootCopilot,\n claude: bootClaude,\n codex: bootCodex,\n};\n\nconst LIST_MODELS: Record<ProviderName, ListModelsFn> = {\n opencode: listOpencodeModels,\n copilot: listCopilotModels,\n claude: listClaudeModels,\n codex: listCodexModels,\n};\n\n/**\n * All registered provider names — useful for CLI help text and validation.\n */\nexport const PROVIDER_NAMES = Object.keys(PROVIDERS) as ProviderName[];\n\n/**\n * Boot a provider by name.\n *\n * @throws if the provider name is not registered.\n */\nexport async function bootProvider(\n name: ProviderName,\n opts?: ProviderBootOptions\n): Promise<ProviderInstance> {\n const bootFn = PROVIDERS[name];\n if (!bootFn) {\n throw new Error(\n `Unknown provider \"${name}\". Available: ${PROVIDER_NAMES.join(\", \")}`\n );\n }\n return bootFn(opts);\n}\n\n/**\n * List available models for a provider by name.\n *\n * Starts a temporary provider instance (or connects to an existing server),\n * fetches the model list, and tears down. Returns model IDs as strings.\n * Throws if the provider is unavailable (caller should handle gracefully).\n *\n * @throws if the provider name is not registered or the provider is unavailable.\n */\nexport async function listProviderModels(\n name: ProviderName,\n opts?: ProviderBootOptions\n): Promise<string[]> {\n const fn = LIST_MODELS[name];\n if (!fn) {\n throw new Error(\n `Unknown provider \"${name}\". Available: ${PROVIDER_NAMES.join(\", \")}`\n );\n }\n return fn(opts);\n}\n\nexport type { ProviderName, ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nexport { PROVIDER_BINARIES, checkProviderInstalled } from \"./detect.js\";\n","/**\n * Process-level cleanup registry.\n *\n * Sub-modules (orchestrator, spec-generator) register their provider's\n * `cleanup()` here when the provider boots. The CLI signal handlers and\n * error handler drain the registry before exiting.\n *\n * All registered functions are invoked once; the registry is cleared\n * after each drain so repeated calls are harmless.\n */\n\nconst cleanups: Array<() => Promise<void>> = [];\n\n/**\n * Register an async cleanup function to be called on process shutdown.\n */\nexport function registerCleanup(fn: () => Promise<void>): void {\n cleanups.push(fn);\n}\n\n/**\n * Run all registered cleanup functions, then clear the registry.\n * Errors are swallowed to prevent cleanup failures from masking the\n * original error or blocking process exit.\n */\nexport async function runCleanup(): Promise<void> {\n const fns = cleanups.splice(0);\n for (const fn of fns) {\n try {\n await fn();\n } catch {\n // swallow — cleanup must not throw\n }\n }\n}\n","/**\n * Runtime environment detection for OS-aware agent prompts.\n *\n * Detects the host operating system and produces a formatted text block\n * that can be injected into agent system prompts so they know to run\n * commands directly instead of writing intermediate scripts.\n */\n\nexport interface EnvironmentInfo {\n /** Raw Node.js platform string (e.g. \"win32\", \"linux\", \"darwin\"). */\n platform: string;\n /** Human-readable OS name. */\n os: string;\n /** Default shell description for the platform. */\n shell: string;\n}\n\n/**\n * Detect the runtime environment from `process.platform`.\n */\nexport function getEnvironmentInfo(): EnvironmentInfo {\n const platform = process.platform;\n switch (platform) {\n case \"win32\":\n return { platform, os: \"Windows\", shell: \"cmd.exe/PowerShell\" };\n case \"darwin\":\n return { platform, os: \"macOS\", shell: \"zsh/bash\" };\n default:\n return { platform, os: \"Linux\", shell: \"bash\" };\n }\n}\n\n/**\n * Format environment information as a prompt text block.\n *\n * Returns a multi-line string describing the host OS, default shell,\n * and an instruction to run commands directly.\n */\nexport function formatEnvironmentPrompt(): string {\n const env = getEnvironmentInfo();\n return [\n `## Environment`,\n `- **Operating System:** ${env.os}`,\n `- **Default Shell:** ${env.shell}`,\n `- Always run commands directly in the shell. Do NOT write intermediate scripts (e.g. .bat, .ps1, .py files) unless the task explicitly requires creating a script.`,\n ].join(\"\\n\");\n}\n\n/** Alias used by the dispatcher module. */\nexport const getEnvironmentBlock = formatEnvironmentPrompt;\n","/**\n * Fix-tests pipeline — detects the project's test command, runs the test\n * suite, captures failure output, dispatches an AI agent to fix the broken\n * tests, and optionally re-runs tests to verify the fix.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { execFile as execFileCb } from \"node:child_process\";\nimport type { FixTestsSummary } from \"./runner.js\";\nimport type { ProviderName } from \"../providers/interface.js\";\nimport { bootProvider } from \"../providers/index.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { FileLogger, fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/* ------------------------------------------------------------------ */\n/* Types */\n/* ------------------------------------------------------------------ */\n\nexport interface FixTestsPipelineOptions {\n cwd: string;\n provider: string;\n serverUrl?: string;\n verbose: boolean;\n dryRun?: boolean;\n testTimeout?: number;\n}\n\nexport interface TestRunResult {\n exitCode: number | null;\n stdout: string;\n stderr: string;\n command: string;\n}\n\n/* ------------------------------------------------------------------ */\n/* Test runner utilities */\n/* ------------------------------------------------------------------ */\n\n/** Detect the test command from package.json in the given directory. */\nexport async function detectTestCommand(cwd: string): Promise<string | null> {\n try {\n const raw = await readFile(join(cwd, \"package.json\"), \"utf-8\");\n let pkg: any;\n try {\n pkg = JSON.parse(raw);\n } catch {\n log.debug(\n `Failed to parse package.json: ${raw.slice(0, 200)}`,\n );\n return null;\n }\n const testScript: unknown = pkg?.scripts?.test;\n if (\n typeof testScript === \"string\" &&\n testScript !== 'echo \"Error: no test specified\" && exit 1'\n ) {\n return \"npm test\";\n }\n return null;\n } catch {\n return null;\n }\n}\n\n/** Run a shell command and capture its output. Does NOT throw on non-zero exit. */\nexport function runTestCommand(\n command: string,\n cwd: string,\n): Promise<TestRunResult> {\n return new Promise((resolve) => {\n const [cmd, ...args] = command.split(\" \");\n execFileCb(\n cmd,\n args,\n { cwd, maxBuffer: 10 * 1024 * 1024, shell: process.platform === \"win32\" },\n (error, stdout, stderr) => {\n const exitCode =\n error && \"code\" in error\n ? ((error as { code?: number }).code ?? 1)\n : error\n ? 1\n : 0;\n resolve({ exitCode, stdout, stderr, command });\n },\n );\n });\n}\n\n/* ------------------------------------------------------------------ */\n/* Prompt builder */\n/* ------------------------------------------------------------------ */\n\n/** Build a focused AI prompt from test failure output. */\nexport function buildFixTestsPrompt(\n testResult: TestRunResult,\n cwd: string,\n): string {\n const output = [testResult.stdout, testResult.stderr]\n .filter(Boolean)\n .join(\"\\n\");\n return [\n `You are fixing failing tests in a project.`,\n ``,\n `**Working directory:** ${cwd}`,\n `**Test command:** ${testResult.command}`,\n `**Exit code:** ${testResult.exitCode}`,\n ``,\n formatEnvironmentPrompt(),\n ``,\n `## Test Output`,\n ``,\n \"```\",\n output,\n \"```\",\n ``,\n `## Instructions`,\n ``,\n `- Read the failing test files and the source code they test.`,\n `- Understand why the tests are failing.`,\n `- Make minimal fixes — fix the tests or fix the source code, whichever is appropriate.`,\n `- Do NOT commit changes — the developer controls commits.`,\n `- Do NOT modify tests to simply skip or ignore failures.`,\n `- When finished, confirm by saying \"Tests fixed.\"`,\n ].join(\"\\n\");\n}\n\n/* ------------------------------------------------------------------ */\n/* Main pipeline */\n/* ------------------------------------------------------------------ */\n\n/** Run the fix-tests pipeline end-to-end. */\nexport async function runFixTestsPipeline(\n opts: FixTestsPipelineOptions,\n): Promise<FixTestsSummary> {\n const { cwd } = opts;\n const testTimeoutMs = (opts.testTimeout ?? 5) * 60_000;\n const start = Date.now();\n\n // Detect test command\n const testCommand = await detectTestCommand(cwd);\n if (!testCommand) {\n log.error(\n 'No test command found. Ensure package.json has a \"test\" script.',\n );\n return { mode: \"fix-tests\", success: false, error: \"No test command found\" };\n }\n log.info(`Detected test command: ${testCommand}`);\n\n // Dry-run mode\n if (opts.dryRun) {\n log.info(`Dry run — would execute: ${testCommand}`);\n log.dim(` Working directory: ${cwd}`);\n return { mode: \"fix-tests\", success: false };\n }\n\n const fileLogger = opts.verbose ? new FileLogger(\"fix-tests\", cwd) : null;\n\n const pipelineBody = async (): Promise<FixTestsSummary> => {\n try {\n // Run the test suite\n log.info(\"Running test suite...\");\n const testResult = await runTestCommand(testCommand, cwd);\n fileLoggerStorage.getStore()?.info(`Test run complete (exit code: ${testResult.exitCode})`);\n\n // Check if tests already pass\n if (testResult.exitCode === 0) {\n log.success(\"All tests pass — nothing to fix.\");\n return { mode: \"fix-tests\", success: true };\n }\n log.warn(\n `Tests failed (exit code ${testResult.exitCode}). Dispatching AI to fix...`,\n );\n\n // Boot the provider\n const provider = (opts.provider ?? \"opencode\") as ProviderName;\n const instance = await bootProvider(provider, { url: opts.serverUrl, cwd });\n registerCleanup(() => instance.cleanup());\n\n // Build prompt and dispatch\n const prompt = buildFixTestsPrompt(testResult, cwd);\n log.debug(`Prompt built (${prompt.length} chars)`);\n fileLoggerStorage.getStore()?.prompt(\"fix-tests\", prompt);\n const sessionId = await instance.createSession();\n const response = await instance.prompt(sessionId, prompt);\n\n if (response === null) {\n fileLoggerStorage.getStore()?.error(\"No response from AI agent.\");\n log.error(\"No response from AI agent.\");\n await instance.cleanup();\n return { mode: \"fix-tests\", success: false, error: \"No response from agent\" };\n }\n if (response) fileLoggerStorage.getStore()?.response(\"fix-tests\", response);\n log.success(\"AI agent completed fixes.\");\n\n // Re-run tests to verify\n fileLoggerStorage.getStore()?.phase(\"Verification\");\n log.info(\"Re-running tests to verify fixes...\");\n const verifyResult = await runTestCommand(testCommand, cwd);\n await instance.cleanup();\n fileLoggerStorage.getStore()?.info(`Verification result: exit code ${verifyResult.exitCode}`);\n\n if (verifyResult.exitCode === 0) {\n log.success(\"All tests pass after fixes!\");\n return { mode: \"fix-tests\", success: true };\n }\n\n log.warn(\n `Tests still failing after fix attempt (exit code ${verifyResult.exitCode}).`,\n );\n return { mode: \"fix-tests\", success: false, error: \"Tests still failing after fix attempt\" };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`Fix-tests pipeline failed: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n log.error(`Fix-tests pipeline failed: ${log.formatErrorChain(err)}`);\n return { mode: \"fix-tests\", success: false, error: message };\n }\n };\n\n if (fileLogger) {\n return fileLoggerStorage.run(fileLogger, async () => {\n try {\n return await pipelineBody();\n } finally {\n fileLogger.close();\n }\n });\n }\n return pipelineBody();\n}\n","/**\n * CLI entry point for `dispatch`.\n *\n * This module is a thin argument-parsing shell. It parses CLI arguments,\n * boots the orchestrator, delegates all workflow logic (config loading,\n * validation, pipeline selection) to the orchestrator's `runFromCli()`\n * method, and exits based on the result.\n *\n * Process-level concerns (signal handlers, config subcommand) remain here.\n */\n\nimport { resolve, join } from \"node:path\";\nimport { Command, Option, CommanderError } from \"commander\";\nimport { boot as bootOrchestrator, type RawCliArgs } from \"./orchestrator/runner.js\";\nimport { log } from \"./helpers/logger.js\";\nimport { runCleanup } from \"./helpers/cleanup.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\nimport { PROVIDER_NAMES } from \"./providers/index.js\";\nimport { DATASOURCE_NAMES } from \"./datasources/index.js\";\nimport { handleConfigCommand, CONFIG_BOUNDS } from \"./config.js\";\n\nexport const MAX_CONCURRENCY = CONFIG_BOUNDS.concurrency.max;\n\nconst HELP = `\n dispatch — AI agent orchestration CLI\n\n Usage:\n dispatch [issue-id...] Dispatch specific issues (or all open issues if none given)\n dispatch --spec <ids> Generate spec files from issues\n dispatch --spec <glob> Generate specs from local markdown files in the configured datasource\n dispatch --respec Regenerate all existing specs\n dispatch --respec <ids> Regenerate specs for specific issues\n dispatch --respec <glob> Regenerate specs matching a glob pattern\n dispatch --spec \"description\" Generate a spec from an inline text description\n dispatch --fix-tests Run tests and fix failures via AI agent\n dispatch --fix-tests <ids> Fix tests on specific issue branches (in worktrees)\n\n Dispatch options:\n --dry-run List tasks without dispatching (also works with --spec)\n --no-plan Skip the planner agent, dispatch directly\n --no-branch Skip branch creation, push, and PR lifecycle\n --no-worktree Skip git worktree isolation for parallel issues\n --feature [name] Group issues into a single feature branch and PR\n --force Ignore prior run state and re-run all tasks\n --concurrency <n> Max parallel dispatches (default: min(cpus, freeMB/500), max: ${MAX_CONCURRENCY})\n --provider <name> Agent backend: ${PROVIDER_NAMES.join(\", \")} (default: opencode)\n --server-url <url> URL of a running provider server\n --plan-timeout <min> Planning timeout in minutes (default: 10)\n --retries <n> Retry attempts for all agents (default: 2)\n --plan-retries <n> Retry attempts after planning timeout (overrides --retries for planner)\n --test-timeout <min> Test timeout in minutes (default: 5)\n --cwd <dir> Working directory (default: cwd)\n\n Spec options:\n --spec <value> Comma-separated issue numbers or glob pattern for .md files (creates specs in configured datasource)\n --respec [value] Regenerate specs: issue numbers, glob, or omit to regenerate all existing specs\n --spec <value> Comma-separated issue numbers, glob pattern for .md files, or inline text description\n --source <name> Issue source: ${DATASOURCE_NAMES.join(\", \")} (optional; auto-detected from git remote, falls back to md)\n --org <url> Azure DevOps organization URL\n --project <name> Azure DevOps project name\n --output-dir <dir> Output directory for specs (default: .dispatch/specs)\n\n General:\n --verbose Show detailed debug output for troubleshooting\n -h, --help Show this help\n -v, --version Show version\n\n Config:\n dispatch config Launch interactive configuration wizard\n\n Examples:\n dispatch 14\n dispatch 14,15,16\n dispatch 14 15 16\n dispatch\n dispatch 14 --dry-run\n dispatch 14 --provider copilot\n dispatch --spec 42,43,44\n dispatch --spec 42,43 --source github --provider copilot\n dispatch --spec 100,200 --source azdevops --org https://dev.azure.com/myorg --project MyProject\n dispatch --spec \"drafts/*.md\"\n dispatch --spec \"drafts/*.md\" --source github\n dispatch --spec \"./my-feature.md\" --provider copilot\n dispatch --respec\n dispatch --respec 42,43,44\n dispatch --respec \"specs/*.md\"\n dispatch --spec \"add dark mode toggle to settings page\"\n dispatch --spec \"feature A should do x\" --provider copilot\n dispatch --feature\n dispatch --feature my-feature\n dispatch --fix-tests\n dispatch --fix-tests 14\n dispatch --fix-tests 14 15 16\n dispatch --fix-tests 14,15,16\n dispatch config\n`.trimStart();\n\n/** Parsed CLI arguments including shell-only flags (help, version). */\nexport interface ParsedArgs extends Omit<RawCliArgs, \"explicitFlags\"> {\n help: boolean;\n version: boolean;\n feature?: string | boolean;\n}\n\nexport function parseArgs(argv: string[]): [ParsedArgs, Set<string>] {\n const program = new Command();\n\n program\n .exitOverride()\n .configureOutput({\n writeOut: () => {},\n writeErr: () => {},\n })\n .helpOption(false)\n .argument(\"[issueIds...]\")\n .option(\"-h, --help\", \"Show help\")\n .option(\"-v, --version\", \"Show version\")\n .option(\"--dry-run\", \"List tasks without dispatching\")\n .option(\"--no-plan\", \"Skip the planner agent\")\n .option(\"--no-branch\", \"Skip branch creation\")\n .option(\"--no-worktree\", \"Skip git worktree isolation\")\n .option(\"--feature [name]\", \"Group issues into a single feature branch\")\n .option(\"--force\", \"Ignore prior run state\")\n .option(\"--verbose\", \"Show detailed debug output\")\n .option(\"--fix-tests\", \"Run tests and fix failures (optionally pass issue IDs to target specific branches)\")\n .option(\"--spec <values...>\", \"Spec mode: issue numbers, glob, or text\")\n .option(\"--respec [values...]\", \"Regenerate specs\")\n .addOption(\n new Option(\"--provider <name>\", \"Agent backend\").choices(PROVIDER_NAMES),\n )\n .addOption(\n new Option(\"--source <name>\", \"Issue source\").choices(\n DATASOURCE_NAMES as string[],\n ),\n )\n .option(\n \"--concurrency <n>\",\n \"Max parallel dispatches\",\n (val: string): number => {\n const n = parseInt(val, 10);\n if (isNaN(n) || n < 1) throw new CommanderError(1, \"commander.invalidArgument\", \"--concurrency must be a positive integer\");\n if (n > MAX_CONCURRENCY) throw new CommanderError(1, \"commander.invalidArgument\", `--concurrency must not exceed ${MAX_CONCURRENCY}`);\n return n;\n },\n )\n .option(\n \"--plan-timeout <min>\",\n \"Planning timeout in minutes\",\n (val: string): number => {\n const n = parseFloat(val);\n if (isNaN(n) || n < CONFIG_BOUNDS.planTimeout.min) throw new CommanderError(1, \"commander.invalidArgument\", \"--plan-timeout must be a positive number (minutes)\");\n if (n > CONFIG_BOUNDS.planTimeout.max) throw new CommanderError(1, \"commander.invalidArgument\", `--plan-timeout must not exceed ${CONFIG_BOUNDS.planTimeout.max}`);\n return n;\n },\n )\n .option(\n \"--retries <n>\",\n \"Retry attempts\",\n (val: string): number => {\n const n = parseInt(val, 10);\n if (isNaN(n) || n < 0) throw new CommanderError(1, \"commander.invalidArgument\", \"--retries must be a non-negative integer\");\n return n;\n },\n )\n .option(\n \"--plan-retries <n>\",\n \"Planner retry attempts\",\n (val: string): number => {\n const n = parseInt(val, 10);\n if (isNaN(n) || n < 0) throw new CommanderError(1, \"commander.invalidArgument\", \"--plan-retries must be a non-negative integer\");\n return n;\n },\n )\n .option(\n \"--test-timeout <min>\",\n \"Test timeout in minutes\",\n (val: string): number => {\n const n = parseFloat(val);\n if (isNaN(n) || n <= 0) throw new CommanderError(1, \"commander.invalidArgument\", \"--test-timeout must be a positive number (minutes)\");\n return n;\n },\n )\n .option(\"--cwd <dir>\", \"Working directory\", (val: string) => resolve(val))\n .option(\"--output-dir <dir>\", \"Output directory\", (val: string) => resolve(val))\n .option(\"--org <url>\", \"Azure DevOps organization URL\")\n .option(\"--project <name>\", \"Azure DevOps project name\")\n .option(\"--server-url <url>\", \"Provider server URL\");\n\n try {\n program.parse(argv, { from: \"user\" });\n } catch (err) {\n if (err instanceof CommanderError) {\n log.error(err.message);\n process.exit(1);\n }\n throw err;\n }\n\n const opts = program.opts();\n\n // ── Build ParsedArgs ────────────────────────────────────────\n const args: ParsedArgs = {\n issueIds: program.args,\n dryRun: opts.dryRun ?? false,\n noPlan: !opts.plan,\n noBranch: !opts.branch,\n noWorktree: !opts.worktree,\n force: opts.force ?? false,\n provider: opts.provider ?? \"opencode\",\n cwd: opts.cwd ?? process.cwd(),\n help: opts.help ?? false,\n version: opts.version ?? false,\n verbose: opts.verbose ?? false,\n };\n\n // Optional fields — only set when explicitly provided\n if (opts.spec !== undefined) {\n args.spec = opts.spec.length === 1 ? opts.spec[0] : opts.spec;\n }\n if (opts.respec !== undefined) {\n if (opts.respec === true) {\n args.respec = [];\n } else {\n args.respec = opts.respec.length === 1 ? opts.respec[0] : opts.respec;\n }\n }\n if (opts.fixTests) args.fixTests = true;\n if (opts.feature) args.feature = opts.feature;\n if (opts.source !== undefined) args.issueSource = opts.source;\n if (opts.concurrency !== undefined) args.concurrency = opts.concurrency;\n if (opts.serverUrl !== undefined) args.serverUrl = opts.serverUrl;\n if (opts.planTimeout !== undefined) args.planTimeout = opts.planTimeout;\n if (opts.retries !== undefined) args.retries = opts.retries;\n if (opts.planRetries !== undefined) args.planRetries = opts.planRetries;\n if (opts.testTimeout !== undefined) args.testTimeout = opts.testTimeout;\n if (opts.org !== undefined) args.org = opts.org;\n if (opts.project !== undefined) args.project = opts.project;\n if (opts.outputDir !== undefined) args.outputDir = opts.outputDir;\n\n // ── Derive explicitFlags from Commander option sources ─────\n const explicitFlags = new Set<string>();\n\n const SOURCE_MAP: Record<string, string> = {\n help: \"help\",\n version: \"version\",\n dryRun: \"dryRun\",\n plan: \"noPlan\",\n branch: \"noBranch\",\n worktree: \"noWorktree\",\n force: \"force\",\n verbose: \"verbose\",\n spec: \"spec\",\n respec: \"respec\",\n fixTests: \"fixTests\",\n feature: \"feature\",\n source: \"issueSource\",\n provider: \"provider\",\n concurrency: \"concurrency\",\n serverUrl: \"serverUrl\",\n planTimeout: \"planTimeout\",\n retries: \"retries\",\n planRetries: \"planRetries\",\n testTimeout: \"testTimeout\",\n cwd: \"cwd\",\n org: \"org\",\n project: \"project\",\n outputDir: \"outputDir\",\n };\n\n for (const [attr, flag] of Object.entries(SOURCE_MAP)) {\n if (program.getOptionValueSource(attr) === \"cli\") {\n explicitFlags.add(flag);\n }\n }\n\n return [args, explicitFlags];\n}\n\nasync function main() {\n const rawArgv = process.argv.slice(2);\n\n // ── Config subcommand via Commander ────────────────────────\n if (rawArgv[0] === \"config\") {\n const configProgram = new Command(\"dispatch-config\")\n .exitOverride()\n .configureOutput({ writeOut: () => {}, writeErr: () => {} })\n .helpOption(false)\n .allowUnknownOption(true)\n .allowExcessArguments(true)\n .option(\"--cwd <dir>\", \"Working directory\", (v: string) => resolve(v));\n\n try {\n configProgram.parse(rawArgv.slice(1), { from: \"user\" });\n } catch (err) {\n if (err instanceof CommanderError) {\n log.error(err.message);\n process.exit(1);\n }\n throw err;\n }\n\n const configDir = join(configProgram.opts().cwd ?? process.cwd(), \".dispatch\");\n await handleConfigCommand(rawArgv.slice(1), configDir);\n process.exit(0);\n }\n\n const [args, explicitFlags] = parseArgs(rawArgv);\n\n // Enable verbose logging before anything else\n log.verbose = args.verbose;\n\n // ── Graceful shutdown on signals ───────────────────────────\n process.on(\"SIGINT\", async () => {\n log.debug(\"Received SIGINT, cleaning up...\");\n await runCleanup();\n process.exit(130);\n });\n\n process.on(\"SIGTERM\", async () => {\n log.debug(\"Received SIGTERM, cleaning up...\");\n await runCleanup();\n process.exit(143);\n });\n\n if (args.help) {\n console.log(HELP);\n process.exit(0);\n }\n\n if (args.version) {\n console.log(`dispatch v${__VERSION__}`);\n process.exit(0);\n }\n\n // ── Delegate to orchestrator ───────────────────────────────\n const orchestrator = await bootOrchestrator({ cwd: args.cwd });\n const { help: _, version: __, ...rawArgs } = args;\n const summary = await orchestrator.runFromCli({ ...rawArgs, explicitFlags });\n\n // Determine exit code from summary\n const failed = \"failed\" in summary ? summary.failed : (\"success\" in summary && !summary.success ? 1 : 0);\n process.exit(failed > 0 ? 1 : 0);\n}\n\nmain().catch(async (err) => {\n log.error(log.formatErrorChain(err));\n await runCleanup();\n process.exit(1);\n});\n","/**\n * Spec generator — fetches issue details from a configured datasource\n * (GitHub, Azure DevOps, or local markdown files), sends them to the AI\n * provider along with instructions to explore the codebase and research\n * the approach, then writes high-level markdown spec files.\n *\n * Pipeline:\n * 1. Resolve the datasource (explicit or auto-detected)\n * 2. Fetch issue/file details via the datasource\n * 3. Boot the AI provider\n * 4. For each item, tell the AI agent the target filepath and prompt it\n * to explore the codebase and write the spec directly to disk\n * 5. Verify the spec file was written\n * 6. Push spec content back to the datasource via update()\n *\n * The generated specs stay high-level (WHAT, WHY, HOW) because the\n * planner agent in the dispatch pipeline handles detailed, line-level\n * implementation planning for each individual task.\n */\n\nimport { cpus, freemem } from \"node:os\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\nimport { getDatasource, detectDatasource, DATASOURCE_NAMES } from \"./datasources/index.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport { log } from \"./helpers/logger.js\";\n\n/** Estimated memory (in MB) required per concurrent spec-generation task. */\nexport const MB_PER_CONCURRENT_TASK = 500;\n\n/** Recognized H2 section headings used to detect spec structure boundaries. */\nexport const RECOGNIZED_H2 = new Set([\n \"## Context\",\n \"## Why\",\n \"## Approach\",\n \"## Integration Points\",\n \"## Tasks\",\n \"## References\",\n \"## Key Guidelines\",\n]);\n\nexport interface SpecOptions {\n /** Comma-separated issue numbers, glob pattern(s), or \"list\" to use datasource.list() */\n issues: string | string[];\n /** Explicit datasource override (auto-detected if omitted) */\n issueSource?: DatasourceName;\n /** AI agent backend */\n provider: ProviderName;\n /** Model override to pass to the provider (provider-specific format). */\n model?: string;\n /** URL of a running provider server */\n serverUrl?: string;\n /** Working directory */\n cwd: string;\n /** Output directory for spec files (default: .dispatch/specs) */\n outputDir?: string;\n /** Azure DevOps organization URL */\n org?: string;\n /** Azure DevOps project name */\n project?: string;\n /** Azure DevOps work item type (e.g. \"User Story\", \"Product Backlog Item\") */\n workItemType?: string;\n /** Azure DevOps iteration path filter (e.g. \"MyProject\\\\Sprint 1\" or \"@CurrentIteration\") */\n iteration?: string;\n /** Azure DevOps area path filter (e.g. \"MyProject\\\\Team A\") */\n area?: string;\n /** Max parallel fetches/generations (default: min(cpuCount, freeMB/500)) */\n concurrency?: number;\n /** When true, log a preview of what would be generated without booting the provider or writing files. */\n dryRun?: boolean;\n /** Number of retry attempts for spec generation (default: 2) */\n retries?: number;\n}\n\n/**\n * Returns a safe default concurrency: min(cpuCount, freeMB/500), at least 1.\n *\n * Each concurrent agent process (provider runtime) is estimated to consume\n * roughly 500 MB of resident memory. The formula caps parallelism at the\n * lesser of the available CPU count and the number of 500 MB slots that fit\n * in current free memory, ensuring the host is not over-committed. The\n * result is floored to at least 1 so that the pipeline always makes progress.\n *\n * Users can override this computed value via the `--concurrency` CLI flag\n * or the `concurrency` key in `.dispatch/config.json`.\n */\nexport function defaultConcurrency(): number {\n return Math.max(1, Math.min(cpus().length, Math.floor(freemem() / 1024 / 1024 / MB_PER_CONCURRENT_TASK)));\n}\n\n/**\n * Returns `true` when the input string consists solely of comma-separated\n * issue numbers (digits, commas, and optional whitespace). Anything else\n * — paths, globs, filenames — returns `false`.\n *\n * This is the branching point for the two spec-generation code paths:\n * issue-tracker mode vs. local-file/glob mode.\n */\nexport function isIssueNumbers(input: string | string[]): input is string {\n if (Array.isArray(input)) return false;\n return /^\\d+(,\\s*\\d+)*$/.test(input);\n}\n\n/**\n * Returns `true` when the input looks like a glob pattern or file path\n * rather than free-form inline text.\n *\n * Checks for:\n * - Glob metacharacters: `*`, `?`, `[`, `{`\n * - Path separators: `/`, `\\`\n * - Dot-prefix relative paths: `./`, `../`\n * - Common file extensions: `.md`, `.txt`, `.yaml`, `.yml`, `.json`, `.ts`,\n * `.js`, `.tsx`, `.jsx`\n *\n * This is a pure function intended to be called *after* `isIssueNumbers()`\n * has already returned `false`, providing the second level of input\n * discrimination for the spec pipeline.\n */\nexport function isGlobOrFilePath(input: string | string[]): boolean {\n if (Array.isArray(input)) return true;\n // Glob metacharacters\n if (/[*?\\[{]/.test(input)) return true;\n\n // Path separators (forward slash or backslash)\n if (/[/\\\\]/.test(input)) return true;\n\n // Dot-prefix relative paths (./something, ../something, .\\something, ..\\something)\n if (/^\\.\\.?[\\/\\\\]/.test(input)) return true;\n\n // Common file extensions at end of string\n if (/\\.(md|txt|yaml|yml|json|ts|js|tsx|jsx)$/i.test(input)) return true;\n\n return false;\n}\n\n/**\n * Post-process raw spec file content written by the AI agent.\n *\n * Strips code-fence wrapping, preamble text before the first H1 heading,\n * and postamble text after the last recognized spec section. Returns the\n * content unchanged when no recognizable spec structure is found.\n *\n * Pure function — no I/O, no side-effects.\n */\nexport function extractSpecContent(raw: string): string {\n let content = raw;\n\n // 1. Strip code-fence wrapping (``` or ```markdown around entire content)\n // The fence may wrap the entire input or may appear after preamble text,\n // so we search for a fenced block containing an H1 heading.\n const fenceMatch = content.match(/^\\s*```(?:markdown)?\\s*\\n([\\s\\S]*?)\\n\\s*```\\s*$/);\n if (fenceMatch) {\n content = fenceMatch[1];\n } else {\n // Try to find a fenced block that contains an H1, even with surrounding text\n const innerFenceMatch = content.match(/```(?:markdown)?\\s*\\n([\\s\\S]*?)\\n\\s*```/);\n if (innerFenceMatch && /^# /m.test(innerFenceMatch[1])) {\n content = innerFenceMatch[1];\n }\n }\n\n // 2. Remove preamble — everything before the first H1 heading\n const h1Index = content.search(/^# /m);\n if (h1Index === -1) {\n // No H1 found — return original content unchanged\n return raw;\n }\n content = content.slice(h1Index);\n\n // 3. Remove postamble — trim after the last recognized H2 section's content\n const lines = content.split(\"\\n\");\n let lastRecognizedSectionEnd = lines.length;\n\n // Walk backwards to find the last recognized H2 and its content extent\n let foundLastRecognized = false;\n for (let i = lines.length - 1; i >= 0; i--) {\n const trimmed = lines[i].trimEnd();\n if (trimmed.startsWith(\"## \")) {\n if (RECOGNIZED_H2.has(trimmed)) {\n // This is the last recognized H2 — everything up to end is the section content\n foundLastRecognized = true;\n break;\n } else {\n // Unrecognized H2 — this and everything after it is postamble\n lastRecognizedSectionEnd = i;\n }\n }\n }\n\n if (foundLastRecognized || lastRecognizedSectionEnd < lines.length) {\n // Trim trailing blank lines from the kept portion\n let end = lastRecognizedSectionEnd;\n while (end > 0 && lines[end - 1].trim() === \"\") {\n end--;\n }\n content = lines.slice(0, end).join(\"\\n\");\n }\n\n // Ensure trailing newline\n if (!content.endsWith(\"\\n\")) {\n content += \"\\n\";\n }\n\n return content;\n}\n\nexport interface ValidationResult {\n /** Whether the spec content has valid structure */\n valid: boolean;\n /** Human-readable reason when validation fails */\n reason?: string;\n}\n\n/**\n * Validate that spec content has the expected structural markers.\n *\n * Checks:\n * 1. Content starts with an H1 heading (`# `)\n * 2. Contains a `## Tasks` section with at least one `- [ ]` checkbox\n *\n * This is a guardrail, not a gate — validation failures are warned but\n * do not block the pipeline. Returns a structured result so callers can\n * act on it.\n */\nexport function validateSpecStructure(content: string): ValidationResult {\n const trimmed = content.trimStart();\n\n // Check 1: Must start with an H1 heading\n if (!trimmed.startsWith(\"# \")) {\n const reason = \"Spec does not start with an H1 heading (expected \\\"# \\\")\";\n log.warn(reason);\n return { valid: false, reason };\n }\n\n // Check 2: Must contain a ## Tasks section\n const tasksIndex = content.search(/^## Tasks\\s*$/m);\n if (tasksIndex === -1) {\n const reason = \"Spec is missing a \\\"## Tasks\\\" section\";\n log.warn(reason);\n return { valid: false, reason };\n }\n\n // Check 3: Must have at least one checkbox after ## Tasks\n const afterTasks = content.slice(tasksIndex);\n if (!/- \\[ \\]/.test(afterTasks)) {\n const reason = \"\\\"## Tasks\\\" section contains no unchecked tasks (expected at least one \\\"- [ ]\\\")\";\n log.warn(reason);\n return { valid: false, reason };\n }\n\n return { valid: true };\n}\n\n/**\n * Resolve the datasource name for a spec-generation run.\n *\n * Priority:\n * 1. Explicit `issueSource` (from --source flag or config) — always wins.\n * 2. Auto-detect from the git remote URL.\n * 3. For glob/file inputs, fall back to `\"md\"` when auto-detection fails.\n * 4. For issue-number inputs, return `null` when auto-detection fails (caller should abort).\n */\nexport async function resolveSource(\n issues: string | string[],\n issueSource: DatasourceName | undefined,\n cwd: string\n): Promise<DatasourceName | null> {\n if (issueSource) {\n return issueSource;\n }\n log.info(\"Detecting datasource from git remote...\");\n const detected = await detectDatasource(cwd);\n if (detected) {\n log.info(`Detected datasource: ${detected}`);\n return detected;\n }\n if (!isIssueNumbers(issues)) {\n return \"md\";\n }\n log.error(\n `Could not detect datasource from the repository remote URL.\\n` +\n ` Supported sources: ${DATASOURCE_NAMES.join(\", \")}\\n` +\n ` Use --source <name> to specify explicitly, or ensure the git remote\\n` +\n ` points to a supported platform (github.com, dev.azure.com).`\n );\n return null;\n}\n\nexport interface SpecSummary {\n /** Total issues requested */\n total: number;\n /** Successfully generated spec files */\n generated: number;\n /** Failed to generate */\n failed: number;\n /** Paths of generated spec files */\n files: string[];\n /** Issue numbers created or updated during spec generation (empty when datasource is md) */\n issueNumbers: string[];\n /** Dispatch identifiers for the \"Run these specs with\" hint (issue numbers or file paths) */\n identifiers?: string[];\n /** Total pipeline wall-clock duration in milliseconds */\n durationMs: number;\n /** Per-file generation durations in milliseconds (filepath → ms) */\n fileDurationsMs: Record<string, number>;\n}\n\n","/**\n * Datasource registry — maps datasource names to their implementations\n * and provides auto-detection of the datasource from the git remote URL.\n *\n * To add a new datasource:\n * 1. Create `src/datasources/<name>.ts` exporting a `datasource` object\n * 2. Import and register it in the `DATASOURCES` map below\n * 3. Add the name to the `DatasourceName` type in `src/datasources/interface.ts`\n * 4. Add a URL pattern to `detectDatasource` if auto-detection is possible\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { Datasource, DatasourceName } from \"./interface.js\";\nimport { datasource as githubDatasource } from \"./github.js\";\nimport { datasource as azdevopsDatasource } from \"./azdevops.js\";\nimport { datasource as mdDatasource } from \"./md.js\";\nexport type { Datasource, DatasourceName, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\n\nconst exec = promisify(execFile);\n\nconst DATASOURCES: Partial<Record<DatasourceName, Datasource>> = {\n github: githubDatasource,\n azdevops: azdevopsDatasource,\n md: mdDatasource,\n};\n\n/**\n * All registered datasource names — useful for CLI help text and validation.\n */\nexport const DATASOURCE_NAMES = Object.keys(DATASOURCES) as DatasourceName[];\n\n/**\n * Get a datasource by name.\n *\n * @throws if the datasource name is not registered.\n */\nexport function getDatasource(name: DatasourceName): Datasource {\n const datasource = DATASOURCES[name];\n if (!datasource) {\n throw new Error(\n `Unknown datasource \"${name}\". Available: ${DATASOURCE_NAMES.join(\", \")}`\n );\n }\n return datasource;\n}\n\n/**\n * Get the git remote URL for the `origin` remote.\n *\n * @param cwd - Working directory to run the git command in\n * @returns The remote URL string, or `null` if unavailable\n */\nexport async function getGitRemoteUrl(cwd: string): Promise<string | null> {\n try {\n const { stdout } = await exec(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd,\n shell: process.platform === \"win32\",\n });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/**\n * URL patterns used to detect the datasource from a git remote.\n *\n * Each entry maps a regex (tested against the remote URL) to the\n * corresponding `DatasourceName`. Patterns are tested in order;\n * the first match wins.\n */\nconst SOURCE_PATTERNS: { pattern: RegExp; source: DatasourceName }[] = [\n { pattern: /github\\.com/i, source: \"github\" },\n { pattern: /dev\\.azure\\.com/i, source: \"azdevops\" },\n { pattern: /visualstudio\\.com/i, source: \"azdevops\" },\n];\n\n/**\n * Auto-detect the datasource by inspecting the `origin` remote URL.\n *\n * Returns the detected `DatasourceName`, or `null` if the remote URL\n * does not match any known pattern.\n */\nexport async function detectDatasource(\n cwd: string\n): Promise<DatasourceName | null> {\n const url = await getGitRemoteUrl(cwd);\n if (!url) return null;\n\n for (const { pattern, source } of SOURCE_PATTERNS) {\n if (pattern.test(url)) {\n return source;\n }\n }\n\n return null;\n}\n\n/**\n * Parse an Azure DevOps git remote URL and extract the organization URL and project name.\n *\n * Supports all three Azure DevOps remote URL formats:\n * - **HTTPS:** `https://dev.azure.com/{org}/{project}/_git/{repo}`\n * - **SSH:** `git@ssh.dev.azure.com:v3/{org}/{project}/{repo}`\n * - **Legacy HTTPS:** `https://{org}.visualstudio.com/{project}/_git/{repo}`\n *\n * The org URL is always normalized to `https://dev.azure.com/{org}`.\n *\n * @param url - The git remote URL to parse\n * @returns The parsed org URL and project name, or `null` if the URL is not a recognized Azure DevOps format\n */\nexport function parseAzDevOpsRemoteUrl(\n url: string\n): { orgUrl: string; project: string } | null {\n // HTTPS: https://[user@]dev.azure.com/{org}/{project}/_git/{repo}\n const httpsMatch = url.match(\n /^https?:\\/\\/(?:[^@]+@)?dev\\.azure\\.com\\/([^/]+)\\/([^/]+)\\/_git\\//i\n );\n if (httpsMatch) {\n return {\n orgUrl: `https://dev.azure.com/${decodeURIComponent(httpsMatch[1])}`,\n project: decodeURIComponent(httpsMatch[2]),\n };\n }\n\n // SSH: git@ssh.dev.azure.com:v3/{org}/{project}/{repo}\n const sshMatch = url.match(\n /^git@ssh\\.dev\\.azure\\.com:v3\\/([^/]+)\\/([^/]+)\\//i\n );\n if (sshMatch) {\n return {\n orgUrl: `https://dev.azure.com/${decodeURIComponent(sshMatch[1])}`,\n project: decodeURIComponent(sshMatch[2]),\n };\n }\n\n // Legacy: https://{org}.visualstudio.com/[DefaultCollection/]{project}/_git/{repo}\n const legacyMatch = url.match(\n /^https?:\\/\\/([^.]+)\\.visualstudio\\.com\\/(?:DefaultCollection\\/)?([^/]+)\\/_git\\//i\n );\n if (legacyMatch) {\n return {\n orgUrl: `https://dev.azure.com/${decodeURIComponent(legacyMatch[1])}`,\n project: decodeURIComponent(legacyMatch[2]),\n };\n }\n\n return null;\n}\n","/**\n * GitHub datasource — reads and writes issues using the `gh` CLI.\n *\n * Requires:\n * - `gh` CLI installed and authenticated\n * - Working directory inside a GitHub repository (or GITHUB_REPOSITORY set)\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { Datasource, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\nimport { slugify } from \"../helpers/slugify.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { InvalidBranchNameError, isValidBranchName } from \"../helpers/branch-validation.js\";\n\nexport { InvalidBranchNameError } from \"../helpers/branch-validation.js\";\n\nconst exec = promisify(execFile);\n\n/** Execute a git command and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/** Execute a gh CLI command and return stdout. */\nasync function gh(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"gh\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/**\n * Build a branch name from an issue number, title, and username.\n * Produces: `<username>/dispatch/<number>-<slugified-title>`\n *\n * @param issueNumber - The issue number/ID\n * @param title - The issue title (will be slugified)\n * @param username - The slugified git username to namespace the branch\n */\nfunction buildBranchName(issueNumber: string, title: string, username: string = \"unknown\"): string {\n const slug = slugify(title, 50);\n return `${username}/dispatch/${issueNumber}-${slug}`;\n}\n\n/**\n * Detect the default branch of the repository.\n * Tries `git symbolic-ref refs/remotes/origin/HEAD` first,\n * falls back to checking if \"main\" or \"master\" exists.\n */\nasync function getDefaultBranch(cwd: string): Promise<string> {\n const PREFIX = \"refs/remotes/origin/\";\n try {\n const ref = await git([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], cwd);\n // ref looks like \"refs/remotes/origin/main\" or \"refs/remotes/origin/release/2024\"\n const trimmed = ref.trim();\n const branch = trimmed.startsWith(PREFIX)\n ? trimmed.slice(PREFIX.length)\n : trimmed;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch, \"from symbolic-ref output\");\n }\n return branch;\n } catch (err) {\n if (err instanceof InvalidBranchNameError) {\n throw err;\n }\n // Fallback: check if \"main\" branch exists\n try {\n await git([\"rev-parse\", \"--verify\", \"main\"], cwd);\n return \"main\";\n } catch {\n return \"master\";\n }\n }\n}\n\n/**\n * Gather commit messages from the current branch relative to the default branch.\n * Uses `git log` to list commits that exist on the current branch but not on\n * the default branch, returning each commit's subject line.\n *\n * @param defaultBranch - The default branch name to compare against (e.g. \"main\")\n * @param cwd - The working directory (git repo root)\n * @returns An array of commit message subject lines\n */\nexport async function getCommitMessages(defaultBranch: string, cwd: string): Promise<string[]> {\n try {\n const output = await git(\n [\"log\", `origin/${defaultBranch}..HEAD`, \"--pretty=format:%s\"],\n cwd,\n );\n return output.trim().split(\"\\n\").filter(Boolean);\n } catch {\n return [];\n }\n}\n\nexport const datasource: Datasource = {\n name: \"github\",\n\n supportsGit(): boolean {\n return true;\n },\n\n async list(opts: IssueFetchOptions = {}): Promise<IssueDetails[]> {\n const cwd = opts.cwd || process.cwd();\n\n const { stdout } = await exec(\n \"gh\",\n [\n \"issue\",\n \"list\",\n \"--state\",\n \"open\",\n \"--json\",\n \"number,title,body,labels,state,url\",\n ],\n { cwd, shell: process.platform === \"win32\" }\n );\n\n let issues;\n try {\n issues = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse GitHub CLI output: ${stdout.slice(0, 200)}`);\n }\n\n return issues.map(\n (issue: {\n number: number;\n title?: string;\n body?: string;\n labels?: { name: string }[];\n state?: string;\n url?: string;\n }): IssueDetails => ({\n number: String(issue.number),\n title: issue.title ?? \"\",\n body: issue.body ?? \"\",\n labels: (issue.labels ?? []).map((l) => l.name),\n state: issue.state ?? \"OPEN\",\n url: issue.url ?? \"\",\n comments: [],\n acceptanceCriteria: \"\",\n })\n );\n },\n\n async fetch(issueId: string, opts: IssueFetchOptions = {}): Promise<IssueDetails> {\n const cwd = opts.cwd || process.cwd();\n\n const { stdout } = await exec(\n \"gh\",\n [\n \"issue\",\n \"view\",\n issueId,\n \"--json\",\n \"number,title,body,labels,state,url,comments\",\n ],\n { cwd, shell: process.platform === \"win32\" }\n );\n\n let issue;\n try {\n issue = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse GitHub CLI output: ${stdout.slice(0, 200)}`);\n }\n\n const comments: string[] = [];\n if (issue.comments && Array.isArray(issue.comments)) {\n for (const c of issue.comments) {\n const author = c.author?.login ?? \"unknown\";\n comments.push(`**${author}:** ${c.body}`);\n }\n }\n\n return {\n number: String(issue.number),\n title: issue.title ?? \"\",\n body: issue.body ?? \"\",\n labels: (issue.labels ?? []).map((l: { name: string }) => l.name),\n state: issue.state ?? \"OPEN\",\n url: issue.url ?? \"\",\n comments,\n acceptanceCriteria: \"\",\n };\n },\n\n async update(issueId: string, title: string, body: string, opts: IssueFetchOptions = {}): Promise<void> {\n const cwd = opts.cwd || process.cwd();\n await exec(\"gh\", [\"issue\", \"edit\", issueId, \"--title\", title, \"--body\", body], { cwd, shell: process.platform === \"win32\" });\n },\n\n async close(issueId: string, opts: IssueFetchOptions = {}): Promise<void> {\n const cwd = opts.cwd || process.cwd();\n await exec(\"gh\", [\"issue\", \"close\", issueId], { cwd, shell: process.platform === \"win32\" });\n },\n\n async create(title: string, body: string, opts: IssueFetchOptions = {}): Promise<IssueDetails> {\n const cwd = opts.cwd || process.cwd();\n\n // gh issue create outputs the URL of the created issue on stdout.\n // It does not support --json (unlike gh issue view / gh issue list).\n const { stdout } = await exec(\n \"gh\",\n [\"issue\", \"create\", \"--title\", title, \"--body\", body],\n { cwd, shell: process.platform === \"win32\" }\n );\n\n const url = stdout.trim();\n const match = url.match(/\\/issues\\/(\\d+)$/);\n const number = match ? match[1] : \"0\";\n\n return {\n number,\n title,\n body,\n labels: [],\n state: \"open\",\n url,\n comments: [],\n acceptanceCriteria: \"\",\n };\n },\n\n async getUsername(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const name = await git([\"config\", \"user.name\"], opts.cwd);\n const slug = slugify(name.trim());\n return slug || \"unknown\";\n } catch {\n return \"unknown\";\n }\n },\n\n getDefaultBranch(opts) {\n return getDefaultBranch(opts.cwd);\n },\n\n buildBranchName(issueNumber: string, title: string, username?: string): string {\n return buildBranchName(issueNumber, title, username ?? \"unknown\");\n },\n\n async createAndSwitchBranch(branchName, opts) {\n const cwd = opts.cwd;\n try {\n await git([\"checkout\", \"-b\", branchName], cwd);\n } catch (err) {\n // Branch may already exist — switch to it instead\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n await git([\"checkout\", branchName], cwd);\n } else {\n throw err;\n }\n }\n },\n\n async switchBranch(branchName, opts) {\n await git([\"checkout\", branchName], opts.cwd);\n },\n\n async pushBranch(branchName, opts) {\n await git([\"push\", \"--set-upstream\", \"origin\", branchName], opts.cwd);\n },\n\n async commitAllChanges(message, opts) {\n const cwd = opts.cwd;\n await git([\"add\", \"-A\"], cwd);\n const status = await git([\"diff\", \"--cached\", \"--stat\"], cwd);\n if (!status.trim()) {\n return; // nothing to commit\n }\n await git([\"commit\", \"-m\", message], cwd);\n },\n\n async createPullRequest(branchName, issueNumber, title, body, opts) {\n const cwd = opts.cwd;\n const prBody = body || `Closes #${issueNumber}`;\n try {\n const url = await gh(\n [\n \"pr\",\n \"create\",\n \"--title\",\n title,\n \"--body\",\n prBody,\n \"--head\",\n branchName,\n ],\n cwd,\n );\n return url.trim();\n } catch (err) {\n // If a PR already exists for this branch, retrieve its URL\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n const existing = await gh(\n [\"pr\", \"view\", branchName, \"--json\", \"url\", \"--jq\", \".url\"],\n cwd,\n );\n return existing.trim();\n }\n throw err;\n }\n },\n};\n","/**\n * Shared slug generation utility.\n *\n * Converts an arbitrary string into a URL/filename-safe slug by lowercasing,\n * replacing non-alphanumeric runs with hyphens, stripping leading/trailing\n * hyphens, and optionally truncating to a maximum length.\n *\n * Consolidates the identical slugification pattern previously duplicated\n * across datasource and orchestrator modules.\n */\n\n/** Default max slug length for filenames. */\nexport const MAX_SLUG_LENGTH = 60;\n\n/**\n * Convert a string into a lowercase, hyphen-separated slug.\n *\n * Applies the following transformations in order:\n * 1. Lowercase the entire string\n * 2. Replace runs of non-alphanumeric characters with a single hyphen\n * 3. Strip leading and trailing hyphens\n * 4. Truncate to `maxLength` characters (if provided)\n *\n * @param input - The string to slugify\n * @param maxLength - Optional maximum length of the resulting slug\n * @returns The slugified string\n */\nexport function slugify(input: string, maxLength?: number): string {\n const slug = input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n return maxLength != null ? slug.slice(0, maxLength) : slug;\n}\n","/**\n * Shared branch-name validation utilities.\n *\n * Provides a strict validator (`isValidBranchName`) and a typed error class\n * (`InvalidBranchNameError`) that enforce git refname rules. Extracted from\n * the GitHub datasource so every datasource can share the same logic.\n */\n\n/**\n * Thrown when a branch name fails validation.\n * Provides reliable `instanceof` detection instead of brittle message-string checks.\n */\nexport class InvalidBranchNameError extends Error {\n constructor(branch: string, reason?: string) {\n const detail = reason ? ` (${reason})` : \"\";\n super(`Invalid branch name: \"${branch}\"${detail}`);\n this.name = \"InvalidBranchNameError\";\n }\n}\n\n/** Strict pattern for valid git branch name character set. */\nexport const VALID_BRANCH_NAME_RE = /^[a-zA-Z0-9._\\-/]+$/;\n\n/**\n * Check whether a branch name is safe to use in git/gh commands.\n * Enforces git refname rules beyond simple character validation:\n * - Must be 1–255 characters of allowed characters\n * - Cannot start or end with \"/\"\n * - Cannot contain \"..\" (parent traversal)\n * - Cannot end with \".lock\"\n * - Cannot contain \"@{\" (reflog syntax)\n * - Cannot contain \"//\" (empty path component)\n */\nexport function isValidBranchName(name: string): boolean {\n if (name.length === 0 || name.length > 255) return false;\n if (!VALID_BRANCH_NAME_RE.test(name)) return false;\n if (name.startsWith(\"/\") || name.endsWith(\"/\")) return false;\n if (name.includes(\"..\")) return false;\n if (name.endsWith(\".lock\")) return false;\n if (name.includes(\"@{\")) return false;\n if (name.includes(\"//\")) return false;\n return true;\n}\n","/**\n * Azure DevOps datasource — reads and writes work items using the `az` CLI.\n *\n * Requires:\n * - `az` CLI installed with the `azure-devops` extension\n * - User authenticated via `az login`\n * - Organization and project specified via --org / --project flags\n * or configured as defaults in the az CLI\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { Datasource, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\nimport { slugify } from \"../helpers/slugify.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { InvalidBranchNameError, isValidBranchName } from \"../helpers/branch-validation.js\";\n\nconst exec = promisify(execFile);\nconst doneStateCache = new Map<string, string>();\n\n/**\n * Map a raw Azure DevOps work item JSON object to an IssueDetails.\n */\nfunction mapWorkItemToIssueDetails(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n item: any,\n id: string,\n comments: string[],\n defaults?: { title?: string; body?: string; state?: string; workItemType?: string }\n): IssueDetails {\n const fields = item.fields ?? {};\n return {\n number: String(item.id ?? id),\n title: fields[\"System.Title\"] ?? defaults?.title ?? \"\",\n body: fields[\"System.Description\"] ?? defaults?.body ?? \"\",\n labels: (fields[\"System.Tags\"] ?? \"\")\n .split(\";\")\n .map((t: string) => t.trim())\n .filter(Boolean),\n state: fields[\"System.State\"] ?? defaults?.state ?? \"\",\n url: item._links?.html?.href ?? item.url ?? \"\",\n comments,\n acceptanceCriteria:\n fields[\"Microsoft.VSTS.Common.AcceptanceCriteria\"] ?? \"\",\n iterationPath: fields[\"System.IterationPath\"] || undefined,\n areaPath: fields[\"System.AreaPath\"] || undefined,\n assignee: fields[\"System.AssignedTo\"]?.displayName || undefined,\n priority: fields[\"Microsoft.VSTS.Common.Priority\"] ?? undefined,\n storyPoints:\n fields[\"Microsoft.VSTS.Scheduling.StoryPoints\"] ??\n fields[\"Microsoft.VSTS.Scheduling.Effort\"] ??\n fields[\"Microsoft.VSTS.Scheduling.Size\"] ??\n undefined,\n workItemType: fields[\"System.WorkItemType\"] || defaults?.workItemType || undefined,\n };\n}\n\nexport async function detectWorkItemType(\n opts: IssueFetchOptions = {}\n): Promise<string | null> {\n try {\n const args = [\"boards\", \"work-item\", \"type\", \"list\", \"--output\", \"json\"];\n if (opts.project) args.push(\"--project\", opts.project);\n if (opts.org) args.push(\"--org\", opts.org);\n\n const { stdout } = await exec(\"az\", args, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n const types: { name: string }[] = JSON.parse(stdout);\n if (!Array.isArray(types) || types.length === 0) return null;\n\n const names = types.map((t) => t.name);\n const preferred = [\"User Story\", \"Product Backlog Item\", \"Requirement\", \"Issue\"];\n for (const p of preferred) {\n if (names.includes(p)) return p;\n }\n return names[0] ?? null;\n } catch {\n return null;\n }\n}\n\nexport async function detectDoneState(\n workItemType: string,\n opts: IssueFetchOptions = {}\n): Promise<string> {\n const cacheKey = `${opts.org ?? \"\"}|${opts.project ?? \"\"}|${workItemType}`;\n const cached = doneStateCache.get(cacheKey);\n if (cached) return cached;\n\n try {\n const args = [\n \"boards\", \"work-item\", \"type\", \"state\", \"list\",\n \"--type\", workItemType,\n \"--output\", \"json\",\n ];\n if (opts.project) args.push(\"--project\", opts.project);\n if (opts.org) args.push(\"--org\", opts.org);\n\n const { stdout } = await exec(\"az\", args, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n const states: { name: string; category?: string }[] = JSON.parse(stdout);\n\n // Primary: find state with \"Completed\" category\n if (Array.isArray(states)) {\n const completed = states.find((s) => s.category === \"Completed\");\n if (completed) {\n doneStateCache.set(cacheKey, completed.name);\n return completed.name;\n }\n\n // Fallback: check for known terminal states in priority order\n const names = states.map((s) => s.name);\n const fallbacks = [\"Done\", \"Closed\", \"Resolved\", \"Completed\"];\n for (const f of fallbacks) {\n if (names.includes(f)) {\n doneStateCache.set(cacheKey, f);\n return f;\n }\n }\n }\n } catch {\n // Fall through to default\n }\n\n // Don't cache the default — a transient CLI/parse error should not\n // prevent subsequent calls from retrying the detection.\n return \"Closed\";\n}\n\nexport const datasource: Datasource = {\n name: \"azdevops\",\n\n supportsGit(): boolean {\n return true;\n },\n\n async list(opts: IssueFetchOptions = {}): Promise<IssueDetails[]> {\n const conditions = [\n \"[System.State] <> 'Closed'\",\n \"[System.State] <> 'Done'\",\n \"[System.State] <> 'Removed'\",\n ];\n\n if (opts.iteration) {\n const iterValue = String(opts.iteration).trim();\n if (iterValue === \"@CurrentIteration\") {\n conditions.push(`[System.IterationPath] UNDER @CurrentIteration`);\n } else {\n const escaped = iterValue.replace(/'/g, \"''\");\n if (escaped) conditions.push(`[System.IterationPath] UNDER '${escaped}'`);\n }\n }\n\n if (opts.area) {\n const area = String(opts.area).trim().replace(/'/g, \"''\");\n if (area) {\n conditions.push(`[System.AreaPath] UNDER '${area}'`);\n }\n }\n\n const wiql = `SELECT [System.Id] FROM workitems WHERE ${conditions.join(\" AND \")} ORDER BY [System.CreatedDate] DESC`;\n\n const args = [\"boards\", \"query\", \"--wiql\", wiql, \"--output\", \"json\"];\n if (opts.org) args.push(\"--org\", opts.org);\n if (opts.project) args.push(\"--project\", opts.project);\n\n const { stdout } = await exec(\"az\", args, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n let data;\n try {\n data = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse Azure CLI output: ${stdout.slice(0, 200)}`);\n }\n\n if (!Array.isArray(data)) return [];\n\n const ids = data\n .map((row) => String(row.id ?? row.ID ?? \"\"))\n .filter(Boolean);\n\n if (ids.length === 0) return [];\n\n try {\n const batchArgs = [\n \"boards\", \"work-item\", \"show\",\n \"--id\", ...ids,\n \"--output\", \"json\",\n ];\n if (opts.org) batchArgs.push(\"--org\", opts.org);\n\n const { stdout: batchStdout } = await exec(\"az\", batchArgs, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n let batchItems;\n try {\n batchItems = JSON.parse(batchStdout);\n } catch {\n throw new Error(`Failed to parse Azure CLI output: ${batchStdout.slice(0, 200)}`);\n }\n\n const itemsArray = Array.isArray(batchItems) ? batchItems : [batchItems];\n\n // Fetch comments with bounded concurrency (batches of 5)\n const commentsArray: string[][] = [];\n const CONCURRENCY = 5;\n for (let i = 0; i < itemsArray.length; i += CONCURRENCY) {\n const batch = itemsArray.slice(i, i + CONCURRENCY);\n const batchResults = await Promise.all(\n batch.map((item) => fetchComments(String(item.id), opts))\n );\n commentsArray.push(...batchResults);\n }\n\n return itemsArray.map((item, i) =>\n mapWorkItemToIssueDetails(item, String(item.id), commentsArray[i])\n );\n } catch (err) {\n log.debug(`Batch work-item show failed, falling back to individual fetches: ${log.extractMessage(err)}`);\n // Fallback: fetch items individually in parallel\n const results = await Promise.all(\n ids.map((id) => datasource.fetch(id, opts))\n );\n return results;\n }\n },\n\n async fetch(\n issueId: string,\n opts: IssueFetchOptions = {}\n ): Promise<IssueDetails> {\n const args = [\n \"boards\",\n \"work-item\",\n \"show\",\n \"--id\",\n issueId,\n \"--output\",\n \"json\",\n ];\n\n if (opts.org) {\n args.push(\"--org\", opts.org);\n }\n\n const { stdout } = await exec(\"az\", args, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n let item;\n try {\n item = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse Azure CLI output: ${stdout.slice(0, 200)}`);\n }\n const comments = await fetchComments(issueId, opts);\n\n return mapWorkItemToIssueDetails(item, issueId, comments);\n },\n\n async update(\n issueId: string,\n title: string,\n body: string,\n opts: IssueFetchOptions = {}\n ): Promise<void> {\n const args = [\n \"boards\",\n \"work-item\",\n \"update\",\n \"--id\",\n issueId,\n \"--title\",\n title,\n \"--description\",\n body,\n ];\n if (opts.org) args.push(\"--org\", opts.org);\n await exec(\"az\", args, { cwd: opts.cwd || process.cwd(), shell: process.platform === \"win32\" });\n },\n\n async close(\n issueId: string,\n opts: IssueFetchOptions = {}\n ): Promise<void> {\n let workItemType = opts.workItemType;\n if (!workItemType) {\n const showArgs = [\n \"boards\",\n \"work-item\",\n \"show\",\n \"--id\",\n issueId,\n \"--output\",\n \"json\",\n ];\n if (opts.org) showArgs.push(\"--org\", opts.org);\n const { stdout } = await exec(\"az\", showArgs, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n try {\n const item = JSON.parse(stdout);\n workItemType = item.fields?.[\"System.WorkItemType\"] ?? undefined;\n } catch {\n workItemType = undefined;\n }\n }\n\n const state = workItemType\n ? await detectDoneState(workItemType, opts)\n : \"Closed\";\n\n const args = [\n \"boards\",\n \"work-item\",\n \"update\",\n \"--id\",\n issueId,\n \"--state\",\n state,\n ];\n if (opts.org) args.push(\"--org\", opts.org);\n await exec(\"az\", args, { cwd: opts.cwd || process.cwd(), shell: process.platform === \"win32\" });\n },\n\n async create(\n title: string,\n body: string,\n opts: IssueFetchOptions = {}\n ): Promise<IssueDetails> {\n const workItemType =\n opts.workItemType ?? (await detectWorkItemType(opts));\n\n if (!workItemType) {\n throw new Error(\n \"Could not determine work item type. Set workItemType in your config (for example via `dispatch config`).\"\n );\n }\n\n const args = [\n \"boards\",\n \"work-item\",\n \"create\",\n \"--type\",\n workItemType,\n \"--title\",\n title,\n \"--description\",\n body,\n \"--output\",\n \"json\",\n ];\n if (opts.org) args.push(\"--org\", opts.org);\n if (opts.project) args.push(\"--project\", opts.project);\n\n const { stdout } = await exec(\"az\", args, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n let item;\n try {\n item = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse Azure CLI output: ${stdout.slice(0, 200)}`);\n }\n return mapWorkItemToIssueDetails(item, String(item.id), [], {\n title,\n body,\n state: \"New\",\n workItemType: workItemType,\n });\n },\n\n async getDefaultBranch(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const parts = stdout.trim().split(\"/\");\n const branch = parts[parts.length - 1];\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch, \"from symbolic-ref output\");\n }\n return branch;\n } catch (err) {\n if (err instanceof InvalidBranchNameError) {\n throw err;\n }\n try {\n await exec(\"git\", [\"rev-parse\", \"--verify\", \"main\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n return \"main\";\n } catch {\n return \"master\";\n }\n }\n },\n\n async getUsername(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"config\", \"user.name\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const name = slugify(stdout.trim());\n if (name) return name;\n } catch {\n // fall through\n }\n\n try {\n const { stdout } = await exec(\"az\", [\"account\", \"show\", \"--query\", \"user.name\", \"-o\", \"tsv\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const name = slugify(stdout.trim());\n if (name) return name;\n } catch {\n // fall through\n }\n\n try {\n const { stdout } = await exec(\"az\", [\"account\", \"show\", \"--query\", \"user.principalName\", \"-o\", \"tsv\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const principal = stdout.trim();\n const prefix = principal.split(\"@\")[0];\n const name = slugify(prefix);\n if (name) return name;\n } catch {\n // fall through\n }\n\n return \"unknown\";\n },\n\n buildBranchName(issueNumber: string, title: string, username: string): string {\n const slug = slugify(title, 50);\n const branch = `${username}/dispatch/${issueNumber}-${slug}`;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch);\n }\n return branch;\n },\n\n async createAndSwitchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n if (!isValidBranchName(branchName)) {\n throw new InvalidBranchNameError(branchName);\n }\n try {\n await exec(\"git\", [\"checkout\", \"-b\", branchName], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n } catch (err) {\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n await exec(\"git\", [\"checkout\", branchName], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n } else {\n throw err;\n }\n }\n },\n\n async switchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n await exec(\"git\", [\"checkout\", branchName], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n },\n\n async pushBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n await exec(\"git\", [\"push\", \"--set-upstream\", \"origin\", branchName], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n },\n\n async commitAllChanges(message: string, opts: DispatchLifecycleOptions): Promise<void> {\n await exec(\"git\", [\"add\", \"-A\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const { stdout } = await exec(\"git\", [\"diff\", \"--cached\", \"--stat\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n if (!stdout.trim()) {\n return; // nothing to commit\n }\n await exec(\"git\", [\"commit\", \"-m\", message], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n },\n\n async createPullRequest(\n branchName: string,\n issueNumber: string,\n title: string,\n body: string,\n opts: DispatchLifecycleOptions,\n ): Promise<string> {\n try {\n const { stdout } = await exec(\n \"az\",\n [\n \"repos\",\n \"pr\",\n \"create\",\n \"--title\",\n title,\n \"--description\",\n body || `Resolves AB#${issueNumber}`,\n \"--source-branch\",\n branchName,\n \"--work-items\",\n issueNumber,\n \"--output\",\n \"json\",\n ],\n { cwd: opts.cwd, shell: process.platform === \"win32\" },\n );\n let pr;\n try {\n pr = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse Azure CLI output: ${stdout.slice(0, 200)}`);\n }\n return pr.url ?? \"\";\n } catch (err) {\n // If a PR already exists for this branch, retrieve its URL\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n const { stdout } = await exec(\n \"az\",\n [\n \"repos\",\n \"pr\",\n \"list\",\n \"--source-branch\",\n branchName,\n \"--status\",\n \"active\",\n \"--output\",\n \"json\",\n ],\n { cwd: opts.cwd, shell: process.platform === \"win32\" },\n );\n let prs;\n try {\n prs = JSON.parse(stdout);\n } catch {\n throw new Error(`Failed to parse Azure CLI output: ${stdout.slice(0, 200)}`);\n }\n if (Array.isArray(prs) && prs.length > 0) {\n return prs[0].url ?? \"\";\n }\n return \"\";\n }\n throw err;\n }\n },\n};\n\n/**\n * Fetch comments for an Azure DevOps work item.\n * Non-fatal — returns empty array on failure.\n */\nasync function fetchComments(\n workItemId: string,\n opts: IssueFetchOptions\n): Promise<string[]> {\n try {\n const args = [\n \"boards\",\n \"work-item\",\n \"relation\",\n \"list-comment\",\n \"--work-item-id\",\n workItemId,\n \"--output\",\n \"json\",\n ];\n\n if (opts.org) {\n args.push(\"--org\", opts.org);\n }\n\n const { stdout } = await exec(\"az\", args, {\n cwd: opts.cwd || process.cwd(),\n shell: process.platform === \"win32\",\n });\n\n const data = JSON.parse(stdout);\n if (data.comments && Array.isArray(data.comments)) {\n return data.comments.map(\n (c: { text?: string; createdBy?: { displayName?: string } }) => {\n const author = c.createdBy?.displayName ?? \"unknown\";\n return `**${author}:** ${c.text ?? \"\"}`;\n }\n );\n }\n return [];\n } catch {\n return [];\n }\n}\n","/**\n * Local markdown datasource — reads and writes `.md` files from a configurable\n * directory, treating each file as a work item / spec.\n *\n * Default directory: `.dispatch/specs/` (relative to the working directory).\n *\n * This datasource enables fully offline operation and local-first workflows\n * where markdown files serve as the source of truth.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { readFile, writeFile, readdir, mkdir, rename } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, parse as parsePath, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { glob } from \"glob\";\nimport type { Datasource, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\nimport { slugify } from \"../helpers/slugify.js\";\nimport { loadConfig, saveConfig } from \"../config.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { InvalidBranchNameError, isValidBranchName } from \"../helpers/branch-validation.js\";\n\nconst exec = promisify(execFile);\n\n/** Execute a git command and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/** Default directory for markdown specs, relative to cwd. */\nconst DEFAULT_DIR = \".dispatch/specs\";\n\n/**\n * Resolve the specs directory from options.\n * Uses `opts.cwd` joined with `DEFAULT_DIR`, or just `DEFAULT_DIR`\n * relative to `process.cwd()`.\n */\nfunction resolveDir(opts?: IssueFetchOptions): string {\n const cwd = opts?.cwd ?? process.cwd();\n return join(cwd, DEFAULT_DIR);\n}\n\n/**\n * Normalize an issue ID to a `.md` filename and resolve its full path.\n * - Absolute paths → returned as-is\n * - Relative paths (contain `/`, `\\`, or start with `./` / `../`) → resolved\n * relative to `opts.cwd` (or `process.cwd()`)\n * - Plain filenames → joined with the specs directory (existing behavior)\n */\nfunction resolveFilePath(issueId: string, opts?: IssueFetchOptions): string {\n const filename = issueId.endsWith(\".md\") ? issueId : `${issueId}.md`;\n if (isAbsolute(filename)) return filename;\n if (/[/\\\\]/.test(filename)) {\n const cwd = opts?.cwd ?? process.cwd();\n return resolve(cwd, filename);\n }\n return join(resolveDir(opts), filename);\n}\n\n/**\n * Resolve a potentially numeric issue ID to its full file path.\n * If `issueId` is purely numeric (e.g. \"1\"), scans the specs directory for\n * a file matching `{id}-*.md` and returns its path. Falls back to the\n * standard `resolveFilePath` when no match is found or the ID is not numeric.\n */\nasync function resolveNumericFilePath(issueId: string, opts?: IssueFetchOptions): Promise<string> {\n if (/^\\d+$/.test(issueId)) {\n const dir = resolveDir(opts);\n const entries = await readdir(dir);\n const match = entries.find((f) => f.startsWith(`${issueId}-`) && f.endsWith(\".md\"));\n if (match) {\n return join(dir, match);\n }\n }\n return resolveFilePath(issueId, opts);\n}\n\n/**\n * Extract a title from markdown content.\n * Looks for the first `# Heading` line; if not found, derives a title from the\n * first meaningful line of content (stripping markdown formatting and truncating\n * to ~80 characters at a word boundary). Falls back to the filename when the\n * content has no usable text.\n */\nexport function extractTitle(content: string, filename: string): string {\n // Primary: H1 heading\n const match = content.match(/^#\\s+(.+)$/m);\n if (match) return match[1].trim();\n\n // Secondary: first meaningful content line\n const lines = content.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n // Strip leading markdown prefixes (##, -, *, >, or combinations)\n const cleaned = trimmed.replace(/^[#>*\\-]+\\s*/, \"\").trim();\n if (!cleaned) continue;\n\n // Truncate to ~80 chars at a word boundary\n if (cleaned.length <= 80) return cleaned;\n const truncated = cleaned.slice(0, 80);\n const lastSpace = truncated.lastIndexOf(\" \");\n return lastSpace > 0 ? truncated.slice(0, lastSpace) : truncated;\n }\n\n // Fallback: filename without extension\n return parsePath(filename).name;\n}\n\n/**\n * Build an `IssueDetails` object from a markdown file's content and filename.\n */\nfunction toIssueDetails(filename: string, content: string, dir: string): IssueDetails {\n const idMatch = /^(\\d+)-/.exec(filename);\n return {\n number: idMatch ? idMatch[1] : filename,\n title: extractTitle(content, filename),\n body: content,\n labels: [],\n state: \"open\",\n url: join(dir, filename),\n comments: [],\n acceptanceCriteria: \"\",\n };\n}\n\nexport const datasource: Datasource = {\n name: \"md\",\n\n supportsGit(): boolean {\n return true;\n },\n\n async list(opts?: IssueFetchOptions): Promise<IssueDetails[]> {\n if (opts?.pattern) {\n const cwd = opts.cwd ?? process.cwd();\n const files = await glob(opts.pattern, { cwd, absolute: true });\n const mdFiles = files.filter((f) => f.endsWith(\".md\")).sort();\n const results: IssueDetails[] = [];\n\n for (const filePath of mdFiles) {\n const content = await readFile(filePath, \"utf-8\");\n const filename = basename(filePath);\n const dir = dirname(filePath);\n results.push(toIssueDetails(filename, content, dir));\n }\n\n return results;\n }\n\n const dir = resolveDir(opts);\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n\n const mdFiles = entries.filter((f) => f.endsWith(\".md\")).sort();\n const results: IssueDetails[] = [];\n\n for (const filename of mdFiles) {\n const filePath = join(dir, filename);\n const content = await readFile(filePath, \"utf-8\");\n results.push(toIssueDetails(filename, content, dir));\n }\n\n return results;\n },\n\n async fetch(issueId: string, opts?: IssueFetchOptions): Promise<IssueDetails> {\n if (/^\\d+$/.test(issueId)) {\n const dir = resolveDir(opts);\n const entries = await readdir(dir);\n const match = entries.find((f) => f.startsWith(`${issueId}-`) && f.endsWith(\".md\"));\n if (match) {\n const content = await readFile(join(dir, match), \"utf-8\");\n return toIssueDetails(match, content, dir);\n }\n }\n const filePath = resolveFilePath(issueId, opts);\n const content = await readFile(filePath, \"utf-8\");\n const filename = basename(filePath);\n const dir = dirname(filePath);\n return toIssueDetails(filename, content, dir);\n },\n\n async update(issueId: string, _title: string, body: string, opts?: IssueFetchOptions): Promise<void> {\n const filePath = await resolveNumericFilePath(issueId, opts);\n await writeFile(filePath, body, \"utf-8\");\n },\n\n async close(issueId: string, opts?: IssueFetchOptions): Promise<void> {\n const filePath = await resolveNumericFilePath(issueId, opts);\n const filename = basename(filePath);\n const archiveDir = join(dirname(filePath), \"archive\");\n await mkdir(archiveDir, { recursive: true });\n await rename(filePath, join(archiveDir, filename));\n },\n\n async create(title: string, body: string, opts?: IssueFetchOptions): Promise<IssueDetails> {\n const cwd = opts?.cwd ?? process.cwd();\n const configDir = join(cwd, \".dispatch\");\n const config = await loadConfig(configDir);\n const id = config.nextIssueId ?? 1;\n\n const dir = resolveDir(opts);\n await mkdir(dir, { recursive: true });\n const filename = `${id}-${slugify(title)}.md`;\n const filePath = join(dir, filename);\n await writeFile(filePath, body, \"utf-8\");\n\n config.nextIssueId = id + 1;\n await saveConfig(config, configDir);\n\n return {\n ...toIssueDetails(filename, body, dir),\n number: String(id),\n };\n },\n\n async getDefaultBranch(opts: DispatchLifecycleOptions): Promise<string> {\n const PREFIX = \"refs/remotes/origin/\";\n try {\n const ref = await git([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], opts.cwd);\n const trimmed = ref.trim();\n const branch = trimmed.startsWith(PREFIX)\n ? trimmed.slice(PREFIX.length)\n : trimmed;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch, \"from symbolic-ref output\");\n }\n return branch;\n } catch (err) {\n if (err instanceof InvalidBranchNameError) {\n throw err;\n }\n try {\n await git([\"rev-parse\", \"--verify\", \"main\"], opts.cwd);\n return \"main\";\n } catch {\n return \"master\";\n }\n }\n },\n\n async getUsername(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"config\", \"user.name\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const name = stdout.trim();\n if (!name) return \"local\";\n return slugify(name);\n } catch {\n return \"local\";\n }\n },\n\n buildBranchName(issueNumber: string, title: string, username: string): string {\n const slug = slugify(title, 50);\n return `${username}/dispatch/${issueNumber}-${slug}`;\n },\n\n async createAndSwitchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n try {\n await git([\"checkout\", \"-b\", branchName], opts.cwd);\n } catch (err) {\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n await git([\"checkout\", branchName], opts.cwd);\n } else {\n throw err;\n }\n }\n },\n\n async switchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n await git([\"checkout\", branchName], opts.cwd);\n },\n\n async pushBranch(_branchName: string, _opts: DispatchLifecycleOptions): Promise<void> {\n // No-op: MD datasource does not push to a remote\n },\n\n async commitAllChanges(message: string, opts: DispatchLifecycleOptions): Promise<void> {\n const cwd = opts.cwd;\n await git([\"add\", \"-A\"], cwd);\n const status = await git([\"diff\", \"--cached\", \"--stat\"], cwd);\n if (!status.trim()) {\n return;\n }\n await git([\"commit\", \"-m\", message], cwd);\n },\n\n async createPullRequest(\n _branchName: string,\n _issueNumber: string,\n _title: string,\n _body: string,\n _opts: DispatchLifecycleOptions,\n ): Promise<string> {\n // No-op: MD datasource does not create pull requests\n return \"\";\n },\n};\n","/**\n * Configuration data layer for Dispatch.\n *\n * Manages persistent user configuration stored in {CWD}/.dispatch/config.json.\n * Provides functions for loading, saving, and validating config values.\n */\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { PROVIDER_NAMES } from \"./providers/index.js\";\nimport { DATASOURCE_NAMES } from \"./datasources/index.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\nimport { runInteractiveConfigWizard } from \"./config-prompts.js\";\n\n/**\n * Persistent configuration options for Dispatch.\n * All fields are optional since the config file may contain any subset.\n */\nexport interface DispatchConfig {\n provider?: ProviderName;\n /**\n * Model to use when spawning agents, in provider-specific format.\n * - Copilot: bare model ID (e.g. \"claude-sonnet-4-5\")\n * - OpenCode: \"provider/model\" (e.g. \"anthropic/claude-sonnet-4\")\n * When omitted the provider uses its auto-detected default.\n */\n model?: string;\n source?: DatasourceName;\n testTimeout?: number;\n planTimeout?: number;\n concurrency?: number;\n org?: string;\n project?: string;\n workItemType?: string;\n iteration?: string;\n area?: string;\n /** Internal auto-increment counter for MD datasource issue IDs. Defaults to 1 when absent. */\n nextIssueId?: number;\n}\n\n/** Minimum and maximum bounds for numeric configuration values. */\nexport const CONFIG_BOUNDS = {\n testTimeout: { min: 1, max: 120 },\n planTimeout: { min: 1, max: 120 },\n concurrency: { min: 1, max: 64 },\n} as const;\n\n/** Valid configuration key names. */\nexport const CONFIG_KEYS = [\"provider\", \"model\", \"source\", \"testTimeout\", \"planTimeout\", \"concurrency\", \"org\", \"project\", \"workItemType\", \"iteration\", \"area\"] as const;\n\n/** A valid configuration key name. */\nexport type ConfigKey = (typeof CONFIG_KEYS)[number];\n\n/**\n * Get the path to the config file.\n * Accepts an optional `configDir` override for testing.\n */\nexport function getConfigPath(configDir?: string): string {\n const dir = configDir ?? join(process.cwd(), \".dispatch\");\n return join(dir, \"config.json\");\n}\n\n/**\n * Load the config from disk.\n * Returns `{}` if the file doesn't exist or contains invalid JSON.\n * Accepts an optional `configDir` override for testing.\n */\nexport async function loadConfig(configDir?: string): Promise<DispatchConfig> {\n const configPath = getConfigPath(configDir);\n try {\n const raw = await readFile(configPath, \"utf-8\");\n return JSON.parse(raw) as DispatchConfig;\n } catch {\n return {};\n }\n}\n\n/**\n * Save the config to disk as pretty-printed JSON.\n * Creates the parent directory if it doesn't exist.\n * Accepts an optional `configDir` override for testing.\n */\nexport async function saveConfig(\n config: DispatchConfig,\n configDir?: string,\n): Promise<void> {\n const configPath = getConfigPath(configDir);\n await mkdir(dirname(configPath), { recursive: true });\n await writeFile(configPath, JSON.stringify(config, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Validate a value for a given config key.\n * Returns `null` if valid, or an error message string if invalid.\n */\nexport function validateConfigValue(key: ConfigKey, value: string): string | null {\n switch (key) {\n case \"provider\":\n if (!PROVIDER_NAMES.includes(value as ProviderName)) {\n return `Invalid provider \"${value}\". Available: ${PROVIDER_NAMES.join(\", \")}`;\n }\n return null;\n\n case \"model\":\n if (!value || value.trim() === \"\") {\n return `Invalid model: value must not be empty`;\n }\n return null;\n\n case \"source\":\n if (!DATASOURCE_NAMES.includes(value as DatasourceName)) {\n return `Invalid source \"${value}\". Available: ${DATASOURCE_NAMES.join(\", \")}`;\n }\n return null;\n\n case \"testTimeout\": {\n const num = Number(value);\n if (!Number.isFinite(num) || num < CONFIG_BOUNDS.testTimeout.min || num > CONFIG_BOUNDS.testTimeout.max) {\n return `Invalid testTimeout \"${value}\". Must be a number between ${CONFIG_BOUNDS.testTimeout.min} and ${CONFIG_BOUNDS.testTimeout.max} (minutes)`;\n }\n return null;\n }\n\n case \"planTimeout\": {\n const num = Number(value);\n if (!Number.isFinite(num) || num < CONFIG_BOUNDS.planTimeout.min || num > CONFIG_BOUNDS.planTimeout.max) {\n return `Invalid planTimeout \"${value}\". Must be a number between ${CONFIG_BOUNDS.planTimeout.min} and ${CONFIG_BOUNDS.planTimeout.max} (minutes)`;\n }\n return null;\n }\n\n case \"concurrency\": {\n const num = Number(value);\n if (!Number.isInteger(num) || num < CONFIG_BOUNDS.concurrency.min || num > CONFIG_BOUNDS.concurrency.max) {\n return `Invalid concurrency \"${value}\". Must be an integer between ${CONFIG_BOUNDS.concurrency.min} and ${CONFIG_BOUNDS.concurrency.max}`;\n }\n return null;\n }\n\n case \"org\":\n case \"project\":\n case \"workItemType\":\n case \"iteration\":\n case \"area\":\n if (!value || value.trim() === \"\") {\n return `Invalid ${key}: value must not be empty`;\n }\n return null;\n\n default:\n return `Unknown config key \"${key}\"`;\n }\n}\n\n/**\n * Handle the `dispatch config` subcommand.\n *\n * Launches the interactive configuration wizard.\n */\nexport async function handleConfigCommand(_argv: string[], configDir?: string): Promise<void> {\n await runInteractiveConfigWizard(configDir);\n}\n","/**\n * Interactive configuration wizard for Dispatch.\n *\n * Guides users through provider, datasource, and model selection\n * via an interactive terminal flow.\n */\n\nimport { select, confirm, input } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { log } from \"./helpers/logger.js\";\nimport {\n loadConfig,\n saveConfig,\n type DispatchConfig,\n} from \"./config.js\";\nimport { PROVIDER_NAMES, listProviderModels, checkProviderInstalled } from \"./providers/index.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport {\n DATASOURCE_NAMES,\n detectDatasource,\n getGitRemoteUrl,\n parseAzDevOpsRemoteUrl,\n} from \"./datasources/index.js\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\n\n/**\n * Run the interactive configuration wizard.\n *\n * Loads existing config, walks the user through provider, model, and\n * datasource selection, displays a summary, and saves on confirmation.\n */\nexport async function runInteractiveConfigWizard(configDir?: string): Promise<void> {\n console.log();\n log.info(chalk.bold(\"Dispatch Configuration Wizard\"));\n console.log();\n\n // ── Load existing config ───────────────────────────────────\n const existing = await loadConfig(configDir);\n const hasExisting = Object.keys(existing).length > 0;\n\n if (hasExisting) {\n log.dim(\"Current configuration:\");\n for (const [key, value] of Object.entries(existing)) {\n if (value !== undefined) {\n log.dim(` ${key} = ${value}`);\n }\n }\n console.log();\n\n const reconfigure = await confirm({\n message: \"Do you want to reconfigure?\",\n default: true,\n });\n\n if (!reconfigure) {\n log.dim(\"Configuration unchanged.\");\n return;\n }\n console.log();\n }\n\n // ── Provider selection ─────────────────────────────────────\n const installStatuses = await Promise.all(\n PROVIDER_NAMES.map((name) => checkProviderInstalled(name)),\n );\n\n const provider = await select<ProviderName>({\n message: \"Select a provider:\",\n choices: PROVIDER_NAMES.map((name, i) => ({\n name: `${installStatuses[i] ? chalk.green(\"●\") : chalk.red(\"●\")} ${name}`,\n value: name,\n })),\n default: existing.provider,\n });\n\n // ── Model selection ────────────────────────────────────────\n let selectedModel: string | undefined = existing.model;\n try {\n log.dim(\"Fetching available models...\");\n const models = await listProviderModels(provider);\n if (models.length > 0) {\n const modelChoice = await select<string>({\n message: \"Select a model:\",\n choices: [\n { name: \"default (provider decides)\", value: \"\" },\n ...models.map((m) => ({ name: m, value: m })),\n ],\n default: existing.model ?? \"\",\n });\n selectedModel = modelChoice || undefined;\n } else {\n log.dim(\"No models returned by provider — skipping model selection.\");\n selectedModel = existing.model;\n }\n } catch {\n log.dim(\"Could not list models (provider may not be running) — skipping model selection.\");\n selectedModel = existing.model;\n }\n\n // ── Auto-detect datasource from git remote ─────────────────\n const detectedSource = await detectDatasource(process.cwd());\n const datasourceDefault: DatasourceName | \"auto\" = existing.source ?? \"auto\";\n if (detectedSource) {\n log.info(\n `Detected datasource ${chalk.cyan(detectedSource)} from git remote`,\n );\n }\n\n // ── Datasource selection ───────────────────────────────────\n const selectedSource = await select<DatasourceName | \"auto\">({\n message: \"Select a datasource:\",\n choices: [\n {\n name: \"auto\",\n value: \"auto\" as const,\n description: \"detect from git remote at runtime\",\n },\n ...DATASOURCE_NAMES.map((name) => ({ name, value: name })),\n ],\n default: datasourceDefault,\n });\n const source: DatasourceName | undefined =\n selectedSource === \"auto\" ? undefined : selectedSource;\n\n // ── Azure DevOps-specific fields ───────────────────────────\n let org: string | undefined;\n let project: string | undefined;\n let workItemType: string | undefined;\n let iteration: string | undefined;\n let area: string | undefined;\n\n const effectiveSource = source ?? detectedSource;\n if (effectiveSource === \"azdevops\") {\n // Try to pre-fill org and project from git remote\n let defaultOrg = existing.org ?? \"\";\n let defaultProject = existing.project ?? \"\";\n try {\n const remoteUrl = await getGitRemoteUrl(process.cwd());\n if (remoteUrl) {\n const parsed = parseAzDevOpsRemoteUrl(remoteUrl);\n if (parsed) {\n if (!defaultOrg) defaultOrg = parsed.orgUrl;\n if (!defaultProject) defaultProject = parsed.project;\n }\n }\n } catch {\n // ignore — pre-fill is best-effort\n }\n\n console.log();\n log.info(chalk.bold(\"Azure DevOps settings\") + chalk.dim(\" (leave empty to skip):\"));\n\n const orgInput = await input({\n message: \"Organization URL:\",\n default: defaultOrg || undefined,\n });\n if (orgInput.trim()) org = orgInput.trim();\n\n const projectInput = await input({\n message: \"Project name:\",\n default: defaultProject || undefined,\n });\n if (projectInput.trim()) project = projectInput.trim();\n\n const workItemTypeInput = await input({\n message: \"Work item type (e.g. User Story, Bug):\",\n default: existing.workItemType ?? undefined,\n });\n if (workItemTypeInput.trim()) workItemType = workItemTypeInput.trim();\n\n const iterationInput = await input({\n message: \"Iteration path (e.g. MyProject\\\\Sprint 1, or @CurrentIteration):\",\n default: existing.iteration ?? undefined,\n });\n if (iterationInput.trim()) iteration = iterationInput.trim();\n\n const areaInput = await input({\n message: \"Area path (e.g. MyProject\\\\Team A):\",\n default: existing.area ?? undefined,\n });\n if (areaInput.trim()) area = areaInput.trim();\n }\n\n // ── Build new config ───────────────────────────────────────\n const newConfig: DispatchConfig = {\n provider,\n source,\n };\n\n if (selectedModel !== undefined) {\n newConfig.model = selectedModel;\n }\n if (org !== undefined) newConfig.org = org;\n if (project !== undefined) newConfig.project = project;\n if (workItemType !== undefined) newConfig.workItemType = workItemType;\n if (iteration !== undefined) newConfig.iteration = iteration;\n if (area !== undefined) newConfig.area = area;\n\n // ── Summary ────────────────────────────────────────────────\n console.log();\n log.info(chalk.bold(\"Configuration summary:\"));\n for (const [key, value] of Object.entries(newConfig)) {\n if (value !== undefined) {\n console.log(` ${chalk.cyan(key)} = ${value}`);\n }\n }\n if (selectedSource === \"auto\") {\n console.log(\n ` ${chalk.cyan(\"source\")} = auto (detect from git remote at runtime)`,\n );\n }\n console.log();\n\n // ── Confirm and save ───────────────────────────────────────\n const shouldSave = await confirm({\n message: \"Save this configuration?\",\n default: true,\n });\n\n if (shouldSave) {\n await saveConfig(newConfig, configDir);\n log.success(\"Configuration saved.\");\n } else {\n log.dim(\"Configuration not saved.\");\n }\n}\n","import { basename, join } from \"node:path\";\nimport { mkdtemp, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { log } from \"../helpers/logger.js\";\nimport type { Datasource, DatasourceName, IssueDetails, IssueFetchOptions } from \"../datasources/interface.js\";\nimport type { Task } from \"../parser.js\";\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport { slugify, MAX_SLUG_LENGTH } from \"../helpers/slugify.js\";\n\nconst exec = promisify(execFile);\n\n/** Result of writing issue items to a temp directory. */\nexport interface WriteItemsResult {\n /** Sorted list of written file paths */\n files: string[];\n /** Mapping from file path to the original IssueDetails */\n issueDetailsByFile: Map<string, IssueDetails>;\n}\n\n/**\n * Parse an issue ID and slug from a `<id>-<slug>.md` filename.\n *\n * Returns the numeric issue ID and slug, or `null` if the filename\n * does not match the expected `<id>-<slug>.md` pattern.\n */\nexport function parseIssueFilename(filePath: string): { issueId: string; slug: string } | null {\n const filename = basename(filePath);\n const match = /^(\\d+)-(.+)\\.md$/.exec(filename);\n if (!match) return null;\n return { issueId: match[1], slug: match[2] };\n}\n\n/**\n * Fetch specific issues by ID from a datasource.\n * Logs a warning and skips any ID that fails to fetch.\n */\nexport async function fetchItemsById(\n issueIds: string[],\n datasource: Datasource,\n fetchOpts: IssueFetchOptions,\n): Promise<IssueDetails[]> {\n const ids = issueIds.flatMap((id) =>\n id.split(\",\").map((s) => s.trim()).filter(Boolean)\n );\n const items = [];\n for (const id of ids) {\n try {\n const item = await datasource.fetch(id, fetchOpts);\n items.push(item);\n } catch (err) {\n const prefix = id.includes(\"/\") || id.includes(\"\\\\\") || id.endsWith(\".md\") ? \"\" : \"#\";\n log.warn(`Could not fetch issue ${prefix}${id}: ${log.formatErrorChain(err)}`);\n }\n }\n return items;\n}\n\n/**\n * Write a list of IssueDetails to a temp directory as `{number}-{slug}.md` files.\n * Returns the sorted file paths and a mapping from each path to its original IssueDetails.\n */\nexport async function writeItemsToTempDir(items: IssueDetails[]): Promise<WriteItemsResult> {\n const tempDir = await mkdtemp(join(tmpdir(), \"dispatch-\"));\n const files: string[] = [];\n const issueDetailsByFile = new Map<string, IssueDetails>();\n\n for (const item of items) {\n const slug = slugify(item.title, MAX_SLUG_LENGTH);\n // When item.number is a file path, extract just the basename without extension\n const id = item.number.includes(\"/\") || item.number.includes(\"\\\\\")\n ? basename(item.number, \".md\")\n : item.number;\n const filename = `${id}-${slug}.md`;\n const filepath = join(tempDir, filename);\n await writeFile(filepath, item.body, \"utf-8\");\n files.push(filepath);\n issueDetailsByFile.set(filepath, item);\n }\n\n files.sort((a, b) => {\n const numA = parseInt(basename(a).match(/^(\\d+)/)?.[1] ?? \"0\", 10);\n const numB = parseInt(basename(b).match(/^(\\d+)/)?.[1] ?? \"0\", 10);\n if (numA !== numB) return numA - numB;\n return a.localeCompare(b);\n });\n\n return { files, issueDetailsByFile };\n}\n\n/**\n * Retrieve one-line commit summaries for commits on the current branch\n * that are not on the given default branch.\n *\n * @param defaultBranch - The base branch to compare against (e.g. \"main\")\n * @param cwd - Working directory (git repo root)\n * @returns Array of commit summary strings, one per commit\n */\nasync function getCommitSummaries(defaultBranch: string, cwd: string): Promise<string[]> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", `${defaultBranch}..HEAD`, \"--pretty=format:%s\"],\n { cwd, shell: process.platform === \"win32\" },\n );\n return stdout\n .trim()\n .split(\"\\n\")\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Retrieve the full diff of the current branch relative to the default branch.\n *\n * @param defaultBranch - The base branch to compare against (e.g. \"main\")\n * @param cwd - Working directory (git repo root)\n * @returns The diff output as a string, or an empty string on failure\n */\nexport async function getBranchDiff(defaultBranch: string, cwd: string): Promise<string> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"diff\", `${defaultBranch}..HEAD`],\n { cwd, maxBuffer: 10 * 1024 * 1024, shell: process.platform === \"win32\" },\n );\n return stdout;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Amend the most recent commit's message without changing its content.\n *\n * @param message - The new commit message\n * @param cwd - Working directory (git repo root)\n */\nexport async function amendCommitMessage(message: string, cwd: string): Promise<void> {\n await exec(\n \"git\",\n [\"commit\", \"--amend\", \"-m\", message],\n { cwd, shell: process.platform === \"win32\" },\n );\n}\n\n/**\n * Squash all commits on the current branch (relative to the default branch)\n * into a single commit with the given message.\n *\n * Uses a soft reset to the merge-base followed by a fresh commit, which\n * avoids interactive rebase complexity.\n *\n * @param defaultBranch - The base branch to compare against (e.g. \"main\")\n * @param message - The commit message for the squashed commit\n * @param cwd - Working directory (git repo root)\n */\nexport async function squashBranchCommits(\n defaultBranch: string,\n message: string,\n cwd: string,\n): Promise<void> {\n const { stdout } = await exec(\n \"git\",\n [\"merge-base\", defaultBranch, \"HEAD\"],\n { cwd, shell: process.platform === \"win32\" },\n );\n const mergeBase = stdout.trim();\n await exec(\"git\", [\"reset\", \"--soft\", mergeBase], { cwd, shell: process.platform === \"win32\" });\n await exec(\"git\", [\"commit\", \"-m\", message], { cwd, shell: process.platform === \"win32\" });\n}\n\n/**\n * Assemble a descriptive pull request body from pipeline data.\n *\n * Includes:\n * - A summary section with commit messages from the branch\n * - The list of completed tasks\n * - Labels from the issue (if any)\n * - An issue-close reference appropriate for the datasource\n *\n * @param details - The issue details (title, body, labels, number)\n * @param tasks - The tasks that were dispatched for this issue\n * @param results - The dispatch results for all tasks\n * @param defaultBranch - The base branch to compare commits against\n * @param datasourceName - The datasource backend name (\"github\", \"azdevops\", \"md\")\n * @param cwd - Working directory (git repo root)\n * @returns The assembled PR body as a markdown string\n */\nexport async function buildPrBody(\n details: IssueDetails,\n tasks: Task[],\n results: DispatchResult[],\n defaultBranch: string,\n datasourceName: DatasourceName,\n cwd: string,\n): Promise<string> {\n const sections: string[] = [];\n\n // ── Commit summary section ──────────────────────────────────\n const commits = await getCommitSummaries(defaultBranch, cwd);\n if (commits.length > 0) {\n sections.push(\"## Summary\\n\");\n for (const commit of commits) {\n sections.push(`- ${commit}`);\n }\n sections.push(\"\");\n }\n\n // ── Completed tasks section ─────────────────────────────────\n const taskResults = new Map(\n results\n .filter((r) => tasks.includes(r.task))\n .map((r) => [r.task, r]),\n );\n\n const completedTasks = tasks.filter((t) => taskResults.get(t)?.success);\n const failedTasks = tasks.filter((t) => {\n const r = taskResults.get(t);\n return r && !r.success;\n });\n\n if (completedTasks.length > 0 || failedTasks.length > 0) {\n sections.push(\"## Tasks\\n\");\n for (const task of completedTasks) {\n sections.push(`- [x] ${task.text}`);\n }\n for (const task of failedTasks) {\n sections.push(`- [ ] ${task.text}`);\n }\n sections.push(\"\");\n }\n\n // ── Labels section ──────────────────────────────────────────\n if (details.labels.length > 0) {\n sections.push(`**Labels:** ${details.labels.join(\", \")}\\n`);\n }\n\n // ── Issue-close reference ───────────────────────────────────\n if (datasourceName === \"github\") {\n sections.push(`Closes #${details.number}`);\n } else if (datasourceName === \"azdevops\") {\n sections.push(`Resolves AB#${details.number}`);\n }\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Generate a descriptive PR title from commit messages on the branch.\n *\n * If a single commit exists, its message is used as the title.\n * If multiple commits exist, a summary title is generated that\n * captures the scope, prefixed with the issue title.\n * Falls back to the issue title if no commits are found.\n *\n * @param issueTitle - The original issue title (used as fallback)\n * @param defaultBranch - The base branch to compare commits against\n * @param cwd - Working directory (git repo root)\n * @returns A descriptive PR title string\n */\nexport async function buildPrTitle(\n issueTitle: string,\n defaultBranch: string,\n cwd: string,\n): Promise<string> {\n const commits = await getCommitSummaries(defaultBranch, cwd);\n\n if (commits.length === 0) {\n return issueTitle;\n }\n\n if (commits.length === 1) {\n return commits[0];\n }\n\n // Multiple commits — use the first commit message with a count suffix\n return `${commits[commits.length - 1]} (+${commits.length - 1} more)`;\n}\n\n/**\n * Build an aggregated PR title for feature mode.\n *\n * When a single issue is processed, the PR title is just that issue's title.\n * For multiple issues, the title includes the feature branch name and\n * references to all issues.\n *\n * @param featureBranchName - The feature branch name (e.g. \"dispatch/feature-a1b2c3d4\")\n * @param issues - All issue details processed in this feature run\n * @returns An aggregated PR title string\n */\nexport function buildFeaturePrTitle(featureBranchName: string, issues: IssueDetails[]): string {\n if (issues.length === 1) {\n return issues[0].title;\n }\n const issueRefs = issues.map((d) => `#${d.number}`).join(\", \");\n return `feat: ${featureBranchName} (${issueRefs})`;\n}\n\n/**\n * Build an aggregated PR body for feature mode that references all issues,\n * their tasks, and completion status.\n *\n * Includes:\n * - An issues section listing all issues addressed\n * - A tasks section with completion checkboxes\n * - Issue-close references appropriate for the datasource\n *\n * @param issues - All issue details processed in this feature run\n * @param tasks - All tasks dispatched across all issues\n * @param results - The dispatch results for all tasks\n * @param datasourceName - The datasource backend name (\"github\", \"azdevops\", \"md\")\n * @returns The assembled aggregated PR body as a markdown string\n */\nexport function buildFeaturePrBody(\n issues: IssueDetails[],\n tasks: Task[],\n results: DispatchResult[],\n datasourceName: DatasourceName,\n): string {\n const sections: string[] = [];\n\n sections.push(\"## Issues\\n\");\n for (const issue of issues) {\n sections.push(`- #${issue.number}: ${issue.title}`);\n }\n sections.push(\"\");\n\n const taskResults = new Map(results.map((r) => [r.task, r]));\n const completedTasks = tasks.filter((t) => taskResults.get(t)?.success);\n const failedTasks = tasks.filter((t) => {\n const r = taskResults.get(t);\n return r && !r.success;\n });\n\n if (completedTasks.length > 0 || failedTasks.length > 0) {\n sections.push(\"## Tasks\\n\");\n for (const task of completedTasks) {\n sections.push(`- [x] ${task.text}`);\n }\n for (const task of failedTasks) {\n sections.push(`- [ ] ${task.text}`);\n }\n sections.push(\"\");\n }\n\n for (const issue of issues) {\n if (datasourceName === \"github\") {\n sections.push(`Closes #${issue.number}`);\n } else if (datasourceName === \"azdevops\") {\n sections.push(`Resolves AB#${issue.number}`);\n }\n }\n\n return sections.join(\"\\n\");\n}\n","/**\n * Git worktree lifecycle manager.\n *\n * Creates, removes, and lists git worktrees in `.dispatch/worktrees/`.\n * Worktree directory names are derived from the leading numeric ID of the\n * issue filename (e.g., `123-fix-auth-bug.md` → `issue-123`).\n */\n\nimport { join, basename } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { randomUUID } from \"node:crypto\";\nimport { slugify } from \"./slugify.js\";\nimport { log } from \"./logger.js\";\n\nconst exec = promisify(execFile);\n\n/** Base directory for worktrees, relative to the repository root. */\nconst WORKTREE_DIR = \".dispatch/worktrees\";\n\n/** Execute a git command in the given working directory and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/**\n * Derive a worktree directory name from an issue filename.\n *\n * Extracts the leading numeric ID and returns `issue-{id}`.\n * Example: `123-fix-auth-bug.md` → `issue-123`\n *\n * @param issueFilename - The issue filename (basename or full path)\n * @returns A directory name suitable for a worktree\n */\nexport function worktreeName(issueFilename: string): string {\n const base = basename(issueFilename);\n const withoutExt = base.replace(/\\.md$/i, \"\");\n const match = withoutExt.match(/^(\\d+)/);\n return match ? `issue-${match[1]}` : slugify(withoutExt);\n}\n\n/**\n * Create a git worktree for the given issue file.\n *\n * The worktree is placed at `.dispatch/worktrees/<name>` (relative to `repoRoot`)\n * and checks out a new branch with the specified `branchName`.\n *\n * @param repoRoot - Absolute path to the repository root\n * @param issueFilename - The issue filename used to derive the worktree directory name\n * @param branchName - The branch name to create and check out in the worktree\n * @returns The absolute path to the created worktree directory\n */\nexport async function createWorktree(\n repoRoot: string,\n issueFilename: string,\n branchName: string,\n startPoint?: string,\n): Promise<string> {\n const name = worktreeName(issueFilename);\n const worktreePath = join(repoRoot, WORKTREE_DIR, name);\n\n try {\n const args = [\"worktree\", \"add\", worktreePath, \"-b\", branchName];\n if (startPoint) args.push(startPoint);\n await git(args, repoRoot);\n log.debug(`Created worktree at ${worktreePath} on branch ${branchName}`);\n } catch (err) {\n const message = log.extractMessage(err);\n // If the branch already exists, try adding without -b\n if (message.includes(\"already exists\")) {\n await git([\"worktree\", \"add\", worktreePath, branchName], repoRoot);\n log.debug(`Created worktree at ${worktreePath} using existing branch ${branchName}`);\n } else {\n throw err;\n }\n }\n\n return worktreePath;\n}\n\n/**\n * Remove a git worktree.\n *\n * Attempts a normal removal first, falling back to `--force` if needed.\n * Runs `git worktree prune` afterwards to clean up stale references.\n * Logs a warning instead of throwing on failure so execution can continue.\n *\n * @param repoRoot - Absolute path to the repository root\n * @param issueFilename - The issue filename used to derive the worktree directory name\n */\nexport async function removeWorktree(\n repoRoot: string,\n issueFilename: string,\n): Promise<void> {\n const name = worktreeName(issueFilename);\n const worktreePath = join(repoRoot, WORKTREE_DIR, name);\n\n try {\n await git([\"worktree\", \"remove\", worktreePath], repoRoot);\n } catch {\n // Force removal as fallback\n try {\n await git([\"worktree\", \"remove\", \"--force\", worktreePath], repoRoot);\n } catch (err) {\n log.warn(`Could not remove worktree ${name}: ${log.formatErrorChain(err)}`);\n return;\n }\n }\n\n // Prune stale worktree references\n try {\n await git([\"worktree\", \"prune\"], repoRoot);\n } catch (err) {\n log.warn(`Could not prune worktrees: ${log.formatErrorChain(err)}`);\n }\n}\n\n/**\n * List all current git worktrees in the repository.\n *\n * Returns the raw `git worktree list` output for diagnostic purposes.\n *\n * @param repoRoot - Absolute path to the repository root\n * @returns The worktree list output string\n */\nexport async function listWorktrees(repoRoot: string): Promise<string> {\n try {\n return await git([\"worktree\", \"list\"], repoRoot);\n } catch (err) {\n log.warn(`Could not list worktrees: ${log.formatErrorChain(err)}`);\n return \"\";\n }\n}\n\n/**\n * Generate a unique feature branch name.\n *\n * Produces a name in the format `dispatch/feature-{octet}`, where `{octet}`\n * is the first 8 hex characters of a random UUID.\n *\n * @returns A feature branch name like `dispatch/feature-a1b2c3d4`\n */\nexport function generateFeatureBranchName(): string {\n const uuid = randomUUID();\n const octet = uuid.split(\"-\")[0];\n return `dispatch/feature-${octet}`;\n}\n","/**\n * Runner — thin coordinator that delegates to extracted pipeline modules.\n */\n\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport type { AgentBootOptions } from \"../agents/interface.js\";\nimport type { ProviderName } from \"../providers/interface.js\";\nimport type { DatasourceName } from \"../datasources/interface.js\";\nimport type { SpecOptions, SpecSummary } from \"../spec-generator.js\";\nimport { defaultConcurrency, resolveSource } from \"../spec-generator.js\";\nimport { getDatasource } from \"../datasources/index.js\";\nimport { fetchItemsById } from \"./datasource-helpers.js\";\nimport { createWorktree, removeWorktree } from \"../helpers/worktree.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { confirmLargeBatch } from \"../helpers/confirm-large-batch.js\";\nimport { checkPrereqs } from \"../helpers/prereqs.js\";\nimport { ensureGitignoreEntry } from \"../helpers/gitignore.js\";\nimport { resolveCliConfig } from \"./cli-config.js\";\nimport { runSpecPipeline } from \"./spec-pipeline.js\";\nimport { runDispatchPipeline } from \"./dispatch-pipeline.js\";\n\n/** Runtime options passed to `orchestrate()`. */\nexport interface OrchestrateRunOptions {\n issueIds: string[];\n concurrency?: number;\n dryRun: boolean;\n noPlan?: boolean;\n noBranch?: boolean;\n noWorktree?: boolean;\n force?: boolean;\n provider?: ProviderName;\n /** Model override to pass to the provider (provider-specific format). */\n model?: string;\n serverUrl?: string;\n source?: DatasourceName;\n org?: string;\n project?: string;\n workItemType?: string;\n iteration?: string;\n area?: string;\n planTimeout?: number;\n planRetries?: number;\n retries?: number;\n feature?: string | boolean;\n}\n\n/** Raw CLI arguments before config resolution. */\nexport interface RawCliArgs {\n issueIds: string[];\n dryRun: boolean;\n noPlan: boolean;\n noBranch: boolean;\n noWorktree: boolean;\n force: boolean;\n concurrency?: number;\n provider: ProviderName;\n /** Model override from config or CLI (provider-specific format). */\n model?: string;\n serverUrl?: string;\n cwd: string;\n verbose: boolean;\n spec?: string | string[];\n respec?: string | string[];\n fixTests?: boolean;\n issueSource?: DatasourceName;\n org?: string;\n project?: string;\n workItemType?: string;\n iteration?: string;\n area?: string;\n planTimeout?: number;\n planRetries?: number;\n testTimeout?: number;\n retries?: number;\n feature?: string | boolean;\n outputDir?: string;\n explicitFlags: Set<string>;\n}\n\nexport interface DispatchSummary {\n total: number;\n completed: number;\n failed: number;\n skipped: number;\n results: DispatchResult[];\n}\n\n/** Per-issue result for fix-tests runs targeting specific issues. */\nexport interface IssueResult {\n issueId: string;\n branch: string;\n success: boolean;\n error?: string;\n}\n\nexport interface FixTestsSummary {\n mode: \"fix-tests\";\n success: boolean;\n error?: string;\n issueResults?: IssueResult[];\n}\n\n/** Dispatch-mode run options with explicit mode discriminator. */\nexport interface DispatchRunOptions extends OrchestrateRunOptions {\n mode: \"dispatch\";\n}\n\n/** Spec-mode run options with explicit mode discriminator. */\nexport interface SpecRunOptions extends Omit<SpecOptions, \"cwd\"> {\n mode: \"spec\";\n}\n\n/** Fix-tests-mode run options with explicit mode discriminator. */\nexport interface FixTestsRunOptions {\n mode: \"fix-tests\";\n testTimeout?: number;\n issueIds?: string[];\n provider?: ProviderName;\n serverUrl?: string;\n verbose?: boolean;\n dryRun?: boolean;\n source?: DatasourceName;\n org?: string;\n project?: string;\n cwd?: string;\n}\n\n/** Discriminated union of all runner run options. */\nexport type UnifiedRunOptions = DispatchRunOptions | SpecRunOptions | FixTestsRunOptions;\n\n/** Unified result type — DispatchSummary or SpecSummary depending on mode. */\nexport type RunResult = DispatchSummary | SpecSummary | FixTestsSummary;\n\n/** A booted runner that coordinates dispatch and spec pipelines. */\nexport interface OrchestratorAgent {\n orchestrate(opts: OrchestrateRunOptions): Promise<DispatchSummary>;\n generateSpecs(opts: SpecOptions): Promise<SpecSummary>;\n run(opts: UnifiedRunOptions): Promise<RunResult>;\n runFromCli(args: RawCliArgs): Promise<RunResult>;\n}\n\n/** Options for the multi-issue worktree fix-tests flow. */\ninterface MultiIssueFixTestsOptions {\n cwd: string;\n issueIds: string[];\n source: DatasourceName;\n provider: ProviderName;\n serverUrl?: string;\n verbose: boolean;\n testTimeout?: number;\n org?: string;\n project?: string;\n}\n\n/**\n * Run fix-tests across multiple issues, each in its own worktree.\n *\n * Fetches the specified issues from the configured datasource,\n * creates a worktree per issue, runs `runFixTestsPipeline` inside\n * each worktree, and collects per-issue results.\n */\nasync function runMultiIssueFixTests(opts: MultiIssueFixTestsOptions): Promise<FixTestsSummary> {\n const { runFixTestsPipeline } = await import(\"./fix-tests-pipeline.js\");\n const datasource = getDatasource(opts.source);\n const fetchOpts = { cwd: opts.cwd, org: opts.org, project: opts.project };\n const items = await fetchItemsById(opts.issueIds, datasource, fetchOpts);\n\n if (items.length === 0) {\n log.warn(\"No issues found for the given IDs\");\n return { mode: \"fix-tests\", success: false, error: \"No issues found\" };\n }\n\n let username = \"\";\n try {\n username = await datasource.getUsername({ cwd: opts.cwd });\n } catch (err) {\n log.warn(`Could not resolve git username for branch naming: ${log.formatErrorChain(err)}`);\n }\n\n log.info(`Running fix-tests for ${items.length} issue(s) in worktrees`);\n\n const issueResults: IssueResult[] = [];\n\n for (const item of items) {\n const branchName = datasource.buildBranchName(item.number, item.title, username);\n const issueFilename = `${item.number}-fix-tests.md`;\n let worktreePath: string | undefined;\n\n try {\n worktreePath = await createWorktree(opts.cwd, issueFilename, branchName);\n registerCleanup(async () => { await removeWorktree(opts.cwd, issueFilename); });\n log.info(`Created worktree for issue #${item.number} at ${worktreePath}`);\n\n const result = await runFixTestsPipeline({\n cwd: worktreePath,\n provider: opts.provider,\n serverUrl: opts.serverUrl,\n verbose: opts.verbose,\n testTimeout: opts.testTimeout,\n });\n\n issueResults.push({ issueId: item.number, branch: branchName, success: result.success, error: result.error });\n } catch (err) {\n const message = log.extractMessage(err);\n log.error(`Fix-tests failed for issue #${item.number}: ${message}`);\n issueResults.push({ issueId: item.number, branch: branchName, success: false, error: message });\n } finally {\n if (worktreePath) {\n try {\n await removeWorktree(opts.cwd, issueFilename);\n } catch (err) {\n log.warn(`Could not remove worktree for issue #${item.number}: ${log.formatErrorChain(err)}`);\n }\n }\n }\n }\n\n const allSuccess = issueResults.length > 0 && issueResults.every((r) => r.success);\n return { mode: \"fix-tests\", success: allSuccess, issueResults };\n}\n\n/** Boot a runner. */\nexport async function boot(opts: AgentBootOptions): Promise<OrchestratorAgent> {\n const { cwd } = opts;\n\n const runner: OrchestratorAgent = {\n orchestrate: (runOpts) => runDispatchPipeline(runOpts, cwd),\n\n generateSpecs: (specOpts) => runSpecPipeline(specOpts),\n\n async run(opts: UnifiedRunOptions): Promise<RunResult> {\n if (opts.mode === \"spec\") {\n const { mode: _, ...rest } = opts;\n return runner.generateSpecs({ ...rest, cwd });\n }\n if (opts.mode === \"fix-tests\") {\n const { runFixTestsPipeline } = await import(\"./fix-tests-pipeline.js\");\n\n // No issue IDs — run in current cwd (existing behavior)\n if (!opts.issueIds || opts.issueIds.length === 0) {\n return runFixTestsPipeline({ cwd, provider: opts.provider ?? \"opencode\", serverUrl: opts.serverUrl, verbose: opts.verbose ?? false, testTimeout: opts.testTimeout });\n }\n\n // Multi-issue fix-tests via worktrees\n const source = opts.source;\n if (!source) {\n log.error(\"No datasource configured for multi-issue fix-tests.\");\n return { mode: \"fix-tests\" as const, success: false, error: \"No datasource configured\" };\n }\n\n return runMultiIssueFixTests({\n cwd, issueIds: opts.issueIds, source,\n provider: opts.provider ?? \"opencode\", serverUrl: opts.serverUrl,\n verbose: opts.verbose ?? false, testTimeout: opts.testTimeout,\n org: opts.org, project: opts.project,\n });\n }\n const { mode: _, ...rest } = opts;\n return runner.orchestrate(rest);\n },\n\n async runFromCli(args: RawCliArgs): Promise<RunResult> {\n const m = await resolveCliConfig(args);\n\n // ── Prerequisite checks ───────────────────────────────────\n const prereqFailures = await checkPrereqs({ datasource: m.issueSource });\n if (prereqFailures.length > 0) {\n for (const msg of prereqFailures) {\n log.error(msg);\n }\n process.exit(1);\n }\n\n // Ensure .dispatch/worktrees/ is gitignored in the main repo\n await ensureGitignoreEntry(m.cwd, \".dispatch/worktrees/\");\n\n // ── Mutual exclusion: --spec, --respec, --fix-tests ────\n const modeFlags = [\n m.spec !== undefined && \"--spec\",\n m.respec !== undefined && \"--respec\",\n m.fixTests && \"--fix-tests\",\n m.feature && \"--feature\",\n ].filter(Boolean) as string[];\n\n if (modeFlags.length > 1) {\n log.error(`${modeFlags.join(\" and \")} are mutually exclusive`);\n process.exit(1);\n }\n\n // --feature requires branching — mutually exclusive with --no-branch\n if (m.feature && m.noBranch) {\n log.error(\"--feature and --no-branch are mutually exclusive\");\n process.exit(1);\n }\n\n if (m.fixTests) {\n const { runFixTestsPipeline } = await import(\"./fix-tests-pipeline.js\");\n\n // No issue IDs — run in current cwd (existing behavior)\n if (m.issueIds.length === 0) {\n return runFixTestsPipeline({ cwd: m.cwd, provider: m.provider, serverUrl: m.serverUrl, verbose: m.verbose, testTimeout: m.testTimeout });\n }\n\n // Multi-issue fix-tests via worktrees\n const source = m.issueSource;\n if (!source) {\n log.error(\"No datasource configured. Use --source or run 'dispatch config' to set up defaults.\");\n process.exit(1);\n }\n\n return runMultiIssueFixTests({\n cwd: m.cwd, issueIds: m.issueIds, source,\n provider: m.provider, serverUrl: m.serverUrl,\n verbose: m.verbose, testTimeout: m.testTimeout,\n org: m.org, project: m.project,\n });\n }\n\n if (m.spec) {\n return this.generateSpecs({\n issues: m.spec, issueSource: m.issueSource, provider: m.provider,\n model: m.model, serverUrl: m.serverUrl, cwd: m.cwd, outputDir: m.outputDir,\n org: m.org, project: m.project, workItemType: m.workItemType, iteration: m.iteration, area: m.area, concurrency: m.concurrency,\n dryRun: m.dryRun,\n });\n }\n\n if (m.respec) {\n const respecArgs = m.respec;\n const isEmpty = Array.isArray(respecArgs) && respecArgs.length === 0;\n\n let issues: string | string[];\n if (isEmpty) {\n // No arguments: discover all existing specs via datasource.list()\n const source = await resolveSource(respecArgs, m.issueSource, m.cwd);\n if (!source) {\n process.exit(1);\n }\n const datasource = getDatasource(source);\n const existing = await datasource.list({ cwd: m.cwd, org: m.org, project: m.project, workItemType: m.workItemType, iteration: m.iteration, area: m.area });\n if (existing.length === 0) {\n log.error(\"No existing specs found to regenerate\");\n process.exit(1);\n }\n const identifiers = existing.map((item) => item.number);\n const allNumeric = identifiers.every((id) => /^\\d+$/.test(id));\n issues = allNumeric ? identifiers.join(\",\") : identifiers;\n\n const confirmed = await confirmLargeBatch(existing.length);\n if (!confirmed) {\n process.exit(0);\n }\n } else {\n // With arguments: pass directly (same as --spec)\n issues = respecArgs;\n }\n\n return this.generateSpecs({\n issues, issueSource: m.issueSource, provider: m.provider,\n model: m.model, serverUrl: m.serverUrl, cwd: m.cwd, outputDir: m.outputDir,\n org: m.org, project: m.project, workItemType: m.workItemType, iteration: m.iteration, area: m.area, concurrency: m.concurrency,\n dryRun: m.dryRun,\n });\n }\n\n return this.orchestrate({\n issueIds: m.issueIds, concurrency: m.concurrency ?? defaultConcurrency(),\n dryRun: m.dryRun, noPlan: m.noPlan, noBranch: m.noBranch, noWorktree: m.noWorktree, provider: m.provider,\n model: m.model, serverUrl: m.serverUrl, source: m.issueSource, org: m.org, project: m.project,\n workItemType: m.workItemType, iteration: m.iteration, area: m.area, planTimeout: m.planTimeout, planRetries: m.planRetries, retries: m.retries,\n force: m.force, feature: m.feature,\n });\n },\n };\n\n return runner;\n}\n\nexport { parseIssueFilename } from \"./datasource-helpers.js\";\n","/**\n * Large-batch confirmation prompt.\n *\n * Asks the user to explicitly type \"yes\" before proceeding when a\n * spec or respec operation targets more items than the safety threshold.\n * Extracted into its own module so both the runner and spec-pipeline\n * call sites can share the logic and tests can mock it via `vi.mock()`.\n */\n\nimport { input } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { log } from \"./logger.js\";\n\n/** Default threshold above which confirmation is required. */\nexport const LARGE_BATCH_THRESHOLD = 100;\n\n/**\n * Prompt the user to confirm a large batch operation.\n *\n * If `count` is at or below `threshold`, returns `true` immediately.\n * Otherwise, warns the user and requires them to type \"yes\" to proceed.\n *\n * @param count - Number of specs that will be processed\n * @param threshold - Minimum count that triggers the prompt (default {@link LARGE_BATCH_THRESHOLD})\n * @returns `true` if the user confirmed (or count ≤ threshold), `false` otherwise\n */\nexport async function confirmLargeBatch(\n count: number,\n threshold: number = LARGE_BATCH_THRESHOLD,\n): Promise<boolean> {\n if (count <= threshold) return true;\n\n log.warn(\n `This operation will process ${chalk.bold(String(count))} specs, which exceeds the safety threshold of ${threshold}.`,\n );\n\n const answer = await input({\n message: `Type ${chalk.bold('\"yes\"')} to proceed:`,\n });\n\n return answer.trim().toLowerCase() === \"yes\";\n}\n","/**\n * Startup prerequisite checker.\n *\n * Verifies that required external tools and runtime versions are available\n * before any pipeline logic runs. Returns an array of human-readable failure\n * messages — an empty array means all checks pass.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport type { DatasourceName } from \"../datasources/interface.js\";\n\nconst exec = promisify(execFile);\n\n/** Optional context for datasource-specific prerequisite checks. */\nexport interface PrereqContext {\n /** The resolved datasource name. */\n datasource?: DatasourceName;\n}\n\n/** Minimum supported Node.js version (matches package.json engines field). */\nconst MIN_NODE_VERSION = \"20.12.0\";\n\n/**\n * Parse a semver-style version string into [major, minor, patch] numbers.\n */\nfunction parseSemver(version: string): [number, number, number] {\n const [major, minor, patch] = version.split(\".\").map(Number);\n return [major ?? 0, minor ?? 0, patch ?? 0];\n}\n\n/**\n * Return true if `current` is greater than or equal to `minimum`\n * using major.minor.patch comparison.\n */\nfunction semverGte(current: string, minimum: string): boolean {\n const [cMaj, cMin, cPat] = parseSemver(current);\n const [mMaj, mMin, mPat] = parseSemver(minimum);\n if (cMaj !== mMaj) return cMaj > mMaj;\n if (cMin !== mMin) return cMin > mMin;\n return cPat >= mPat;\n}\n\n/**\n * Verify that required external tools and runtime versions are available.\n *\n * Checks performed:\n * 1. `git` is available on PATH (via `git --version`)\n * 2. Node.js version meets the `>=20.12.0` minimum\n * 3. `gh` (GitHub CLI) is available when datasource is `github`\n * 4. `az` (Azure CLI) is available when datasource is `azdevops`\n *\n * @param context Optional datasource context for conditional CLI checks.\n * @returns An array of human-readable failure message strings.\n * An empty array means all checks passed.\n */\nexport async function checkPrereqs(context?: PrereqContext): Promise<string[]> {\n const failures: string[] = [];\n\n // Check git availability\n try {\n await exec(\"git\", [\"--version\"], { shell: process.platform === \"win32\" });\n } catch {\n failures.push(\"git is required but was not found on PATH. Install it from https://git-scm.com\");\n }\n\n // Check Node.js version\n const nodeVersion = process.versions.node;\n if (!semverGte(nodeVersion, MIN_NODE_VERSION)) {\n failures.push(\n `Node.js >= ${MIN_NODE_VERSION} is required but found ${nodeVersion}. Please upgrade Node.js`,\n );\n }\n\n // Datasource-specific CLI tool checks\n if (context?.datasource === \"github\") {\n try {\n await exec(\"gh\", [\"--version\"], { shell: process.platform === \"win32\" });\n } catch {\n failures.push(\n \"gh (GitHub CLI) is required for the github datasource but was not found on PATH. Install it from https://cli.github.com/\",\n );\n }\n }\n\n if (context?.datasource === \"azdevops\") {\n try {\n await exec(\"az\", [\"--version\"], { shell: process.platform === \"win32\" });\n } catch {\n failures.push(\n \"az (Azure CLI) is required for the azdevops datasource but was not found on PATH. Install it from https://learn.microsoft.com/en-us/cli/azure/\",\n );\n }\n }\n\n return failures;\n}\n","/**\n * Utility for ensuring entries exist in a repository's .gitignore file.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { log } from \"./logger.js\";\n\n/**\n * Ensure `entry` appears as a line in `<repoRoot>/.gitignore`.\n *\n * Creates the file if it doesn't exist. No-ops if the entry (with or without\n * a trailing slash) is already present. Logs a warning and continues on\n * failure — this is non-fatal so a permissions issue won't abort the run.\n *\n * @param repoRoot - Absolute path to the repository root\n * @param entry - The gitignore pattern to add (e.g. `.dispatch/worktrees/`)\n */\nexport async function ensureGitignoreEntry(repoRoot: string, entry: string): Promise<void> {\n const gitignorePath = join(repoRoot, \".gitignore\");\n\n let contents = \"\";\n try {\n contents = await readFile(gitignorePath, \"utf8\");\n } catch (err: unknown) {\n if (err instanceof Error && \"code\" in err && (err as NodeJS.ErrnoException).code === \"ENOENT\") {\n // File doesn't exist — will be created below\n } else {\n log.warn(`Could not read .gitignore: ${String(err)}`);\n return;\n }\n }\n\n const lines = contents.split(/\\r?\\n/);\n // Match with or without trailing slash to avoid adding a duplicate when\n // the user already has the bare form (e.g. `.dispatch/worktrees`) or the\n // slash form (e.g. `.dispatch/worktrees/`).\n const bare = entry.replace(/\\/$/, \"\");\n const withSlash = bare + \"/\";\n if (lines.includes(entry) || lines.includes(bare) || lines.includes(withSlash)) {\n return;\n }\n\n try {\n const separator = contents.length > 0 && !contents.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await writeFile(gitignorePath, `${contents}${separator}${entry}\\n`, \"utf8\");\n log.debug(`Added '${entry}' to .gitignore`);\n } catch (err) {\n log.warn(`Could not update .gitignore: ${String(err)}`);\n }\n}\n","/**\n * CLI config resolution — loads the config file, merges config defaults\n * beneath CLI flags, validates mandatory configuration, and enables\n * verbose logging.\n *\n * Extracted from the orchestrator's `runFromCli()` method to keep the\n * coordinator thin and this logic independently testable.\n */\n\nimport { join } from \"node:path\";\nimport { access } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { log } from \"../helpers/logger.js\";\nimport { loadConfig, CONFIG_KEYS, type DispatchConfig, type ConfigKey } from \"../config.js\";\nimport type { RawCliArgs } from \"./runner.js\";\nimport { detectDatasource, DATASOURCE_NAMES } from \"../datasources/index.js\";\n\n/**\n * Config key → RawCliArgs field mapping.\n *\n * Maps persistent config keys (from `{cwd}/.dispatch/config.json`) to their\n * corresponding field names on `RawCliArgs`. Used during the merge step\n * to fill in CLI flag defaults from the config file.\n */\nconst CONFIG_TO_CLI: Record<ConfigKey, keyof RawCliArgs> = {\n provider: \"provider\",\n model: \"model\",\n source: \"issueSource\",\n testTimeout: \"testTimeout\",\n planTimeout: \"planTimeout\",\n concurrency: \"concurrency\",\n org: \"org\",\n project: \"project\",\n workItemType: \"workItemType\",\n iteration: \"iteration\",\n area: \"area\",\n};\n\n/** Type-safe indexed write into a RawCliArgs object. */\nfunction setCliField<K extends keyof RawCliArgs>(\n target: RawCliArgs,\n key: K,\n value: RawCliArgs[K],\n): void {\n target[key] = value;\n}\n\n/**\n * Resolve raw CLI arguments into a fully-merged and validated options\n * object, ready for pipeline delegation.\n *\n * 1. Loads the persistent config file (`{cwd}/.dispatch/config.json`)\n * 2. Merges config defaults beneath CLI flags (CLI wins when explicit)\n * 3. Validates that mandatory configuration (provider + source) is present\n * — calls `process.exit(1)` on validation failure, matching current behavior\n * 4. Auto-detects the datasource from the git remote when not explicitly set\n * — skipped for spec/respec modes, which defer source resolution to the\n * pipeline's own `resolveSource()` (context-aware fallback logic)\n * 5. Enables verbose logging if requested\n *\n * @param args - Raw CLI arguments as parsed by the CLI entry point\n * @returns The merged `RawCliArgs` with config defaults applied\n */\nexport async function resolveCliConfig(args: RawCliArgs): Promise<RawCliArgs> {\n const { explicitFlags } = args;\n\n // ── Load and merge config-file defaults beneath CLI flags ───\n const configDir = join(args.cwd, \".dispatch\");\n const config = await loadConfig(configDir);\n\n const merged = { ...args };\n for (const configKey of CONFIG_KEYS) {\n const cliField = CONFIG_TO_CLI[configKey];\n const configValue = config[configKey];\n if (configValue !== undefined && !explicitFlags.has(cliField)) {\n setCliField(merged, cliField, configValue);\n }\n }\n\n // ── Mandatory config validation ────────────────────────────\n const providerConfigured =\n explicitFlags.has(\"provider\") || config.provider !== undefined;\n\n if (!providerConfigured) {\n log.error(\"Missing required configuration: provider\");\n log.dim(\" Run 'dispatch config' to configure defaults interactively.\");\n log.dim(\" Or pass it as a CLI flag: --provider <name>\");\n process.exit(1);\n }\n\n // ── Output-dir validation ─────────────────────────────────\n if (merged.outputDir) {\n try {\n await access(merged.outputDir, constants.W_OK);\n } catch {\n log.error(\n `--output-dir path does not exist or is not writable: ${merged.outputDir}`,\n );\n process.exit(1);\n }\n }\n\n // ── Auto-detect datasource when not explicitly set ─────────\n const sourceConfigured =\n explicitFlags.has(\"issueSource\") || config.source !== undefined;\n const needsSource = !(merged.fixTests && merged.issueIds.length === 0) && !merged.spec && !merged.respec;\n\n if (needsSource && !sourceConfigured) {\n const detected = await detectDatasource(merged.cwd);\n if (detected) {\n log.info(`Auto-detected datasource from git remote: ${detected}`);\n merged.issueSource = detected;\n } else {\n log.error(\"Datasource auto-detection failed — could not determine issue source from git remote.\");\n log.dim(` Available datasources: ${DATASOURCE_NAMES.join(\", \")}`);\n log.dim(\" Run 'dispatch config' to configure defaults interactively.\");\n log.dim(\" Or pass it as a CLI flag: --issue-source <name>\");\n process.exit(1);\n }\n }\n\n // ── Enable verbose logging ─────────────────────────────────\n log.verbose = merged.verbose;\n\n return merged;\n}\n","/**\n * Spec generation pipeline — extracted from the orchestrator to keep the\n * coordinator thin and this pipeline independently testable.\n *\n * Handles: datasource resolution, issue fetching (tracker and file/glob\n * modes), provider/agent booting, batch spec generation, datasource sync\n * (update existing issues or create new ones), and cleanup.\n */\n\nimport { join } from \"node:path\";\nimport { mkdir, readFile, rename, unlink } from \"node:fs/promises\";\nimport { glob } from \"glob\";\nimport type { SpecOptions, SpecSummary } from \"../spec-generator.js\";\nimport { isIssueNumbers, isGlobOrFilePath, resolveSource, defaultConcurrency } from \"../spec-generator.js\";\nimport type { IssueDetails, IssueFetchOptions, Datasource, DatasourceName } from \"../datasources/interface.js\";\nimport { getDatasource } from \"../datasources/index.js\";\nimport { extractTitle } from \"../datasources/md.js\";\nimport type { ProviderInstance, ProviderName } from \"../providers/interface.js\";\nimport { bootProvider } from \"../providers/index.js\";\nimport type { SpecAgent } from \"../agents/spec.js\";\nimport { boot as bootSpecAgent } from \"../agents/spec.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { FileLogger, fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { confirmLargeBatch } from \"../helpers/confirm-large-batch.js\";\nimport chalk from \"chalk\";\nimport { elapsed, renderHeaderLines } from \"../helpers/format.js\";\nimport { withRetry } from \"../helpers/retry.js\";\nimport { withTimeout } from \"../helpers/timeout.js\";\nimport { slugify, MAX_SLUG_LENGTH } from \"../helpers/slugify.js\";\nimport { parseIssueFilename } from \"./datasource-helpers.js\";\n\n/** Per-item timeout for datasource fetch calls (ms). */\nconst FETCH_TIMEOUT_MS = 30_000;\n\n// ── Shared types for pipeline stages ──────────────────────────\n\n/** An item resolved from any input mode (tracker, file, or inline text). */\ninterface ResolvedItem {\n id: string;\n details: IssueDetails | null;\n error?: string;\n}\n\n/** A successfully resolved item with non-null details. */\ninterface ValidItem {\n id: string;\n details: IssueDetails;\n error?: string;\n}\n\n/** Result of the datasource resolution stage. */\ninterface ResolvedSource {\n source: DatasourceName;\n datasource: Datasource;\n fetchOpts: IssueFetchOptions;\n}\n\n/** Accumulated state from the batch generation loop. */\ninterface GenerationResults {\n generatedFiles: string[];\n issueNumbers: string[];\n dispatchIdentifiers: string[];\n failed: number;\n fileDurationsMs: Record<string, number>;\n}\n\n// ── Pipeline stage functions ──────────────────────────────────\n\n/**\n * Resolve the datasource from options.\n * Returns null when resolution fails (caller should return early).\n */\nasync function resolveDatasource(\n issues: string | string[],\n issueSource: DatasourceName | undefined,\n specCwd: string,\n org?: string,\n project?: string,\n workItemType?: string,\n iteration?: string,\n area?: string,\n): Promise<ResolvedSource | null> {\n const source = await resolveSource(issues, issueSource, specCwd);\n if (!source) return null;\n\n const datasource = getDatasource(source);\n const fetchOpts: IssueFetchOptions = { cwd: specCwd, org, project, workItemType, iteration, area };\n return { source, datasource, fetchOpts };\n}\n\n/**\n * Fetch items from an issue tracker by number.\n * Returns an empty array if no issue numbers were provided.\n */\nasync function fetchTrackerItems(\n issues: string,\n datasource: Datasource,\n fetchOpts: IssueFetchOptions,\n concurrency: number,\n source: DatasourceName,\n): Promise<ResolvedItem[]> {\n const issueNumbers = issues\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (issueNumbers.length === 0) {\n log.error(\"No issue numbers provided. Use --spec 1,2,3\");\n return [];\n }\n\n const fetchStart = Date.now();\n log.info(`Fetching ${issueNumbers.length} issue(s) from ${source} (concurrency: ${concurrency})...`);\n\n const items: ResolvedItem[] = [];\n const fetchQueue = [...issueNumbers];\n\n while (fetchQueue.length > 0) {\n const batch = fetchQueue.splice(0, concurrency);\n log.debug(`Fetching batch of ${batch.length}: #${batch.join(\", #\")}`);\n const batchResults = await Promise.all(\n batch.map(async (id) => {\n try {\n const details = await withTimeout(datasource.fetch(id, fetchOpts), FETCH_TIMEOUT_MS, \"datasource fetch\");\n log.success(`Fetched #${id}: ${details.title}`);\n log.debug(`Body: ${details.body?.length ?? 0} chars, Labels: ${details.labels.length}, Comments: ${details.comments.length}`);\n return { id, details };\n } catch (err) {\n const message = log.extractMessage(err);\n log.error(`Failed to fetch #${id}: ${log.formatErrorChain(err)}`);\n log.debug(log.formatErrorChain(err));\n return { id, details: null, error: message };\n }\n })\n );\n items.push(...batchResults);\n }\n log.debug(`Issue fetching completed in ${elapsed(Date.now() - fetchStart)}`);\n return items;\n}\n\n/** Construct a single item from inline text input. */\nfunction buildInlineTextItem(\n issues: string | string[],\n outputDir: string,\n): ResolvedItem[] {\n const text = Array.isArray(issues) ? issues.join(\" \") : issues;\n const title = text.length > 80 ? text.slice(0, 80).trimEnd() + \"…\" : text;\n const slug = slugify(text, MAX_SLUG_LENGTH);\n const filename = `${slug}.md`;\n const filepath = join(outputDir, filename);\n\n const details: IssueDetails = {\n number: filepath,\n title,\n body: text,\n labels: [],\n state: \"open\",\n url: filepath,\n comments: [],\n acceptanceCriteria: \"\",\n };\n\n log.info(`Inline text spec: \"${title}\"`);\n return [{ id: filepath, details }];\n}\n\n/** Resolve items from a glob pattern or file paths. */\nasync function resolveFileItems(\n issues: string | string[],\n specCwd: string,\n concurrency: number,\n): Promise<ResolvedItem[] | null> {\n const files = await glob(issues, { cwd: specCwd, absolute: true });\n\n if (files.length === 0) {\n log.error(`No files matched the pattern \"${Array.isArray(issues) ? issues.join(\", \") : issues}\".`);\n return null;\n }\n\n log.info(`Matched ${files.length} file(s) for spec generation (concurrency: ${concurrency})...`);\n\n const items: ResolvedItem[] = [];\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, \"utf-8\");\n const title = extractTitle(content, filePath);\n const details: IssueDetails = {\n number: filePath,\n title,\n body: content,\n labels: [],\n state: \"open\",\n url: filePath,\n comments: [],\n acceptanceCriteria: \"\",\n };\n items.push({ id: filePath, details });\n } catch (err) {\n items.push({ id: filePath, details: null, error: log.extractMessage(err) });\n }\n }\n return items;\n}\n\n/** Filter items to those with non-null details. */\nfunction filterValidItems(\n items: ResolvedItem[],\n isTrackerMode: boolean,\n isInlineText: boolean,\n): ValidItem[] | null {\n const validItems = items.filter(\n (i): i is ValidItem => i.details !== null,\n );\n if (validItems.length === 0) {\n const noun = isTrackerMode ? \"issues\" : isInlineText ? \"inline specs\" : \"files\";\n log.error(`No ${noun} could be loaded. Aborting spec generation.`);\n return null;\n }\n return validItems;\n}\n\n/** Log a dry-run preview of what would be generated. */\nfunction previewDryRun(\n validItems: ValidItem[],\n items: ResolvedItem[],\n isTrackerMode: boolean,\n isInlineText: boolean,\n outputDir: string,\n pipelineStart: number,\n): SpecSummary {\n const mode = isTrackerMode ? \"tracker\" : isInlineText ? \"inline\" : \"file\";\n log.info(`[DRY RUN] Would generate ${validItems.length} spec(s) (mode: ${mode}):\\n`);\n\n for (const { id, details } of validItems) {\n let filepath: string;\n if (isTrackerMode) {\n const slug = slugify(details.title, 60);\n filepath = join(outputDir, `${id}-${slug}.md`);\n } else {\n filepath = id;\n }\n\n const label = isTrackerMode ? `#${id}` : filepath;\n log.info(`[DRY RUN] Would generate spec for ${label}: \"${details.title}\"`);\n log.dim(` → ${filepath}`);\n }\n\n return {\n total: items.length,\n generated: 0,\n failed: items.filter((i) => i.details === null).length,\n files: [],\n issueNumbers: [],\n durationMs: Date.now() - pipelineStart,\n fileDurationsMs: {},\n };\n}\n\n/** Boot the AI provider and spec agent, render the header banner. */\nasync function bootPipeline(\n provider: ProviderName,\n serverUrl: string | undefined,\n specCwd: string,\n model: string | undefined,\n source: DatasourceName,\n): Promise<{ specAgent: SpecAgent; instance: ProviderInstance }> {\n const bootStart = Date.now();\n log.info(`Booting ${provider} provider...`);\n log.debug(serverUrl ? `Using server URL: ${serverUrl}` : \"No --server-url, will spawn local server\");\n const instance = await bootProvider(provider, { url: serverUrl, cwd: specCwd, model });\n registerCleanup(() => instance.cleanup());\n log.debug(`Provider booted in ${elapsed(Date.now() - bootStart)}`);\n\n const headerLines = renderHeaderLines({\n provider,\n model: instance.model,\n source,\n });\n console.log(\"\");\n for (const line of headerLines) {\n console.log(line);\n }\n console.log(chalk.dim(\" ─\".repeat(24)));\n console.log(\"\");\n\n const specAgent = await bootSpecAgent({ provider: instance, cwd: specCwd });\n\n return { specAgent, instance };\n}\n\n/** Generate specs in parallel batches, sync to datasource, and track results. */\nasync function generateSpecsBatch(\n validItems: ValidItem[],\n items: ResolvedItem[],\n specAgent: SpecAgent,\n instance: ProviderInstance,\n isTrackerMode: boolean,\n isInlineText: boolean,\n datasource: Datasource,\n fetchOpts: IssueFetchOptions,\n outputDir: string,\n specCwd: string,\n concurrency: number,\n retries: number,\n): Promise<GenerationResults> {\n await mkdir(outputDir, { recursive: true });\n\n const generatedFiles: string[] = [];\n const issueNumbers: string[] = [];\n const dispatchIdentifiers: string[] = [];\n let failed = items.filter((i) => i.details === null).length;\n const fileDurationsMs: Record<string, number> = {};\n\n const genQueue = [...validItems];\n let modelLoggedInBanner = !!instance.model;\n\n while (genQueue.length > 0) {\n const batch = genQueue.splice(0, concurrency);\n log.info(`Generating specs for batch of ${batch.length} (${generatedFiles.length + failed}/${items.length} done)...`);\n\n const batchResults = await Promise.all(\n batch.map(async ({ id, details }) => {\n const specStart = Date.now();\n\n if (!details) {\n log.error(`Skipping item ${id}: missing issue details`);\n return null;\n }\n\n const itemBody = async (): Promise<{ filepath: string; identifier: string } | null> => {\n let filepath: string;\n if (isTrackerMode) {\n const slug = slugify(details.title, MAX_SLUG_LENGTH);\n const filename = `${id}-${slug}.md`;\n filepath = join(outputDir, filename);\n } else if (isInlineText) {\n filepath = id;\n } else {\n filepath = id;\n }\n\n fileLoggerStorage.getStore()?.info(`Output path: ${filepath}`);\n\n try {\n fileLoggerStorage.getStore()?.info(`Starting spec generation for ${isTrackerMode ? `#${id}` : filepath}`);\n log.info(`Generating spec for ${isTrackerMode ? `#${id}` : filepath}: ${details.title}...`);\n\n const result = await withRetry(\n () => specAgent.generate({\n issue: isTrackerMode ? details : undefined,\n filePath: isTrackerMode ? undefined : id,\n fileContent: isTrackerMode ? undefined : details.body,\n cwd: specCwd,\n outputPath: filepath,\n }),\n retries,\n { label: `specAgent.generate(${isTrackerMode ? `#${id}` : filepath})` },\n );\n\n if (!result.success) {\n throw new Error(result.error ?? \"Spec generation failed\");\n }\n\n fileLoggerStorage.getStore()?.info(`Spec generated successfully`);\n\n if (isTrackerMode || isInlineText) {\n const h1Title = extractTitle(result.data.content, filepath);\n const h1Slug = slugify(h1Title, MAX_SLUG_LENGTH);\n const finalFilename = isTrackerMode ? `${id}-${h1Slug}.md` : `${h1Slug}.md`;\n const finalFilepath = join(outputDir, finalFilename);\n if (finalFilepath !== filepath) {\n await rename(filepath, finalFilepath);\n filepath = finalFilepath;\n }\n }\n\n const specDuration = Date.now() - specStart;\n fileDurationsMs[filepath] = specDuration;\n log.success(`Spec written: ${filepath} (${elapsed(specDuration)})`);\n\n let identifier = filepath;\n\n fileLoggerStorage.getStore()?.phase(\"Datasource sync\");\n try {\n if (isTrackerMode) {\n await datasource.update(id, details.title, result.data.content, fetchOpts);\n log.success(`Updated issue #${id} with spec content`);\n await unlink(filepath);\n log.success(`Deleted local spec ${filepath} (now tracked as issue #${id})`);\n identifier = id;\n issueNumbers.push(id);\n } else if (datasource.name === \"md\") {\n const parsed = parseIssueFilename(filepath);\n if (parsed) {\n await datasource.update(parsed.issueId, details.title, result.data.content, fetchOpts);\n log.success(`Updated spec #${parsed.issueId} in-place`);\n identifier = parsed.issueId;\n issueNumbers.push(parsed.issueId);\n }\n // If no ID prefix, spec is already written in-place at filepath — no sync needed\n } else {\n const created = await datasource.create(details.title, result.data.content, fetchOpts);\n log.success(`Created issue #${created.number} from ${filepath}`);\n await unlink(filepath);\n log.success(`Deleted local spec ${filepath} (now tracked as issue #${created.number})`);\n identifier = created.number;\n issueNumbers.push(created.number);\n }\n } catch (err) {\n const label = isTrackerMode ? `issue #${id}` : filepath;\n log.warn(`Could not sync ${label} to datasource: ${log.formatErrorChain(err)}`);\n }\n\n return { filepath, identifier };\n } catch (err) {\n fileLoggerStorage.getStore()?.error(`Spec generation failed for ${id}: ${log.extractMessage(err)}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n log.error(`Failed to generate spec for ${isTrackerMode ? `#${id}` : filepath}: ${log.formatErrorChain(err)}`);\n log.debug(log.formatErrorChain(err));\n return null;\n }\n };\n\n const fileLogger = log.verbose ? new FileLogger(id, specCwd) : null;\n if (fileLogger) {\n return fileLoggerStorage.run(fileLogger, async () => {\n try {\n fileLogger.phase(`Spec generation: ${id}`);\n return await itemBody();\n } finally {\n fileLogger.close();\n }\n });\n }\n return itemBody();\n }));\n\n for (const result of batchResults) {\n if (result !== null) {\n generatedFiles.push(result.filepath);\n dispatchIdentifiers.push(result.identifier);\n } else {\n failed++;\n }\n }\n\n if (!modelLoggedInBanner && instance.model) {\n log.info(`Detected model: ${instance.model}`);\n modelLoggedInBanner = true;\n }\n }\n\n return { generatedFiles, issueNumbers, dispatchIdentifiers, failed, fileDurationsMs };\n}\n\n/** Clean up spec agent and provider, logging warnings on failure. */\nasync function cleanupPipeline(\n specAgent: SpecAgent,\n instance: ProviderInstance,\n): Promise<void> {\n try {\n await specAgent.cleanup();\n } catch (err) {\n log.warn(`Spec agent cleanup failed: ${log.formatErrorChain(err)}`);\n }\n try {\n await instance.cleanup();\n } catch (err) {\n log.warn(`Provider cleanup failed: ${log.formatErrorChain(err)}`);\n }\n}\n\n/** Log the final summary and dispatch hint. */\nfunction logSummary(\n generatedFiles: string[],\n dispatchIdentifiers: string[],\n failed: number,\n totalDuration: number,\n): void {\n log.info(\n `Spec generation complete: ${generatedFiles.length} generated, ${failed} failed in ${elapsed(totalDuration)}`\n );\n\n if (generatedFiles.length > 0) {\n log.dim(`\\n Run these specs with:`);\n const allNumeric = dispatchIdentifiers.every((id) => /^\\d+$/.test(id));\n if (allNumeric) {\n log.dim(` dispatch ${dispatchIdentifiers.join(\",\")}\\n`);\n } else {\n log.dim(` dispatch ${dispatchIdentifiers.map((f) => '\"' + f + '\"').join(\" \")}\\n`);\n }\n }\n}\n\n// ── Public API ────────────────────────────────────────────────\n\n/**\n * Run the spec-generation pipeline end-to-end.\n *\n * This is the extracted core of the orchestrator's `generateSpecs()` method.\n * It accepts `SpecOptions` and returns a `SpecSummary`.\n */\nexport async function runSpecPipeline(opts: SpecOptions): Promise<SpecSummary> {\n const {\n issues,\n provider,\n model,\n serverUrl,\n cwd: specCwd,\n outputDir = join(specCwd, \".dispatch\", \"specs\"),\n org,\n project,\n workItemType,\n iteration,\n area,\n concurrency = defaultConcurrency(),\n dryRun,\n retries = 2,\n } = opts;\n\n const pipelineStart = Date.now();\n\n // ── Resolve datasource ─────────────────────────────────────\n const resolved = await resolveDatasource(issues, opts.issueSource, specCwd, org, project, workItemType, iteration, area);\n if (!resolved) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n const { source, datasource, fetchOpts } = resolved;\n\n // ── Determine items to process ─────────────────────────────\n const isTrackerMode = isIssueNumbers(issues);\n const isInlineText = !isTrackerMode && !isGlobOrFilePath(issues);\n let items: ResolvedItem[];\n\n if (isTrackerMode) {\n items = await fetchTrackerItems(issues, datasource, fetchOpts, concurrency, source);\n if (items.length === 0) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n } else if (isInlineText) {\n items = buildInlineTextItem(issues, outputDir);\n } else {\n const fileItems = await resolveFileItems(issues, specCwd, concurrency);\n if (!fileItems) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n items = fileItems;\n }\n\n // ── Filter valid items ─────────────────────────────────────\n const validItems = filterValidItems(items, isTrackerMode, isInlineText);\n if (!validItems) {\n return { total: items.length, generated: 0, failed: items.length, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n\n // ── Dry-run preview ────────────────────────────────────────\n if (dryRun) {\n return previewDryRun(validItems, items, isTrackerMode, isInlineText, outputDir, pipelineStart);\n }\n\n // ── Confirm large batch ────────────────────────────────────\n const confirmed = await confirmLargeBatch(validItems.length);\n if (!confirmed) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n\n // ── Boot provider and spec agent ───────────────────────────\n const { specAgent, instance } = await bootPipeline(provider, serverUrl, specCwd, model, source);\n\n // ── Generate specs in batches ──────────────────────────────\n const results = await generateSpecsBatch(\n validItems, items, specAgent, instance,\n isTrackerMode, isInlineText,\n datasource, fetchOpts, outputDir, specCwd,\n concurrency, retries,\n );\n\n // ── Cleanup ────────────────────────────────────────────────\n await cleanupPipeline(specAgent, instance);\n\n // ── Summary ────────────────────────────────────────────────\n const totalDuration = Date.now() - pipelineStart;\n logSummary(results.generatedFiles, results.dispatchIdentifiers, results.failed, totalDuration);\n\n return {\n total: items.length,\n generated: results.generatedFiles.length,\n failed: results.failed,\n files: results.generatedFiles,\n issueNumbers: results.issueNumbers,\n identifiers: results.dispatchIdentifiers,\n durationMs: totalDuration,\n fileDurationsMs: results.fileDurationsMs,\n };\n}\n","/**\n * Spec agent — generates high-level markdown spec files from issue details\n * or file content by interacting with an AI provider.\n *\n * The spec agent follows the same pattern as the planner agent: it receives\n * a provider instance at boot time and exposes a `generate()` method for\n * producing specs. It writes to a temp file in `.dispatch/tmp/`, post-processes\n * and validates the content, then writes the cleaned result to the final\n * output path.\n */\n\nimport { mkdir, readFile, writeFile, unlink } from \"node:fs/promises\";\nimport { join, resolve, sep } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { AgentResult, SpecData } from \"./types.js\";\nimport type { IssueDetails } from \"../datasources/interface.js\";\nimport { extractSpecContent, validateSpecStructure } from \"../spec-generator.js\";\nimport { extractTitle } from \"../datasources/md.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/**\n * Options passed to the spec agent's `generate()` method.\n */\nexport interface SpecGenerateOptions {\n /** Issue details (for tracker mode) — mutually exclusive with fileContent */\n issue?: IssueDetails;\n /** File path (for file/glob mode) — used as source file reference */\n filePath?: string;\n /** File content (for file/glob mode) — mutually exclusive with issue */\n fileContent?: string;\n /** Inline text (for inline text mode) — mutually exclusive with issue and fileContent */\n inlineText?: string;\n /** Working directory */\n cwd: string;\n /** Final output path where the spec should be written */\n outputPath: string;\n /** Worktree root directory for isolation, if operating in a worktree */\n worktreeRoot?: string;\n}\n\n/**\n * A booted spec agent that can generate spec files.\n */\nexport interface SpecAgent extends Agent {\n /**\n * Generate a single spec. Creates an isolated session, instructs the AI\n * to write to a temp file, post-processes and validates the content,\n * writes the cleaned result to the final output path, and cleans up.\n */\n generate(opts: SpecGenerateOptions): Promise<AgentResult<SpecData>>;\n}\n\n/**\n * Boot a spec agent backed by the given provider.\n *\n * @throws if `opts.provider` is not supplied — the spec agent requires a\n * provider to create sessions and send prompts.\n */\nexport async function boot(opts: AgentBootOptions): Promise<SpecAgent> {\n const { provider } = opts;\n\n if (!provider) {\n throw new Error(\"Spec agent requires a provider instance in boot options\");\n }\n\n return {\n name: \"spec\",\n\n async generate(genOpts: SpecGenerateOptions): Promise<AgentResult<SpecData>> {\n const { issue, filePath, fileContent, inlineText, cwd: workingDir, outputPath } = genOpts;\n const startTime = Date.now();\n\n try {\n // 0. Normalize cwd and validate outputPath stays within it\n const resolvedCwd = resolve(workingDir);\n const resolvedOutput = resolve(outputPath);\n if (\n resolvedOutput !== resolvedCwd &&\n !resolvedOutput.startsWith(resolvedCwd + sep)\n ) {\n return {\n data: null,\n success: false,\n error: `Output path \"${outputPath}\" escapes the working directory \"${workingDir}\"`,\n durationMs: Date.now() - startTime,\n };\n }\n\n // 1. Create .dispatch/tmp/ on demand\n const tmpDir = join(resolvedCwd, \".dispatch\", \"tmp\");\n await mkdir(tmpDir, { recursive: true });\n\n // 2. Generate a unique temp file path\n const tmpFilename = `spec-${randomUUID()}.md`;\n const tmpPath = join(tmpDir, tmpFilename);\n\n // 3. Build the appropriate prompt, pointing at the temp file path\n let prompt: string;\n if (issue) {\n prompt = buildSpecPrompt(issue, workingDir, tmpPath);\n } else if (inlineText) {\n prompt = buildInlineTextSpecPrompt(inlineText, workingDir, tmpPath);\n } else if (filePath && fileContent !== undefined) {\n prompt = buildFileSpecPrompt(filePath, fileContent, workingDir, tmpPath);\n } else {\n return {\n data: null,\n success: false,\n error: \"Either issue, inlineText, or filePath+fileContent must be provided\",\n durationMs: Date.now() - startTime,\n };\n }\n\n fileLoggerStorage.getStore()?.prompt(\"spec\", prompt);\n\n // 4. Create a session via the provider and send the prompt\n const sessionId = await provider.createSession();\n log.debug(`Spec prompt built (${prompt.length} chars)`);\n const response = await provider.prompt(sessionId, prompt);\n\n if (response === null) {\n return {\n data: null,\n success: false,\n error: \"AI agent returned no response\",\n durationMs: Date.now() - startTime,\n };\n }\n\n log.debug(`Spec agent response (${response.length} chars)`);\n fileLoggerStorage.getStore()?.response(\"spec\", response);\n\n // 5. Read the temp file\n let rawContent: string;\n try {\n rawContent = await readFile(tmpPath, \"utf-8\");\n } catch {\n return {\n data: null,\n success: false,\n error: `Spec agent did not write the file to ${tmpPath}. Agent response: ${response.slice(0, 300)}`,\n durationMs: Date.now() - startTime,\n };\n }\n\n // 6. Apply extractSpecContent post-processing\n const cleanedContent = extractSpecContent(rawContent);\n log.debug(`Post-processed spec (${rawContent.length} → ${cleanedContent.length} chars)`);\n\n // 7. Run validateSpecStructure\n const validation = validateSpecStructure(cleanedContent);\n if (!validation.valid) {\n log.warn(`Spec validation warning for ${outputPath}: ${validation.reason}`);\n }\n\n // 8. Write the cleaned content to the final output path\n await writeFile(resolvedOutput, cleanedContent, \"utf-8\");\n log.debug(`Wrote cleaned spec to ${resolvedOutput}`);\n\n // 9. Clean up the temp file\n try {\n await unlink(tmpPath);\n } catch {\n // Ignore cleanup errors — temp file may already be gone\n }\n\n fileLoggerStorage.getStore()?.agentEvent(\"spec\", \"completed\", `${Date.now() - startTime}ms`);\n return {\n data: {\n content: cleanedContent,\n valid: validation.valid,\n validationReason: validation.reason,\n },\n success: true,\n durationMs: Date.now() - startTime,\n };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`spec error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return {\n data: null,\n success: false,\n error: message,\n durationMs: Date.now() - startTime,\n };\n }\n },\n\n async cleanup(): Promise<void> {\n // Spec agent has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n\n/**\n * Build the source-specific section for tracker/issue mode.\n */\nfunction buildIssueSourceSection(issue: IssueDetails): string[] {\n const lines: string[] = [\n ``,\n `## Issue Details`,\n ``,\n `- **Number:** #${issue.number}`,\n `- **Title:** ${issue.title}`,\n `- **State:** ${issue.state}`,\n `- **URL:** ${issue.url}`,\n ];\n\n if (issue.labels.length > 0) {\n lines.push(`- **Labels:** ${issue.labels.join(\", \")}`);\n }\n\n if (issue.body) {\n lines.push(``, `### Description`, ``, issue.body);\n }\n\n if (issue.acceptanceCriteria) {\n lines.push(``, `### Acceptance Criteria`, ``, issue.acceptanceCriteria);\n }\n\n if (issue.comments.length > 0) {\n lines.push(``, `### Discussion`, ``);\n for (const comment of issue.comments) {\n lines.push(comment, ``);\n }\n }\n\n return lines;\n}\n\n/**\n * Build the source-specific section for file/glob mode.\n */\nfunction buildFileSourceSection(filePath: string, content: string, title: string): string[] {\n const lines: string[] = [\n ``,\n `## File Details`,\n ``,\n `- **Title:** ${title}`,\n `- **Source file:** ${filePath}`,\n ];\n\n if (content) {\n lines.push(``, `### Content`, ``, content);\n }\n\n return lines;\n}\n\n/**\n * Build the source-specific section for inline text mode.\n */\nfunction buildInlineTextSourceSection(title: string, text: string): string[] {\n return [\n ``,\n `## Inline Text`,\n ``,\n `- **Title:** ${title}`,\n ``,\n `### Description`,\n ``,\n text,\n ];\n}\n\n/**\n * Build the full spec prompt by assembling role preamble, pipeline explanation,\n * output constraints, source-specific section, working directory, instructions,\n * output template, task tagging rules, references, and key guidelines.\n *\n * All three public prompt builders delegate to this function with their\n * source-specific parameters.\n */\nfunction buildCommonSpecInstructions(params: {\n /** Subject phrase for the role preamble (e.g., \"the issue below\"). */\n subject: string;\n /** Source-specific section lines to insert after output constraints. */\n sourceSection: string[];\n /** Working directory path. */\n cwd: string;\n /** Output file path. */\n outputPath: string;\n /** Full text of instruction step 2. */\n understandStep: string;\n /** Title template line for the spec structure. */\n titleTemplate: string;\n /** One-line summary template line. */\n summaryTemplate: string;\n /** Variable ending lines for the \"Why\" section template. */\n whyLines: string[];\n}): string[] {\n const {\n subject,\n sourceSection,\n cwd,\n outputPath,\n understandStep,\n titleTemplate,\n summaryTemplate,\n whyLines,\n } = params;\n\n return [\n `You are a **spec agent**. Your job is to explore the codebase, understand ${subject}, and write a high-level **markdown spec file** to disk that will drive an automated implementation pipeline.`,\n ``,\n `**Important:** This file will be consumed by a two-stage pipeline:`,\n `1. A **planner agent** reads each task together with the prose context in this file, then explores the codebase to produce a detailed, line-level implementation plan.`,\n `2. A **coder agent** follows that detailed plan to make the actual code changes.`,\n ``,\n `Because the planner agent handles low-level details, your spec must stay **high-level and strategic**. Focus on the WHAT, WHY, and HOW — not exact code or line numbers.`,\n ``,\n `**CRITICAL — Output constraints (read carefully):**`,\n `The file you write must contain ONLY the structured spec content described below. You MUST NOT include:`,\n `- **No preamble:** Do not add any text before the H1 heading (e.g., \"Here's the spec:\", \"I've written the spec file to...\")`,\n `- **No postamble:** Do not add any text after the last spec section (e.g., \"Let me know if you'd like changes\", \"Here's a summary of...\")`,\n `- **No summaries:** Do not append a summary or recap of what you wrote`,\n `- **No code fences:** Do not wrap the spec content in \\`\\`\\`markdown ... \\`\\`\\` or any other code fence`,\n `- **No conversational text:** Do not include any explanations, commentary, or dialogue — the file is consumed by an automated pipeline, not a human`,\n `The file content must start with \\`# \\` (the H1 heading) and contain nothing before or after the structured spec sections.`,\n ...sourceSection,\n ``,\n `## Working Directory`,\n ``,\n `\\`${cwd}\\``,\n ``,\n formatEnvironmentPrompt(),\n ``,\n `## Instructions`,\n ``,\n `1. **Explore the codebase** — read relevant files, search for symbols, understand the project structure, language, frameworks, conventions, and patterns. Identify the tech stack (languages, package managers, frameworks, test runners) so your spec aligns with the project's actual standards.`,\n ``,\n understandStep,\n ``,\n `3. **Research the approach** — look up relevant documentation, libraries, and patterns. Consider how the change integrates with the existing architecture, standards, and technologies already in use. For example, if the project is TypeScript, do not propose a Python solution; if it uses Vitest, do not suggest Jest.`,\n ``,\n `4. **Identify integration points** — determine which existing modules, interfaces, patterns, and conventions the implementation must align with. Note the key files and modules involved, but do NOT prescribe exact code changes — the planner agent will handle that.`,\n ``,\n `5. **DO NOT make any code changes** — you are only producing a spec, not implementing.`,\n ``,\n `## Output`,\n ``,\n `Write the complete spec as a markdown file to this exact path:`,\n ``,\n `\\`${outputPath}\\``,\n ``,\n `Use your Write tool to save the file. The file content MUST begin with the H1 heading — no preamble, no code fences, no conversational text before it. Do not add any text after the final spec section — no postamble, no summary, no commentary. The file must follow this structure exactly:`,\n ``,\n titleTemplate,\n ``,\n summaryTemplate,\n ``,\n `## Context`,\n ``,\n `<Describe the relevant parts of the codebase: key modules, directory structure,`,\n `language/framework, and architectural patterns. Name specific files and modules`,\n `that are involved so the planner agent knows where to look, but do not include`,\n `code snippets or line-level details.>`,\n ``,\n `## Why`,\n ``,\n `<Explain the motivation — why this change is needed, what problem it solves,`,\n ...whyLines,\n ``,\n `## Approach`,\n ``,\n `<High-level description of the implementation strategy. Explain the overall`,\n `approach, which patterns to follow, what to extend vs. create new, and how`,\n `the change fits into the existing architecture. Mention relevant standards,`,\n `technologies, and conventions the implementation MUST align with.>`,\n ``,\n `## Integration Points`,\n ``,\n `<List the specific modules, interfaces, configurations, and conventions that`,\n `the implementation must integrate with. For example: existing provider`,\n `interfaces to implement, CLI argument patterns to follow, test framework`,\n `and conventions to match, build system requirements, etc.>`,\n ``,\n `## Tasks`,\n ``,\n `Each task MUST be prefixed with an execution-mode tag:`,\n ``,\n `- \\`(P)\\` — **Parallel-safe.** This task has no dependency on the output of a prior task and can run concurrently with other \\`(P)\\` tasks.`,\n `- \\`(S)\\` — **Serial / dependent.** This task depends on a prior task's output or modifies shared state that conflicts with concurrent work. It acts as a barrier: all preceding tasks complete before it starts, and it completes before subsequent tasks begin.`,\n `- \\`(I)\\` — **Isolated / barrier.** This task must run alone after all preceding tasks complete and before any subsequent tasks begin. Use for validation tasks like running tests, linting, or builds that read the output of prior tasks.`,\n ``,\n `**Default to \\`(P)\\`.** Most tasks are independent (e.g., adding a function in one module, writing tests in another). Only use \\`(S)\\` when a task genuinely depends on the result of a prior task (e.g., \"refactor module X\" followed by \"update callers of module X\"). Use \\`(I)\\` for validation or barrier tasks that must run alone after all prior work completes (e.g., \"run tests\", \"run linting\", \"build the project\").`,\n ``,\n `If a task has no \\`(P)\\`, \\`(S)\\`, or \\`(I)\\` prefix, the system treats it as serial, so always tag explicitly.`,\n ``,\n `Example:`,\n ``,\n `- [ ] (P) Add validation helper to the form utils module`,\n `- [ ] (P) Add unit tests for the new validation helper`,\n `- [ ] (S) Refactor the form component to use the new validation helper`,\n `- [ ] (P) Update documentation for the form utils module`,\n `- [ ] (I) Run the full test suite to verify all changes pass`,\n ``,\n ``,\n `## References`,\n ``,\n `- <Links to relevant docs, related issues, or external resources>`,\n ``,\n `## Key Guidelines`,\n ``,\n `- **Stay high-level.** Do NOT include code snippets, exact line numbers, diffs, or step-by-step coding instructions. A dedicated planner agent will produce those details for each task at execution time.`,\n `- **Respect the project's stack.** Your spec must align with the languages, frameworks, libraries, test tools, and conventions already in use. Never suggest technologies that conflict with the existing project.`,\n `- **Explain WHAT, WHY, and HOW (strategically).** Each task should say what needs to happen, why it's needed, and which part of the codebase it touches — but leave the tactical \"how\" to the planner agent.`,\n `- **Detail integration points.** The prose sections (Context, Approach, Integration Points) are critical — they tell the planner agent where to look and what constraints to respect.`,\n `- **Keep tasks atomic and ordered.** Each \\`- [ ]\\` task must be a single, clear unit of work. Order them so dependencies come first.`,\n `- **Tag every task with \\`(P)\\`, \\`(S)\\`, or \\`(I)\\`.** Default to \\`(P)\\` (parallel) unless the task depends on a prior task's output. Use \\`(I)\\` for validation/barrier tasks. Group related serial dependencies together and prefer parallelism to maximize throughput.`,\n `- **Embed commit instructions within task descriptions.** You control when commits happen. Instead of creating standalone commit tasks (which would fail — each task runs in an isolated agent session), include commit instructions at the end of implementation task descriptions at logical boundaries. For example: \"Implement the validation helper and commit with a conventional commit message.\" Group related changes into a single commit where it makes logical sense, and use the project's conventional commit types: \\`feat\\`, \\`fix\\`, \\`docs\\`, \\`refactor\\`, \\`test\\`, \\`chore\\`, \\`style\\`, \\`perf\\`, \\`ci\\`. Not every task needs a commit instruction — use your judgment to place them at logical boundaries.`,\n `- **Keep the markdown clean** — it will be parsed by an automated tool.`,\n ];\n}\n\n/**\n * Build the prompt that instructs the AI agent to explore the codebase,\n * understand the issue, and write a high-level markdown spec file to disk.\n *\n * The agent is responsible for writing the file — this is not a completion\n * API call. The output emphasises WHAT needs to change, WHY it needs to\n * change, and HOW it fits into the existing project — but deliberately\n * avoids low-level implementation specifics (exact code, line numbers,\n * diffs). A dedicated planner agent handles that granularity per-task at\n * dispatch time.\n */\nexport function buildSpecPrompt(issue: IssueDetails, cwd: string, outputPath: string): string {\n return buildCommonSpecInstructions({\n subject: \"the issue below\",\n sourceSection: buildIssueSourceSection(issue),\n cwd,\n outputPath,\n understandStep: `2. **Understand the issue** — analyze the issue description, acceptance criteria, and discussion comments to fully understand what needs to be done and why.`,\n titleTemplate: `# <Issue title> (#<number>)`,\n summaryTemplate: `> <One-line summary: what this issue achieves and why it matters>`,\n whyLines: [\n `what user or system benefit it provides. Pull from the issue description,`,\n `acceptance criteria, and discussion.>`,\n ],\n }).join(\"\\n\");\n}\n\n/**\n * Build a spec prompt from a local markdown file instead of an issue-tracker\n * issue. The title is extracted from the first `# Heading` in the content,\n * falling back to the filename without extension. The file content serves as\n * the description.\n *\n * When `outputPath` is provided, the prompt instructs the AI to write to that\n * path instead of the source file. When omitted, the source `filePath` is\n * used as the output target (in-place overwrite), preserving backward\n * compatibility with existing callers.\n *\n * The output-format instructions, spec structure template, (P)/(S) tagging\n * rules, and agent guidelines are identical to those in `buildSpecPrompt()`.\n */\nexport function buildFileSpecPrompt(filePath: string, content: string, cwd: string, outputPath?: string): string {\n const title = extractTitle(content, filePath);\n const writePath = outputPath ?? filePath;\n\n return buildCommonSpecInstructions({\n subject: \"the content below\",\n sourceSection: buildFileSourceSection(filePath, content, title),\n cwd,\n outputPath: writePath,\n understandStep: `2. **Understand the content** — analyze the file content to fully understand what needs to be done and why.`,\n titleTemplate: `# <Title>`,\n summaryTemplate: `> <One-line summary: what this achieves and why it matters>`,\n whyLines: [\n `what user or system benefit it provides. Pull from the file content.>`,\n ],\n }).join(\"\\n\");\n}\n\n/**\n * Build a spec prompt from inline text provided directly on the command line.\n *\n * Unlike `buildFileSpecPrompt()`, there is no source file — the user's text\n * serves as both the title and the description. The output-format\n * instructions, spec structure template, (P)/(S) tagging rules, and agent\n * guidelines are identical to those in `buildSpecPrompt()` and\n * `buildFileSpecPrompt()`.\n */\nexport function buildInlineTextSpecPrompt(text: string, cwd: string, outputPath: string): string {\n const title = text.length > 80 ? text.slice(0, 80).trimEnd() + \"…\" : text;\n\n return buildCommonSpecInstructions({\n subject: \"the request below\",\n sourceSection: buildInlineTextSourceSection(title, text),\n cwd,\n outputPath,\n understandStep: `2. **Understand the request** — analyze the inline text to fully understand what needs to be done and why. Since this is a brief description rather than a detailed issue or document, you may need to infer details from the codebase.`,\n titleTemplate: `# <Title>`,\n summaryTemplate: `> <One-line summary: what this achieves and why it matters>`,\n whyLines: [\n `what user or system benefit it provides. Pull from the inline text description.>`,\n ],\n }).join(\"\\n\");\n}\n","/**\n * Shared formatting utilities used across the CLI.\n */\n\nimport chalk from \"chalk\";\n\n/**\n * Format a duration in milliseconds into a human-readable string.\n *\n * Examples:\n * elapsed(0) → \"0s\"\n * elapsed(45000) → \"45s\"\n * elapsed(133000) → \"2m 13s\"\n */\nexport function elapsed(ms: number): string {\n const s = Math.floor(ms / 1000);\n const m = Math.floor(s / 60);\n const sec = s % 60;\n if (m > 0) return `${m}m ${sec}s`;\n return `${sec}s`;\n}\n\n/** Options for the shared header renderer. */\nexport interface HeaderInfo {\n provider?: string;\n model?: string;\n source?: string;\n}\n\n/**\n * Build the standard dispatch header lines used by both the TUI and\n * the spec-generation banner.\n *\n * Returns an array of chalk-formatted strings (one per line).\n * Each metadata field (provider, model, source) is rendered on its own line.\n */\nexport function renderHeaderLines(info: HeaderInfo): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold.white(\" ⚡ dispatch\") + chalk.dim(` — AI task orchestration`));\n if (info.provider) {\n lines.push(chalk.dim(` provider: ${info.provider}`));\n }\n if (info.model) {\n lines.push(chalk.dim(` model: ${info.model}`));\n }\n if (info.source) {\n lines.push(chalk.dim(` source: ${info.source}`));\n }\n return lines;\n}\n","/**\n * Generic retry utility.\n *\n * Provides a reusable `withRetry` wrapper that retries an async function\n * on any thrown error up to a configurable number of times. Used by the\n * dispatch pipeline to add resilience to agent calls.\n */\n\nimport { log } from \"./logger.js\";\n\n/** Options for `withRetry`. */\nexport interface RetryOptions {\n /** Label for log messages identifying the operation being retried. */\n label?: string;\n}\n\n/**\n * Retry an async function up to `maxRetries` times on failure.\n *\n * Calls `fn` and returns its result on the first success. If `fn` throws,\n * it is retried up to `maxRetries` additional times. If all attempts fail,\n * the last error is re-thrown.\n *\n * @param fn - Async function to execute (called with no arguments)\n * @param maxRetries - Number of retry attempts (0 = no retries, 1 = one retry, etc.)\n * @param options - Optional label for log output\n * @returns The resolved value of `fn`\n * @throws The last error if all attempts are exhausted\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n maxRetries: number,\n options?: RetryOptions,\n): Promise<T> {\n const maxAttempts = maxRetries + 1;\n const label = options?.label;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (err) {\n lastError = err;\n const suffix = label ? ` [${label}]` : \"\";\n if (attempt < maxAttempts) {\n log.warn(\n `Attempt ${attempt}/${maxAttempts} failed${suffix}: ${log.extractMessage(err)}`,\n );\n log.debug(`Retrying${suffix} (attempt ${attempt + 1}/${maxAttempts})`);\n }\n }\n }\n\n throw lastError;\n}\n","/**\n * Dispatch pipeline — the core execution pipeline that discovers tasks,\n * optionally plans them via the planner agent, executes them via the\n * executor agent, syncs completion state back to the datasource, and\n * cleans up resources.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { readFile } from \"node:fs/promises\";\nimport { glob } from \"glob\";\nimport { parseTaskFile, buildTaskContext, groupTasksByMode, type TaskFile, type Task } from \"../parser.js\";\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport { boot as bootPlanner, type PlannerAgent } from \"../agents/planner.js\";\nimport type { AgentResult, PlannerData, ExecutorData } from \"../agents/types.js\";\nimport { boot as bootExecutor, type ExecutorAgent } from \"../agents/executor.js\";\nimport { boot as bootCommit, type CommitAgent } from \"../agents/commit.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { createWorktree, removeWorktree, worktreeName, generateFeatureBranchName } from \"../helpers/worktree.js\";\nimport { isValidBranchName } from \"../helpers/branch-validation.js\";\nimport { createTui, type TuiState } from \"../tui.js\";\nimport type { ProviderName, ProviderInstance } from \"../providers/interface.js\";\nimport { bootProvider } from \"../providers/index.js\";\nimport { getDatasource } from \"../datasources/index.js\";\nimport type { DatasourceName, DispatchLifecycleOptions, IssueDetails, IssueFetchOptions } from \"../datasources/interface.js\";\nimport type { OrchestrateRunOptions, DispatchSummary } from \"./runner.js\";\nimport {\n fetchItemsById,\n writeItemsToTempDir,\n parseIssueFilename,\n buildPrBody,\n buildPrTitle,\n buildFeaturePrTitle,\n buildFeaturePrBody,\n getBranchDiff,\n squashBranchCommits,\n} from \"./datasource-helpers.js\";\nimport { withTimeout, TimeoutError } from \"../helpers/timeout.js\";\nimport { withRetry } from \"../helpers/retry.js\";\nimport { isGlobOrFilePath } from \"../spec-generator.js\";\nimport { extractTitle } from \"../datasources/md.js\";\nimport chalk from \"chalk\";\nimport { elapsed, renderHeaderLines } from \"../helpers/format.js\";\nimport { FileLogger, fileLoggerStorage } from \"../helpers/file-logger.js\";\n\nconst exec = promisify(execFile);\n\n/**\n * Expand glob patterns / file paths into IssueDetails[].\n * Mirrors resolveFileItems() from the spec pipeline.\n */\nasync function resolveGlobItems(\n patterns: string[],\n cwd: string,\n): Promise<IssueDetails[]> {\n const files = await glob(patterns, { cwd, absolute: true });\n\n if (files.length === 0) {\n log.warn(`No files matched the pattern(s): ${patterns.join(\", \")}`);\n return [];\n }\n\n log.info(`Matched ${files.length} file(s) from glob pattern(s)`);\n\n const items: IssueDetails[] = [];\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, \"utf-8\");\n const title = extractTitle(content, filePath);\n items.push({\n number: filePath,\n title,\n body: content,\n labels: [],\n state: \"open\",\n url: filePath,\n comments: [],\n acceptanceCriteria: \"\",\n });\n } catch (err) {\n log.warn(`Could not read file ${filePath}: ${log.formatErrorChain(err)}`);\n }\n }\n return items;\n}\n\n/** Default planning timeout in minutes when not specified by the user. */\nconst DEFAULT_PLAN_TIMEOUT_MIN = 10;\n\n/** Default number of planning retries when not specified by the user. */\nconst DEFAULT_PLAN_RETRIES = 1;\n\n/**\n * Run the full dispatch pipeline: discover tasks from a datasource,\n * optionally plan them via the planner agent, execute via the executor\n * agent, sync completion state, and clean up.\n */\nexport async function runDispatchPipeline(\n opts: OrchestrateRunOptions,\n cwd: string,\n): Promise<DispatchSummary> {\n const {\n issueIds,\n concurrency,\n dryRun,\n serverUrl,\n noPlan,\n noBranch,\n noWorktree,\n feature,\n provider = \"opencode\",\n model,\n source,\n org,\n project,\n workItemType,\n iteration,\n area,\n planTimeout,\n planRetries,\n retries,\n } = opts;\n\n // Planning timeout/retry defaults\n const planTimeoutMs = (planTimeout ?? DEFAULT_PLAN_TIMEOUT_MIN) * 60_000;\n const maxPlanAttempts = (planRetries ?? retries ?? DEFAULT_PLAN_RETRIES) + 1; // retries + initial attempt\n\n log.debug(`Plan timeout: ${planTimeout ?? DEFAULT_PLAN_TIMEOUT_MIN}m (${planTimeoutMs}ms), max attempts: ${maxPlanAttempts}`);\n\n // Dry-run mode uses simple log output\n if (dryRun) {\n return dryRunMode(issueIds, cwd, source, org, project, workItemType, iteration, area);\n }\n\n // ── Start TUI (or inline logging for verbose mode) ──────────\n const verbose = log.verbose;\n let tui: ReturnType<typeof createTui>;\n\n if (verbose) {\n // Print inline header banner (same pattern as spec pipeline)\n const headerLines = renderHeaderLines({ provider, source });\n console.log(\"\");\n for (const line of headerLines) console.log(line);\n console.log(chalk.dim(\" ─\".repeat(24)));\n console.log(\"\");\n log.info(\"Discovering task files...\");\n\n // Silent state container — no animated rendering\n const state: TuiState = {\n tasks: [],\n phase: \"discovering\",\n startTime: Date.now(),\n filesFound: 0,\n provider,\n source,\n };\n tui = { state, update: () => {}, stop: () => {} };\n } else {\n tui = createTui();\n tui.state.provider = provider;\n tui.state.source = source;\n }\n\n try {\n // ── 1. Discover task files ──────────────────────────────────\n tui.state.phase = \"discovering\";\n\n if (!source) {\n tui.state.phase = \"done\";\n tui.stop();\n log.error(\"No datasource configured. Use --source or run 'dispatch config' to set up defaults.\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const datasource = getDatasource(source);\n const fetchOpts: IssueFetchOptions = { cwd, org, project, workItemType, iteration, area };\n let items: IssueDetails[];\n if (issueIds.length > 0 && source === \"md\" && issueIds.some(id => isGlobOrFilePath(id))) {\n items = await resolveGlobItems(issueIds, cwd);\n } else if (issueIds.length > 0) {\n items = await fetchItemsById(issueIds, datasource, fetchOpts);\n } else {\n items = await datasource.list(fetchOpts);\n }\n\n if (items.length === 0) {\n tui.state.phase = \"done\";\n tui.stop();\n const label = issueIds.length > 0 ? `issue(s) ${issueIds.join(\", \")}` : `datasource: ${source}`;\n log.warn(\"No work items found from \" + label);\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const { files, issueDetailsByFile } = await writeItemsToTempDir(items);\n tui.state.filesFound = files.length;\n if (verbose) log.debug(`Found ${files.length} task file(s)`);\n\n // ── 2. Parse all tasks ──────────────────────────────────────\n tui.state.phase = \"parsing\";\n if (verbose) log.info(\"Parsing tasks...\");\n const taskFiles: TaskFile[] = [];\n\n for (const file of files) {\n const tf = await parseTaskFile(file);\n if (tf.tasks.length > 0) {\n taskFiles.push(tf);\n }\n }\n\n const allTasks = taskFiles.flatMap((tf) => tf.tasks);\n\n // Build a lookup from file path → raw content for filtered planner context\n const fileContentMap = new Map<string, string>();\n for (const tf of taskFiles) {\n fileContentMap.set(tf.path, tf.content);\n }\n\n if (allTasks.length === 0) {\n tui.state.phase = \"done\";\n tui.stop();\n log.warn(\"No unchecked tasks found\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n // Populate TUI task list\n tui.state.tasks = allTasks.map((task) => ({\n task,\n status: \"pending\" as const,\n }));\n\n // Group tasks by their source file (each file = one issue)\n const tasksByFile = new Map<string, typeof allTasks>();\n for (const task of allTasks) {\n const list = tasksByFile.get(task.file) ?? [];\n list.push(task);\n tasksByFile.set(task.file, list);\n }\n\n // Determine whether to use worktree-based parallel execution.\n // Worktrees are used when: not opted out, branching is enabled, and\n // there are multiple issues to process (single-issue runs use serial\n // mode to avoid unnecessary worktree overhead).\n const useWorktrees = !noWorktree && (feature || (!noBranch && tasksByFile.size > 1));\n\n // ── 3. Boot provider ────────────────────────────────────────\n tui.state.phase = \"booting\";\n if (verbose) log.info(`Booting ${provider} provider...`);\n if (serverUrl) {\n tui.state.serverUrl = serverUrl;\n }\n if (verbose && serverUrl) log.debug(`Server URL: ${serverUrl}`);\n\n // When using worktrees, providers are booted per-worktree inside\n // processIssueFile. Otherwise, boot a single shared provider.\n let instance: ProviderInstance | undefined;\n let planner: PlannerAgent | null = null;\n let executor: ExecutorAgent | undefined;\n let commitAgent: CommitAgent | undefined;\n\n if (!useWorktrees) {\n instance = await bootProvider(provider, { url: serverUrl, cwd, model });\n registerCleanup(() => instance!.cleanup());\n if (instance.model) {\n tui.state.model = instance.model;\n }\n if (verbose && instance.model) log.debug(`Model: ${instance.model}`);\n\n // ── 4. Boot planner agent (unless --no-plan) ────────────────\n planner = noPlan ? null : await bootPlanner({ provider: instance, cwd });\n executor = await bootExecutor({ provider: instance, cwd });\n commitAgent = await bootCommit({ provider: instance, cwd });\n }\n\n // ── 5. Dispatch tasks ───────────────────────────────────────\n tui.state.phase = \"dispatching\";\n if (verbose) log.info(`Dispatching ${allTasks.length} task(s)...`);\n const results: DispatchResult[] = [];\n let completed = 0;\n let failed = 0;\n\n const lifecycleOpts: DispatchLifecycleOptions = { cwd };\n\n // ── Feature-branch setup (when --feature) ──────────────────────\n let featureBranchName: string | undefined;\n let featureDefaultBranch: string | undefined;\n\n if (feature) {\n // Resolve the feature branch name\n if (typeof feature === \"string\") {\n if (!isValidBranchName(feature)) {\n log.error(`Invalid feature branch name: \"${feature}\"`);\n tui.state.phase = \"done\";\n tui.stop();\n return { total: allTasks.length, completed: 0, failed: allTasks.length, skipped: 0, results: [] };\n }\n featureBranchName = feature.includes(\"/\") ? feature : `dispatch/${feature}`;\n } else {\n featureBranchName = generateFeatureBranchName();\n }\n\n try {\n featureDefaultBranch = await datasource.getDefaultBranch(lifecycleOpts);\n\n // Ensure we are on the default branch so the feature branch starts from the correct commit\n await datasource.switchBranch(featureDefaultBranch, lifecycleOpts);\n\n // Create the feature branch from the default branch (or switch to it if it already exists)\n try {\n await datasource.createAndSwitchBranch(featureBranchName, lifecycleOpts);\n log.debug(`Created feature branch ${featureBranchName} from ${featureDefaultBranch}`);\n } catch (createErr) {\n const message = log.extractMessage(createErr);\n if (message.includes(\"already exists\")) {\n await datasource.switchBranch(featureBranchName, lifecycleOpts);\n log.debug(`Switched to existing feature branch ${featureBranchName}`);\n } else {\n throw createErr;\n }\n }\n\n // Register cleanup for the feature branch\n registerCleanup(async () => {\n try {\n await datasource.switchBranch(featureDefaultBranch!, lifecycleOpts);\n } catch { /* swallow */ }\n });\n\n // Switch back to default branch so worktrees can be created from the main repo\n await datasource.switchBranch(featureDefaultBranch, lifecycleOpts);\n log.debug(`Switched back to ${featureDefaultBranch} for worktree creation`);\n } catch (err) {\n log.error(`Feature branch creation failed: ${log.extractMessage(err)}`);\n tui.state.phase = \"done\";\n tui.stop();\n return { total: allTasks.length, completed: 0, failed: allTasks.length, skipped: 0, results: [] };\n }\n }\n\n // Resolve git username once for branch naming\n let username = \"\";\n try {\n username = await datasource.getUsername(lifecycleOpts);\n } catch (err) {\n log.warn(`Could not resolve git username for branch naming: ${log.formatErrorChain(err)}`);\n }\n\n // Process a single issue file's tasks — handles both worktree and\n // serial branch modes, parameterised by useWorktrees.\n const processIssueFile = async (file: string, fileTasks: typeof allTasks) => {\n const details = issueDetailsByFile.get(file);\n const fileLogger = verbose && details ? new FileLogger(details.number, cwd) : null;\n\n const body = async () => {\n let defaultBranch: string | undefined;\n let branchName: string | undefined;\n let worktreePath: string | undefined;\n let issueCwd = cwd;\n\n // ── Branch / worktree setup (unless --no-branch) ────────────\n if (!noBranch && details) {\n fileLogger?.phase(\"Branch/worktree setup\");\n try {\n defaultBranch = feature ? featureBranchName! : await datasource.getDefaultBranch(lifecycleOpts);\n branchName = datasource.buildBranchName(details.number, details.title, username);\n\n if (useWorktrees) {\n worktreePath = await createWorktree(cwd, file, branchName, ...(feature && featureBranchName ? [featureBranchName] : []));\n registerCleanup(async () => { await removeWorktree(cwd, file); });\n issueCwd = worktreePath;\n log.debug(`Created worktree for issue #${details.number} at ${worktreePath}`);\n fileLogger?.info(`Worktree created at ${worktreePath}`);\n\n // Tag TUI tasks with worktree name for display\n const wtName = worktreeName(file);\n for (const task of fileTasks) {\n const tuiTask = tui.state.tasks.find((t) => t.task === task);\n if (tuiTask) tuiTask.worktree = wtName;\n }\n } else if (datasource.supportsGit()) {\n await datasource.createAndSwitchBranch(branchName, lifecycleOpts);\n log.debug(`Switched to branch ${branchName}`);\n fileLogger?.info(`Switched to branch ${branchName}`);\n }\n } catch (err) {\n const errorMsg = `Branch creation failed for issue #${details.number}: ${log.extractMessage(err)}`;\n fileLogger?.error(`Branch creation failed: ${log.extractMessage(err)}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n log.error(errorMsg);\n for (const task of fileTasks) {\n const tuiTask = tui.state.tasks.find((t) => t.task === task);\n if (tuiTask) {\n tuiTask.status = \"failed\";\n tuiTask.error = errorMsg;\n }\n results.push({ task, success: false, error: errorMsg });\n }\n failed += fileTasks.length;\n return;\n }\n }\n\n const worktreeRoot = useWorktrees ? worktreePath : undefined;\n const issueLifecycleOpts: DispatchLifecycleOptions = { cwd: issueCwd };\n\n // ── Boot per-worktree provider and agents (or use shared ones) ──\n fileLogger?.phase(\"Provider/agent boot\");\n let localInstance: ProviderInstance;\n let localPlanner: PlannerAgent | null;\n let localExecutor: ExecutorAgent;\n let localCommitAgent: CommitAgent;\n\n if (useWorktrees) {\n localInstance = await bootProvider(provider, { url: serverUrl, cwd: issueCwd, model });\n registerCleanup(() => localInstance.cleanup());\n if (localInstance.model && !tui.state.model) {\n tui.state.model = localInstance.model;\n }\n if (verbose && localInstance.model) log.debug(`Model: ${localInstance.model}`);\n localPlanner = noPlan ? null : await bootPlanner({ provider: localInstance, cwd: issueCwd });\n localExecutor = await bootExecutor({ provider: localInstance, cwd: issueCwd });\n localCommitAgent = await bootCommit({ provider: localInstance, cwd: issueCwd });\n fileLogger?.info(`Provider booted: ${localInstance.model ?? provider}`);\n } else {\n localInstance = instance!;\n localPlanner = planner;\n localExecutor = executor!;\n localCommitAgent = commitAgent!;\n }\n\n // ── Dispatch file's tasks ─────────────────────────────────\n const groups = groupTasksByMode(fileTasks);\n const issueResults: DispatchResult[] = [];\n\n for (const group of groups) {\n const groupQueue = [...group];\n\n while (groupQueue.length > 0) {\n const batch = groupQueue.splice(0, concurrency);\n const batchResults = await Promise.all(\n batch.map(async (task) => {\n const tuiTask = tui.state.tasks.find((t) => t.task === task)!;\n const startTime = Date.now();\n tuiTask.elapsed = startTime;\n\n // ── Phase A: Plan (unless --no-plan) ─────────────────\n let plan: string | undefined;\n if (localPlanner) {\n tuiTask.status = \"planning\";\n fileLogger?.phase(`Planning task: ${task.text}`);\n if (verbose) log.info(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: planning — \"${task.text}\"`);\n const rawContent = fileContentMap.get(task.file);\n const fileContext = rawContent ? buildTaskContext(rawContent, task) : undefined;\n\n let planResult: AgentResult<PlannerData> | undefined;\n\n for (let attempt = 1; attempt <= maxPlanAttempts; attempt++) {\n try {\n planResult = await withTimeout(\n localPlanner.plan(task, fileContext, issueCwd, worktreeRoot),\n planTimeoutMs,\n \"planner.plan()\",\n );\n break; // success — exit retry loop\n } catch (err) {\n if (err instanceof TimeoutError) {\n log.warn(\n `Planning timed out for task \"${task.text}\" (attempt ${attempt}/${maxPlanAttempts})`,\n );\n fileLogger?.warn(`Planning timeout (attempt ${attempt}/${maxPlanAttempts})`);\n if (attempt < maxPlanAttempts) {\n log.debug(`Retrying planning (attempt ${attempt + 1}/${maxPlanAttempts})`);\n fileLogger?.info(`Retrying planning (attempt ${attempt + 1}/${maxPlanAttempts})`);\n }\n } else {\n // Non-timeout error — do not retry, surface immediately\n planResult = {\n data: null,\n success: false,\n error: log.extractMessage(err),\n durationMs: 0,\n };\n break;\n }\n }\n }\n\n // All attempts exhausted with timeout — produce failure result\n if (!planResult) {\n const timeoutMin = planTimeout ?? 10;\n planResult = {\n data: null,\n success: false,\n error: `Planning timed out after ${timeoutMin}m (${maxPlanAttempts} attempts)`,\n durationMs: 0,\n };\n }\n\n if (!planResult.success) {\n tuiTask.status = \"failed\";\n tuiTask.error = `Planning failed: ${planResult.error}`;\n fileLogger?.error(`Planning failed: ${planResult.error}`);\n tuiTask.elapsed = Date.now() - startTime;\n if (verbose) log.error(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: failed — ${tuiTask.error} (${elapsed(tuiTask.elapsed)})`);\n failed++;\n return { task, success: false, error: tuiTask.error } as DispatchResult;\n }\n\n plan = planResult.data.prompt;\n fileLogger?.info(`Planning completed (${planResult.durationMs ?? 0}ms)`);\n }\n\n // ── Phase B: Execute via executor agent ──────────────\n tuiTask.status = \"running\";\n fileLogger?.phase(`Executing task: ${task.text}`);\n if (verbose) log.info(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: executing — \"${task.text}\"`);\n const execRetries = 2;\n const execResult = await withRetry(\n async () => {\n const result = await localExecutor.execute({\n task,\n cwd: issueCwd,\n plan: plan ?? null,\n worktreeRoot,\n });\n if (!result.success) {\n throw new Error(result.error ?? \"Execution failed\");\n }\n return result;\n },\n execRetries,\n { label: `executor \"${task.text}\"` },\n ).catch((err): AgentResult<ExecutorData> => ({\n data: null,\n success: false,\n error: log.extractMessage(err),\n durationMs: 0,\n }));\n\n if (execResult.success) {\n fileLogger?.info(`Execution completed successfully (${Date.now() - startTime}ms)`);\n // Sync checked-off state back to the datasource\n try {\n const parsed = parseIssueFilename(task.file);\n const updatedContent = await readFile(task.file, \"utf-8\");\n if (parsed) {\n const issueDetails = issueDetailsByFile.get(task.file);\n const title = issueDetails?.title ?? parsed.slug;\n await datasource.update(parsed.issueId, title, updatedContent, fetchOpts);\n log.success(`Synced task completion to issue #${parsed.issueId}`);\n } else {\n const issueDetails = issueDetailsByFile.get(task.file);\n if (issueDetails) {\n await datasource.update(issueDetails.number, issueDetails.title, updatedContent, fetchOpts);\n log.success(`Synced task completion to issue #${issueDetails.number}`);\n }\n }\n } catch (err) {\n log.warn(`Could not sync task completion to datasource: ${log.formatErrorChain(err)}`);\n }\n\n tuiTask.status = \"done\";\n tuiTask.elapsed = Date.now() - startTime;\n if (verbose) log.success(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: done — \"${task.text}\" (${elapsed(tuiTask.elapsed)})`);\n completed++;\n } else {\n fileLogger?.error(`Execution failed: ${execResult.error}`);\n tuiTask.status = \"failed\";\n tuiTask.error = execResult.error;\n tuiTask.elapsed = Date.now() - startTime;\n if (verbose) log.error(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: failed — \"${task.text}\" (${elapsed(tuiTask.elapsed)})${tuiTask.error ? `: ${tuiTask.error}` : \"\"}`);\n failed++;\n }\n\n const dispatchResult: DispatchResult = execResult.success\n ? execResult.data.dispatchResult\n : {\n task,\n success: false,\n error: execResult.error ?? \"Executor failed without returning a dispatch result.\",\n };\n return dispatchResult;\n })\n );\n\n issueResults.push(...batchResults);\n\n // Update TUI once the provider detects the actual model (lazy detection)\n if (!tui.state.model && localInstance.model) {\n tui.state.model = localInstance.model;\n }\n }\n }\n\n results.push(...issueResults);\n\n // ── Safety-net commit (stage any uncommitted changes) ─────\n if (!noBranch && branchName && defaultBranch && details && datasource.supportsGit()) {\n try {\n await datasource.commitAllChanges(\n `chore: stage uncommitted changes for issue #${details.number}`,\n issueLifecycleOpts,\n );\n log.debug(`Staged uncommitted changes for issue #${details.number}`);\n } catch (err) {\n log.warn(`Could not commit uncommitted changes for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n }\n\n // ── Commit agent (rewrite commits + generate PR metadata) ───\n fileLogger?.phase(\"Commit generation\");\n let commitAgentResult: import(\"../agents/commit.js\").CommitResult | undefined;\n if (!noBranch && branchName && defaultBranch && details && datasource.supportsGit()) {\n try {\n const branchDiff = await getBranchDiff(defaultBranch, issueCwd);\n if (branchDiff) {\n const result = await localCommitAgent.generate({\n branchDiff,\n issue: details,\n taskResults: issueResults,\n cwd: issueCwd,\n worktreeRoot,\n });\n if (result.success) {\n commitAgentResult = result;\n fileLogger?.info(`Commit message generated for issue #${details.number}`);\n // Rewrite commit history with the generated message\n try {\n await squashBranchCommits(defaultBranch, result.commitMessage, issueCwd);\n log.debug(`Rewrote commit message for issue #${details.number}`);\n fileLogger?.info(`Rewrote commit history for issue #${details.number}`);\n } catch (err) {\n log.warn(`Could not rewrite commit message for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n } else {\n log.warn(`Commit agent failed for issue #${details.number}: ${result.error}`);\n fileLogger?.warn(`Commit agent failed: ${result.error}`);\n }\n }\n } catch (err) {\n log.warn(`Commit agent error for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n }\n\n // ── Branch teardown (push, PR, cleanup) ──────────────────\n fileLogger?.phase(\"PR lifecycle\");\n if (!noBranch && branchName && defaultBranch && details) {\n if (feature && featureBranchName) {\n // ── Feature mode: merge working branch into feature branch ──\n if (worktreePath) {\n try {\n await removeWorktree(cwd, file);\n } catch (err) {\n log.warn(`Could not remove worktree for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n }\n\n try {\n await datasource.switchBranch(featureBranchName, lifecycleOpts);\n await exec(\"git\", [\"merge\", branchName, \"--no-ff\", \"-m\", `merge: issue #${details.number}`], { cwd, shell: process.platform === \"win32\" });\n log.debug(`Merged ${branchName} into ${featureBranchName}`);\n } catch (err) {\n const mergeError = `Could not merge ${branchName} into feature branch: ${log.formatErrorChain(err)}`;\n log.warn(mergeError);\n // Abort the failed merge so the repo is left in a clean state\n try {\n await exec(\"git\", [\"merge\", \"--abort\"], { cwd, shell: process.platform === \"win32\" });\n } catch { /* merge --abort may fail if there's nothing to abort */ }\n // Record every task in this issue as failed\n for (const task of fileTasks) {\n const tuiTask = tui.state.tasks.find((t) => t.task === task);\n if (tuiTask) {\n tuiTask.status = \"failed\";\n tuiTask.error = mergeError;\n }\n const existingResult = results.find((r) => r.task === task);\n if (existingResult) {\n existingResult.success = false;\n existingResult.error = mergeError;\n }\n }\n return;\n }\n\n try {\n await exec(\"git\", [\"branch\", \"-d\", branchName], { cwd, shell: process.platform === \"win32\" });\n log.debug(`Deleted local branch ${branchName}`);\n } catch (err) {\n log.warn(`Could not delete local branch ${branchName}: ${log.formatErrorChain(err)}`);\n }\n\n try {\n await datasource.switchBranch(featureDefaultBranch!, lifecycleOpts);\n } catch (err) {\n log.warn(`Could not switch back to ${featureDefaultBranch}: ${log.formatErrorChain(err)}`);\n }\n } else {\n // ── Normal mode: push and create per-issue PR ──\n if (datasource.supportsGit()) {\n try {\n await datasource.pushBranch(branchName, issueLifecycleOpts);\n log.debug(`Pushed branch ${branchName}`);\n fileLogger?.info(`Pushed branch ${branchName}`);\n } catch (err) {\n log.warn(`Could not push branch ${branchName}: ${log.formatErrorChain(err)}`);\n }\n }\n\n if (datasource.supportsGit()) {\n try {\n const prTitle = commitAgentResult?.prTitle\n || await buildPrTitle(details.title, defaultBranch, issueLifecycleOpts.cwd);\n const prBody = commitAgentResult?.prDescription\n || await buildPrBody(\n details,\n fileTasks,\n issueResults,\n defaultBranch,\n datasource.name,\n issueLifecycleOpts.cwd,\n );\n const prUrl = await datasource.createPullRequest(\n branchName,\n details.number,\n prTitle,\n prBody,\n issueLifecycleOpts,\n );\n if (prUrl) {\n log.success(`Created PR for issue #${details.number}: ${prUrl}`);\n fileLogger?.info(`Created PR: ${prUrl}`);\n }\n } catch (err) {\n log.warn(`Could not create PR for issue #${details.number}: ${log.formatErrorChain(err)}`);\n fileLogger?.warn(`PR creation failed: ${log.extractMessage(err)}`);\n }\n }\n\n if (useWorktrees && worktreePath) {\n try {\n await removeWorktree(cwd, file);\n } catch (err) {\n log.warn(`Could not remove worktree for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n } else if (!useWorktrees && datasource.supportsGit()) {\n try {\n await datasource.switchBranch(defaultBranch, lifecycleOpts);\n log.debug(`Switched back to ${defaultBranch}`);\n } catch (err) {\n log.warn(`Could not switch back to ${defaultBranch}: ${log.formatErrorChain(err)}`);\n }\n }\n }\n }\n\n // ── Per-worktree resource cleanup ───────────────────────────\n fileLogger?.phase(\"Resource cleanup\");\n if (useWorktrees) {\n await localExecutor.cleanup();\n await localPlanner?.cleanup();\n await localInstance.cleanup();\n }\n };\n\n if (fileLogger) {\n await fileLoggerStorage.run(fileLogger, async () => {\n try {\n await body();\n } finally {\n fileLogger.close();\n }\n });\n } else {\n await body();\n }\n };\n\n // Execute issues: parallel via worktrees, or serial fallback\n // Feature mode forces serial execution to avoid merge conflicts\n if (useWorktrees && !feature) {\n await Promise.all(\n Array.from(tasksByFile).map(([file, fileTasks]) =>\n processIssueFile(file, fileTasks)\n )\n );\n } else {\n for (const [file, fileTasks] of tasksByFile) {\n await processIssueFile(file, fileTasks);\n }\n }\n\n // ── Feature branch finalization (push + aggregated PR) ──────\n if (feature && featureBranchName && featureDefaultBranch) {\n try {\n await datasource.switchBranch(featureBranchName, lifecycleOpts);\n log.debug(`Switched to feature branch ${featureBranchName}`);\n } catch (err) {\n log.warn(`Could not switch to feature branch: ${log.formatErrorChain(err)}`);\n }\n\n try {\n await datasource.pushBranch(featureBranchName, lifecycleOpts);\n log.debug(`Pushed feature branch ${featureBranchName}`);\n } catch (err) {\n log.warn(`Could not push feature branch: ${log.formatErrorChain(err)}`);\n }\n\n try {\n const allIssueDetails = Array.from(issueDetailsByFile.values());\n const prTitle = buildFeaturePrTitle(featureBranchName, allIssueDetails);\n const prBody = buildFeaturePrBody(allIssueDetails, allTasks, results, source!);\n const primaryIssue = allIssueDetails[0]?.number ?? \"\";\n const prUrl = await datasource.createPullRequest(\n featureBranchName,\n primaryIssue,\n prTitle,\n prBody,\n lifecycleOpts,\n );\n if (prUrl) {\n log.success(`Created feature PR: ${prUrl}`);\n }\n } catch (err) {\n log.warn(`Could not create feature PR: ${log.formatErrorChain(err)}`);\n }\n\n try {\n await datasource.switchBranch(featureDefaultBranch, lifecycleOpts);\n } catch (err) {\n log.warn(`Could not switch back to ${featureDefaultBranch}: ${log.formatErrorChain(err)}`);\n }\n }\n\n // ── 6. Cleanup ──────────────────────────────────────────────\n // Per-worktree resources are cleaned up inside processIssueFile.\n // Shared resources (when !useWorktrees) are cleaned up here.\n await commitAgent?.cleanup();\n await executor?.cleanup();\n await planner?.cleanup();\n await instance?.cleanup();\n\n tui.state.phase = \"done\";\n tui.stop();\n if (verbose) log.success(`Done — ${completed} completed, ${failed} failed (${elapsed(Date.now() - tui.state.startTime)})`);\n\n return { total: allTasks.length, completed, failed, skipped: 0, results };\n } catch (err) {\n tui.stop();\n throw err;\n }\n}\n\n/**\n * Dry-run mode — discovers and parses tasks, logs them, but does not\n * execute anything.\n */\nexport async function dryRunMode(\n issueIds: string[],\n cwd: string,\n source?: DatasourceName,\n org?: string,\n project?: string,\n workItemType?: string,\n iteration?: string,\n area?: string,\n): Promise<DispatchSummary> {\n if (!source) {\n log.error(\"No datasource configured. Use --source or run 'dispatch config' to set up defaults.\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const datasource = getDatasource(source);\n const fetchOpts: IssueFetchOptions = { cwd, org, project, workItemType, iteration, area };\n\n const lifecycleOpts = { cwd };\n let username = \"\";\n try {\n username = await datasource.getUsername(lifecycleOpts);\n } catch {\n // Fall back to empty prefix if username resolution fails\n }\n\n let items: IssueDetails[];\n if (issueIds.length > 0 && source === \"md\" && issueIds.some(id => isGlobOrFilePath(id))) {\n items = await resolveGlobItems(issueIds, cwd);\n } else if (issueIds.length > 0) {\n items = await fetchItemsById(issueIds, datasource, fetchOpts);\n } else {\n items = await datasource.list(fetchOpts);\n }\n\n if (items.length === 0) {\n const label = issueIds.length > 0 ? `issue(s) ${issueIds.join(\", \")}` : `datasource: ${source}`;\n log.warn(\"No work items found from \" + label);\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const { files, issueDetailsByFile } = await writeItemsToTempDir(items);\n\n const taskFiles: TaskFile[] = [];\n for (const file of files) {\n const tf = await parseTaskFile(file);\n if (tf.tasks.length > 0) {\n taskFiles.push(tf);\n }\n }\n\n const allTasks = taskFiles.flatMap((tf) => tf.tasks);\n\n if (allTasks.length === 0) {\n log.warn(\"No unchecked tasks found\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n log.info(`Dry run — ${allTasks.length} task(s) across ${taskFiles.length} file(s):\\n`);\n for (const task of allTasks) {\n const parsed = parseIssueFilename(task.file);\n const details = parsed\n ? items.find((item) => item.number === parsed.issueId)\n : issueDetailsByFile.get(task.file);\n const branchInfo = details\n ? ` [branch: ${datasource.buildBranchName(details.number, details.title, username)}]`\n : \"\";\n log.task(allTasks.indexOf(task), allTasks.length, `${task.file}:${task.line} — ${task.text}${branchInfo}`);\n }\n\n return {\n total: allTasks.length,\n completed: 0,\n failed: 0,\n skipped: allTasks.length,\n results: [],\n };\n}\n","/**\n * Markdown task parser — extracts unchecked `[ ]` tasks from markdown files\n * and provides utilities to mark them as complete `[x]`.\n *\n * Non-task content (headings, prose, notes) is preserved in `TaskFile.context`\n * so the planner agent can use it for implementation guidance.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\n\nexport interface Task {\n /** Zero-based index within the file */\n index: number;\n /** The raw text after `- [ ] `, with any (P)/(S) prefix stripped */\n text: string;\n /** Line number in the file (1-based) */\n line: number;\n /** Full original line content */\n raw: string;\n /** The source file path */\n file: string;\n /** Execution mode — \"parallel\", \"serial\", or \"isolated\". Defaults to \"serial\" when unspecified. */\n mode?: \"parallel\" | \"serial\" | \"isolated\";\n}\n\nexport interface TaskFile {\n path: string;\n tasks: Task[];\n /** Full file content — includes non-task prose, headings, and notes */\n content: string;\n}\n\n/** Matches an unchecked markdown task item, e.g. `- [ ] Implement feature` */\nconst UNCHECKED_RE = /^(\\s*[-*]\\s)\\[ \\]\\s+(.+)$/;\n/** Matches a checked markdown task item, e.g. `- [x] Implement feature` */\nconst CHECKED_RE = /^(\\s*[-*]\\s)\\[[xX]\\]\\s+/;\n/** Replacement string used with UNCHECKED_RE to mark a task complete, e.g. `- [ ] task` → `- [x] task` */\nconst CHECKED_SUB = \"$1[x] $2\";\n/** Matches a mode prefix at the start of task text, e.g. `(P) Run tests in parallel` */\nconst MODE_PREFIX_RE = /^\\(([PSI])\\)\\s+/;\n\n/**\n * Build a filtered view of the file content for a single task's planner context.\n * Keeps:\n * - All non-task lines (headings, prose, notes, blank lines, checked tasks)\n * - The specific unchecked task line being planned\n * Removes:\n * - All *other* unchecked `[ ]` task lines\n *\n * This prevents the planner (and downstream executor) from being confused\n * by sibling tasks that belong to different agents.\n */\nexport function buildTaskContext(content: string, task: Task): string {\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n\n const filtered = lines.filter((line, i) => {\n // Always keep the line that matches the current task\n if (i + 1 === task.line) return true;\n // Remove other unchecked task lines\n if (UNCHECKED_RE.test(line)) return false;\n // Keep everything else (headings, prose, checked tasks, blank lines)\n return true;\n });\n\n return filtered.join(\"\\n\");\n}\n\n/**\n * Parse markdown content (string) and return all unchecked tasks.\n * Pure function — no file I/O. Useful for testing and reuse.\n */\nexport function parseTaskContent(content: string, filePath: string): TaskFile {\n // Normalize CRLF → LF so the regex anchors work consistently\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n const tasks: Task[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const match = lines[i].match(UNCHECKED_RE);\n if (match) {\n let text = match[2].trim();\n let mode: \"parallel\" | \"serial\" | \"isolated\" = \"serial\";\n\n const modeMatch = text.match(MODE_PREFIX_RE);\n if (modeMatch) {\n const modeMap: Record<string, \"parallel\" | \"serial\" | \"isolated\"> = {\n P: \"parallel\",\n S: \"serial\",\n I: \"isolated\",\n };\n mode = modeMap[modeMatch[1]] ?? \"serial\";\n text = text.slice(modeMatch[0].length);\n }\n\n tasks.push({\n index: tasks.length,\n text,\n line: i + 1,\n raw: lines[i],\n file: filePath,\n mode,\n });\n }\n }\n\n return { path: filePath, tasks, content };\n}\n\n/**\n * Parse a single markdown file and return all unchecked tasks.\n */\nexport async function parseTaskFile(filePath: string): Promise<TaskFile> {\n const content = await readFile(filePath, \"utf-8\");\n return parseTaskContent(content, filePath);\n}\n\n/**\n * Mark a specific task as complete in its source file by replacing `[ ]` with `[x]`.\n */\nexport async function markTaskComplete(task: Task): Promise<void> {\n const content = await readFile(task.file, \"utf-8\");\n const eol = content.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n const lineIndex = task.line - 1;\n\n if (lineIndex < 0 || lineIndex >= lines.length) {\n throw new Error(\n `Line ${task.line} out of range in ${task.file} (${lines.length} lines)`\n );\n }\n\n const original = lines[lineIndex];\n const updated = original.replace(UNCHECKED_RE, CHECKED_SUB);\n\n if (original === updated) {\n throw new Error(\n `Line ${task.line} in ${task.file} does not match expected unchecked pattern: \"${original}\"`\n );\n }\n\n lines[lineIndex] = updated;\n await writeFile(task.file, lines.join(eol), \"utf-8\");\n}\n\n/**\n * Group a flat task list into ordered execution groups.\n *\n * - Consecutive parallel tasks accumulate into the current group.\n * - A serial task caps the current group (is appended to it), then a new group begins.\n * - A lone serial task (no preceding parallel tasks) forms a solo group.\n * - An isolated task flushes the current group (if non-empty) as its own group,\n * then creates a solo group containing only the isolated task, then resets\n * the accumulator. This guarantees the isolated task runs alone.\n *\n * The orchestrator runs each group concurrently, waiting for the group to\n * complete before starting the next one.\n */\nexport function groupTasksByMode(tasks: Task[]): Task[][] {\n if (tasks.length === 0) return [];\n\n const groups: Task[][] = [];\n let current: Task[] = [];\n\n for (const task of tasks) {\n const mode = task.mode ?? \"serial\";\n\n if (mode === \"parallel\") {\n current.push(task);\n } else if (mode === \"isolated\") {\n // Flush accumulated tasks as their own group\n if (current.length > 0) {\n groups.push(current);\n current = [];\n }\n // Push a solo group for the isolated task\n groups.push([task]);\n } else {\n // Serial task caps the current group\n current.push(task);\n groups.push(current);\n current = [];\n }\n }\n\n // Flush any remaining parallel tasks that weren't capped by a serial task\n if (current.length > 0) {\n groups.push(current);\n }\n\n return groups;\n}\n","/**\n * Planner agent — explores the codebase and researches the implementation\n * for a task, then produces a focused system prompt for the executor agent.\n *\n * The planner runs in its own session with read-only intent: it reads files,\n * searches symbols, and reasons about the task without making any changes.\n * Its output is a rich, context-aware prompt that the executor can follow\n * to make precise edits.\n */\n\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { Task } from \"../parser.js\";\nimport type { AgentResult, PlannerData } from \"./types.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/**\n * A booted planner agent that can produce execution plans for tasks.\n *\n * To add a new planner implementation:\n * 1. Create `src/agents/<name>.ts`\n * 2. Export an async `boot` function that returns a `PlannerAgent`\n * 3. Register it in `src/agents/index.ts`\n */\nexport interface PlannerAgent extends Agent {\n /**\n * Run the planner for a single task. Creates an isolated session,\n * sends the planning prompt, and extracts the resulting execution plan.\n *\n * When `fileContext` is provided (filtered markdown from the task file),\n * it is included so the planner can use non-task prose (headings, notes,\n * implementation details) as additional guidance.\n *\n * When `cwd` is provided, it overrides the boot-time working directory\n * in the planning prompt — use this for worktree tasks.\n *\n * When `worktreeRoot` is provided, the prompt includes directory-restriction\n * instructions that confine the agent to that worktree directory.\n */\n plan(task: Task, fileContext?: string, cwd?: string, worktreeRoot?: string): Promise<AgentResult<PlannerData>>;\n}\n\n/**\n * Boot a planner agent backed by the given provider.\n *\n * @throws if `opts.provider` is not supplied — the planner requires a\n * provider to create sessions and send prompts.\n */\nexport async function boot(opts: AgentBootOptions): Promise<PlannerAgent> {\n const { provider, cwd } = opts;\n\n if (!provider) {\n throw new Error(\"Planner agent requires a provider instance in boot options\");\n }\n\n return {\n name: \"planner\",\n\n async plan(task: Task, fileContext?: string, cwdOverride?: string, worktreeRoot?: string): Promise<AgentResult<PlannerData>> {\n const startTime = Date.now();\n try {\n const sessionId = await provider.createSession();\n const prompt = buildPlannerPrompt(task, cwdOverride ?? cwd, fileContext, worktreeRoot);\n fileLoggerStorage.getStore()?.prompt(\"planner\", prompt);\n\n const plan = await provider.prompt(sessionId, prompt);\n if (plan) fileLoggerStorage.getStore()?.response(\"planner\", plan);\n\n if (!plan?.trim()) {\n return { data: null, success: false, error: \"Planner returned empty plan\", durationMs: Date.now() - startTime };\n }\n\n fileLoggerStorage.getStore()?.agentEvent(\"planner\", \"completed\", `${Date.now() - startTime}ms`);\n return { data: { prompt: plan }, success: true, durationMs: Date.now() - startTime };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`planner error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return { data: null, success: false, error: message, durationMs: Date.now() - startTime };\n }\n },\n\n async cleanup(): Promise<void> {\n // Planner has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n\n/**\n * Build the prompt that instructs the planner to explore the codebase,\n * understand the task, and produce an execution plan.\n *\n * When file context is provided, it is included as a \"Task File Contents\"\n * section so the planner can use headings, prose, and notes from the\n * markdown file as implementation guidance.\n *\n * When `worktreeRoot` is provided, directory-restriction instructions are\n * appended to confine all agent operations within the worktree boundary.\n */\nfunction buildPlannerPrompt(task: Task, cwd: string, fileContext?: string, worktreeRoot?: string): string {\n const sections: string[] = [\n `You are a **planning agent**. Your job is to explore the codebase, understand the task below, and produce a detailed execution prompt that another agent will follow to implement the changes.`,\n ``,\n `## Task`,\n `- **Working directory:** ${cwd}`,\n `- **Source file:** ${task.file}`,\n `- **Task (line ${task.line}):** ${task.text}`,\n ];\n\n if (fileContext) {\n sections.push(\n ``,\n `## Task File Contents`,\n ``,\n `The task comes from a markdown file that may contain important implementation`,\n `details, requirements, and context in its non-task content (headings, prose,`,\n `notes). Review this carefully — it may describe conventions, constraints, or`,\n `technical details that are critical for the implementation.`,\n ``,\n `\\`\\`\\`markdown`,\n fileContext,\n `\\`\\`\\``,\n );\n }\n\n if (worktreeRoot) {\n sections.push(\n ``,\n `## Worktree Isolation`,\n ``,\n `You are operating inside a git worktree. All file operations MUST be confined`,\n `to the following directory tree:`,\n ``,\n ` ${worktreeRoot}`,\n ``,\n `- Do NOT read, write, or execute commands that access files outside this directory.`,\n `- Do NOT reference or modify files in the main repository working tree or other worktrees.`,\n `- All relative paths must resolve within the worktree root above.`,\n );\n }\n\n sections.push(\n ``,\n formatEnvironmentPrompt(),\n );\n\n sections.push(\n ``,\n `## Instructions`,\n ``,\n `1. **Explore the codebase** — read relevant files, search for symbols, and understand the project structure, conventions, and patterns.`,\n `2. **Review the task file contents above** — pay close attention to non-task text (headings, prose, notes) as it often contains important implementation details, requirements, and constraints.`,\n `3. **Identify the files** that need to be created or modified to complete this task.`,\n `4. **Research the implementation** — understand the existing code patterns, imports, types, and APIs involved.`,\n `5. **DO NOT make any changes** — you are only planning, not executing.`,\n ``,\n `## Output Format`,\n ``,\n `Produce your response as a **system prompt for an executor agent**. The executor will receive your output verbatim as its instructions. Write it in second person (\"You will...\", \"Modify the file...\").`,\n ``,\n `Your output MUST include:`,\n ``,\n `1. **Context** — A brief summary of the relevant project structure, conventions, and patterns the executor needs to know. Include any important details from the task file's non-task content.`,\n `2. **Files to modify** — The exact file paths that need to be created or changed, with the rationale for each.`,\n `3. **Step-by-step implementation** — Precise, ordered steps the executor should follow. Include:`,\n ` - Exact file paths`,\n ` - What to add, change, or remove`,\n ` - Code snippets, type signatures, or patterns to follow (based on existing code you read)`,\n ` - Import statements needed`,\n `4. **Constraints** — Any important constraints:`,\n ` - If the task description includes a commit instruction, include a final step in the plan to commit the changes using conventional commit conventions (supported types: feat, fix, docs, refactor, test, chore, style, perf, ci). If the task does not mention committing, instruct the executor to NOT commit changes.`,\n ` - Make minimal, correct changes — do not refactor unrelated code.`,\n ` - Follow existing code style and conventions found in the project.`,\n ``,\n `Be specific and concrete. Reference actual code you found during exploration. The executor has no prior context about this codebase — your prompt is all it gets.`,\n );\n\n return sections.join(\"\\n\");\n}\n","/**\n * Task dispatcher — creates a fresh session per task to keep contexts\n * isolated and avoid context rot. Works with any registered provider.\n */\n\nimport type { ProviderInstance } from \"./providers/interface.js\";\nimport type { Task } from \"./parser.js\";\nimport { log } from \"./helpers/logger.js\";\nimport { fileLoggerStorage } from \"./helpers/file-logger.js\";\nimport { getEnvironmentBlock } from \"./helpers/environment.js\";\n\nexport interface DispatchResult {\n task: Task;\n success: boolean;\n error?: string;\n}\n\n/**\n * Dispatch a single task to the provider in its own session.\n * Each task gets a fresh session for context isolation.\n *\n * When a `plan` is provided (from the planner agent), it replaces the\n * generic prompt with the planner's context-rich execution instructions.\n */\nexport async function dispatchTask(\n instance: ProviderInstance,\n task: Task,\n cwd: string,\n plan?: string,\n worktreeRoot?: string,\n): Promise<DispatchResult> {\n try {\n log.debug(`Dispatching task: ${task.file}:${task.line} — ${task.text.slice(0, 80)}`);\n const sessionId = await instance.createSession();\n const prompt = plan ? buildPlannedPrompt(task, cwd, plan, worktreeRoot) : buildPrompt(task, cwd, worktreeRoot);\n log.debug(`Prompt built (${prompt.length} chars, ${plan ? \"with plan\" : \"no plan\"})`);\n fileLoggerStorage.getStore()?.prompt(\"dispatchTask\", prompt);\n\n const response = await instance.prompt(sessionId, prompt);\n\n if (response === null) {\n log.debug(\"Task dispatch returned null response\");\n fileLoggerStorage.getStore()?.warn(\"dispatchTask: null response\");\n return { task, success: false, error: \"No response from agent\" };\n }\n\n log.debug(`Task dispatch completed (${response.length} chars response)`);\n fileLoggerStorage.getStore()?.response(\"dispatchTask\", response);\n return { task, success: true };\n } catch (err) {\n const message = log.extractMessage(err);\n log.debug(`Task dispatch failed: ${log.formatErrorChain(err)}`);\n fileLoggerStorage.getStore()?.error(`dispatchTask error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return { task, success: false, error: message };\n }\n}\n\n/**\n * Build a focused prompt for a single task. Includes context about the\n * project but scopes the work to just this one unit.\n */\nfunction buildPrompt(task: Task, cwd: string, worktreeRoot?: string): string {\n return [\n `You are completing a task from a markdown task file.`,\n ``,\n `**Working directory:** ${cwd}`,\n `**Source file:** ${task.file}`,\n `**Task (line ${task.line}):** ${task.text}`,\n ``,\n getEnvironmentBlock(),\n ``,\n `Instructions:`,\n `- Complete ONLY this specific task — do not work on other tasks.`,\n `- Make the minimal, correct changes needed.`,\n buildCommitInstruction(task.text),\n ...buildWorktreeIsolation(worktreeRoot),\n `- When finished, confirm by saying \"Task complete.\"`,\n ].join(\"\\n\");\n}\n\n/**\n * Build a prompt for the executor when a planner has already explored\n * the codebase and produced a detailed execution plan.\n */\nfunction buildPlannedPrompt(task: Task, cwd: string, plan: string, worktreeRoot?: string): string {\n return [\n `You are an **executor agent** completing a task that has been pre-planned by a planner agent.`,\n `The planner has already explored the codebase and produced detailed instructions below.`,\n ``,\n `**Working directory:** ${cwd}`,\n `**Source file:** ${task.file}`,\n `**Task (line ${task.line}):** ${task.text}`,\n ``,\n getEnvironmentBlock(),\n ``,\n `---`,\n ``,\n `## Execution Plan`,\n ``,\n plan,\n ``,\n `---`,\n ``,\n `## Executor Constraints`,\n `- Follow the plan above precisely — do not deviate, skip steps, or reorder.`,\n `- Complete ONLY this specific task — do not work on other tasks.`,\n `- Make the minimal, correct changes needed — do not refactor unrelated code.`,\n `- Do NOT explore the codebase. The planner has already done all necessary research. Only read or modify the files explicitly referenced in the plan.`,\n `- Do NOT re-plan, question, or revise the plan. Trust it as given and execute it faithfully.`,\n `- Do NOT search for additional context using grep, find, or similar tools unless the plan explicitly instructs you to.`,\n buildCommitInstruction(task.text),\n ...buildWorktreeIsolation(worktreeRoot),\n `- When finished, confirm by saying \"Task complete.\"`,\n ].join(\"\\n\");\n}\n\n/**\n * Check whether a task description includes an instruction to commit.\n */\nfunction taskRequestsCommit(taskText: string): boolean {\n return /\\bcommit\\b/i.test(taskText);\n}\n\n/**\n * Build a commit instruction line based on whether the task requests a commit.\n */\nfunction buildCommitInstruction(taskText: string): string {\n if (taskRequestsCommit(taskText)) {\n return (\n `- The task description includes a commit instruction. After completing the implementation, ` +\n `stage all changes and create a conventional commit. Use one of these types: ` +\n `feat, fix, docs, refactor, test, chore, style, perf, ci.`\n );\n }\n return `- Do NOT commit changes — the orchestrator handles commits.`;\n}\n\n/**\n * Build worktree isolation instructions when operating inside a git worktree.\n * Returns an empty array when no worktreeRoot is provided (non-worktree mode).\n */\nfunction buildWorktreeIsolation(worktreeRoot?: string): string[] {\n if (!worktreeRoot) return [];\n return [\n `- **Worktree isolation:** You are operating inside a git worktree at \\`${worktreeRoot}\\`. ` +\n `You MUST NOT read, write, or execute commands that access files outside this directory. ` +\n `All file paths must resolve within \\`${worktreeRoot}\\`.`,\n ];\n}\n","/**\n * Executor agent — executes a single task by dispatching it to the AI\n * provider and marking it complete on success.\n *\n * The executor consumes a plan produced by the planner (or null when\n * planning is disabled). It never calls the planner itself — the plan\n * is treated as authoritative input from the orchestrator.\n */\n\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { AgentResult, ExecutorData } from \"./types.js\";\nimport type { Task } from \"../parser.js\";\nimport { markTaskComplete } from \"../parser.js\";\nimport { dispatchTask } from \"../dispatcher.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\n\n/**\n * Input to the executor for a single task.\n *\n * `plan` is the planner's output prompt string, or `null` when planning\n * was skipped (--no-plan). The executor uses this to decide whether to\n * build a planned prompt or a generic prompt via the dispatcher.\n */\nexport interface ExecuteInput {\n /** The task to execute */\n task: Task;\n /** Working directory */\n cwd: string;\n /** Planner output prompt, or null if planning was skipped */\n plan: string | null;\n /** Worktree root directory for isolation, if operating in a worktree */\n worktreeRoot?: string;\n}\n\n/**\n * A booted executor agent that can execute planned (or unplanned) tasks.\n */\nexport interface ExecutorAgent extends Agent {\n /**\n * Execute a single task. Dispatches to the provider, marks the task\n * complete on success, and returns a structured result.\n */\n execute(input: ExecuteInput): Promise<AgentResult<ExecutorData>>;\n}\n\n/**\n * Boot an executor agent backed by the given provider.\n *\n * @throws if `opts.provider` is not supplied — the executor requires a\n * provider to create sessions and send prompts.\n */\nexport async function boot(opts: AgentBootOptions): Promise<ExecutorAgent> {\n const { provider } = opts;\n\n if (!provider) {\n throw new Error(\"Executor agent requires a provider instance in boot options\");\n }\n\n return {\n name: \"executor\",\n\n async execute(input: ExecuteInput): Promise<AgentResult<ExecutorData>> {\n const { task, cwd, plan, worktreeRoot } = input;\n const startTime = Date.now();\n\n try {\n fileLoggerStorage.getStore()?.agentEvent(\"executor\", \"started\", task.text);\n // Dispatch the task — plan being non-null triggers the planned prompt path\n // in dispatchTask, otherwise the generic prompt is used\n const result = await dispatchTask(provider, task, cwd, plan ?? undefined, worktreeRoot);\n\n if (result.success) {\n await markTaskComplete(task);\n fileLoggerStorage.getStore()?.agentEvent(\"executor\", \"completed\", `${Date.now() - startTime}ms`);\n return { data: { dispatchResult: result }, success: true, durationMs: Date.now() - startTime };\n }\n\n fileLoggerStorage.getStore()?.agentEvent(\"executor\", \"failed\", result.error ?? \"unknown error\");\n return { data: null, success: false, error: result.error, durationMs: Date.now() - startTime };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`executor error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return { data: null, success: false, error: message, durationMs: Date.now() - startTime };\n }\n },\n\n async cleanup(): Promise<void> {\n // Executor has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n","/**\n * Commit agent — analyzes branch changes and generates meaningful\n * conventional-commit-compliant commit messages, PR titles, and PR\n * descriptions using an AI provider.\n *\n * The commit agent runs after all tasks complete but before the PR is\n * created. It receives the branch diff, issue context, and task results,\n * prompts the AI provider, parses the structured response, and writes\n * the results to a temporary markdown file.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { IssueDetails } from \"../datasources/interface.js\";\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/** Options for the commit agent's `generate()` method. */\nexport interface CommitGenerateOptions {\n /** Git diff of the branch relative to the default branch */\n branchDiff: string;\n /** Issue details for context */\n issue: IssueDetails;\n /** Task dispatch results */\n taskResults: DispatchResult[];\n /** Working directory */\n cwd: string;\n /** Worktree root directory for isolation, if operating in a worktree */\n worktreeRoot?: string;\n}\n\n/** Structured result returned by the commit agent. */\nexport interface CommitResult {\n /** The generated conventional commit message */\n commitMessage: string;\n /** The generated PR title */\n prTitle: string;\n /** The generated PR description */\n prDescription: string;\n /** Whether generation succeeded */\n success: boolean;\n /** Error message if generation failed */\n error?: string;\n /** Path to the temp markdown file with the full output */\n outputPath?: string;\n}\n\n/** Commit agent — extends `Agent` with a `generate()` method. */\nexport interface CommitAgent extends Agent {\n /**\n * Generate commit message, PR title, and PR description from branch\n * changes and context. Writes results to a temp markdown file.\n */\n generate(opts: CommitGenerateOptions): Promise<CommitResult>;\n}\n\n/**\n * Boot the commit agent.\n *\n * @throws if `opts.provider` is not supplied.\n */\nexport async function boot(opts: AgentBootOptions): Promise<CommitAgent> {\n const { provider } = opts;\n\n if (!provider) {\n throw new Error(\n \"Commit agent requires a provider instance in boot options\"\n );\n }\n\n return {\n name: \"commit\",\n\n async generate(genOpts: CommitGenerateOptions): Promise<CommitResult> {\n try {\n const resolvedCwd = resolve(genOpts.cwd);\n const tmpDir = join(resolvedCwd, \".dispatch\", \"tmp\");\n await mkdir(tmpDir, { recursive: true });\n\n const tmpFilename = `commit-${randomUUID()}.md`;\n const tmpPath = join(tmpDir, tmpFilename);\n\n const prompt = buildCommitPrompt(genOpts);\n fileLoggerStorage.getStore()?.prompt(\"commit\", prompt);\n\n const sessionId = await provider.createSession();\n log.debug(`Commit prompt built (${prompt.length} chars)`);\n const response = await provider.prompt(sessionId, prompt);\n if (response) fileLoggerStorage.getStore()?.response(\"commit\", response);\n\n if (!response?.trim()) {\n return {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n success: false,\n error: \"Commit agent returned empty response\",\n };\n }\n\n log.debug(`Commit agent response (${response.length} chars)`);\n\n const parsed = parseCommitResponse(response);\n\n if (!parsed.commitMessage && !parsed.prTitle) {\n return {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n success: false,\n error:\n \"Failed to parse commit agent response: no commit message or PR title found\",\n };\n }\n\n const outputContent = formatOutputFile(parsed);\n await writeFile(tmpPath, outputContent, \"utf-8\");\n log.debug(`Wrote commit agent output to ${tmpPath}`);\n\n fileLoggerStorage.getStore()?.agentEvent(\"commit\", \"completed\", `message: ${parsed.commitMessage.slice(0, 80)}`);\n return {\n ...parsed,\n success: true,\n outputPath: tmpPath,\n };\n } catch (err) {\n fileLoggerStorage.getStore()?.error(`commit error: ${log.extractMessage(err)}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n const message = log.extractMessage(err);\n return {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n success: false,\n error: message,\n };\n }\n },\n\n async cleanup(): Promise<void> {\n // Commit agent has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n\n/**\n * Build the prompt that instructs the AI to analyze the branch diff and\n * generate a conventional commit message, PR title, and PR description.\n */\nexport function buildCommitPrompt(opts: CommitGenerateOptions): string {\n const { branchDiff, issue, taskResults } = opts;\n\n const sections: string[] = [\n `You are a **commit message agent**. Your job is to analyze the git diff below and generate a meaningful, conventional-commit-compliant commit message, a PR title, and a PR description.`,\n ``,\n formatEnvironmentPrompt(),\n ``,\n `## Conventional Commit Guidelines`,\n ``,\n `Follow the Conventional Commits specification (https://www.conventionalcommits.org/):`,\n `- Format: \\`<type>(<optional scope>): <description>\\``,\n `- Types: \\`feat\\`, \\`fix\\`, \\`docs\\`, \\`refactor\\`, \\`test\\`, \\`chore\\`, \\`style\\`, \\`perf\\`, \\`ci\\``,\n `- The description should be concise, imperative mood, lowercase first letter, no period at the end`,\n `- If the change includes breaking changes, add \\`!\\` after the type/scope (e.g., \\`feat!: ...\\`)`,\n ``,\n `## Issue Context`,\n ``,\n `- **Issue #${issue.number}:** ${issue.title}`,\n ];\n\n if (issue.body) {\n sections.push(\n `- **Description:** ${issue.body.slice(0, 500)}${issue.body.length > 500 ? \"...\" : \"\"}`\n );\n }\n\n if (issue.labels.length > 0) {\n sections.push(`- **Labels:** ${issue.labels.join(\", \")}`);\n }\n\n const completed = taskResults.filter((r) => r.success);\n const failed = taskResults.filter((r) => !r.success);\n\n if (taskResults.length > 0) {\n sections.push(``, `## Tasks`);\n if (completed.length > 0) {\n sections.push(``, `### Completed`);\n for (const r of completed) {\n sections.push(`- ${r.task.text}`);\n }\n }\n if (failed.length > 0) {\n sections.push(``, `### Failed`);\n for (const r of failed) {\n sections.push(\n `- ${r.task.text}${r.error ? ` (error: ${r.error})` : \"\"}`\n );\n }\n }\n }\n\n const maxDiffLength = 50_000;\n const truncatedDiff =\n branchDiff.length > maxDiffLength\n ? branchDiff.slice(0, maxDiffLength) +\n \"\\n\\n... (diff truncated due to size)\"\n : branchDiff;\n\n sections.push(\n ``,\n `## Git Diff`,\n ``,\n `\\`\\`\\`diff`,\n truncatedDiff,\n `\\`\\`\\``,\n ``,\n `## Required Output Format`,\n ``,\n `You MUST respond with exactly the following three sections, using these exact headers:`,\n ``,\n `### COMMIT_MESSAGE`,\n `<your conventional commit message here>`,\n ``,\n `### PR_TITLE`,\n `<your PR title here>`,\n ``,\n `### PR_DESCRIPTION`,\n `<your PR description in markdown here>`,\n ``,\n `**Rules:**`,\n `- The commit message MUST follow conventional commit format`,\n `- The PR title should be a concise, descriptive summary of the overall change`,\n `- The PR description should explain what changed and why, referencing the issue context`,\n `- Do NOT include any text outside these three sections`\n );\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Parse the AI agent's structured response into commit message, PR title,\n * and PR description. Uses robust matching to handle minor formatting\n * variations.\n */\nexport function parseCommitResponse(response: string): {\n commitMessage: string;\n prTitle: string;\n prDescription: string;\n} {\n const result = {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n };\n\n const commitMatch = response.match(\n /###\\s*COMMIT_MESSAGE\\s*\\n([\\s\\S]*?)(?=###\\s*PR_TITLE|$)/i\n );\n const titleMatch = response.match(\n /###\\s*PR_TITLE\\s*\\n([\\s\\S]*?)(?=###\\s*PR_DESCRIPTION|$)/i\n );\n const descMatch = response.match(\n /###\\s*PR_DESCRIPTION\\s*\\n([\\s\\S]*?)$/i\n );\n\n if (commitMatch?.[1]) {\n result.commitMessage = commitMatch[1].trim();\n }\n if (titleMatch?.[1]) {\n result.prTitle = titleMatch[1].trim();\n }\n if (descMatch?.[1]) {\n result.prDescription = descMatch[1].trim();\n }\n\n return result;\n}\n\n/**\n * Format the parsed results into a markdown file for pipeline consumption.\n */\nfunction formatOutputFile(parsed: {\n commitMessage: string;\n prTitle: string;\n prDescription: string;\n}): string {\n const sections: string[] = [\n `# Commit Agent Output`,\n ``,\n `## Commit Message`,\n ``,\n parsed.commitMessage,\n ``,\n `## PR Title`,\n ``,\n parsed.prTitle,\n ``,\n `## PR Description`,\n ``,\n parsed.prDescription,\n ``,\n ];\n return sections.join(\"\\n\");\n}\n","/**\n * TUI renderer — draws a real-time dashboard to the terminal showing\n * dispatch progress, current task, and results.\n */\n\nimport chalk from \"chalk\";\nimport { elapsed, renderHeaderLines } from \"./helpers/format.js\";\nimport type { Task } from \"./parser.js\";\n\nexport type TaskStatus = \"pending\" | \"planning\" | \"running\" | \"done\" | \"failed\";\n\nexport interface TaskState {\n task: Task;\n status: TaskStatus;\n elapsed?: number;\n error?: string;\n /** Worktree directory name when running in a worktree (e.g. \"123-fix-auth-bug\") */\n worktree?: string;\n}\n\nexport interface TuiState {\n tasks: TaskState[];\n phase: \"discovering\" | \"parsing\" | \"booting\" | \"dispatching\" | \"done\";\n startTime: number;\n filesFound: number;\n serverUrl?: string;\n /** Active provider name — shown in the booting phase */\n provider?: string;\n /** Model identifier reported by the provider, if available */\n model?: string;\n /** Datasource name (e.g. \"github\", \"azdevops\", \"md\") */\n source?: string;\n /** Currently-processing issue context (number + title) */\n currentIssue?: { number: string; title: string };\n}\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst BAR_WIDTH = 30;\n\nlet spinnerIndex = 0;\nlet interval: ReturnType<typeof setInterval> | null = null;\nlet lastLineCount = 0;\n\nfunction spinner(): string {\n return chalk.cyan(SPINNER_FRAMES[spinnerIndex % SPINNER_FRAMES.length]);\n}\n\nfunction progressBar(done: number, total: number): string {\n if (total === 0) return chalk.dim(\"░\".repeat(BAR_WIDTH));\n const filled = Math.round((done / total) * BAR_WIDTH);\n const empty = BAR_WIDTH - filled;\n const pct = Math.round((done / total) * 100);\n return (\n chalk.green(\"█\".repeat(filled)) +\n chalk.dim(\"░\".repeat(empty)) +\n chalk.white(` ${pct}%`)\n );\n}\n\nfunction statusIcon(status: TaskStatus): string {\n switch (status) {\n case \"pending\":\n return chalk.dim(\"○\");\n case \"planning\":\n return spinner();\n case \"running\":\n return spinner();\n case \"done\":\n return chalk.green(\"●\");\n case \"failed\":\n return chalk.red(\"✖\");\n }\n}\n\nfunction statusLabel(status: TaskStatus): string {\n switch (status) {\n case \"pending\":\n return chalk.dim(\"pending\");\n case \"planning\":\n return chalk.magenta(\"planning\");\n case \"running\":\n return chalk.cyan(\"executing\");\n case \"done\":\n return chalk.green(\"done\");\n case \"failed\":\n return chalk.red(\"failed\");\n }\n}\n\nfunction phaseLabel(phase: TuiState[\"phase\"], provider?: string): string {\n switch (phase) {\n case \"discovering\":\n return `${spinner()} Discovering task files...`;\n case \"parsing\":\n return `${spinner()} Parsing tasks...`;\n case \"booting\": {\n const name = provider ?? \"provider\";\n return `${spinner()} Connecting to ${name}...`;\n }\n case \"dispatching\":\n return `${spinner()} Dispatching tasks...`;\n case \"done\":\n return chalk.green(\"✔\") + \" Complete\";\n }\n}\n\nfunction countVisualRows(text: string, cols: number): number {\n const stripped = text.replace(/\\x1B\\[[0-9;]*m/g, \"\");\n const safeCols = Math.max(1, cols);\n return stripped.split(\"\\n\").reduce((sum, line) => {\n return sum + Math.max(1, Math.ceil(line.length / safeCols));\n }, 0);\n}\n\nfunction render(state: TuiState): string {\n const lines: string[] = [];\n const now = Date.now();\n const totalElapsed = elapsed(now - state.startTime);\n\n const done = state.tasks.filter((t) => t.status === \"done\").length;\n const failed = state.tasks.filter((t) => t.status === \"failed\").length;\n const total = state.tasks.length;\n\n // ── Header ──────────────────────────────────────────────────\n lines.push(\"\");\n lines.push(\n ...renderHeaderLines({\n provider: state.provider,\n model: state.model,\n source: state.source,\n })\n );\n\n if (state.currentIssue) {\n lines.push(\n chalk.dim(` issue: `) + chalk.white(`#${state.currentIssue.number}`) + chalk.dim(` — ${state.currentIssue.title}`)\n );\n }\n\n lines.push(chalk.dim(\" ─\".repeat(24)));\n\n // ── Phase + Timer ───────────────────────────────────────────\n lines.push(` ${phaseLabel(state.phase, state.provider)}` + chalk.dim(` ${totalElapsed}`));\n\n if (state.phase === \"dispatching\" || state.phase === \"done\") {\n // ── Progress bar ────────────────────────────────────────\n lines.push(\"\");\n lines.push(` ${progressBar(done + failed, total)} ${chalk.dim(`${done + failed}/${total} tasks`)}`);\n lines.push(\"\");\n\n // ── Task list ───────────────────────────────────────────\n // Determine if multiple worktrees are active (show indicator only when >1)\n const activeWorktrees = new Set(\n state.tasks.map((t) => t.worktree).filter(Boolean)\n );\n const showWorktree = activeWorktrees.size > 1;\n\n const cols = process.stdout.columns || 80;\n const maxTextLen = cols - 30;\n\n const running = state.tasks.filter((t) => t.status === \"running\" || t.status === \"planning\");\n const completed = state.tasks.filter(\n (t) => t.status === \"done\" || t.status === \"failed\"\n );\n const pending = state.tasks.filter((t) => t.status === \"pending\");\n\n if (showWorktree) {\n // ── Grouped-by-worktree display ───────────────────────\n const groups = new Map<string, TaskState[]>();\n const ungrouped: TaskState[] = [];\n for (const ts of state.tasks) {\n if (ts.worktree) {\n const arr = groups.get(ts.worktree) ?? [];\n arr.push(ts);\n groups.set(ts.worktree, arr);\n } else {\n ungrouped.push(ts);\n }\n }\n\n const doneGroups: [string, TaskState[]][] = [];\n const activeGroups: [string, TaskState[]][] = [];\n for (const [wt, tasks] of groups) {\n const allDone = tasks.every((t) => t.status === \"done\" || t.status === \"failed\");\n if (allDone) {\n doneGroups.push([wt, tasks]);\n } else {\n activeGroups.push([wt, tasks]);\n }\n }\n\n // Done groups (collapsed, last 3)\n if (doneGroups.length > 3) {\n lines.push(chalk.dim(` ··· ${doneGroups.length - 3} earlier issue(s) completed`));\n }\n for (const [wt, tasks] of doneGroups.slice(-3)) {\n const issueNum = wt.match(/^(\\d+)/)?.[1] ?? wt.slice(0, 12);\n const anyFailed = tasks.some((t) => t.status === \"failed\");\n const icon = anyFailed ? chalk.red(\"✖\") : chalk.green(\"●\");\n const doneCount = tasks.filter((t) => t.status === \"done\").length;\n const maxElapsed = Math.max(...tasks.map((t) => t.elapsed ?? 0));\n lines.push(` ${icon} ${chalk.dim(`#${issueNum}`)} ${chalk.dim(`${doneCount}/${tasks.length} tasks`)} ${chalk.dim(elapsed(maxElapsed))}`);\n }\n\n // Active groups (one row per group)\n for (const [wt, tasks] of activeGroups) {\n const issueNum = wt.match(/^(\\d+)/)?.[1] ?? wt.slice(0, 12);\n const activeTasks = tasks.filter((t) => t.status === \"running\" || t.status === \"planning\");\n const activeCount = activeTasks.length;\n const firstActive = activeTasks[0];\n const truncLen = Math.min(cols - 26, 60);\n let text = firstActive?.task.text ?? \"\";\n if (text.length > truncLen) {\n text = text.slice(0, truncLen - 1) + \"…\";\n }\n const earliest = Math.min(...activeTasks.map((t) => t.elapsed ?? now));\n const elapsedStr = elapsed(now - earliest);\n lines.push(` ${spinner()} ${chalk.white(`#${issueNum}`)} ${activeCount} active ${text} ${chalk.dim(elapsedStr)}`);\n }\n\n // Ungrouped tasks (only running/planning, flat)\n for (const ts of ungrouped) {\n if (ts.status !== \"running\" && ts.status !== \"planning\") continue;\n const icon = statusIcon(ts.status);\n const idx = chalk.dim(`#${state.tasks.indexOf(ts) + 1}`);\n let text = ts.task.text;\n if (text.length > maxTextLen) {\n text = text.slice(0, maxTextLen - 1) + \"…\";\n }\n const elapsedStr = chalk.dim(` ${elapsed(now - (ts.elapsed || now))}`);\n const label = statusLabel(ts.status);\n lines.push(` ${icon} ${idx} ${text} ${label}${elapsedStr}`);\n if (ts.error) {\n lines.push(chalk.red(` └─ ${ts.error}`));\n }\n }\n } else {\n // ── Flat display with running cap ─────────────────────\n const visibleRunning = running.slice(0, 8);\n const visible: TaskState[] = [\n ...completed.slice(-3),\n ...visibleRunning,\n ...pending.slice(0, 3),\n ];\n\n if (completed.length > 3) {\n lines.push(chalk.dim(` ··· ${completed.length - 3} earlier task(s) completed`));\n }\n\n for (const ts of visible) {\n const icon = statusIcon(ts.status);\n const idx = chalk.dim(`#${state.tasks.indexOf(ts) + 1}`);\n let text = ts.task.text;\n if (text.length > maxTextLen) {\n text = text.slice(0, maxTextLen - 1) + \"…\";\n }\n\n const elapsedStr =\n ts.status === \"running\" || ts.status === \"planning\"\n ? chalk.dim(` ${elapsed(now - (ts.elapsed || now))}`)\n : ts.status === \"done\" && ts.elapsed\n ? chalk.dim(` ${elapsed(ts.elapsed)}`)\n : \"\";\n\n const label = statusLabel(ts.status);\n\n lines.push(` ${icon} ${idx} ${text} ${label}${elapsedStr}`);\n\n if (ts.error) {\n lines.push(chalk.red(` └─ ${ts.error}`));\n }\n }\n\n if (running.length > 8) {\n lines.push(chalk.dim(` ··· ${running.length - 8} more running`));\n }\n\n if (pending.length > 3) {\n lines.push(chalk.dim(` ··· ${pending.length - 3} more task(s) pending`));\n }\n }\n\n // ── Summary line ────────────────────────────────────────\n lines.push(\"\");\n const parts: string[] = [];\n if (done > 0) parts.push(chalk.green(`${done} passed`));\n if (failed > 0) parts.push(chalk.red(`${failed} failed`));\n if (total - done - failed > 0)\n parts.push(chalk.dim(`${total - done - failed} remaining`));\n lines.push(` ${parts.join(chalk.dim(\" · \"))}`);\n } else if (state.filesFound > 0) {\n lines.push(chalk.dim(` Found ${state.filesFound} file(s)`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Clear the previous render and draw a new frame.\n * Uses a single-write, per-line overwrite strategy to eliminate flicker.\n */\nfunction draw(state: TuiState): void {\n const output = render(state);\n const cols = process.stdout.columns || 80;\n const newLineCount = countVisualRows(output, cols);\n\n let buffer = \"\";\n\n // Move cursor up to the beginning of the previous frame\n if (lastLineCount > 0) {\n buffer += `\\x1B[${lastLineCount}A`;\n }\n\n // Append each line with \\x1B[K (Erase to End of Line)\n const lines = output.split(\"\\n\");\n buffer += lines.map((line) => line + \"\\x1B[K\").join(\"\\n\");\n\n // Clean up leftover rows if new frame is shorter than previous\n const leftover = lastLineCount - newLineCount;\n if (leftover > 0) {\n for (let i = 0; i < leftover; i++) {\n buffer += \"\\n\\x1B[K\";\n }\n buffer += `\\x1B[${leftover}A`;\n }\n\n process.stdout.write(buffer);\n lastLineCount = newLineCount;\n}\n\n/**\n * Create and start the TUI — returns a controller to update state.\n */\nexport function createTui(): {\n state: TuiState;\n update: () => void;\n stop: () => void;\n} {\n const state: TuiState = {\n tasks: [],\n phase: \"discovering\",\n startTime: Date.now(),\n filesFound: 0,\n };\n\n // Animate spinner at ~80ms\n interval = setInterval(() => {\n spinnerIndex++;\n draw(state);\n }, 80);\n\n const update = () => draw(state);\n\n const stop = () => {\n if (interval) {\n clearInterval(interval);\n interval = null;\n }\n draw(state);\n };\n\n draw(state);\n\n return { state, update, stop };\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAS,W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AEJ,SAAO;AAAA,IACL,6EAA6E,OAAO;AAAA,IACpF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK,GAAG;AAAA,IACR;AAAA,IACA,wBAAwB;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK,UAAU;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;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,QAAM,EAAE,MAAM,GAAG,SAAS,IAAI,GAAG,QAAQ,IAAI;AAC7C,QAAM,UAAU,MAAM,aAAa,WAAW,EAAE,GAAG,SAAS,cAAc,CAAC;AAG3E,QAAM,SAAS,YAAY,UAAU,QAAQ,SAAU,aAAa,WAAW,CAAC,QAAQ,UAAU,IAAI;AACtG,UAAQ,KAAK,SAAS,IAAI,IAAI,CAAC;AACjC;AAEA,KAAK,EAAE,MAAM,OAAO,QAAQ;AAC1B,MAAI,MAAM,IAAI,iBAAiB,GAAG,CAAC;AACnC,QAAM,WAAW;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["resolve","listModels","boot","resolve","listModels","boot","randomUUID","listModels","boot","execFile","promisify","exec","boot","listModels","readFile","join","resolve","resolve","join","execFile","promisify","input","execFile","promisify","exec","promisify","execFile","datasource","execFile","readFile","writeFile","mkdir","dirname","join","promisify","join","dirname","chalk","chalk","join","dirname","exec","promisify","execFile","git","join","datasource","mdFiles","results","readFile","dir","dirname","content","writeFile","mkdir","exec","promisify","execFile","datasource","input","basename","join","writeFile","execFile","promisify","exec","promisify","execFile","basename","datasource","join","writeFile","exec","join","basename","execFile","promisify","randomUUID","exec","promisify","execFile","git","basename","join","randomUUID","input","chalk","execFile","promisify","exec","readFile","writeFile","join","join","join","join","mkdir","readFile","rename","unlink","glob","mkdir","readFile","writeFile","join","resolve","randomUUID","boot","resolve","join","mkdir","randomUUID","readFile","writeFile","chalk","chalk","datasource","join","glob","readFile","chalk","boot","mkdir","rename","unlink","execFile","promisify","readFile","glob","readFile","writeFile","readFile","writeFile","boot","boot","input","mkdir","writeFile","join","resolve","randomUUID","boot","chalk","chalk","chalk","exec","promisify","execFile","glob","readFile","chalk","datasource","boot","runFixTestsPipeline","datasource","boot","opts","_","rest","resolve","join","boot"]}
1
+ {"version":3,"sources":["../src/helpers/file-logger.ts","../src/helpers/logger.ts","../src/helpers/guards.ts","../src/providers/opencode.ts","../src/helpers/timeout.ts","../node_modules/vscode-jsonrpc/lib/common/is.js","../node_modules/vscode-jsonrpc/lib/common/messages.js","../node_modules/vscode-jsonrpc/lib/common/linkedMap.js","../node_modules/vscode-jsonrpc/lib/common/disposable.js","../node_modules/vscode-jsonrpc/lib/common/ral.js","../node_modules/vscode-jsonrpc/lib/common/events.js","../node_modules/vscode-jsonrpc/lib/common/cancellation.js","../node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js","../node_modules/vscode-jsonrpc/lib/common/semaphore.js","../node_modules/vscode-jsonrpc/lib/common/messageReader.js","../node_modules/vscode-jsonrpc/lib/common/messageWriter.js","../node_modules/vscode-jsonrpc/lib/common/messageBuffer.js","../node_modules/vscode-jsonrpc/lib/common/connection.js","../node_modules/vscode-jsonrpc/lib/common/api.js","../node_modules/vscode-jsonrpc/lib/node/ril.js","../node_modules/vscode-jsonrpc/lib/node/main.js","../node_modules/vscode-jsonrpc/node.js","../node_modules/@github/copilot-sdk/dist/generated/rpc.js","../node_modules/@github/copilot-sdk/dist/sdkProtocolVersion.js","../node_modules/@github/copilot-sdk/dist/session.js","../node_modules/@github/copilot-sdk/dist/client.js","../node_modules/@github/copilot-sdk/dist/types.js","../node_modules/@github/copilot-sdk/dist/index.js","../src/providers/copilot.ts","../src/providers/claude.ts","../src/providers/codex.ts","../src/providers/detect.ts","../src/providers/index.ts","../src/helpers/cleanup.ts","../src/helpers/environment.ts","../src/orchestrator/fix-tests-pipeline.ts","../src/cli.ts","../src/spec-generator.ts","../src/datasources/index.ts","../src/datasources/github.ts","../src/helpers/slugify.ts","../src/helpers/branch-validation.ts","../src/helpers/auth.ts","../src/constants.ts","../src/datasources/azdevops.ts","../src/datasources/md.ts","../src/config.ts","../src/config-prompts.ts","../src/orchestrator/datasource-helpers.ts","../src/helpers/worktree.ts","../src/orchestrator/runner.ts","../src/helpers/confirm-large-batch.ts","../src/helpers/prereqs.ts","../src/helpers/gitignore.ts","../src/orchestrator/cli-config.ts","../src/orchestrator/spec-pipeline.ts","../src/agents/spec.ts","../src/helpers/format.ts","../src/helpers/retry.ts","../src/orchestrator/dispatch-pipeline.ts","../src/parser.ts","../src/agents/planner.ts","../src/dispatcher.ts","../src/agents/executor.ts","../src/agents/commit.ts","../src/tui.ts"],"sourcesContent":["/**\n * Per-issue file logger for detailed, structured log output.\n *\n * Writes timestamped, plain-text log entries to `.dispatch/logs/issue-{id}.log`.\n * Each log line is prefixed with an ISO 8601 timestamp. The logger provides\n * standard level methods (`info`, `debug`, `warn`, `error`) plus structured\n * methods for prompts, responses, phase transitions, and agent lifecycle events.\n *\n * An `AsyncLocalStorage<FileLogger>` instance is exported for scoping file\n * loggers to async contexts, allowing each issue processed in parallel to\n * maintain its own log file without threading parameters through call stacks.\n */\n\nimport { mkdirSync, writeFileSync, appendFileSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport const fileLoggerStorage = new AsyncLocalStorage<FileLogger>();\n\nexport class FileLogger {\n readonly filePath: string;\n\n private static sanitizeIssueId(issueId: string | number): string {\n const raw = String(issueId);\n return raw.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n }\n\n constructor(issueId: string | number, cwd: string) {\n const safeIssueId = FileLogger.sanitizeIssueId(issueId);\n this.filePath = join(cwd, \".dispatch\", \"logs\", `issue-${safeIssueId}.log`);\n mkdirSync(dirname(this.filePath), { recursive: true });\n writeFileSync(this.filePath, \"\", \"utf-8\");\n }\n\n private write(level: string, message: string): void {\n const timestamp = new Date().toISOString();\n const line = `[${timestamp}] [${level}] ${message}\\n`;\n appendFileSync(this.filePath, line, \"utf-8\");\n }\n\n info(message: string): void {\n this.write(\"INFO\", message);\n }\n\n debug(message: string): void {\n this.write(\"DEBUG\", message);\n }\n\n warn(message: string): void {\n this.write(\"WARN\", message);\n }\n\n error(message: string): void {\n this.write(\"ERROR\", message);\n }\n\n success(message: string): void {\n this.write(\"SUCCESS\", message);\n }\n\n task(message: string): void {\n this.write(\"TASK\", message);\n }\n\n dim(message: string): void {\n this.write(\"DIM\", message);\n }\n\n prompt(label: string, content: string): void {\n const separator = \"─\".repeat(40);\n this.write(\"PROMPT\", `${label}\\n${separator}\\n${content}\\n${separator}`);\n }\n\n response(label: string, content: string): void {\n const separator = \"─\".repeat(40);\n this.write(\"RESPONSE\", `${label}\\n${separator}\\n${content}\\n${separator}`);\n }\n\n phase(name: string): void {\n const banner = \"═\".repeat(40);\n this.write(\"PHASE\", `${banner}\\n${name}\\n${banner}`);\n }\n\n agentEvent(agent: string, event: string, detail?: string): void {\n const msg = detail ? `[${agent}] ${event}: ${detail}` : `[${agent}] ${event}`;\n this.write(\"AGENT\", msg);\n }\n\n close(): void {\n // no-op for sync writes; provides a cleanup hook for future use\n }\n}\n","/**\n * Minimal structured logger for CLI output.\n *\n * The initial log level is resolved at module load from environment variables:\n * 1. `LOG_LEVEL` env var — one of `\"debug\"`, `\"info\"`, `\"warn\"`, `\"error\"`\n * 2. `DEBUG` env var — any truthy value sets the level to `\"debug\"`\n * 3. Default: `\"info\"`\n *\n * At runtime, `log.verbose` (or the `--verbose` CLI flag) can override the\n * env-resolved level — setting it to `true` forces `\"debug\"`, and `false`\n * resets to `\"info\"` regardless of the original env value.\n */\n\nimport chalk from \"chalk\";\nimport { fileLoggerStorage } from \"./file-logger.js\";\n\n/** Supported log levels, ordered from most to least verbose. */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVEL_SEVERITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Resolve the effective log level from environment variables.\n * Priority: LOG_LEVEL > DEBUG > default (\"info\").\n */\nfunction resolveLogLevel(): LogLevel {\n const envLevel = process.env.LOG_LEVEL?.toLowerCase();\n if (envLevel && Object.hasOwn(LOG_LEVEL_SEVERITY, envLevel)) {\n return envLevel as LogLevel;\n }\n if (process.env.DEBUG) {\n return \"debug\";\n }\n return \"info\";\n}\n\n/** Current effective log level. */\nlet currentLevel: LogLevel = resolveLogLevel();\n\n/** Returns the current effective log level. */\nexport function getLogLevel(): LogLevel {\n return currentLevel;\n}\n\nfunction shouldLog(level: LogLevel): boolean {\n return LOG_LEVEL_SEVERITY[level] >= LOG_LEVEL_SEVERITY[currentLevel];\n}\n\n/** Strip ANSI escape codes from a string for plain-text file logging. */\nfunction stripAnsi(str: string): string {\n return str.replace(/\\x1B\\[[0-9;]*m/g, \"\");\n}\n\n/** Maximum depth to traverse when unwinding nested error `.cause` chains. */\nconst MAX_CAUSE_CHAIN_DEPTH = 5;\n\nexport const log = {\n verbose: false as boolean,\n\n info(msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.blue(\"ℹ\"), msg);\n fileLoggerStorage.getStore()?.info(stripAnsi(msg));\n },\n success(msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.green(\"✔\"), msg);\n fileLoggerStorage.getStore()?.success(stripAnsi(msg));\n },\n warn(msg: string) {\n if (!shouldLog(\"warn\")) return;\n console.error(chalk.yellow(\"⚠\"), msg);\n fileLoggerStorage.getStore()?.warn(stripAnsi(msg));\n },\n error(msg: string) {\n if (!shouldLog(\"error\")) return;\n console.error(chalk.red(\"✖\"), msg);\n fileLoggerStorage.getStore()?.error(stripAnsi(msg));\n },\n task(index: number, total: number, msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.cyan(`[${index + 1}/${total}]`), msg);\n fileLoggerStorage.getStore()?.task(stripAnsi(`[${index + 1}/${total}] ${msg}`));\n },\n dim(msg: string) {\n if (!shouldLog(\"info\")) return;\n console.log(chalk.dim(msg));\n fileLoggerStorage.getStore()?.dim(stripAnsi(msg));\n },\n\n /**\n * Print a debug/verbose message. Only visible when the log level is\n * `\"debug\"`. Messages are prefixed with a dim arrow to visually nest\n * them under the preceding info/error line.\n */\n debug(msg: string) {\n if (!shouldLog(\"debug\")) return;\n console.log(chalk.dim(` ⤷ ${msg}`));\n fileLoggerStorage.getStore()?.debug(stripAnsi(msg));\n },\n\n /**\n * Extract and format the full error cause chain. Node.js network errors\n * (e.g. `TypeError: fetch failed`) bury the real reason in nested `.cause`\n * properties — this helper surfaces them all.\n */\n formatErrorChain(err: unknown): string {\n const parts: string[] = [];\n let current: unknown = err;\n let depth = 0;\n\n while (current && depth < MAX_CAUSE_CHAIN_DEPTH) {\n if (current instanceof Error) {\n const prefix = depth === 0 ? \"Error\" : \"Cause\";\n parts.push(`${prefix}: ${current.message}`);\n if (current.cause) {\n current = current.cause;\n } else {\n break;\n }\n } else {\n parts.push(`${depth === 0 ? \"Error\" : \"Cause\"}: ${String(current)}`);\n break;\n }\n depth++;\n }\n\n return parts.join(\"\\n ⤷ \");\n },\n\n /**\n * Extract the raw error message string from an unknown thrown value.\n * Returns `err.message` for Error instances, `String(err)` for other\n * truthy values, and `\"\"` for null/undefined.\n */\n extractMessage(err: unknown): string {\n if (err instanceof Error) return err.message;\n if (err != null) return String(err);\n return \"\";\n },\n};\n\nObject.defineProperty(log, \"verbose\", {\n get(): boolean {\n return currentLevel === \"debug\";\n },\n set(value: boolean) {\n currentLevel = value ? \"debug\" : \"info\";\n },\n enumerable: true,\n configurable: true,\n});\n","/**\n * Runtime type guard utilities.\n *\n * Provides small, reusable type predicates that validate unknown values\n * at runtime, enabling safe property access without unsafe `as` casts.\n */\n\n/**\n * Check whether an unknown value is a non-null object that contains\n * the specified key.\n *\n * Narrows the value to `Record<K, unknown>` so the caller can safely\n * access `value[key]` without an `as` cast.\n *\n * @param value - The value to inspect (may be any type).\n * @param key - The property name to look for.\n * @returns `true` when `value` is an object with the given key.\n */\nexport function hasProperty<K extends string>(\n value: unknown,\n key: K,\n): value is Record<K, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n","/**\n * OpenCode provider — wraps the @opencode-ai/sdk to conform to the\n * generic ProviderInstance interface.\n *\n * Uses the asynchronous prompt API (`promptAsync`) combined with SSE\n * event streaming to avoid HTTP timeout issues. The blocking `prompt()`\n * SDK method sends a single long-lived HTTP request that can exceed\n * Node.js/undici's default headers timeout for slow LLM responses.\n *\n * Flow:\n * 1. `promptAsync()` — fire-and-forget POST that returns 204 immediately\n * 2. `event.subscribe()` — SSE stream that yields session lifecycle events\n * 3. Wait for `session.idle` (success) or `session.error` (failure)\n * 4. `session.messages()` — fetch the completed response\n */\n\nimport {\n createOpencode,\n createOpencodeClient,\n type OpencodeClient,\n type Part,\n type TextPart,\n type Event as SdkEvent,\n} from \"@opencode-ai/sdk\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { hasProperty } from \"../helpers/guards.js\";\n\n/**\n * List available OpenCode models for configured providers.\n *\n * Starts a temporary server (or connects to an existing one), fetches\n * providers that have an API key configured, and returns their models\n * in \"providerId/modelId\" format (e.g. \"anthropic/claude-sonnet-4\").\n */\nexport async function listModels(opts?: ProviderBootOptions): Promise<string[]> {\n let client: OpencodeClient;\n let stopServer: (() => void) | undefined;\n\n if (opts?.url) {\n client = createOpencodeClient({ baseUrl: opts.url });\n } else {\n // See boot() for details on the SDK cwd limitation.\n if (opts?.cwd) {\n log.debug(`listModels: requested cwd \"${opts.cwd}\" — OpenCode SDK does not support spawn-level cwd`);\n }\n try {\n const oc = await createOpencode({ port: 0 });\n client = oc.client;\n stopServer = () => oc.server.close();\n } catch (err) {\n log.debug(`listModels: failed to start OpenCode server: ${log.formatErrorChain(err)}`);\n throw err;\n }\n }\n\n try {\n const { data } = await client.config.providers();\n if (!data) return [];\n return data.providers\n .filter((p) => p.source === \"env\" || p.source === \"config\" || p.source === \"custom\")\n .flatMap((p) => Object.keys(p.models).map((modelId) => `${p.id}/${modelId}`))\n .sort();\n } finally {\n stopServer?.();\n }\n}\n\n/**\n * Boot an OpenCode instance — either connect to a running server\n * or start a new one.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n let client: OpencodeClient;\n let stopServer: (() => void) | undefined;\n let cleaned = false;\n\n if (opts?.url) {\n log.debug(`Connecting to existing OpenCode server at ${opts.url}`);\n client = createOpencodeClient({ baseUrl: opts.url });\n } else {\n log.debug(\"No --server-url provided, spawning local OpenCode server...\");\n // NOTE: The @opencode-ai/sdk `createOpencodeServer` spawns the `opencode`\n // process via `child_process.spawn()` without a `cwd` option — the server\n // inherits `process.cwd()`. There is no `ServerOptions.cwd` or `Config`\n // field to control the working directory. When a worktree `cwd` is needed,\n // the prompt-level cwd (set by the executor/dispatcher) ensures the agent\n // operates in the correct directory.\n if (opts?.cwd) {\n log.debug(`Requested cwd \"${opts.cwd}\" — OpenCode SDK does not support spawn-level cwd; relying on prompt-level cwd`);\n }\n try {\n const oc = await createOpencode({ port: 0 });\n client = oc.client;\n stopServer = () => oc.server.close();\n log.debug(\"OpenCode server started successfully\");\n } catch (err) {\n log.debug(`Failed to start OpenCode server: ${log.formatErrorChain(err)}`);\n throw err;\n }\n }\n\n // ── Parse model override from boot options ────────────────────\n // Format: \"providerID/modelID\" (e.g. \"anthropic/claude-sonnet-4\")\n let modelOverride: { providerID: string; modelID: string } | undefined;\n if (opts?.model) {\n const slash = opts.model.indexOf(\"/\");\n if (slash > 0) {\n modelOverride = {\n providerID: opts.model.slice(0, slash),\n modelID: opts.model.slice(slash + 1),\n };\n log.debug(`Model override: ${opts.model}`);\n } else {\n log.debug(`Ignoring model override \"${opts.model}\": must be in \"provider/model\" format`);\n }\n }\n\n // ── Retrieve the active model (best-effort) ──────────────────\n let model: string | undefined = opts?.model;\n if (!model) {\n try {\n const { data: config } = await client.config.get();\n if (config?.model) {\n // model is in \"provider/model\" format (e.g. \"anthropic/claude-sonnet-4\")\n model = config.model;\n log.debug(`Detected model: ${model}`);\n }\n } catch (err) {\n log.debug(`Failed to retrieve model from config: ${log.formatErrorChain(err)}`);\n }\n }\n\n return {\n name: \"opencode\",\n model,\n\n async createSession(): Promise<string> {\n log.debug(\"Creating OpenCode session...\");\n try {\n const { data: session } = await client.session.create();\n if (!session) {\n throw new Error(\"Failed to create OpenCode session\");\n }\n log.debug(`Session created: ${session.id}`);\n return session.id;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n log.debug(`Sending async prompt to session ${sessionId} (${text.length} chars)...`);\n\n let controller: AbortController | undefined;\n\n try {\n // ── 1. Fire-and-forget: start the LLM processing ──────────\n const { error: promptError } = await client.session.promptAsync({\n path: { id: sessionId },\n body: {\n parts: [{ type: \"text\", text }],\n ...(modelOverride ? { model: modelOverride } : {}),\n },\n });\n\n if (promptError) {\n throw new Error(`OpenCode promptAsync failed: ${JSON.stringify(promptError)}`);\n }\n\n log.debug(\"Async prompt accepted, subscribing to events...\");\n\n // ── 2. Subscribe to SSE events ────────────────────────────\n controller = new AbortController();\n try {\n const { stream } = await client.event.subscribe({\n signal: controller.signal,\n });\n\n // ── 3. Wait for session to become idle or error ───────────\n for await (const event of stream) {\n if (!isSessionEvent(event, sessionId)) continue;\n\n if (\n event.type === \"message.part.updated\" &&\n event.properties.part.type === \"text\"\n ) {\n const delta = event.properties.delta;\n if (delta) {\n log.debug(`Streaming text (+${delta.length} chars)...`);\n }\n continue;\n }\n\n if (event.type === \"session.error\") {\n const err = event.properties.error;\n throw new Error(\n `OpenCode session error: ${err ? JSON.stringify(err) : \"unknown error\"}`\n );\n }\n\n if (event.type === \"session.idle\") {\n log.debug(\"Session went idle, fetching result...\");\n break;\n }\n }\n } finally {\n if (controller && !controller.signal.aborted) controller.abort();\n }\n\n // ── 4. Fetch the completed message ────────────────────────\n const { data: messages } = await client.session.messages({\n path: { id: sessionId },\n });\n\n if (!messages || messages.length === 0) {\n log.debug(\"No messages found in session\");\n return null;\n }\n\n const lastAssistant = [...messages]\n .reverse()\n .find((m) => m.info.role === \"assistant\");\n\n if (!lastAssistant) {\n log.debug(\"No assistant message found in session\");\n return null;\n }\n\n // Check for errors on the assistant message\n if (hasProperty(lastAssistant.info, \"error\") && lastAssistant.info.error) {\n throw new Error(\n `OpenCode assistant error: ${JSON.stringify(lastAssistant.info.error)}`\n );\n }\n\n // ── 5. Extract text parts ─────────────────────────────────\n const textParts = lastAssistant.parts.filter(\n (p: Part): p is TextPart => p.type === \"text\" && \"text\" in p\n );\n const result = textParts.map((p: TextPart) => p.text).join(\"\\n\") || null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n if (cleaned) return;\n cleaned = true;\n log.debug(\"Cleaning up OpenCode provider...\");\n try {\n stopServer?.();\n } catch (err) {\n log.debug(`Failed to stop OpenCode server: ${log.formatErrorChain(err)}`);\n }\n },\n };\n}\n\n/**\n * Check whether an SSE event belongs to the given session.\n *\n * Different event types store the session ID in different places:\n * - `session.*` events → `properties.sessionID`\n * - `message.*` events → `properties.info.sessionID` or `properties.part.sessionID`\n */\nfunction isSessionEvent(event: SdkEvent, sessionId: string): boolean {\n const props: unknown = event.properties;\n\n if (!hasProperty(props, \"sessionID\") && !hasProperty(props, \"info\") && !hasProperty(props, \"part\")) {\n return false;\n }\n\n // Direct sessionID on the event (session.idle, session.error, session.status, etc.)\n if (hasProperty(props, \"sessionID\") && props.sessionID === sessionId) return true;\n\n // Nested in .info (message.updated)\n if (hasProperty(props, \"info\") && hasProperty(props.info, \"sessionID\") && props.info.sessionID === sessionId) {\n return true;\n }\n\n // Nested in .part (message.part.updated)\n if (hasProperty(props, \"part\") && hasProperty(props.part, \"sessionID\") && props.part.sessionID === sessionId) {\n return true;\n }\n\n return false;\n}\n","/**\n * Generic promise timeout utility.\n *\n * Provides a reusable `withTimeout` wrapper that races a promise against\n * a `setTimeout` rejection. Used by the dispatch pipeline to bound\n * planning and execution durations. Timeout failures are distinguished\n * from other errors via the custom `TimeoutError` class.\n */\n\n/**\n * Thrown when a `withTimeout` call exceeds the specified duration.\n *\n * The `label` property (if set) identifies which operation timed out,\n * making log output and error messages more diagnosable.\n */\nexport class TimeoutError extends Error {\n /** Optional label identifying the operation that timed out. */\n readonly label?: string;\n\n constructor(ms: number, label?: string) {\n const suffix = label ? ` [${label}]` : \"\";\n super(`Timed out after ${ms}ms${suffix}`);\n this.name = \"TimeoutError\";\n this.label = label;\n }\n}\n\n/**\n * Race a promise against a timeout.\n *\n * If the promise resolves or rejects before `ms` milliseconds, its\n * result is returned (or its error re-thrown). If the timeout fires\n * first, a `TimeoutError` is thrown.\n *\n * The timer is always cleaned up to avoid leaking handles, regardless\n * of which branch wins the race.\n *\n * @param promise - The async operation to time-bound\n * @param ms - Timeout duration in milliseconds\n * @param label - Optional label included in the `TimeoutError` message\n * @returns The resolved value of `promise`\n * @throws {TimeoutError} If the timeout fires before the promise settles\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n label?: string,\n): Promise<T> {\n const p = new Promise<T>((resolve, reject) => {\n let settled = false;\n\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n reject(new TimeoutError(ms, label));\n }, ms);\n\n promise.then(\n (value) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n\n // Attach a no-op handler so the rejection is never briefly \"unhandled\"\n // when the losing side of the race fires during fake-timer advancement.\n p.catch(() => {});\n\n return p;\n}\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;\nfunction boolean(value) {\n return value === true || value === false;\n}\nexports.boolean = boolean;\nfunction string(value) {\n return typeof value === 'string' || value instanceof String;\n}\nexports.string = string;\nfunction number(value) {\n return typeof value === 'number' || value instanceof Number;\n}\nexports.number = number;\nfunction error(value) {\n return value instanceof Error;\n}\nexports.error = error;\nfunction func(value) {\n return typeof value === 'function';\n}\nexports.func = func;\nfunction array(value) {\n return Array.isArray(value);\n}\nexports.array = array;\nfunction stringArray(value) {\n return array(value) && value.every(elem => string(elem));\n}\nexports.stringArray = stringArray;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0;\nconst is = require(\"./is\");\n/**\n * Predefined error codes.\n */\nvar ErrorCodes;\n(function (ErrorCodes) {\n // Defined by JSON RPC\n ErrorCodes.ParseError = -32700;\n ErrorCodes.InvalidRequest = -32600;\n ErrorCodes.MethodNotFound = -32601;\n ErrorCodes.InvalidParams = -32602;\n ErrorCodes.InternalError = -32603;\n /**\n * This is the start range of JSON RPC reserved error codes.\n * It doesn't denote a real error code. No application error codes should\n * be defined between the start and end range. For backwards\n * compatibility the `ServerNotInitialized` and the `UnknownErrorCode`\n * are left in the range.\n *\n * @since 3.16.0\n */\n ErrorCodes.jsonrpcReservedErrorRangeStart = -32099;\n /** @deprecated use jsonrpcReservedErrorRangeStart */\n ErrorCodes.serverErrorStart = -32099;\n /**\n * An error occurred when write a message to the transport layer.\n */\n ErrorCodes.MessageWriteError = -32099;\n /**\n * An error occurred when reading a message from the transport layer.\n */\n ErrorCodes.MessageReadError = -32098;\n /**\n * The connection got disposed or lost and all pending responses got\n * rejected.\n */\n ErrorCodes.PendingResponseRejected = -32097;\n /**\n * The connection is inactive and a use of it failed.\n */\n ErrorCodes.ConnectionInactive = -32096;\n /**\n * Error code indicating that a server received a notification or\n * request before the server has received the `initialize` request.\n */\n ErrorCodes.ServerNotInitialized = -32002;\n ErrorCodes.UnknownErrorCode = -32001;\n /**\n * This is the end range of JSON RPC reserved error codes.\n * It doesn't denote a real error code.\n *\n * @since 3.16.0\n */\n ErrorCodes.jsonrpcReservedErrorRangeEnd = -32000;\n /** @deprecated use jsonrpcReservedErrorRangeEnd */\n ErrorCodes.serverErrorEnd = -32000;\n})(ErrorCodes || (exports.ErrorCodes = ErrorCodes = {}));\n/**\n * An error object return in a response in case a request\n * has failed.\n */\nclass ResponseError extends Error {\n constructor(code, message, data) {\n super(message);\n this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;\n this.data = data;\n Object.setPrototypeOf(this, ResponseError.prototype);\n }\n toJson() {\n const result = {\n code: this.code,\n message: this.message\n };\n if (this.data !== undefined) {\n result.data = this.data;\n }\n return result;\n }\n}\nexports.ResponseError = ResponseError;\nclass ParameterStructures {\n constructor(kind) {\n this.kind = kind;\n }\n static is(value) {\n return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;\n }\n toString() {\n return this.kind;\n }\n}\nexports.ParameterStructures = ParameterStructures;\n/**\n * The parameter structure is automatically inferred on the number of parameters\n * and the parameter type in case of a single param.\n */\nParameterStructures.auto = new ParameterStructures('auto');\n/**\n * Forces `byPosition` parameter structure. This is useful if you have a single\n * parameter which has a literal type.\n */\nParameterStructures.byPosition = new ParameterStructures('byPosition');\n/**\n * Forces `byName` parameter structure. This is only useful when having a single\n * parameter. The library will report errors if used with a different number of\n * parameters.\n */\nParameterStructures.byName = new ParameterStructures('byName');\n/**\n * An abstract implementation of a MessageType.\n */\nclass AbstractMessageSignature {\n constructor(method, numberOfParams) {\n this.method = method;\n this.numberOfParams = numberOfParams;\n }\n get parameterStructures() {\n return ParameterStructures.auto;\n }\n}\nexports.AbstractMessageSignature = AbstractMessageSignature;\n/**\n * Classes to type request response pairs\n */\nclass RequestType0 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 0);\n }\n}\nexports.RequestType0 = RequestType0;\nclass RequestType extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.RequestType = RequestType;\nclass RequestType1 extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.RequestType1 = RequestType1;\nclass RequestType2 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 2);\n }\n}\nexports.RequestType2 = RequestType2;\nclass RequestType3 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 3);\n }\n}\nexports.RequestType3 = RequestType3;\nclass RequestType4 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 4);\n }\n}\nexports.RequestType4 = RequestType4;\nclass RequestType5 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 5);\n }\n}\nexports.RequestType5 = RequestType5;\nclass RequestType6 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 6);\n }\n}\nexports.RequestType6 = RequestType6;\nclass RequestType7 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 7);\n }\n}\nexports.RequestType7 = RequestType7;\nclass RequestType8 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 8);\n }\n}\nexports.RequestType8 = RequestType8;\nclass RequestType9 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 9);\n }\n}\nexports.RequestType9 = RequestType9;\nclass NotificationType extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.NotificationType = NotificationType;\nclass NotificationType0 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 0);\n }\n}\nexports.NotificationType0 = NotificationType0;\nclass NotificationType1 extends AbstractMessageSignature {\n constructor(method, _parameterStructures = ParameterStructures.auto) {\n super(method, 1);\n this._parameterStructures = _parameterStructures;\n }\n get parameterStructures() {\n return this._parameterStructures;\n }\n}\nexports.NotificationType1 = NotificationType1;\nclass NotificationType2 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 2);\n }\n}\nexports.NotificationType2 = NotificationType2;\nclass NotificationType3 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 3);\n }\n}\nexports.NotificationType3 = NotificationType3;\nclass NotificationType4 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 4);\n }\n}\nexports.NotificationType4 = NotificationType4;\nclass NotificationType5 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 5);\n }\n}\nexports.NotificationType5 = NotificationType5;\nclass NotificationType6 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 6);\n }\n}\nexports.NotificationType6 = NotificationType6;\nclass NotificationType7 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 7);\n }\n}\nexports.NotificationType7 = NotificationType7;\nclass NotificationType8 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 8);\n }\n}\nexports.NotificationType8 = NotificationType8;\nclass NotificationType9 extends AbstractMessageSignature {\n constructor(method) {\n super(method, 9);\n }\n}\nexports.NotificationType9 = NotificationType9;\nvar Message;\n(function (Message) {\n /**\n * Tests if the given message is a request message\n */\n function isRequest(message) {\n const candidate = message;\n return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));\n }\n Message.isRequest = isRequest;\n /**\n * Tests if the given message is a notification message\n */\n function isNotification(message) {\n const candidate = message;\n return candidate && is.string(candidate.method) && message.id === void 0;\n }\n Message.isNotification = isNotification;\n /**\n * Tests if the given message is a response message\n */\n function isResponse(message) {\n const candidate = message;\n return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);\n }\n Message.isResponse = isResponse;\n})(Message || (exports.Message = Message = {}));\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LRUCache = exports.LinkedMap = exports.Touch = void 0;\nvar Touch;\n(function (Touch) {\n Touch.None = 0;\n Touch.First = 1;\n Touch.AsOld = Touch.First;\n Touch.Last = 2;\n Touch.AsNew = Touch.Last;\n})(Touch || (exports.Touch = Touch = {}));\nclass LinkedMap {\n constructor() {\n this[_a] = 'LinkedMap';\n this._map = new Map();\n this._head = undefined;\n this._tail = undefined;\n this._size = 0;\n this._state = 0;\n }\n clear() {\n this._map.clear();\n this._head = undefined;\n this._tail = undefined;\n this._size = 0;\n this._state++;\n }\n isEmpty() {\n return !this._head && !this._tail;\n }\n get size() {\n return this._size;\n }\n get first() {\n return this._head?.value;\n }\n get last() {\n return this._tail?.value;\n }\n has(key) {\n return this._map.has(key);\n }\n get(key, touch = Touch.None) {\n const item = this._map.get(key);\n if (!item) {\n return undefined;\n }\n if (touch !== Touch.None) {\n this.touch(item, touch);\n }\n return item.value;\n }\n set(key, value, touch = Touch.None) {\n let item = this._map.get(key);\n if (item) {\n item.value = value;\n if (touch !== Touch.None) {\n this.touch(item, touch);\n }\n }\n else {\n item = { key, value, next: undefined, previous: undefined };\n switch (touch) {\n case Touch.None:\n this.addItemLast(item);\n break;\n case Touch.First:\n this.addItemFirst(item);\n break;\n case Touch.Last:\n this.addItemLast(item);\n break;\n default:\n this.addItemLast(item);\n break;\n }\n this._map.set(key, item);\n this._size++;\n }\n return this;\n }\n delete(key) {\n return !!this.remove(key);\n }\n remove(key) {\n const item = this._map.get(key);\n if (!item) {\n return undefined;\n }\n this._map.delete(key);\n this.removeItem(item);\n this._size--;\n return item.value;\n }\n shift() {\n if (!this._head && !this._tail) {\n return undefined;\n }\n if (!this._head || !this._tail) {\n throw new Error('Invalid list');\n }\n const item = this._head;\n this._map.delete(item.key);\n this.removeItem(item);\n this._size--;\n return item.value;\n }\n forEach(callbackfn, thisArg) {\n const state = this._state;\n let current = this._head;\n while (current) {\n if (thisArg) {\n callbackfn.bind(thisArg)(current.value, current.key, this);\n }\n else {\n callbackfn(current.value, current.key, this);\n }\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n current = current.next;\n }\n }\n keys() {\n const state = this._state;\n let current = this._head;\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n if (current) {\n const result = { value: current.key, done: false };\n current = current.next;\n return result;\n }\n else {\n return { value: undefined, done: true };\n }\n }\n };\n return iterator;\n }\n values() {\n const state = this._state;\n let current = this._head;\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n if (current) {\n const result = { value: current.value, done: false };\n current = current.next;\n return result;\n }\n else {\n return { value: undefined, done: true };\n }\n }\n };\n return iterator;\n }\n entries() {\n const state = this._state;\n let current = this._head;\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n if (this._state !== state) {\n throw new Error(`LinkedMap got modified during iteration.`);\n }\n if (current) {\n const result = { value: [current.key, current.value], done: false };\n current = current.next;\n return result;\n }\n else {\n return { value: undefined, done: true };\n }\n }\n };\n return iterator;\n }\n [(_a = Symbol.toStringTag, Symbol.iterator)]() {\n return this.entries();\n }\n trimOld(newSize) {\n if (newSize >= this.size) {\n return;\n }\n if (newSize === 0) {\n this.clear();\n return;\n }\n let current = this._head;\n let currentSize = this.size;\n while (current && currentSize > newSize) {\n this._map.delete(current.key);\n current = current.next;\n currentSize--;\n }\n this._head = current;\n this._size = currentSize;\n if (current) {\n current.previous = undefined;\n }\n this._state++;\n }\n addItemFirst(item) {\n // First time Insert\n if (!this._head && !this._tail) {\n this._tail = item;\n }\n else if (!this._head) {\n throw new Error('Invalid list');\n }\n else {\n item.next = this._head;\n this._head.previous = item;\n }\n this._head = item;\n this._state++;\n }\n addItemLast(item) {\n // First time Insert\n if (!this._head && !this._tail) {\n this._head = item;\n }\n else if (!this._tail) {\n throw new Error('Invalid list');\n }\n else {\n item.previous = this._tail;\n this._tail.next = item;\n }\n this._tail = item;\n this._state++;\n }\n removeItem(item) {\n if (item === this._head && item === this._tail) {\n this._head = undefined;\n this._tail = undefined;\n }\n else if (item === this._head) {\n // This can only happened if size === 1 which is handle\n // by the case above.\n if (!item.next) {\n throw new Error('Invalid list');\n }\n item.next.previous = undefined;\n this._head = item.next;\n }\n else if (item === this._tail) {\n // This can only happened if size === 1 which is handle\n // by the case above.\n if (!item.previous) {\n throw new Error('Invalid list');\n }\n item.previous.next = undefined;\n this._tail = item.previous;\n }\n else {\n const next = item.next;\n const previous = item.previous;\n if (!next || !previous) {\n throw new Error('Invalid list');\n }\n next.previous = previous;\n previous.next = next;\n }\n item.next = undefined;\n item.previous = undefined;\n this._state++;\n }\n touch(item, touch) {\n if (!this._head || !this._tail) {\n throw new Error('Invalid list');\n }\n if ((touch !== Touch.First && touch !== Touch.Last)) {\n return;\n }\n if (touch === Touch.First) {\n if (item === this._head) {\n return;\n }\n const next = item.next;\n const previous = item.previous;\n // Unlink the item\n if (item === this._tail) {\n // previous must be defined since item was not head but is tail\n // So there are more than on item in the map\n previous.next = undefined;\n this._tail = previous;\n }\n else {\n // Both next and previous are not undefined since item was neither head nor tail.\n next.previous = previous;\n previous.next = next;\n }\n // Insert the node at head\n item.previous = undefined;\n item.next = this._head;\n this._head.previous = item;\n this._head = item;\n this._state++;\n }\n else if (touch === Touch.Last) {\n if (item === this._tail) {\n return;\n }\n const next = item.next;\n const previous = item.previous;\n // Unlink the item.\n if (item === this._head) {\n // next must be defined since item was not tail but is head\n // So there are more than on item in the map\n next.previous = undefined;\n this._head = next;\n }\n else {\n // Both next and previous are not undefined since item was neither head nor tail.\n next.previous = previous;\n previous.next = next;\n }\n item.next = undefined;\n item.previous = this._tail;\n this._tail.next = item;\n this._tail = item;\n this._state++;\n }\n }\n toJSON() {\n const data = [];\n this.forEach((value, key) => {\n data.push([key, value]);\n });\n return data;\n }\n fromJSON(data) {\n this.clear();\n for (const [key, value] of data) {\n this.set(key, value);\n }\n }\n}\nexports.LinkedMap = LinkedMap;\nclass LRUCache extends LinkedMap {\n constructor(limit, ratio = 1) {\n super();\n this._limit = limit;\n this._ratio = Math.min(Math.max(0, ratio), 1);\n }\n get limit() {\n return this._limit;\n }\n set limit(limit) {\n this._limit = limit;\n this.checkTrim();\n }\n get ratio() {\n return this._ratio;\n }\n set ratio(ratio) {\n this._ratio = Math.min(Math.max(0, ratio), 1);\n this.checkTrim();\n }\n get(key, touch = Touch.AsNew) {\n return super.get(key, touch);\n }\n peek(key) {\n return super.get(key, Touch.None);\n }\n set(key, value) {\n super.set(key, value, Touch.Last);\n this.checkTrim();\n return this;\n }\n checkTrim() {\n if (this.size > this._limit) {\n this.trimOld(Math.round(this._limit * this._ratio));\n }\n }\n}\nexports.LRUCache = LRUCache;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Disposable = void 0;\nvar Disposable;\n(function (Disposable) {\n function create(func) {\n return {\n dispose: func\n };\n }\n Disposable.create = create;\n})(Disposable || (exports.Disposable = Disposable = {}));\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nlet _ral;\nfunction RAL() {\n if (_ral === undefined) {\n throw new Error(`No runtime abstraction layer installed`);\n }\n return _ral;\n}\n(function (RAL) {\n function install(ral) {\n if (ral === undefined) {\n throw new Error(`No runtime abstraction layer provided`);\n }\n _ral = ral;\n }\n RAL.install = install;\n})(RAL || (RAL = {}));\nexports.default = RAL;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Emitter = exports.Event = void 0;\nconst ral_1 = require(\"./ral\");\nvar Event;\n(function (Event) {\n const _disposable = { dispose() { } };\n Event.None = function () { return _disposable; };\n})(Event || (exports.Event = Event = {}));\nclass CallbackList {\n add(callback, context = null, bucket) {\n if (!this._callbacks) {\n this._callbacks = [];\n this._contexts = [];\n }\n this._callbacks.push(callback);\n this._contexts.push(context);\n if (Array.isArray(bucket)) {\n bucket.push({ dispose: () => this.remove(callback, context) });\n }\n }\n remove(callback, context = null) {\n if (!this._callbacks) {\n return;\n }\n let foundCallbackWithDifferentContext = false;\n for (let i = 0, len = this._callbacks.length; i < len; i++) {\n if (this._callbacks[i] === callback) {\n if (this._contexts[i] === context) {\n // callback & context match => remove it\n this._callbacks.splice(i, 1);\n this._contexts.splice(i, 1);\n return;\n }\n else {\n foundCallbackWithDifferentContext = true;\n }\n }\n }\n if (foundCallbackWithDifferentContext) {\n throw new Error('When adding a listener with a context, you should remove it with the same context');\n }\n }\n invoke(...args) {\n if (!this._callbacks) {\n return [];\n }\n const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);\n for (let i = 0, len = callbacks.length; i < len; i++) {\n try {\n ret.push(callbacks[i].apply(contexts[i], args));\n }\n catch (e) {\n // eslint-disable-next-line no-console\n (0, ral_1.default)().console.error(e);\n }\n }\n return ret;\n }\n isEmpty() {\n return !this._callbacks || this._callbacks.length === 0;\n }\n dispose() {\n this._callbacks = undefined;\n this._contexts = undefined;\n }\n}\nclass Emitter {\n constructor(_options) {\n this._options = _options;\n }\n /**\n * For the public to allow to subscribe\n * to events from this Emitter\n */\n get event() {\n if (!this._event) {\n this._event = (listener, thisArgs, disposables) => {\n if (!this._callbacks) {\n this._callbacks = new CallbackList();\n }\n if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {\n this._options.onFirstListenerAdd(this);\n }\n this._callbacks.add(listener, thisArgs);\n const result = {\n dispose: () => {\n if (!this._callbacks) {\n // disposable is disposed after emitter is disposed.\n return;\n }\n this._callbacks.remove(listener, thisArgs);\n result.dispose = Emitter._noop;\n if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {\n this._options.onLastListenerRemove(this);\n }\n }\n };\n if (Array.isArray(disposables)) {\n disposables.push(result);\n }\n return result;\n };\n }\n return this._event;\n }\n /**\n * To be kept private to fire an event to\n * subscribers\n */\n fire(event) {\n if (this._callbacks) {\n this._callbacks.invoke.call(this._callbacks, event);\n }\n }\n dispose() {\n if (this._callbacks) {\n this._callbacks.dispose();\n this._callbacks = undefined;\n }\n }\n}\nexports.Emitter = Emitter;\nEmitter._noop = function () { };\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CancellationTokenSource = exports.CancellationToken = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst events_1 = require(\"./events\");\nvar CancellationToken;\n(function (CancellationToken) {\n CancellationToken.None = Object.freeze({\n isCancellationRequested: false,\n onCancellationRequested: events_1.Event.None\n });\n CancellationToken.Cancelled = Object.freeze({\n isCancellationRequested: true,\n onCancellationRequested: events_1.Event.None\n });\n function is(value) {\n const candidate = value;\n return candidate && (candidate === CancellationToken.None\n || candidate === CancellationToken.Cancelled\n || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));\n }\n CancellationToken.is = is;\n})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));\nconst shortcutEvent = Object.freeze(function (callback, context) {\n const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);\n return { dispose() { handle.dispose(); } };\n});\nclass MutableToken {\n constructor() {\n this._isCancelled = false;\n }\n cancel() {\n if (!this._isCancelled) {\n this._isCancelled = true;\n if (this._emitter) {\n this._emitter.fire(undefined);\n this.dispose();\n }\n }\n }\n get isCancellationRequested() {\n return this._isCancelled;\n }\n get onCancellationRequested() {\n if (this._isCancelled) {\n return shortcutEvent;\n }\n if (!this._emitter) {\n this._emitter = new events_1.Emitter();\n }\n return this._emitter.event;\n }\n dispose() {\n if (this._emitter) {\n this._emitter.dispose();\n this._emitter = undefined;\n }\n }\n}\nclass CancellationTokenSource {\n get token() {\n if (!this._token) {\n // be lazy and create the token only when\n // actually needed\n this._token = new MutableToken();\n }\n return this._token;\n }\n cancel() {\n if (!this._token) {\n // save an object by returning the default\n // cancelled token when cancellation happens\n // before someone asks for the token\n this._token = CancellationToken.Cancelled;\n }\n else {\n this._token.cancel();\n }\n }\n dispose() {\n if (!this._token) {\n // ensure to initialize with an empty token if we had none\n this._token = CancellationToken.None;\n }\n else if (this._token instanceof MutableToken) {\n // actually dispose\n this._token.dispose();\n }\n }\n}\nexports.CancellationTokenSource = CancellationTokenSource;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = void 0;\nconst cancellation_1 = require(\"./cancellation\");\nvar CancellationState;\n(function (CancellationState) {\n CancellationState.Continue = 0;\n CancellationState.Cancelled = 1;\n})(CancellationState || (CancellationState = {}));\nclass SharedArraySenderStrategy {\n constructor() {\n this.buffers = new Map();\n }\n enableCancellation(request) {\n if (request.id === null) {\n return;\n }\n const buffer = new SharedArrayBuffer(4);\n const data = new Int32Array(buffer, 0, 1);\n data[0] = CancellationState.Continue;\n this.buffers.set(request.id, buffer);\n request.$cancellationData = buffer;\n }\n async sendCancellation(_conn, id) {\n const buffer = this.buffers.get(id);\n if (buffer === undefined) {\n return;\n }\n const data = new Int32Array(buffer, 0, 1);\n Atomics.store(data, 0, CancellationState.Cancelled);\n }\n cleanup(id) {\n this.buffers.delete(id);\n }\n dispose() {\n this.buffers.clear();\n }\n}\nexports.SharedArraySenderStrategy = SharedArraySenderStrategy;\nclass SharedArrayBufferCancellationToken {\n constructor(buffer) {\n this.data = new Int32Array(buffer, 0, 1);\n }\n get isCancellationRequested() {\n return Atomics.load(this.data, 0) === CancellationState.Cancelled;\n }\n get onCancellationRequested() {\n throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);\n }\n}\nclass SharedArrayBufferCancellationTokenSource {\n constructor(buffer) {\n this.token = new SharedArrayBufferCancellationToken(buffer);\n }\n cancel() {\n }\n dispose() {\n }\n}\nclass SharedArrayReceiverStrategy {\n constructor() {\n this.kind = 'request';\n }\n createCancellationTokenSource(request) {\n const buffer = request.$cancellationData;\n if (buffer === undefined) {\n return new cancellation_1.CancellationTokenSource();\n }\n return new SharedArrayBufferCancellationTokenSource(buffer);\n }\n}\nexports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Semaphore = void 0;\nconst ral_1 = require(\"./ral\");\nclass Semaphore {\n constructor(capacity = 1) {\n if (capacity <= 0) {\n throw new Error('Capacity must be greater than 0');\n }\n this._capacity = capacity;\n this._active = 0;\n this._waiting = [];\n }\n lock(thunk) {\n return new Promise((resolve, reject) => {\n this._waiting.push({ thunk, resolve, reject });\n this.runNext();\n });\n }\n get active() {\n return this._active;\n }\n runNext() {\n if (this._waiting.length === 0 || this._active === this._capacity) {\n return;\n }\n (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());\n }\n doRunNext() {\n if (this._waiting.length === 0 || this._active === this._capacity) {\n return;\n }\n const next = this._waiting.shift();\n this._active++;\n if (this._active > this._capacity) {\n throw new Error(`To many thunks active`);\n }\n try {\n const result = next.thunk();\n if (result instanceof Promise) {\n result.then((value) => {\n this._active--;\n next.resolve(value);\n this.runNext();\n }, (err) => {\n this._active--;\n next.reject(err);\n this.runNext();\n });\n }\n else {\n this._active--;\n next.resolve(result);\n this.runNext();\n }\n }\n catch (err) {\n this._active--;\n next.reject(err);\n this.runNext();\n }\n }\n}\nexports.Semaphore = Semaphore;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst events_1 = require(\"./events\");\nconst semaphore_1 = require(\"./semaphore\");\nvar MessageReader;\n(function (MessageReader) {\n function is(value) {\n let candidate = value;\n return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&\n Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);\n }\n MessageReader.is = is;\n})(MessageReader || (exports.MessageReader = MessageReader = {}));\nclass AbstractMessageReader {\n constructor() {\n this.errorEmitter = new events_1.Emitter();\n this.closeEmitter = new events_1.Emitter();\n this.partialMessageEmitter = new events_1.Emitter();\n }\n dispose() {\n this.errorEmitter.dispose();\n this.closeEmitter.dispose();\n }\n get onError() {\n return this.errorEmitter.event;\n }\n fireError(error) {\n this.errorEmitter.fire(this.asError(error));\n }\n get onClose() {\n return this.closeEmitter.event;\n }\n fireClose() {\n this.closeEmitter.fire(undefined);\n }\n get onPartialMessage() {\n return this.partialMessageEmitter.event;\n }\n firePartialMessage(info) {\n this.partialMessageEmitter.fire(info);\n }\n asError(error) {\n if (error instanceof Error) {\n return error;\n }\n else {\n return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\n }\n }\n}\nexports.AbstractMessageReader = AbstractMessageReader;\nvar ResolvedMessageReaderOptions;\n(function (ResolvedMessageReaderOptions) {\n function fromOptions(options) {\n let charset;\n let result;\n let contentDecoder;\n const contentDecoders = new Map();\n let contentTypeDecoder;\n const contentTypeDecoders = new Map();\n if (options === undefined || typeof options === 'string') {\n charset = options ?? 'utf-8';\n }\n else {\n charset = options.charset ?? 'utf-8';\n if (options.contentDecoder !== undefined) {\n contentDecoder = options.contentDecoder;\n contentDecoders.set(contentDecoder.name, contentDecoder);\n }\n if (options.contentDecoders !== undefined) {\n for (const decoder of options.contentDecoders) {\n contentDecoders.set(decoder.name, decoder);\n }\n }\n if (options.contentTypeDecoder !== undefined) {\n contentTypeDecoder = options.contentTypeDecoder;\n contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);\n }\n if (options.contentTypeDecoders !== undefined) {\n for (const decoder of options.contentTypeDecoders) {\n contentTypeDecoders.set(decoder.name, decoder);\n }\n }\n }\n if (contentTypeDecoder === undefined) {\n contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;\n contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);\n }\n return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };\n }\n ResolvedMessageReaderOptions.fromOptions = fromOptions;\n})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));\nclass ReadableStreamMessageReader extends AbstractMessageReader {\n constructor(readable, options) {\n super();\n this.readable = readable;\n this.options = ResolvedMessageReaderOptions.fromOptions(options);\n this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);\n this._partialMessageTimeout = 10000;\n this.nextMessageLength = -1;\n this.messageToken = 0;\n this.readSemaphore = new semaphore_1.Semaphore(1);\n }\n set partialMessageTimeout(timeout) {\n this._partialMessageTimeout = timeout;\n }\n get partialMessageTimeout() {\n return this._partialMessageTimeout;\n }\n listen(callback) {\n this.nextMessageLength = -1;\n this.messageToken = 0;\n this.partialMessageTimer = undefined;\n this.callback = callback;\n const result = this.readable.onData((data) => {\n this.onData(data);\n });\n this.readable.onError((error) => this.fireError(error));\n this.readable.onClose(() => this.fireClose());\n return result;\n }\n onData(data) {\n try {\n this.buffer.append(data);\n while (true) {\n if (this.nextMessageLength === -1) {\n const headers = this.buffer.tryReadHeaders(true);\n if (!headers) {\n return;\n }\n const contentLength = headers.get('content-length');\n if (!contentLength) {\n this.fireError(new Error(`Header must provide a Content-Length property.\\n${JSON.stringify(Object.fromEntries(headers))}`));\n return;\n }\n const length = parseInt(contentLength);\n if (isNaN(length)) {\n this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));\n return;\n }\n this.nextMessageLength = length;\n }\n const body = this.buffer.tryReadBody(this.nextMessageLength);\n if (body === undefined) {\n /** We haven't received the full message yet. */\n this.setPartialMessageTimer();\n return;\n }\n this.clearPartialMessageTimer();\n this.nextMessageLength = -1;\n // Make sure that we convert one received message after the\n // other. Otherwise it could happen that a decoding of a second\n // smaller message finished before the decoding of a first larger\n // message and then we would deliver the second message first.\n this.readSemaphore.lock(async () => {\n const bytes = this.options.contentDecoder !== undefined\n ? await this.options.contentDecoder.decode(body)\n : body;\n const message = await this.options.contentTypeDecoder.decode(bytes, this.options);\n this.callback(message);\n }).catch((error) => {\n this.fireError(error);\n });\n }\n }\n catch (error) {\n this.fireError(error);\n }\n }\n clearPartialMessageTimer() {\n if (this.partialMessageTimer) {\n this.partialMessageTimer.dispose();\n this.partialMessageTimer = undefined;\n }\n }\n setPartialMessageTimer() {\n this.clearPartialMessageTimer();\n if (this._partialMessageTimeout <= 0) {\n return;\n }\n this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {\n this.partialMessageTimer = undefined;\n if (token === this.messageToken) {\n this.firePartialMessage({ messageToken: token, waitingTime: timeout });\n this.setPartialMessageTimer();\n }\n }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);\n }\n}\nexports.ReadableStreamMessageReader = ReadableStreamMessageReader;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst semaphore_1 = require(\"./semaphore\");\nconst events_1 = require(\"./events\");\nconst ContentLength = 'Content-Length: ';\nconst CRLF = '\\r\\n';\nvar MessageWriter;\n(function (MessageWriter) {\n function is(value) {\n let candidate = value;\n return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&\n Is.func(candidate.onError) && Is.func(candidate.write);\n }\n MessageWriter.is = is;\n})(MessageWriter || (exports.MessageWriter = MessageWriter = {}));\nclass AbstractMessageWriter {\n constructor() {\n this.errorEmitter = new events_1.Emitter();\n this.closeEmitter = new events_1.Emitter();\n }\n dispose() {\n this.errorEmitter.dispose();\n this.closeEmitter.dispose();\n }\n get onError() {\n return this.errorEmitter.event;\n }\n fireError(error, message, count) {\n this.errorEmitter.fire([this.asError(error), message, count]);\n }\n get onClose() {\n return this.closeEmitter.event;\n }\n fireClose() {\n this.closeEmitter.fire(undefined);\n }\n asError(error) {\n if (error instanceof Error) {\n return error;\n }\n else {\n return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\n }\n }\n}\nexports.AbstractMessageWriter = AbstractMessageWriter;\nvar ResolvedMessageWriterOptions;\n(function (ResolvedMessageWriterOptions) {\n function fromOptions(options) {\n if (options === undefined || typeof options === 'string') {\n return { charset: options ?? 'utf-8', contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };\n }\n else {\n return { charset: options.charset ?? 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };\n }\n }\n ResolvedMessageWriterOptions.fromOptions = fromOptions;\n})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));\nclass WriteableStreamMessageWriter extends AbstractMessageWriter {\n constructor(writable, options) {\n super();\n this.writable = writable;\n this.options = ResolvedMessageWriterOptions.fromOptions(options);\n this.errorCount = 0;\n this.writeSemaphore = new semaphore_1.Semaphore(1);\n this.writable.onError((error) => this.fireError(error));\n this.writable.onClose(() => this.fireClose());\n }\n async write(msg) {\n return this.writeSemaphore.lock(async () => {\n const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {\n if (this.options.contentEncoder !== undefined) {\n return this.options.contentEncoder.encode(buffer);\n }\n else {\n return buffer;\n }\n });\n return payload.then((buffer) => {\n const headers = [];\n headers.push(ContentLength, buffer.byteLength.toString(), CRLF);\n headers.push(CRLF);\n return this.doWrite(msg, headers, buffer);\n }, (error) => {\n this.fireError(error);\n throw error;\n });\n });\n }\n async doWrite(msg, headers, data) {\n try {\n await this.writable.write(headers.join(''), 'ascii');\n return this.writable.write(data);\n }\n catch (error) {\n this.handleError(error, msg);\n return Promise.reject(error);\n }\n }\n handleError(error, msg) {\n this.errorCount++;\n this.fireError(error, msg, this.errorCount);\n }\n end() {\n this.writable.end();\n }\n}\nexports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;\n","\"use strict\";\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AbstractMessageBuffer = void 0;\nconst CR = 13;\nconst LF = 10;\nconst CRLF = '\\r\\n';\nclass AbstractMessageBuffer {\n constructor(encoding = 'utf-8') {\n this._encoding = encoding;\n this._chunks = [];\n this._totalLength = 0;\n }\n get encoding() {\n return this._encoding;\n }\n append(chunk) {\n const toAppend = typeof chunk === 'string' ? this.fromString(chunk, this._encoding) : chunk;\n this._chunks.push(toAppend);\n this._totalLength += toAppend.byteLength;\n }\n tryReadHeaders(lowerCaseKeys = false) {\n if (this._chunks.length === 0) {\n return undefined;\n }\n let state = 0;\n let chunkIndex = 0;\n let offset = 0;\n let chunkBytesRead = 0;\n row: while (chunkIndex < this._chunks.length) {\n const chunk = this._chunks[chunkIndex];\n offset = 0;\n column: while (offset < chunk.length) {\n const value = chunk[offset];\n switch (value) {\n case CR:\n switch (state) {\n case 0:\n state = 1;\n break;\n case 2:\n state = 3;\n break;\n default:\n state = 0;\n }\n break;\n case LF:\n switch (state) {\n case 1:\n state = 2;\n break;\n case 3:\n state = 4;\n offset++;\n break row;\n default:\n state = 0;\n }\n break;\n default:\n state = 0;\n }\n offset++;\n }\n chunkBytesRead += chunk.byteLength;\n chunkIndex++;\n }\n if (state !== 4) {\n return undefined;\n }\n // The buffer contains the two CRLF at the end. So we will\n // have two empty lines after the split at the end as well.\n const buffer = this._read(chunkBytesRead + offset);\n const result = new Map();\n const headers = this.toString(buffer, 'ascii').split(CRLF);\n if (headers.length < 2) {\n return result;\n }\n for (let i = 0; i < headers.length - 2; i++) {\n const header = headers[i];\n const index = header.indexOf(':');\n if (index === -1) {\n throw new Error(`Message header must separate key and value using ':'\\n${header}`);\n }\n const key = header.substr(0, index);\n const value = header.substr(index + 1).trim();\n result.set(lowerCaseKeys ? key.toLowerCase() : key, value);\n }\n return result;\n }\n tryReadBody(length) {\n if (this._totalLength < length) {\n return undefined;\n }\n return this._read(length);\n }\n get numberOfBytes() {\n return this._totalLength;\n }\n _read(byteCount) {\n if (byteCount === 0) {\n return this.emptyBuffer();\n }\n if (byteCount > this._totalLength) {\n throw new Error(`Cannot read so many bytes!`);\n }\n if (this._chunks[0].byteLength === byteCount) {\n // super fast path, precisely first chunk must be returned\n const chunk = this._chunks[0];\n this._chunks.shift();\n this._totalLength -= byteCount;\n return this.asNative(chunk);\n }\n if (this._chunks[0].byteLength > byteCount) {\n // fast path, the reading is entirely within the first chunk\n const chunk = this._chunks[0];\n const result = this.asNative(chunk, byteCount);\n this._chunks[0] = chunk.slice(byteCount);\n this._totalLength -= byteCount;\n return result;\n }\n const result = this.allocNative(byteCount);\n let resultOffset = 0;\n let chunkIndex = 0;\n while (byteCount > 0) {\n const chunk = this._chunks[chunkIndex];\n if (chunk.byteLength > byteCount) {\n // this chunk will survive\n const chunkPart = chunk.slice(0, byteCount);\n result.set(chunkPart, resultOffset);\n resultOffset += byteCount;\n this._chunks[chunkIndex] = chunk.slice(byteCount);\n this._totalLength -= byteCount;\n byteCount -= byteCount;\n }\n else {\n // this chunk will be entirely read\n result.set(chunk, resultOffset);\n resultOffset += chunk.byteLength;\n this._chunks.shift();\n this._totalLength -= chunk.byteLength;\n byteCount -= chunk.byteLength;\n }\n }\n return result;\n }\n}\nexports.AbstractMessageBuffer = AbstractMessageBuffer;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;\nconst ral_1 = require(\"./ral\");\nconst Is = require(\"./is\");\nconst messages_1 = require(\"./messages\");\nconst linkedMap_1 = require(\"./linkedMap\");\nconst events_1 = require(\"./events\");\nconst cancellation_1 = require(\"./cancellation\");\nvar CancelNotification;\n(function (CancelNotification) {\n CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');\n})(CancelNotification || (CancelNotification = {}));\nvar ProgressToken;\n(function (ProgressToken) {\n function is(value) {\n return typeof value === 'string' || typeof value === 'number';\n }\n ProgressToken.is = is;\n})(ProgressToken || (exports.ProgressToken = ProgressToken = {}));\nvar ProgressNotification;\n(function (ProgressNotification) {\n ProgressNotification.type = new messages_1.NotificationType('$/progress');\n})(ProgressNotification || (ProgressNotification = {}));\nclass ProgressType {\n constructor() {\n }\n}\nexports.ProgressType = ProgressType;\nvar StarRequestHandler;\n(function (StarRequestHandler) {\n function is(value) {\n return Is.func(value);\n }\n StarRequestHandler.is = is;\n})(StarRequestHandler || (StarRequestHandler = {}));\nexports.NullLogger = Object.freeze({\n error: () => { },\n warn: () => { },\n info: () => { },\n log: () => { }\n});\nvar Trace;\n(function (Trace) {\n Trace[Trace[\"Off\"] = 0] = \"Off\";\n Trace[Trace[\"Messages\"] = 1] = \"Messages\";\n Trace[Trace[\"Compact\"] = 2] = \"Compact\";\n Trace[Trace[\"Verbose\"] = 3] = \"Verbose\";\n})(Trace || (exports.Trace = Trace = {}));\nvar TraceValues;\n(function (TraceValues) {\n /**\n * Turn tracing off.\n */\n TraceValues.Off = 'off';\n /**\n * Trace messages only.\n */\n TraceValues.Messages = 'messages';\n /**\n * Compact message tracing.\n */\n TraceValues.Compact = 'compact';\n /**\n * Verbose message tracing.\n */\n TraceValues.Verbose = 'verbose';\n})(TraceValues || (exports.TraceValues = TraceValues = {}));\n(function (Trace) {\n function fromString(value) {\n if (!Is.string(value)) {\n return Trace.Off;\n }\n value = value.toLowerCase();\n switch (value) {\n case 'off':\n return Trace.Off;\n case 'messages':\n return Trace.Messages;\n case 'compact':\n return Trace.Compact;\n case 'verbose':\n return Trace.Verbose;\n default:\n return Trace.Off;\n }\n }\n Trace.fromString = fromString;\n function toString(value) {\n switch (value) {\n case Trace.Off:\n return 'off';\n case Trace.Messages:\n return 'messages';\n case Trace.Compact:\n return 'compact';\n case Trace.Verbose:\n return 'verbose';\n default:\n return 'off';\n }\n }\n Trace.toString = toString;\n})(Trace || (exports.Trace = Trace = {}));\nvar TraceFormat;\n(function (TraceFormat) {\n TraceFormat[\"Text\"] = \"text\";\n TraceFormat[\"JSON\"] = \"json\";\n})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));\n(function (TraceFormat) {\n function fromString(value) {\n if (!Is.string(value)) {\n return TraceFormat.Text;\n }\n value = value.toLowerCase();\n if (value === 'json') {\n return TraceFormat.JSON;\n }\n else {\n return TraceFormat.Text;\n }\n }\n TraceFormat.fromString = fromString;\n})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));\nvar SetTraceNotification;\n(function (SetTraceNotification) {\n SetTraceNotification.type = new messages_1.NotificationType('$/setTrace');\n})(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));\nvar LogTraceNotification;\n(function (LogTraceNotification) {\n LogTraceNotification.type = new messages_1.NotificationType('$/logTrace');\n})(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));\nvar ConnectionErrors;\n(function (ConnectionErrors) {\n /**\n * The connection is closed.\n */\n ConnectionErrors[ConnectionErrors[\"Closed\"] = 1] = \"Closed\";\n /**\n * The connection got disposed.\n */\n ConnectionErrors[ConnectionErrors[\"Disposed\"] = 2] = \"Disposed\";\n /**\n * The connection is already in listening mode.\n */\n ConnectionErrors[ConnectionErrors[\"AlreadyListening\"] = 3] = \"AlreadyListening\";\n})(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));\nclass ConnectionError extends Error {\n constructor(code, message) {\n super(message);\n this.code = code;\n Object.setPrototypeOf(this, ConnectionError.prototype);\n }\n}\nexports.ConnectionError = ConnectionError;\nvar ConnectionStrategy;\n(function (ConnectionStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && Is.func(candidate.cancelUndispatched);\n }\n ConnectionStrategy.is = is;\n})(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));\nvar IdCancellationReceiverStrategy;\n(function (IdCancellationReceiverStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && (candidate.kind === undefined || candidate.kind === 'id') && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));\n }\n IdCancellationReceiverStrategy.is = is;\n})(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));\nvar RequestCancellationReceiverStrategy;\n(function (RequestCancellationReceiverStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && candidate.kind === 'request' && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));\n }\n RequestCancellationReceiverStrategy.is = is;\n})(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));\nvar CancellationReceiverStrategy;\n(function (CancellationReceiverStrategy) {\n CancellationReceiverStrategy.Message = Object.freeze({\n createCancellationTokenSource(_) {\n return new cancellation_1.CancellationTokenSource();\n }\n });\n function is(value) {\n return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);\n }\n CancellationReceiverStrategy.is = is;\n})(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));\nvar CancellationSenderStrategy;\n(function (CancellationSenderStrategy) {\n CancellationSenderStrategy.Message = Object.freeze({\n sendCancellation(conn, id) {\n return conn.sendNotification(CancelNotification.type, { id });\n },\n cleanup(_) { }\n });\n function is(value) {\n const candidate = value;\n return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);\n }\n CancellationSenderStrategy.is = is;\n})(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));\nvar CancellationStrategy;\n(function (CancellationStrategy) {\n CancellationStrategy.Message = Object.freeze({\n receiver: CancellationReceiverStrategy.Message,\n sender: CancellationSenderStrategy.Message\n });\n function is(value) {\n const candidate = value;\n return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);\n }\n CancellationStrategy.is = is;\n})(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));\nvar MessageStrategy;\n(function (MessageStrategy) {\n function is(value) {\n const candidate = value;\n return candidate && Is.func(candidate.handleMessage);\n }\n MessageStrategy.is = is;\n})(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));\nvar ConnectionOptions;\n(function (ConnectionOptions) {\n function is(value) {\n const candidate = value;\n return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));\n }\n ConnectionOptions.is = is;\n})(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));\nvar ConnectionState;\n(function (ConnectionState) {\n ConnectionState[ConnectionState[\"New\"] = 1] = \"New\";\n ConnectionState[ConnectionState[\"Listening\"] = 2] = \"Listening\";\n ConnectionState[ConnectionState[\"Closed\"] = 3] = \"Closed\";\n ConnectionState[ConnectionState[\"Disposed\"] = 4] = \"Disposed\";\n})(ConnectionState || (ConnectionState = {}));\nfunction createMessageConnection(messageReader, messageWriter, _logger, options) {\n const logger = _logger !== undefined ? _logger : exports.NullLogger;\n let sequenceNumber = 0;\n let notificationSequenceNumber = 0;\n let unknownResponseSequenceNumber = 0;\n const version = '2.0';\n let starRequestHandler = undefined;\n const requestHandlers = new Map();\n let starNotificationHandler = undefined;\n const notificationHandlers = new Map();\n const progressHandlers = new Map();\n let timer;\n let messageQueue = new linkedMap_1.LinkedMap();\n let responsePromises = new Map();\n let knownCanceledRequests = new Set();\n let requestTokens = new Map();\n let trace = Trace.Off;\n let traceFormat = TraceFormat.Text;\n let tracer;\n let state = ConnectionState.New;\n const errorEmitter = new events_1.Emitter();\n const closeEmitter = new events_1.Emitter();\n const unhandledNotificationEmitter = new events_1.Emitter();\n const unhandledProgressEmitter = new events_1.Emitter();\n const disposeEmitter = new events_1.Emitter();\n const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message;\n function createRequestQueueKey(id) {\n if (id === null) {\n throw new Error(`Can't send requests with id null since the response can't be correlated.`);\n }\n return 'req-' + id.toString();\n }\n function createResponseQueueKey(id) {\n if (id === null) {\n return 'res-unknown-' + (++unknownResponseSequenceNumber).toString();\n }\n else {\n return 'res-' + id.toString();\n }\n }\n function createNotificationQueueKey() {\n return 'not-' + (++notificationSequenceNumber).toString();\n }\n function addMessageToQueue(queue, message) {\n if (messages_1.Message.isRequest(message)) {\n queue.set(createRequestQueueKey(message.id), message);\n }\n else if (messages_1.Message.isResponse(message)) {\n queue.set(createResponseQueueKey(message.id), message);\n }\n else {\n queue.set(createNotificationQueueKey(), message);\n }\n }\n function cancelUndispatched(_message) {\n return undefined;\n }\n function isListening() {\n return state === ConnectionState.Listening;\n }\n function isClosed() {\n return state === ConnectionState.Closed;\n }\n function isDisposed() {\n return state === ConnectionState.Disposed;\n }\n function closeHandler() {\n if (state === ConnectionState.New || state === ConnectionState.Listening) {\n state = ConnectionState.Closed;\n closeEmitter.fire(undefined);\n }\n // If the connection is disposed don't sent close events.\n }\n function readErrorHandler(error) {\n errorEmitter.fire([error, undefined, undefined]);\n }\n function writeErrorHandler(data) {\n errorEmitter.fire(data);\n }\n messageReader.onClose(closeHandler);\n messageReader.onError(readErrorHandler);\n messageWriter.onClose(closeHandler);\n messageWriter.onError(writeErrorHandler);\n function triggerMessageQueue() {\n if (timer || messageQueue.size === 0) {\n return;\n }\n timer = (0, ral_1.default)().timer.setImmediate(() => {\n timer = undefined;\n processMessageQueue();\n });\n }\n function handleMessage(message) {\n if (messages_1.Message.isRequest(message)) {\n handleRequest(message);\n }\n else if (messages_1.Message.isNotification(message)) {\n handleNotification(message);\n }\n else if (messages_1.Message.isResponse(message)) {\n handleResponse(message);\n }\n else {\n handleInvalidMessage(message);\n }\n }\n function processMessageQueue() {\n if (messageQueue.size === 0) {\n return;\n }\n const message = messageQueue.shift();\n try {\n const messageStrategy = options?.messageStrategy;\n if (MessageStrategy.is(messageStrategy)) {\n messageStrategy.handleMessage(message, handleMessage);\n }\n else {\n handleMessage(message);\n }\n }\n finally {\n triggerMessageQueue();\n }\n }\n const callback = (message) => {\n try {\n // We have received a cancellation message. Check if the message is still in the queue\n // and cancel it if allowed to do so.\n if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {\n const cancelId = message.params.id;\n const key = createRequestQueueKey(cancelId);\n const toCancel = messageQueue.get(key);\n if (messages_1.Message.isRequest(toCancel)) {\n const strategy = options?.connectionStrategy;\n const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);\n if (response && (response.error !== undefined || response.result !== undefined)) {\n messageQueue.delete(key);\n requestTokens.delete(cancelId);\n response.id = toCancel.id;\n traceSendingResponse(response, message.method, Date.now());\n messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));\n return;\n }\n }\n const cancellationToken = requestTokens.get(cancelId);\n // The request is already running. Cancel the token\n if (cancellationToken !== undefined) {\n cancellationToken.cancel();\n traceReceivedNotification(message);\n return;\n }\n else {\n // Remember the cancel but still queue the message to\n // clean up state in process message.\n knownCanceledRequests.add(cancelId);\n }\n }\n addMessageToQueue(messageQueue, message);\n }\n finally {\n triggerMessageQueue();\n }\n };\n function handleRequest(requestMessage) {\n if (isDisposed()) {\n // we return here silently since we fired an event when the\n // connection got disposed.\n return;\n }\n function reply(resultOrError, method, startTime) {\n const message = {\n jsonrpc: version,\n id: requestMessage.id\n };\n if (resultOrError instanceof messages_1.ResponseError) {\n message.error = resultOrError.toJson();\n }\n else {\n message.result = resultOrError === undefined ? null : resultOrError;\n }\n traceSendingResponse(message, method, startTime);\n messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));\n }\n function replyError(error, method, startTime) {\n const message = {\n jsonrpc: version,\n id: requestMessage.id,\n error: error.toJson()\n };\n traceSendingResponse(message, method, startTime);\n messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));\n }\n function replySuccess(result, method, startTime) {\n // The JSON RPC defines that a response must either have a result or an error\n // So we can't treat undefined as a valid response result.\n if (result === undefined) {\n result = null;\n }\n const message = {\n jsonrpc: version,\n id: requestMessage.id,\n result: result\n };\n traceSendingResponse(message, method, startTime);\n messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));\n }\n traceReceivedRequest(requestMessage);\n const element = requestHandlers.get(requestMessage.method);\n let type;\n let requestHandler;\n if (element) {\n type = element.type;\n requestHandler = element.handler;\n }\n const startTime = Date.now();\n if (requestHandler || starRequestHandler) {\n const tokenKey = requestMessage.id ?? String(Date.now()); //\n const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver)\n ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey)\n : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);\n if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {\n cancellationSource.cancel();\n }\n if (requestMessage.id !== null) {\n requestTokens.set(tokenKey, cancellationSource);\n }\n try {\n let handlerResult;\n if (requestHandler) {\n if (requestMessage.params === undefined) {\n if (type !== undefined && type.numberOfParams !== 0) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);\n return;\n }\n handlerResult = requestHandler(cancellationSource.token);\n }\n else if (Array.isArray(requestMessage.params)) {\n if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);\n return;\n }\n handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);\n }\n else {\n if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);\n return;\n }\n handlerResult = requestHandler(requestMessage.params, cancellationSource.token);\n }\n }\n else if (starRequestHandler) {\n handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);\n }\n const promise = handlerResult;\n if (!handlerResult) {\n requestTokens.delete(tokenKey);\n replySuccess(handlerResult, requestMessage.method, startTime);\n }\n else if (promise.then) {\n promise.then((resultOrError) => {\n requestTokens.delete(tokenKey);\n reply(resultOrError, requestMessage.method, startTime);\n }, error => {\n requestTokens.delete(tokenKey);\n if (error instanceof messages_1.ResponseError) {\n replyError(error, requestMessage.method, startTime);\n }\n else if (error && Is.string(error.message)) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\n }\n else {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\n }\n });\n }\n else {\n requestTokens.delete(tokenKey);\n reply(handlerResult, requestMessage.method, startTime);\n }\n }\n catch (error) {\n requestTokens.delete(tokenKey);\n if (error instanceof messages_1.ResponseError) {\n reply(error, requestMessage.method, startTime);\n }\n else if (error && Is.string(error.message)) {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\n }\n else {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\n }\n }\n }\n else {\n replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);\n }\n }\n function handleResponse(responseMessage) {\n if (isDisposed()) {\n // See handle request.\n return;\n }\n if (responseMessage.id === null) {\n if (responseMessage.error) {\n logger.error(`Received response message without id: Error is: \\n${JSON.stringify(responseMessage.error, undefined, 4)}`);\n }\n else {\n logger.error(`Received response message without id. No further error information provided.`);\n }\n }\n else {\n const key = responseMessage.id;\n const responsePromise = responsePromises.get(key);\n traceReceivedResponse(responseMessage, responsePromise);\n if (responsePromise !== undefined) {\n responsePromises.delete(key);\n try {\n if (responseMessage.error) {\n const error = responseMessage.error;\n responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));\n }\n else if (responseMessage.result !== undefined) {\n responsePromise.resolve(responseMessage.result);\n }\n else {\n throw new Error('Should never happen.');\n }\n }\n catch (error) {\n if (error.message) {\n logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);\n }\n else {\n logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);\n }\n }\n }\n }\n }\n function handleNotification(message) {\n if (isDisposed()) {\n // See handle request.\n return;\n }\n let type = undefined;\n let notificationHandler;\n if (message.method === CancelNotification.type.method) {\n const cancelId = message.params.id;\n knownCanceledRequests.delete(cancelId);\n traceReceivedNotification(message);\n return;\n }\n else {\n const element = notificationHandlers.get(message.method);\n if (element) {\n notificationHandler = element.handler;\n type = element.type;\n }\n }\n if (notificationHandler || starNotificationHandler) {\n try {\n traceReceivedNotification(message);\n if (notificationHandler) {\n if (message.params === undefined) {\n if (type !== undefined) {\n if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {\n logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);\n }\n }\n notificationHandler();\n }\n else if (Array.isArray(message.params)) {\n // There are JSON-RPC libraries that send progress message as positional params although\n // specified as named. So convert them if this is the case.\n const params = message.params;\n if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {\n notificationHandler({ token: params[0], value: params[1] });\n }\n else {\n if (type !== undefined) {\n if (type.parameterStructures === messages_1.ParameterStructures.byName) {\n logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);\n }\n if (type.numberOfParams !== message.params.length) {\n logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);\n }\n }\n notificationHandler(...params);\n }\n }\n else {\n if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {\n logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);\n }\n notificationHandler(message.params);\n }\n }\n else if (starNotificationHandler) {\n starNotificationHandler(message.method, message.params);\n }\n }\n catch (error) {\n if (error.message) {\n logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);\n }\n else {\n logger.error(`Notification handler '${message.method}' failed unexpectedly.`);\n }\n }\n }\n else {\n unhandledNotificationEmitter.fire(message);\n }\n }\n function handleInvalidMessage(message) {\n if (!message) {\n logger.error('Received empty message.');\n return;\n }\n logger.error(`Received message which is neither a response nor a notification message:\\n${JSON.stringify(message, null, 4)}`);\n // Test whether we find an id to reject the promise\n const responseMessage = message;\n if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {\n const key = responseMessage.id;\n const responseHandler = responsePromises.get(key);\n if (responseHandler) {\n responseHandler.reject(new Error('The received response has neither a result nor an error property.'));\n }\n }\n }\n function stringifyTrace(params) {\n if (params === undefined || params === null) {\n return undefined;\n }\n switch (trace) {\n case Trace.Verbose:\n return JSON.stringify(params, null, 4);\n case Trace.Compact:\n return JSON.stringify(params);\n default:\n return undefined;\n }\n }\n function traceSendingRequest(message) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);\n }\n else {\n logLSPMessage('send-request', message);\n }\n }\n function traceSendingNotification(message) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n else {\n data = 'No parameters provided.\\n\\n';\n }\n }\n tracer.log(`Sending notification '${message.method}'.`, data);\n }\n else {\n logLSPMessage('send-notification', message);\n }\n }\n function traceSendingResponse(message, method, startTime) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.error && message.error.data) {\n data = `Error data: ${stringifyTrace(message.error.data)}\\n\\n`;\n }\n else {\n if (message.result) {\n data = `Result: ${stringifyTrace(message.result)}\\n\\n`;\n }\n else if (message.error === undefined) {\n data = 'No result returned.\\n\\n';\n }\n }\n }\n tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);\n }\n else {\n logLSPMessage('send-response', message);\n }\n }\n function traceReceivedRequest(message) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n tracer.log(`Received request '${message.method} - (${message.id})'.`, data);\n }\n else {\n logLSPMessage('receive-request', message);\n }\n }\n function traceReceivedNotification(message) {\n if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.params) {\n data = `Params: ${stringifyTrace(message.params)}\\n\\n`;\n }\n else {\n data = 'No parameters provided.\\n\\n';\n }\n }\n tracer.log(`Received notification '${message.method}'.`, data);\n }\n else {\n logLSPMessage('receive-notification', message);\n }\n }\n function traceReceivedResponse(message, responsePromise) {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n if (traceFormat === TraceFormat.Text) {\n let data = undefined;\n if (trace === Trace.Verbose || trace === Trace.Compact) {\n if (message.error && message.error.data) {\n data = `Error data: ${stringifyTrace(message.error.data)}\\n\\n`;\n }\n else {\n if (message.result) {\n data = `Result: ${stringifyTrace(message.result)}\\n\\n`;\n }\n else if (message.error === undefined) {\n data = 'No result returned.\\n\\n';\n }\n }\n }\n if (responsePromise) {\n const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';\n tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);\n }\n else {\n tracer.log(`Received response ${message.id} without active response promise.`, data);\n }\n }\n else {\n logLSPMessage('receive-response', message);\n }\n }\n function logLSPMessage(type, message) {\n if (!tracer || trace === Trace.Off) {\n return;\n }\n const lspMessage = {\n isLSPMessage: true,\n type,\n message,\n timestamp: Date.now()\n };\n tracer.log(lspMessage);\n }\n function throwIfClosedOrDisposed() {\n if (isClosed()) {\n throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');\n }\n if (isDisposed()) {\n throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');\n }\n }\n function throwIfListening() {\n if (isListening()) {\n throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');\n }\n }\n function throwIfNotListening() {\n if (!isListening()) {\n throw new Error('Call listen() first.');\n }\n }\n function undefinedToNull(param) {\n if (param === undefined) {\n return null;\n }\n else {\n return param;\n }\n }\n function nullToUndefined(param) {\n if (param === null) {\n return undefined;\n }\n else {\n return param;\n }\n }\n function isNamedParam(param) {\n return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object';\n }\n function computeSingleParam(parameterStructures, param) {\n switch (parameterStructures) {\n case messages_1.ParameterStructures.auto:\n if (isNamedParam(param)) {\n return nullToUndefined(param);\n }\n else {\n return [undefinedToNull(param)];\n }\n case messages_1.ParameterStructures.byName:\n if (!isNamedParam(param)) {\n throw new Error(`Received parameters by name but param is not an object literal.`);\n }\n return nullToUndefined(param);\n case messages_1.ParameterStructures.byPosition:\n return [undefinedToNull(param)];\n default:\n throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);\n }\n }\n function computeMessageParams(type, params) {\n let result;\n const numberOfParams = type.numberOfParams;\n switch (numberOfParams) {\n case 0:\n result = undefined;\n break;\n case 1:\n result = computeSingleParam(type.parameterStructures, params[0]);\n break;\n default:\n result = [];\n for (let i = 0; i < params.length && i < numberOfParams; i++) {\n result.push(undefinedToNull(params[i]));\n }\n if (params.length < numberOfParams) {\n for (let i = params.length; i < numberOfParams; i++) {\n result.push(null);\n }\n }\n break;\n }\n return result;\n }\n const connection = {\n sendNotification: (type, ...args) => {\n throwIfClosedOrDisposed();\n let method;\n let messageParams;\n if (Is.string(type)) {\n method = type;\n const first = args[0];\n let paramStart = 0;\n let parameterStructures = messages_1.ParameterStructures.auto;\n if (messages_1.ParameterStructures.is(first)) {\n paramStart = 1;\n parameterStructures = first;\n }\n let paramEnd = args.length;\n const numberOfParams = paramEnd - paramStart;\n switch (numberOfParams) {\n case 0:\n messageParams = undefined;\n break;\n case 1:\n messageParams = computeSingleParam(parameterStructures, args[paramStart]);\n break;\n default:\n if (parameterStructures === messages_1.ParameterStructures.byName) {\n throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);\n }\n messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));\n break;\n }\n }\n else {\n const params = args;\n method = type.method;\n messageParams = computeMessageParams(type, params);\n }\n const notificationMessage = {\n jsonrpc: version,\n method: method,\n params: messageParams\n };\n traceSendingNotification(notificationMessage);\n return messageWriter.write(notificationMessage).catch((error) => {\n logger.error(`Sending notification failed.`);\n throw error;\n });\n },\n onNotification: (type, handler) => {\n throwIfClosedOrDisposed();\n let method;\n if (Is.func(type)) {\n starNotificationHandler = type;\n }\n else if (handler) {\n if (Is.string(type)) {\n method = type;\n notificationHandlers.set(type, { type: undefined, handler });\n }\n else {\n method = type.method;\n notificationHandlers.set(type.method, { type, handler });\n }\n }\n return {\n dispose: () => {\n if (method !== undefined) {\n notificationHandlers.delete(method);\n }\n else {\n starNotificationHandler = undefined;\n }\n }\n };\n },\n onProgress: (_type, token, handler) => {\n if (progressHandlers.has(token)) {\n throw new Error(`Progress handler for token ${token} already registered`);\n }\n progressHandlers.set(token, handler);\n return {\n dispose: () => {\n progressHandlers.delete(token);\n }\n };\n },\n sendProgress: (_type, token, value) => {\n // This should not await but simple return to ensure that we don't have another\n // async scheduling. Otherwise one send could overtake another send.\n return connection.sendNotification(ProgressNotification.type, { token, value });\n },\n onUnhandledProgress: unhandledProgressEmitter.event,\n sendRequest: (type, ...args) => {\n throwIfClosedOrDisposed();\n throwIfNotListening();\n let method;\n let messageParams;\n let token = undefined;\n if (Is.string(type)) {\n method = type;\n const first = args[0];\n const last = args[args.length - 1];\n let paramStart = 0;\n let parameterStructures = messages_1.ParameterStructures.auto;\n if (messages_1.ParameterStructures.is(first)) {\n paramStart = 1;\n parameterStructures = first;\n }\n let paramEnd = args.length;\n if (cancellation_1.CancellationToken.is(last)) {\n paramEnd = paramEnd - 1;\n token = last;\n }\n const numberOfParams = paramEnd - paramStart;\n switch (numberOfParams) {\n case 0:\n messageParams = undefined;\n break;\n case 1:\n messageParams = computeSingleParam(parameterStructures, args[paramStart]);\n break;\n default:\n if (parameterStructures === messages_1.ParameterStructures.byName) {\n throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);\n }\n messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));\n break;\n }\n }\n else {\n const params = args;\n method = type.method;\n messageParams = computeMessageParams(type, params);\n const numberOfParams = type.numberOfParams;\n token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;\n }\n const id = sequenceNumber++;\n let disposable;\n if (token) {\n disposable = token.onCancellationRequested(() => {\n const p = cancellationStrategy.sender.sendCancellation(connection, id);\n if (p === undefined) {\n logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);\n return Promise.resolve();\n }\n else {\n return p.catch(() => {\n logger.log(`Sending cancellation messages for id ${id} failed`);\n });\n }\n });\n }\n const requestMessage = {\n jsonrpc: version,\n id: id,\n method: method,\n params: messageParams\n };\n traceSendingRequest(requestMessage);\n if (typeof cancellationStrategy.sender.enableCancellation === 'function') {\n cancellationStrategy.sender.enableCancellation(requestMessage);\n }\n return new Promise(async (resolve, reject) => {\n const resolveWithCleanup = (r) => {\n resolve(r);\n cancellationStrategy.sender.cleanup(id);\n disposable?.dispose();\n };\n const rejectWithCleanup = (r) => {\n reject(r);\n cancellationStrategy.sender.cleanup(id);\n disposable?.dispose();\n };\n const responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };\n try {\n responsePromises.set(id, responsePromise);\n await messageWriter.write(requestMessage);\n }\n catch (error) {\n // Writing the message failed. So we need to delete it from the response promises and\n // reject it.\n responsePromises.delete(id);\n responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : 'Unknown reason'));\n logger.error(`Sending request failed.`);\n throw error;\n }\n });\n },\n onRequest: (type, handler) => {\n throwIfClosedOrDisposed();\n let method = null;\n if (StarRequestHandler.is(type)) {\n method = undefined;\n starRequestHandler = type;\n }\n else if (Is.string(type)) {\n method = null;\n if (handler !== undefined) {\n method = type;\n requestHandlers.set(type, { handler: handler, type: undefined });\n }\n }\n else {\n if (handler !== undefined) {\n method = type.method;\n requestHandlers.set(type.method, { type, handler });\n }\n }\n return {\n dispose: () => {\n if (method === null) {\n return;\n }\n if (method !== undefined) {\n requestHandlers.delete(method);\n }\n else {\n starRequestHandler = undefined;\n }\n }\n };\n },\n hasPendingResponse: () => {\n return responsePromises.size > 0;\n },\n trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {\n let _sendNotification = false;\n let _traceFormat = TraceFormat.Text;\n if (sendNotificationOrTraceOptions !== undefined) {\n if (Is.boolean(sendNotificationOrTraceOptions)) {\n _sendNotification = sendNotificationOrTraceOptions;\n }\n else {\n _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;\n _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;\n }\n }\n trace = _value;\n traceFormat = _traceFormat;\n if (trace === Trace.Off) {\n tracer = undefined;\n }\n else {\n tracer = _tracer;\n }\n if (_sendNotification && !isClosed() && !isDisposed()) {\n await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });\n }\n },\n onError: errorEmitter.event,\n onClose: closeEmitter.event,\n onUnhandledNotification: unhandledNotificationEmitter.event,\n onDispose: disposeEmitter.event,\n end: () => {\n messageWriter.end();\n },\n dispose: () => {\n if (isDisposed()) {\n return;\n }\n state = ConnectionState.Disposed;\n disposeEmitter.fire(undefined);\n const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, 'Pending response rejected since connection got disposed');\n for (const promise of responsePromises.values()) {\n promise.reject(error);\n }\n responsePromises = new Map();\n requestTokens = new Map();\n knownCanceledRequests = new Set();\n messageQueue = new linkedMap_1.LinkedMap();\n // Test for backwards compatibility\n if (Is.func(messageWriter.dispose)) {\n messageWriter.dispose();\n }\n if (Is.func(messageReader.dispose)) {\n messageReader.dispose();\n }\n },\n listen: () => {\n throwIfClosedOrDisposed();\n throwIfListening();\n state = ConnectionState.Listening;\n messageReader.listen(callback);\n },\n inspect: () => {\n // eslint-disable-next-line no-console\n (0, ral_1.default)().console.log('inspect');\n }\n };\n connection.onNotification(LogTraceNotification.type, (params) => {\n if (trace === Trace.Off || !tracer) {\n return;\n }\n const verbose = trace === Trace.Verbose || trace === Trace.Compact;\n tracer.log(params.message, verbose ? params.verbose : undefined);\n });\n connection.onNotification(ProgressNotification.type, (params) => {\n const handler = progressHandlers.get(params.token);\n if (handler) {\n handler(params.value);\n }\n else {\n unhandledProgressEmitter.fire(params);\n }\n });\n return connection;\n}\nexports.createMessageConnection = createMessageConnection;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\n/// <reference path=\"../../typings/thenable.d.ts\" />\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;\nexports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = void 0;\nconst messages_1 = require(\"./messages\");\nObject.defineProperty(exports, \"Message\", { enumerable: true, get: function () { return messages_1.Message; } });\nObject.defineProperty(exports, \"RequestType\", { enumerable: true, get: function () { return messages_1.RequestType; } });\nObject.defineProperty(exports, \"RequestType0\", { enumerable: true, get: function () { return messages_1.RequestType0; } });\nObject.defineProperty(exports, \"RequestType1\", { enumerable: true, get: function () { return messages_1.RequestType1; } });\nObject.defineProperty(exports, \"RequestType2\", { enumerable: true, get: function () { return messages_1.RequestType2; } });\nObject.defineProperty(exports, \"RequestType3\", { enumerable: true, get: function () { return messages_1.RequestType3; } });\nObject.defineProperty(exports, \"RequestType4\", { enumerable: true, get: function () { return messages_1.RequestType4; } });\nObject.defineProperty(exports, \"RequestType5\", { enumerable: true, get: function () { return messages_1.RequestType5; } });\nObject.defineProperty(exports, \"RequestType6\", { enumerable: true, get: function () { return messages_1.RequestType6; } });\nObject.defineProperty(exports, \"RequestType7\", { enumerable: true, get: function () { return messages_1.RequestType7; } });\nObject.defineProperty(exports, \"RequestType8\", { enumerable: true, get: function () { return messages_1.RequestType8; } });\nObject.defineProperty(exports, \"RequestType9\", { enumerable: true, get: function () { return messages_1.RequestType9; } });\nObject.defineProperty(exports, \"ResponseError\", { enumerable: true, get: function () { return messages_1.ResponseError; } });\nObject.defineProperty(exports, \"ErrorCodes\", { enumerable: true, get: function () { return messages_1.ErrorCodes; } });\nObject.defineProperty(exports, \"NotificationType\", { enumerable: true, get: function () { return messages_1.NotificationType; } });\nObject.defineProperty(exports, \"NotificationType0\", { enumerable: true, get: function () { return messages_1.NotificationType0; } });\nObject.defineProperty(exports, \"NotificationType1\", { enumerable: true, get: function () { return messages_1.NotificationType1; } });\nObject.defineProperty(exports, \"NotificationType2\", { enumerable: true, get: function () { return messages_1.NotificationType2; } });\nObject.defineProperty(exports, \"NotificationType3\", { enumerable: true, get: function () { return messages_1.NotificationType3; } });\nObject.defineProperty(exports, \"NotificationType4\", { enumerable: true, get: function () { return messages_1.NotificationType4; } });\nObject.defineProperty(exports, \"NotificationType5\", { enumerable: true, get: function () { return messages_1.NotificationType5; } });\nObject.defineProperty(exports, \"NotificationType6\", { enumerable: true, get: function () { return messages_1.NotificationType6; } });\nObject.defineProperty(exports, \"NotificationType7\", { enumerable: true, get: function () { return messages_1.NotificationType7; } });\nObject.defineProperty(exports, \"NotificationType8\", { enumerable: true, get: function () { return messages_1.NotificationType8; } });\nObject.defineProperty(exports, \"NotificationType9\", { enumerable: true, get: function () { return messages_1.NotificationType9; } });\nObject.defineProperty(exports, \"ParameterStructures\", { enumerable: true, get: function () { return messages_1.ParameterStructures; } });\nconst linkedMap_1 = require(\"./linkedMap\");\nObject.defineProperty(exports, \"LinkedMap\", { enumerable: true, get: function () { return linkedMap_1.LinkedMap; } });\nObject.defineProperty(exports, \"LRUCache\", { enumerable: true, get: function () { return linkedMap_1.LRUCache; } });\nObject.defineProperty(exports, \"Touch\", { enumerable: true, get: function () { return linkedMap_1.Touch; } });\nconst disposable_1 = require(\"./disposable\");\nObject.defineProperty(exports, \"Disposable\", { enumerable: true, get: function () { return disposable_1.Disposable; } });\nconst events_1 = require(\"./events\");\nObject.defineProperty(exports, \"Event\", { enumerable: true, get: function () { return events_1.Event; } });\nObject.defineProperty(exports, \"Emitter\", { enumerable: true, get: function () { return events_1.Emitter; } });\nconst cancellation_1 = require(\"./cancellation\");\nObject.defineProperty(exports, \"CancellationTokenSource\", { enumerable: true, get: function () { return cancellation_1.CancellationTokenSource; } });\nObject.defineProperty(exports, \"CancellationToken\", { enumerable: true, get: function () { return cancellation_1.CancellationToken; } });\nconst sharedArrayCancellation_1 = require(\"./sharedArrayCancellation\");\nObject.defineProperty(exports, \"SharedArraySenderStrategy\", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArraySenderStrategy; } });\nObject.defineProperty(exports, \"SharedArrayReceiverStrategy\", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArrayReceiverStrategy; } });\nconst messageReader_1 = require(\"./messageReader\");\nObject.defineProperty(exports, \"MessageReader\", { enumerable: true, get: function () { return messageReader_1.MessageReader; } });\nObject.defineProperty(exports, \"AbstractMessageReader\", { enumerable: true, get: function () { return messageReader_1.AbstractMessageReader; } });\nObject.defineProperty(exports, \"ReadableStreamMessageReader\", { enumerable: true, get: function () { return messageReader_1.ReadableStreamMessageReader; } });\nconst messageWriter_1 = require(\"./messageWriter\");\nObject.defineProperty(exports, \"MessageWriter\", { enumerable: true, get: function () { return messageWriter_1.MessageWriter; } });\nObject.defineProperty(exports, \"AbstractMessageWriter\", { enumerable: true, get: function () { return messageWriter_1.AbstractMessageWriter; } });\nObject.defineProperty(exports, \"WriteableStreamMessageWriter\", { enumerable: true, get: function () { return messageWriter_1.WriteableStreamMessageWriter; } });\nconst messageBuffer_1 = require(\"./messageBuffer\");\nObject.defineProperty(exports, \"AbstractMessageBuffer\", { enumerable: true, get: function () { return messageBuffer_1.AbstractMessageBuffer; } });\nconst connection_1 = require(\"./connection\");\nObject.defineProperty(exports, \"ConnectionStrategy\", { enumerable: true, get: function () { return connection_1.ConnectionStrategy; } });\nObject.defineProperty(exports, \"ConnectionOptions\", { enumerable: true, get: function () { return connection_1.ConnectionOptions; } });\nObject.defineProperty(exports, \"NullLogger\", { enumerable: true, get: function () { return connection_1.NullLogger; } });\nObject.defineProperty(exports, \"createMessageConnection\", { enumerable: true, get: function () { return connection_1.createMessageConnection; } });\nObject.defineProperty(exports, \"ProgressToken\", { enumerable: true, get: function () { return connection_1.ProgressToken; } });\nObject.defineProperty(exports, \"ProgressType\", { enumerable: true, get: function () { return connection_1.ProgressType; } });\nObject.defineProperty(exports, \"Trace\", { enumerable: true, get: function () { return connection_1.Trace; } });\nObject.defineProperty(exports, \"TraceValues\", { enumerable: true, get: function () { return connection_1.TraceValues; } });\nObject.defineProperty(exports, \"TraceFormat\", { enumerable: true, get: function () { return connection_1.TraceFormat; } });\nObject.defineProperty(exports, \"SetTraceNotification\", { enumerable: true, get: function () { return connection_1.SetTraceNotification; } });\nObject.defineProperty(exports, \"LogTraceNotification\", { enumerable: true, get: function () { return connection_1.LogTraceNotification; } });\nObject.defineProperty(exports, \"ConnectionErrors\", { enumerable: true, get: function () { return connection_1.ConnectionErrors; } });\nObject.defineProperty(exports, \"ConnectionError\", { enumerable: true, get: function () { return connection_1.ConnectionError; } });\nObject.defineProperty(exports, \"CancellationReceiverStrategy\", { enumerable: true, get: function () { return connection_1.CancellationReceiverStrategy; } });\nObject.defineProperty(exports, \"CancellationSenderStrategy\", { enumerable: true, get: function () { return connection_1.CancellationSenderStrategy; } });\nObject.defineProperty(exports, \"CancellationStrategy\", { enumerable: true, get: function () { return connection_1.CancellationStrategy; } });\nObject.defineProperty(exports, \"MessageStrategy\", { enumerable: true, get: function () { return connection_1.MessageStrategy; } });\nconst ral_1 = require(\"./ral\");\nexports.RAL = ral_1.default;\n","\"use strict\";\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ------------------------------------------------------------------------------------------ */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"util\");\nconst api_1 = require(\"../common/api\");\nclass MessageBuffer extends api_1.AbstractMessageBuffer {\n constructor(encoding = 'utf-8') {\n super(encoding);\n }\n emptyBuffer() {\n return MessageBuffer.emptyBuffer;\n }\n fromString(value, encoding) {\n return Buffer.from(value, encoding);\n }\n toString(value, encoding) {\n if (value instanceof Buffer) {\n return value.toString(encoding);\n }\n else {\n return new util_1.TextDecoder(encoding).decode(value);\n }\n }\n asNative(buffer, length) {\n if (length === undefined) {\n return buffer instanceof Buffer ? buffer : Buffer.from(buffer);\n }\n else {\n return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);\n }\n }\n allocNative(length) {\n return Buffer.allocUnsafe(length);\n }\n}\nMessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);\nclass ReadableStreamWrapper {\n constructor(stream) {\n this.stream = stream;\n }\n onClose(listener) {\n this.stream.on('close', listener);\n return api_1.Disposable.create(() => this.stream.off('close', listener));\n }\n onError(listener) {\n this.stream.on('error', listener);\n return api_1.Disposable.create(() => this.stream.off('error', listener));\n }\n onEnd(listener) {\n this.stream.on('end', listener);\n return api_1.Disposable.create(() => this.stream.off('end', listener));\n }\n onData(listener) {\n this.stream.on('data', listener);\n return api_1.Disposable.create(() => this.stream.off('data', listener));\n }\n}\nclass WritableStreamWrapper {\n constructor(stream) {\n this.stream = stream;\n }\n onClose(listener) {\n this.stream.on('close', listener);\n return api_1.Disposable.create(() => this.stream.off('close', listener));\n }\n onError(listener) {\n this.stream.on('error', listener);\n return api_1.Disposable.create(() => this.stream.off('error', listener));\n }\n onEnd(listener) {\n this.stream.on('end', listener);\n return api_1.Disposable.create(() => this.stream.off('end', listener));\n }\n write(data, encoding) {\n return new Promise((resolve, reject) => {\n const callback = (error) => {\n if (error === undefined || error === null) {\n resolve();\n }\n else {\n reject(error);\n }\n };\n if (typeof data === 'string') {\n this.stream.write(data, encoding, callback);\n }\n else {\n this.stream.write(data, callback);\n }\n });\n }\n end() {\n this.stream.end();\n }\n}\nconst _ril = Object.freeze({\n messageBuffer: Object.freeze({\n create: (encoding) => new MessageBuffer(encoding)\n }),\n applicationJson: Object.freeze({\n encoder: Object.freeze({\n name: 'application/json',\n encode: (msg, options) => {\n try {\n return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset));\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n }),\n decoder: Object.freeze({\n name: 'application/json',\n decode: (buffer, options) => {\n try {\n if (buffer instanceof Buffer) {\n return Promise.resolve(JSON.parse(buffer.toString(options.charset)));\n }\n else {\n return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));\n }\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n })\n }),\n stream: Object.freeze({\n asReadableStream: (stream) => new ReadableStreamWrapper(stream),\n asWritableStream: (stream) => new WritableStreamWrapper(stream)\n }),\n console: console,\n timer: Object.freeze({\n setTimeout(callback, ms, ...args) {\n const handle = setTimeout(callback, ms, ...args);\n return { dispose: () => clearTimeout(handle) };\n },\n setImmediate(callback, ...args) {\n const handle = setImmediate(callback, ...args);\n return { dispose: () => clearImmediate(handle) };\n },\n setInterval(callback, ms, ...args) {\n const handle = setInterval(callback, ms, ...args);\n return { dispose: () => clearInterval(handle) };\n }\n })\n});\nfunction RIL() {\n return _ril;\n}\n(function (RIL) {\n function install() {\n api_1.RAL.install(_ril);\n }\n RIL.install = install;\n})(RIL || (RIL = {}));\nexports.default = RIL;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0;\n/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ----------------------------------------------------------------------------------------- */\nconst ril_1 = require(\"./ril\");\n// Install the node runtime abstract.\nril_1.default.install();\nconst path = require(\"path\");\nconst os = require(\"os\");\nconst crypto_1 = require(\"crypto\");\nconst net_1 = require(\"net\");\nconst api_1 = require(\"../common/api\");\n__exportStar(require(\"../common/api\"), exports);\nclass IPCMessageReader extends api_1.AbstractMessageReader {\n constructor(process) {\n super();\n this.process = process;\n let eventEmitter = this.process;\n eventEmitter.on('error', (error) => this.fireError(error));\n eventEmitter.on('close', () => this.fireClose());\n }\n listen(callback) {\n this.process.on('message', callback);\n return api_1.Disposable.create(() => this.process.off('message', callback));\n }\n}\nexports.IPCMessageReader = IPCMessageReader;\nclass IPCMessageWriter extends api_1.AbstractMessageWriter {\n constructor(process) {\n super();\n this.process = process;\n this.errorCount = 0;\n const eventEmitter = this.process;\n eventEmitter.on('error', (error) => this.fireError(error));\n eventEmitter.on('close', () => this.fireClose);\n }\n write(msg) {\n try {\n if (typeof this.process.send === 'function') {\n this.process.send(msg, undefined, undefined, (error) => {\n if (error) {\n this.errorCount++;\n this.handleError(error, msg);\n }\n else {\n this.errorCount = 0;\n }\n });\n }\n return Promise.resolve();\n }\n catch (error) {\n this.handleError(error, msg);\n return Promise.reject(error);\n }\n }\n handleError(error, msg) {\n this.errorCount++;\n this.fireError(error, msg, this.errorCount);\n }\n end() {\n }\n}\nexports.IPCMessageWriter = IPCMessageWriter;\nclass PortMessageReader extends api_1.AbstractMessageReader {\n constructor(port) {\n super();\n this.onData = new api_1.Emitter;\n port.on('close', () => this.fireClose);\n port.on('error', (error) => this.fireError(error));\n port.on('message', (message) => {\n this.onData.fire(message);\n });\n }\n listen(callback) {\n return this.onData.event(callback);\n }\n}\nexports.PortMessageReader = PortMessageReader;\nclass PortMessageWriter extends api_1.AbstractMessageWriter {\n constructor(port) {\n super();\n this.port = port;\n this.errorCount = 0;\n port.on('close', () => this.fireClose());\n port.on('error', (error) => this.fireError(error));\n }\n write(msg) {\n try {\n this.port.postMessage(msg);\n return Promise.resolve();\n }\n catch (error) {\n this.handleError(error, msg);\n return Promise.reject(error);\n }\n }\n handleError(error, msg) {\n this.errorCount++;\n this.fireError(error, msg, this.errorCount);\n }\n end() {\n }\n}\nexports.PortMessageWriter = PortMessageWriter;\nclass SocketMessageReader extends api_1.ReadableStreamMessageReader {\n constructor(socket, encoding = 'utf-8') {\n super((0, ril_1.default)().stream.asReadableStream(socket), encoding);\n }\n}\nexports.SocketMessageReader = SocketMessageReader;\nclass SocketMessageWriter extends api_1.WriteableStreamMessageWriter {\n constructor(socket, options) {\n super((0, ril_1.default)().stream.asWritableStream(socket), options);\n this.socket = socket;\n }\n dispose() {\n super.dispose();\n this.socket.destroy();\n }\n}\nexports.SocketMessageWriter = SocketMessageWriter;\nclass StreamMessageReader extends api_1.ReadableStreamMessageReader {\n constructor(readable, encoding) {\n super((0, ril_1.default)().stream.asReadableStream(readable), encoding);\n }\n}\nexports.StreamMessageReader = StreamMessageReader;\nclass StreamMessageWriter extends api_1.WriteableStreamMessageWriter {\n constructor(writable, options) {\n super((0, ril_1.default)().stream.asWritableStream(writable), options);\n }\n}\nexports.StreamMessageWriter = StreamMessageWriter;\nconst XDG_RUNTIME_DIR = process.env['XDG_RUNTIME_DIR'];\nconst safeIpcPathLengths = new Map([\n ['linux', 107],\n ['darwin', 103]\n]);\nfunction generateRandomPipeName() {\n const randomSuffix = (0, crypto_1.randomBytes)(21).toString('hex');\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\vscode-jsonrpc-${randomSuffix}-sock`;\n }\n let result;\n if (XDG_RUNTIME_DIR) {\n result = path.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);\n }\n else {\n result = path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);\n }\n const limit = safeIpcPathLengths.get(process.platform);\n if (limit !== undefined && result.length > limit) {\n (0, ril_1.default)().console.warn(`WARNING: IPC handle \"${result}\" is longer than ${limit} characters.`);\n }\n return result;\n}\nexports.generateRandomPipeName = generateRandomPipeName;\nfunction createClientPipeTransport(pipeName, encoding = 'utf-8') {\n let connectResolve;\n const connected = new Promise((resolve, _reject) => {\n connectResolve = resolve;\n });\n return new Promise((resolve, reject) => {\n let server = (0, net_1.createServer)((socket) => {\n server.close();\n connectResolve([\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ]);\n });\n server.on('error', reject);\n server.listen(pipeName, () => {\n server.removeListener('error', reject);\n resolve({\n onConnected: () => { return connected; }\n });\n });\n });\n}\nexports.createClientPipeTransport = createClientPipeTransport;\nfunction createServerPipeTransport(pipeName, encoding = 'utf-8') {\n const socket = (0, net_1.createConnection)(pipeName);\n return [\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ];\n}\nexports.createServerPipeTransport = createServerPipeTransport;\nfunction createClientSocketTransport(port, encoding = 'utf-8') {\n let connectResolve;\n const connected = new Promise((resolve, _reject) => {\n connectResolve = resolve;\n });\n return new Promise((resolve, reject) => {\n const server = (0, net_1.createServer)((socket) => {\n server.close();\n connectResolve([\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ]);\n });\n server.on('error', reject);\n server.listen(port, '127.0.0.1', () => {\n server.removeListener('error', reject);\n resolve({\n onConnected: () => { return connected; }\n });\n });\n });\n}\nexports.createClientSocketTransport = createClientSocketTransport;\nfunction createServerSocketTransport(port, encoding = 'utf-8') {\n const socket = (0, net_1.createConnection)(port, '127.0.0.1');\n return [\n new SocketMessageReader(socket, encoding),\n new SocketMessageWriter(socket, encoding)\n ];\n}\nexports.createServerSocketTransport = createServerSocketTransport;\nfunction isReadableStream(value) {\n const candidate = value;\n return candidate.read !== undefined && candidate.addListener !== undefined;\n}\nfunction isWritableStream(value) {\n const candidate = value;\n return candidate.write !== undefined && candidate.addListener !== undefined;\n}\nfunction createMessageConnection(input, output, logger, options) {\n if (!logger) {\n logger = api_1.NullLogger;\n }\n const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;\n const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;\n if (api_1.ConnectionStrategy.is(options)) {\n options = { connectionStrategy: options };\n }\n return (0, api_1.createMessageConnection)(reader, writer, logger, options);\n}\nexports.createMessageConnection = createMessageConnection;\n","/* --------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n * ----------------------------------------------------------------------------------------- */\n'use strict';\n\nmodule.exports = require('./lib/node/main');","function createServerRpc(connection) {\n return {\n ping: async (params) => connection.sendRequest(\"ping\", params),\n models: {\n list: async () => connection.sendRequest(\"models.list\", {})\n },\n tools: {\n list: async (params) => connection.sendRequest(\"tools.list\", params)\n },\n account: {\n getQuota: async () => connection.sendRequest(\"account.getQuota\", {})\n }\n };\n}\nfunction createSessionRpc(connection, sessionId) {\n return {\n model: {\n getCurrent: async () => connection.sendRequest(\"session.model.getCurrent\", { sessionId }),\n switchTo: async (params) => connection.sendRequest(\"session.model.switchTo\", { sessionId, ...params })\n },\n mode: {\n get: async () => connection.sendRequest(\"session.mode.get\", { sessionId }),\n set: async (params) => connection.sendRequest(\"session.mode.set\", { sessionId, ...params })\n },\n plan: {\n read: async () => connection.sendRequest(\"session.plan.read\", { sessionId }),\n update: async (params) => connection.sendRequest(\"session.plan.update\", { sessionId, ...params }),\n delete: async () => connection.sendRequest(\"session.plan.delete\", { sessionId })\n },\n workspace: {\n listFiles: async () => connection.sendRequest(\"session.workspace.listFiles\", { sessionId }),\n readFile: async (params) => connection.sendRequest(\"session.workspace.readFile\", { sessionId, ...params }),\n createFile: async (params) => connection.sendRequest(\"session.workspace.createFile\", { sessionId, ...params })\n },\n fleet: {\n start: async (params) => connection.sendRequest(\"session.fleet.start\", { sessionId, ...params })\n },\n agent: {\n list: async () => connection.sendRequest(\"session.agent.list\", { sessionId }),\n getCurrent: async () => connection.sendRequest(\"session.agent.getCurrent\", { sessionId }),\n select: async (params) => connection.sendRequest(\"session.agent.select\", { sessionId, ...params }),\n deselect: async () => connection.sendRequest(\"session.agent.deselect\", { sessionId })\n },\n compaction: {\n compact: async () => connection.sendRequest(\"session.compaction.compact\", { sessionId })\n },\n tools: {\n handlePendingToolCall: async (params) => connection.sendRequest(\"session.tools.handlePendingToolCall\", { sessionId, ...params })\n },\n permissions: {\n handlePendingPermissionRequest: async (params) => connection.sendRequest(\"session.permissions.handlePendingPermissionRequest\", { sessionId, ...params })\n }\n };\n}\nexport {\n createServerRpc,\n createSessionRpc\n};\n","const SDK_PROTOCOL_VERSION = 3;\nfunction getSdkProtocolVersion() {\n return SDK_PROTOCOL_VERSION;\n}\nexport {\n SDK_PROTOCOL_VERSION,\n getSdkProtocolVersion\n};\n","import { ConnectionError, ResponseError } from \"vscode-jsonrpc/node\";\nimport { createSessionRpc } from \"./generated/rpc.js\";\nclass CopilotSession {\n /**\n * Creates a new CopilotSession instance.\n *\n * @param sessionId - The unique identifier for this session\n * @param connection - The JSON-RPC message connection to the Copilot CLI\n * @param workspacePath - Path to the session workspace directory (when infinite sessions enabled)\n * @internal This constructor is internal. Use {@link CopilotClient.createSession} to create sessions.\n */\n constructor(sessionId, connection, _workspacePath) {\n this.sessionId = sessionId;\n this.connection = connection;\n this._workspacePath = _workspacePath;\n }\n eventHandlers = /* @__PURE__ */ new Set();\n typedEventHandlers = /* @__PURE__ */ new Map();\n toolHandlers = /* @__PURE__ */ new Map();\n permissionHandler;\n userInputHandler;\n hooks;\n _rpc = null;\n /**\n * Typed session-scoped RPC methods.\n */\n get rpc() {\n if (!this._rpc) {\n this._rpc = createSessionRpc(this.connection, this.sessionId);\n }\n return this._rpc;\n }\n /**\n * Path to the session workspace directory when infinite sessions are enabled.\n * Contains checkpoints/, plan.md, and files/ subdirectories.\n * Undefined if infinite sessions are disabled.\n */\n get workspacePath() {\n return this._workspacePath;\n }\n /**\n * Sends a message to this session and waits for the response.\n *\n * The message is processed asynchronously. Subscribe to events via {@link on}\n * to receive streaming responses and other session events.\n *\n * @param options - The message options including the prompt and optional attachments\n * @returns A promise that resolves with the message ID of the response\n * @throws Error if the session has been disconnected or the connection fails\n *\n * @example\n * ```typescript\n * const messageId = await session.send({\n * prompt: \"Explain this code\",\n * attachments: [{ type: \"file\", path: \"./src/index.ts\" }]\n * });\n * ```\n */\n async send(options) {\n const response = await this.connection.sendRequest(\"session.send\", {\n sessionId: this.sessionId,\n prompt: options.prompt,\n attachments: options.attachments,\n mode: options.mode\n });\n return response.messageId;\n }\n /**\n * Sends a message to this session and waits until the session becomes idle.\n *\n * This is a convenience method that combines {@link send} with waiting for\n * the `session.idle` event. Use this when you want to block until the\n * assistant has finished processing the message.\n *\n * Events are still delivered to handlers registered via {@link on} while waiting.\n *\n * @param options - The message options including the prompt and optional attachments\n * @param timeout - Timeout in milliseconds (default: 60000). Controls how long to wait; does not abort in-flight agent work.\n * @returns A promise that resolves with the final assistant message when the session becomes idle,\n * or undefined if no assistant message was received\n * @throws Error if the timeout is reached before the session becomes idle\n * @throws Error if the session has been disconnected or the connection fails\n *\n * @example\n * ```typescript\n * // Send and wait for completion with default 60s timeout\n * const response = await session.sendAndWait({ prompt: \"What is 2+2?\" });\n * console.log(response?.data.content); // \"4\"\n * ```\n */\n async sendAndWait(options, timeout) {\n const effectiveTimeout = timeout ?? 6e4;\n let resolveIdle;\n let rejectWithError;\n const idlePromise = new Promise((resolve, reject) => {\n resolveIdle = resolve;\n rejectWithError = reject;\n });\n let lastAssistantMessage;\n const unsubscribe = this.on((event) => {\n if (event.type === \"assistant.message\") {\n lastAssistantMessage = event;\n } else if (event.type === \"session.idle\") {\n resolveIdle();\n } else if (event.type === \"session.error\") {\n const error = new Error(event.data.message);\n error.stack = event.data.stack;\n rejectWithError(error);\n }\n });\n let timeoutId;\n try {\n await this.send(options);\n const timeoutPromise = new Promise((_, reject) => {\n timeoutId = setTimeout(\n () => reject(\n new Error(\n `Timeout after ${effectiveTimeout}ms waiting for session.idle`\n )\n ),\n effectiveTimeout\n );\n });\n await Promise.race([idlePromise, timeoutPromise]);\n return lastAssistantMessage;\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n unsubscribe();\n }\n }\n on(eventTypeOrHandler, handler) {\n if (typeof eventTypeOrHandler === \"string\" && handler) {\n const eventType = eventTypeOrHandler;\n if (!this.typedEventHandlers.has(eventType)) {\n this.typedEventHandlers.set(eventType, /* @__PURE__ */ new Set());\n }\n const storedHandler = handler;\n this.typedEventHandlers.get(eventType).add(storedHandler);\n return () => {\n const handlers = this.typedEventHandlers.get(eventType);\n if (handlers) {\n handlers.delete(storedHandler);\n }\n };\n }\n const wildcardHandler = eventTypeOrHandler;\n this.eventHandlers.add(wildcardHandler);\n return () => {\n this.eventHandlers.delete(wildcardHandler);\n };\n }\n /**\n * Dispatches an event to all registered handlers.\n * Also handles broadcast request events internally (external tool calls, permissions).\n *\n * @param event - The session event to dispatch\n * @internal This method is for internal use by the SDK.\n */\n _dispatchEvent(event) {\n this._handleBroadcastEvent(event);\n const typedHandlers = this.typedEventHandlers.get(event.type);\n if (typedHandlers) {\n for (const handler of typedHandlers) {\n try {\n handler(event);\n } catch (_error) {\n }\n }\n }\n for (const handler of this.eventHandlers) {\n try {\n handler(event);\n } catch (_error) {\n }\n }\n }\n /**\n * Handles broadcast request events by executing local handlers and responding via RPC.\n * Handlers are dispatched as fire-and-forget — rejections propagate as unhandled promise\n * rejections, consistent with standard EventEmitter / event handler semantics.\n * @internal\n */\n _handleBroadcastEvent(event) {\n if (event.type === \"external_tool.requested\") {\n const { requestId, toolName } = event.data;\n const args = event.data.arguments;\n const toolCallId = event.data.toolCallId;\n const handler = this.toolHandlers.get(toolName);\n if (handler) {\n void this._executeToolAndRespond(requestId, toolName, toolCallId, args, handler);\n }\n } else if (event.type === \"permission.requested\") {\n const { requestId, permissionRequest } = event.data;\n if (this.permissionHandler) {\n void this._executePermissionAndRespond(requestId, permissionRequest);\n }\n }\n }\n /**\n * Executes a tool handler and sends the result back via RPC.\n * @internal\n */\n async _executeToolAndRespond(requestId, toolName, toolCallId, args, handler) {\n try {\n const rawResult = await handler(args, {\n sessionId: this.sessionId,\n toolCallId,\n toolName,\n arguments: args\n });\n let result;\n if (rawResult == null) {\n result = \"\";\n } else if (typeof rawResult === \"string\") {\n result = rawResult;\n } else {\n result = JSON.stringify(rawResult);\n }\n await this.rpc.tools.handlePendingToolCall({ requestId, result });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n try {\n await this.rpc.tools.handlePendingToolCall({ requestId, error: message });\n } catch (rpcError) {\n if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {\n throw rpcError;\n }\n }\n }\n }\n /**\n * Executes a permission handler and sends the result back via RPC.\n * @internal\n */\n async _executePermissionAndRespond(requestId, permissionRequest) {\n try {\n const result = await this.permissionHandler(permissionRequest, {\n sessionId: this.sessionId\n });\n await this.rpc.permissions.handlePendingPermissionRequest({ requestId, result });\n } catch (_error) {\n try {\n await this.rpc.permissions.handlePendingPermissionRequest({\n requestId,\n result: {\n kind: \"denied-no-approval-rule-and-could-not-request-from-user\"\n }\n });\n } catch (rpcError) {\n if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {\n throw rpcError;\n }\n }\n }\n }\n /**\n * Registers custom tool handlers for this session.\n *\n * Tools allow the assistant to execute custom functions. When the assistant\n * invokes a tool, the corresponding handler is called with the tool arguments.\n *\n * @param tools - An array of tool definitions with their handlers, or undefined to clear all tools\n * @internal This method is typically called internally when creating a session with tools.\n */\n registerTools(tools) {\n this.toolHandlers.clear();\n if (!tools) {\n return;\n }\n for (const tool of tools) {\n this.toolHandlers.set(tool.name, tool.handler);\n }\n }\n /**\n * Retrieves a registered tool handler by name.\n *\n * @param name - The name of the tool to retrieve\n * @returns The tool handler if found, or undefined\n * @internal This method is for internal use by the SDK.\n */\n getToolHandler(name) {\n return this.toolHandlers.get(name);\n }\n /**\n * Registers a handler for permission requests.\n *\n * When the assistant needs permission to perform certain actions (e.g., file operations),\n * this handler is called to approve or deny the request.\n *\n * @param handler - The permission handler function, or undefined to remove the handler\n * @internal This method is typically called internally when creating a session.\n */\n registerPermissionHandler(handler) {\n this.permissionHandler = handler;\n }\n /**\n * Registers a user input handler for ask_user requests.\n *\n * When the agent needs input from the user (via ask_user tool),\n * this handler is called to provide the response.\n *\n * @param handler - The user input handler function, or undefined to remove the handler\n * @internal This method is typically called internally when creating a session.\n */\n registerUserInputHandler(handler) {\n this.userInputHandler = handler;\n }\n /**\n * Registers hook handlers for session lifecycle events.\n *\n * Hooks allow custom logic to be executed at various points during\n * the session lifecycle (before/after tool use, session start/end, etc.).\n *\n * @param hooks - The hook handlers object, or undefined to remove all hooks\n * @internal This method is typically called internally when creating a session.\n */\n registerHooks(hooks) {\n this.hooks = hooks;\n }\n /**\n * Handles a permission request in the v2 protocol format (synchronous RPC).\n * Used as a back-compat adapter when connected to a v2 server.\n *\n * @param request - The permission request data from the CLI\n * @returns A promise that resolves with the permission decision\n * @internal This method is for internal use by the SDK.\n */\n async _handlePermissionRequestV2(request) {\n if (!this.permissionHandler) {\n return { kind: \"denied-no-approval-rule-and-could-not-request-from-user\" };\n }\n try {\n const result = await this.permissionHandler(request, {\n sessionId: this.sessionId\n });\n return result;\n } catch (_error) {\n return { kind: \"denied-no-approval-rule-and-could-not-request-from-user\" };\n }\n }\n /**\n * Handles a user input request from the Copilot CLI.\n *\n * @param request - The user input request data from the CLI\n * @returns A promise that resolves with the user's response\n * @internal This method is for internal use by the SDK.\n */\n async _handleUserInputRequest(request) {\n if (!this.userInputHandler) {\n throw new Error(\"User input requested but no handler registered\");\n }\n try {\n const result = await this.userInputHandler(request, {\n sessionId: this.sessionId\n });\n return result;\n } catch (error) {\n throw error;\n }\n }\n /**\n * Handles a hooks invocation from the Copilot CLI.\n *\n * @param hookType - The type of hook being invoked\n * @param input - The input data for the hook\n * @returns A promise that resolves with the hook output, or undefined\n * @internal This method is for internal use by the SDK.\n */\n async _handleHooksInvoke(hookType, input) {\n if (!this.hooks) {\n return void 0;\n }\n const handlerMap = {\n preToolUse: this.hooks.onPreToolUse,\n postToolUse: this.hooks.onPostToolUse,\n userPromptSubmitted: this.hooks.onUserPromptSubmitted,\n sessionStart: this.hooks.onSessionStart,\n sessionEnd: this.hooks.onSessionEnd,\n errorOccurred: this.hooks.onErrorOccurred\n };\n const handler = handlerMap[hookType];\n if (!handler) {\n return void 0;\n }\n try {\n const result = await handler(input, { sessionId: this.sessionId });\n return result;\n } catch (_error) {\n return void 0;\n }\n }\n /**\n * Retrieves all events and messages from this session's history.\n *\n * This returns the complete conversation history including user messages,\n * assistant responses, tool executions, and other session events.\n *\n * @returns A promise that resolves with an array of all session events\n * @throws Error if the session has been disconnected or the connection fails\n *\n * @example\n * ```typescript\n * const events = await session.getMessages();\n * for (const event of events) {\n * if (event.type === \"assistant.message\") {\n * console.log(\"Assistant:\", event.data.content);\n * }\n * }\n * ```\n */\n async getMessages() {\n const response = await this.connection.sendRequest(\"session.getMessages\", {\n sessionId: this.sessionId\n });\n return response.events;\n }\n /**\n * Disconnects this session and releases all in-memory resources (event handlers,\n * tool handlers, permission handlers).\n *\n * Session state on disk (conversation history, planning state, artifacts) is\n * preserved, so the conversation can be resumed later by calling\n * {@link CopilotClient.resumeSession} with the session ID. To permanently\n * remove all session data including files on disk, use\n * {@link CopilotClient.deleteSession} instead.\n *\n * After calling this method, the session object can no longer be used.\n *\n * @returns A promise that resolves when the session is disconnected\n * @throws Error if the connection fails\n *\n * @example\n * ```typescript\n * // Clean up when done — session can still be resumed later\n * await session.disconnect();\n * ```\n */\n async disconnect() {\n await this.connection.sendRequest(\"session.destroy\", {\n sessionId: this.sessionId\n });\n this.eventHandlers.clear();\n this.typedEventHandlers.clear();\n this.toolHandlers.clear();\n this.permissionHandler = void 0;\n }\n /**\n * @deprecated Use {@link disconnect} instead. This method will be removed in a future release.\n *\n * Disconnects this session and releases all in-memory resources.\n * Session data on disk is preserved for later resumption.\n *\n * @returns A promise that resolves when the session is disconnected\n * @throws Error if the connection fails\n */\n async destroy() {\n return this.disconnect();\n }\n /** Enables `await using session = ...` syntax for automatic cleanup. */\n async [Symbol.asyncDispose]() {\n return this.disconnect();\n }\n /**\n * Aborts the currently processing message in this session.\n *\n * Use this to cancel a long-running request. The session remains valid\n * and can continue to be used for new messages.\n *\n * @returns A promise that resolves when the abort request is acknowledged\n * @throws Error if the session has been disconnected or the connection fails\n *\n * @example\n * ```typescript\n * // Start a long-running request\n * const messagePromise = session.send({ prompt: \"Write a very long story...\" });\n *\n * // Abort after 5 seconds\n * setTimeout(async () => {\n * await session.abort();\n * }, 5000);\n * ```\n */\n async abort() {\n await this.connection.sendRequest(\"session.abort\", {\n sessionId: this.sessionId\n });\n }\n /**\n * Change the model for this session.\n * The new model takes effect for the next message. Conversation history is preserved.\n *\n * @param model - Model ID to switch to\n *\n * @example\n * ```typescript\n * await session.setModel(\"gpt-4.1\");\n * ```\n */\n async setModel(model) {\n await this.rpc.model.switchTo({ modelId: model });\n }\n}\nexport {\n CopilotSession\n};\n","import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createMessageConnection,\n StreamMessageReader,\n StreamMessageWriter\n} from \"vscode-jsonrpc/node.js\";\nimport { createServerRpc } from \"./generated/rpc.js\";\nimport { getSdkProtocolVersion } from \"./sdkProtocolVersion.js\";\nimport { CopilotSession } from \"./session.js\";\nconst MIN_PROTOCOL_VERSION = 2;\nfunction isZodSchema(value) {\n return value != null && typeof value === \"object\" && \"toJSONSchema\" in value && typeof value.toJSONSchema === \"function\";\n}\nfunction toJsonSchema(parameters) {\n if (!parameters) return void 0;\n if (isZodSchema(parameters)) {\n return parameters.toJSONSchema();\n }\n return parameters;\n}\nfunction getNodeExecPath() {\n if (process.versions.bun) {\n return \"node\";\n }\n return process.execPath;\n}\nfunction getBundledCliPath() {\n const sdkUrl = import.meta.resolve(\"@github/copilot/sdk\");\n const sdkPath = fileURLToPath(sdkUrl);\n return join(dirname(dirname(sdkPath)), \"index.js\");\n}\nclass CopilotClient {\n cliProcess = null;\n connection = null;\n socket = null;\n actualPort = null;\n actualHost = \"localhost\";\n state = \"disconnected\";\n sessions = /* @__PURE__ */ new Map();\n stderrBuffer = \"\";\n // Captures CLI stderr for error messages\n options;\n isExternalServer = false;\n forceStopping = false;\n modelsCache = null;\n modelsCacheLock = Promise.resolve();\n sessionLifecycleHandlers = /* @__PURE__ */ new Set();\n typedLifecycleHandlers = /* @__PURE__ */ new Map();\n _rpc = null;\n processExitPromise = null;\n // Rejects when CLI process exits\n negotiatedProtocolVersion = null;\n /**\n * Typed server-scoped RPC methods.\n * @throws Error if the client is not connected\n */\n get rpc() {\n if (!this.connection) {\n throw new Error(\"Client is not connected. Call start() first.\");\n }\n if (!this._rpc) {\n this._rpc = createServerRpc(this.connection);\n }\n return this._rpc;\n }\n /**\n * Creates a new CopilotClient instance.\n *\n * @param options - Configuration options for the client\n * @throws Error if mutually exclusive options are provided (e.g., cliUrl with useStdio or cliPath)\n *\n * @example\n * ```typescript\n * // Default options - spawns CLI server using stdio\n * const client = new CopilotClient();\n *\n * // Connect to an existing server\n * const client = new CopilotClient({ cliUrl: \"localhost:3000\" });\n *\n * // Custom CLI path with specific log level\n * const client = new CopilotClient({\n * cliPath: \"/usr/local/bin/copilot\",\n * logLevel: \"debug\"\n * });\n * ```\n */\n constructor(options = {}) {\n if (options.cliUrl && (options.useStdio === true || options.cliPath)) {\n throw new Error(\"cliUrl is mutually exclusive with useStdio and cliPath\");\n }\n if (options.isChildProcess && (options.cliUrl || options.useStdio === false)) {\n throw new Error(\n \"isChildProcess must be used in conjunction with useStdio and not with cliUrl\"\n );\n }\n if (options.cliUrl && (options.githubToken || options.useLoggedInUser !== void 0)) {\n throw new Error(\n \"githubToken and useLoggedInUser cannot be used with cliUrl (external server manages its own auth)\"\n );\n }\n if (options.cliUrl) {\n const { host, port } = this.parseCliUrl(options.cliUrl);\n this.actualHost = host;\n this.actualPort = port;\n this.isExternalServer = true;\n }\n if (options.isChildProcess) {\n this.isExternalServer = true;\n }\n this.options = {\n cliPath: options.cliPath || getBundledCliPath(),\n cliArgs: options.cliArgs ?? [],\n cwd: options.cwd ?? process.cwd(),\n port: options.port || 0,\n useStdio: options.cliUrl ? false : options.useStdio ?? true,\n // Default to stdio unless cliUrl is provided\n isChildProcess: options.isChildProcess ?? false,\n cliUrl: options.cliUrl,\n logLevel: options.logLevel || \"debug\",\n autoStart: options.autoStart ?? true,\n autoRestart: options.autoRestart ?? true,\n env: options.env ?? process.env,\n githubToken: options.githubToken,\n // Default useLoggedInUser to false when githubToken is provided, otherwise true\n useLoggedInUser: options.useLoggedInUser ?? (options.githubToken ? false : true)\n };\n }\n /**\n * Parse CLI URL into host and port\n * Supports formats: \"host:port\", \"http://host:port\", \"https://host:port\", or just \"port\"\n */\n parseCliUrl(url) {\n let cleanUrl = url.replace(/^https?:\\/\\//, \"\");\n if (/^\\d+$/.test(cleanUrl)) {\n return { host: \"localhost\", port: parseInt(cleanUrl, 10) };\n }\n const parts = cleanUrl.split(\":\");\n if (parts.length !== 2) {\n throw new Error(\n `Invalid cliUrl format: ${url}. Expected \"host:port\", \"http://host:port\", or \"port\"`\n );\n }\n const host = parts[0] || \"localhost\";\n const port = parseInt(parts[1], 10);\n if (isNaN(port) || port <= 0 || port > 65535) {\n throw new Error(`Invalid port in cliUrl: ${url}`);\n }\n return { host, port };\n }\n /**\n * Starts the CLI server and establishes a connection.\n *\n * If connecting to an external server (via cliUrl), only establishes the connection.\n * Otherwise, spawns the CLI server process and then connects.\n *\n * This method is called automatically when creating a session if `autoStart` is true (default).\n *\n * @returns A promise that resolves when the connection is established\n * @throws Error if the server fails to start or the connection fails\n *\n * @example\n * ```typescript\n * const client = new CopilotClient({ autoStart: false });\n * await client.start();\n * // Now ready to create sessions\n * ```\n */\n async start() {\n if (this.state === \"connected\") {\n return;\n }\n this.state = \"connecting\";\n try {\n if (!this.isExternalServer) {\n await this.startCLIServer();\n }\n await this.connectToServer();\n await this.verifyProtocolVersion();\n this.state = \"connected\";\n } catch (error) {\n this.state = \"error\";\n throw error;\n }\n }\n /**\n * Stops the CLI server and closes all active sessions.\n *\n * This method performs graceful cleanup:\n * 1. Closes all active sessions (releases in-memory resources)\n * 2. Closes the JSON-RPC connection\n * 3. Terminates the CLI server process (if spawned by this client)\n *\n * Note: session data on disk is preserved, so sessions can be resumed later.\n * To permanently remove session data before stopping, call\n * {@link deleteSession} for each session first.\n *\n * @returns A promise that resolves with an array of errors encountered during cleanup.\n * An empty array indicates all cleanup succeeded.\n *\n * @example\n * ```typescript\n * const errors = await client.stop();\n * if (errors.length > 0) {\n * console.error(\"Cleanup errors:\", errors);\n * }\n * ```\n */\n async stop() {\n const errors = [];\n for (const session of this.sessions.values()) {\n const sessionId = session.sessionId;\n let lastError = null;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await session.disconnect();\n lastError = null;\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n if (attempt < 3) {\n const delay = 100 * Math.pow(2, attempt - 1);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n if (lastError) {\n errors.push(\n new Error(\n `Failed to disconnect session ${sessionId} after 3 attempts: ${lastError.message}`\n )\n );\n }\n }\n this.sessions.clear();\n if (this.connection) {\n try {\n this.connection.dispose();\n } catch (error) {\n errors.push(\n new Error(\n `Failed to dispose connection: ${error instanceof Error ? error.message : String(error)}`\n )\n );\n }\n this.connection = null;\n this._rpc = null;\n }\n this.modelsCache = null;\n if (this.socket) {\n try {\n this.socket.end();\n } catch (error) {\n errors.push(\n new Error(\n `Failed to close socket: ${error instanceof Error ? error.message : String(error)}`\n )\n );\n }\n this.socket = null;\n }\n if (this.cliProcess && !this.isExternalServer) {\n try {\n this.cliProcess.kill();\n } catch (error) {\n errors.push(\n new Error(\n `Failed to kill CLI process: ${error instanceof Error ? error.message : String(error)}`\n )\n );\n }\n this.cliProcess = null;\n }\n this.state = \"disconnected\";\n this.actualPort = null;\n this.stderrBuffer = \"\";\n this.processExitPromise = null;\n return errors;\n }\n /**\n * Forcefully stops the CLI server without graceful cleanup.\n *\n * Use this when {@link stop} fails or takes too long. This method:\n * - Clears all sessions immediately without destroying them\n * - Force closes the connection\n * - Sends SIGKILL to the CLI process (if spawned by this client)\n *\n * @returns A promise that resolves when the force stop is complete\n *\n * @example\n * ```typescript\n * // If normal stop hangs, force stop\n * const stopPromise = client.stop();\n * const timeout = new Promise((_, reject) =>\n * setTimeout(() => reject(new Error(\"Timeout\")), 5000)\n * );\n *\n * try {\n * await Promise.race([stopPromise, timeout]);\n * } catch {\n * await client.forceStop();\n * }\n * ```\n */\n async forceStop() {\n this.forceStopping = true;\n this.sessions.clear();\n if (this.connection) {\n try {\n this.connection.dispose();\n } catch {\n }\n this.connection = null;\n this._rpc = null;\n }\n this.modelsCache = null;\n if (this.socket) {\n try {\n this.socket.destroy();\n } catch {\n }\n this.socket = null;\n }\n if (this.cliProcess && !this.isExternalServer) {\n try {\n this.cliProcess.kill(\"SIGKILL\");\n } catch {\n }\n this.cliProcess = null;\n }\n this.state = \"disconnected\";\n this.actualPort = null;\n this.stderrBuffer = \"\";\n this.processExitPromise = null;\n }\n /**\n * Creates a new conversation session with the Copilot CLI.\n *\n * Sessions maintain conversation state, handle events, and manage tool execution.\n * If the client is not connected and `autoStart` is enabled, this will automatically\n * start the connection.\n *\n * @param config - Optional configuration for the session\n * @returns A promise that resolves with the created session\n * @throws Error if the client is not connected and autoStart is disabled\n *\n * @example\n * ```typescript\n * // Basic session\n * const session = await client.createSession({ onPermissionRequest: approveAll });\n *\n * // Session with model and tools\n * const session = await client.createSession({\n * onPermissionRequest: approveAll,\n * model: \"gpt-4\",\n * tools: [{\n * name: \"get_weather\",\n * description: \"Get weather for a location\",\n * parameters: { type: \"object\", properties: { location: { type: \"string\" } } },\n * handler: async (args) => ({ temperature: 72 })\n * }]\n * });\n * ```\n */\n async createSession(config) {\n if (!config?.onPermissionRequest) {\n throw new Error(\n \"An onPermissionRequest handler is required when creating a session. For example, to allow all permissions, use { onPermissionRequest: approveAll }.\"\n );\n }\n if (!this.connection) {\n if (this.options.autoStart) {\n await this.start();\n } else {\n throw new Error(\"Client not connected. Call start() first.\");\n }\n }\n const response = await this.connection.sendRequest(\"session.create\", {\n model: config.model,\n sessionId: config.sessionId,\n clientName: config.clientName,\n reasoningEffort: config.reasoningEffort,\n tools: config.tools?.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: toJsonSchema(tool.parameters),\n overridesBuiltInTool: tool.overridesBuiltInTool\n })),\n systemMessage: config.systemMessage,\n availableTools: config.availableTools,\n excludedTools: config.excludedTools,\n provider: config.provider,\n requestPermission: true,\n requestUserInput: !!config.onUserInputRequest,\n hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),\n workingDirectory: config.workingDirectory,\n streaming: config.streaming,\n mcpServers: config.mcpServers,\n envValueMode: \"direct\",\n customAgents: config.customAgents,\n configDir: config.configDir,\n skillDirectories: config.skillDirectories,\n disabledSkills: config.disabledSkills,\n infiniteSessions: config.infiniteSessions\n });\n const { sessionId, workspacePath } = response;\n const session = new CopilotSession(sessionId, this.connection, workspacePath);\n session.registerTools(config.tools);\n session.registerPermissionHandler(config.onPermissionRequest);\n if (config.onUserInputRequest) {\n session.registerUserInputHandler(config.onUserInputRequest);\n }\n if (config.hooks) {\n session.registerHooks(config.hooks);\n }\n this.sessions.set(sessionId, session);\n return session;\n }\n /**\n * Resumes an existing conversation session by its ID.\n *\n * This allows you to continue a previous conversation, maintaining all\n * conversation history. The session must have been previously created\n * and not deleted.\n *\n * @param sessionId - The ID of the session to resume\n * @param config - Optional configuration for the resumed session\n * @returns A promise that resolves with the resumed session\n * @throws Error if the session does not exist or the client is not connected\n *\n * @example\n * ```typescript\n * // Resume a previous session\n * const session = await client.resumeSession(\"session-123\", { onPermissionRequest: approveAll });\n *\n * // Resume with new tools\n * const session = await client.resumeSession(\"session-123\", {\n * onPermissionRequest: approveAll,\n * tools: [myNewTool]\n * });\n * ```\n */\n async resumeSession(sessionId, config) {\n if (!config?.onPermissionRequest) {\n throw new Error(\n \"An onPermissionRequest handler is required when resuming a session. For example, to allow all permissions, use { onPermissionRequest: approveAll }.\"\n );\n }\n if (!this.connection) {\n if (this.options.autoStart) {\n await this.start();\n } else {\n throw new Error(\"Client not connected. Call start() first.\");\n }\n }\n const response = await this.connection.sendRequest(\"session.resume\", {\n sessionId,\n clientName: config.clientName,\n model: config.model,\n reasoningEffort: config.reasoningEffort,\n systemMessage: config.systemMessage,\n availableTools: config.availableTools,\n excludedTools: config.excludedTools,\n tools: config.tools?.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: toJsonSchema(tool.parameters),\n overridesBuiltInTool: tool.overridesBuiltInTool\n })),\n provider: config.provider,\n requestPermission: true,\n requestUserInput: !!config.onUserInputRequest,\n hooks: !!(config.hooks && Object.values(config.hooks).some(Boolean)),\n workingDirectory: config.workingDirectory,\n configDir: config.configDir,\n streaming: config.streaming,\n mcpServers: config.mcpServers,\n envValueMode: \"direct\",\n customAgents: config.customAgents,\n skillDirectories: config.skillDirectories,\n disabledSkills: config.disabledSkills,\n infiniteSessions: config.infiniteSessions,\n disableResume: config.disableResume\n });\n const { sessionId: resumedSessionId, workspacePath } = response;\n const session = new CopilotSession(resumedSessionId, this.connection, workspacePath);\n session.registerTools(config.tools);\n session.registerPermissionHandler(config.onPermissionRequest);\n if (config.onUserInputRequest) {\n session.registerUserInputHandler(config.onUserInputRequest);\n }\n if (config.hooks) {\n session.registerHooks(config.hooks);\n }\n this.sessions.set(resumedSessionId, session);\n return session;\n }\n /**\n * Gets the current connection state of the client.\n *\n * @returns The current connection state: \"disconnected\", \"connecting\", \"connected\", or \"error\"\n *\n * @example\n * ```typescript\n * if (client.getState() === \"connected\") {\n * const session = await client.createSession({ onPermissionRequest: approveAll });\n * }\n * ```\n */\n getState() {\n return this.state;\n }\n /**\n * Sends a ping request to the server to verify connectivity.\n *\n * @param message - Optional message to include in the ping\n * @returns A promise that resolves with the ping response containing the message and timestamp\n * @throws Error if the client is not connected\n *\n * @example\n * ```typescript\n * const response = await client.ping(\"health check\");\n * console.log(`Server responded at ${new Date(response.timestamp)}`);\n * ```\n */\n async ping(message) {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const result = await this.connection.sendRequest(\"ping\", { message });\n return result;\n }\n /**\n * Get CLI status including version and protocol information\n */\n async getStatus() {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const result = await this.connection.sendRequest(\"status.get\", {});\n return result;\n }\n /**\n * Get current authentication status\n */\n async getAuthStatus() {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const result = await this.connection.sendRequest(\"auth.getStatus\", {});\n return result;\n }\n /**\n * List available models with their metadata.\n *\n * Results are cached after the first successful call to avoid rate limiting.\n * The cache is cleared when the client disconnects.\n *\n * @throws Error if not authenticated\n */\n async listModels() {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n await this.modelsCacheLock;\n let resolveLock;\n this.modelsCacheLock = new Promise((resolve) => {\n resolveLock = resolve;\n });\n try {\n if (this.modelsCache !== null) {\n return [...this.modelsCache];\n }\n const result = await this.connection.sendRequest(\"models.list\", {});\n const response = result;\n const models = response.models;\n this.modelsCache = models;\n return [...models];\n } finally {\n resolveLock();\n }\n }\n /**\n * Verify that the server's protocol version is within the supported range\n * and store the negotiated version.\n */\n async verifyProtocolVersion() {\n const maxVersion = getSdkProtocolVersion();\n let pingResult;\n if (this.processExitPromise) {\n pingResult = await Promise.race([this.ping(), this.processExitPromise]);\n } else {\n pingResult = await this.ping();\n }\n const serverVersion = pingResult.protocolVersion;\n if (serverVersion === void 0) {\n throw new Error(\n `SDK protocol version mismatch: SDK supports versions ${MIN_PROTOCOL_VERSION}-${maxVersion}, but server does not report a protocol version. Please update your server to ensure compatibility.`\n );\n }\n if (serverVersion < MIN_PROTOCOL_VERSION || serverVersion > maxVersion) {\n throw new Error(\n `SDK protocol version mismatch: SDK supports versions ${MIN_PROTOCOL_VERSION}-${maxVersion}, but server reports version ${serverVersion}. Please update your SDK or server to ensure compatibility.`\n );\n }\n this.negotiatedProtocolVersion = serverVersion;\n }\n /**\n * Gets the ID of the most recently updated session.\n *\n * This is useful for resuming the last conversation when the session ID\n * was not stored.\n *\n * @returns A promise that resolves with the session ID, or undefined if no sessions exist\n * @throws Error if the client is not connected\n *\n * @example\n * ```typescript\n * const lastId = await client.getLastSessionId();\n * if (lastId) {\n * const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });\n * }\n * ```\n */\n async getLastSessionId() {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const response = await this.connection.sendRequest(\"session.getLastId\", {});\n return response.sessionId;\n }\n /**\n * Permanently deletes a session and all its data from disk, including\n * conversation history, planning state, and artifacts.\n *\n * Unlike {@link CopilotSession.disconnect}, which only releases in-memory\n * resources and preserves session data for later resumption, this method\n * is irreversible. The session cannot be resumed after deletion.\n *\n * @param sessionId - The ID of the session to delete\n * @returns A promise that resolves when the session is deleted\n * @throws Error if the session does not exist or deletion fails\n *\n * @example\n * ```typescript\n * await client.deleteSession(\"session-123\");\n * ```\n */\n async deleteSession(sessionId) {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const response = await this.connection.sendRequest(\"session.delete\", {\n sessionId\n });\n const { success, error } = response;\n if (!success) {\n throw new Error(`Failed to delete session ${sessionId}: ${error || \"Unknown error\"}`);\n }\n this.sessions.delete(sessionId);\n }\n /**\n * List all available sessions.\n *\n * @param filter - Optional filter to limit returned sessions by context fields\n *\n * @example\n * // List all sessions\n * const sessions = await client.listSessions();\n *\n * @example\n * // List sessions for a specific repository\n * const sessions = await client.listSessions({ repository: \"owner/repo\" });\n */\n async listSessions(filter) {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const response = await this.connection.sendRequest(\"session.list\", { filter });\n const { sessions } = response;\n return sessions.map((s) => ({\n sessionId: s.sessionId,\n startTime: new Date(s.startTime),\n modifiedTime: new Date(s.modifiedTime),\n summary: s.summary,\n isRemote: s.isRemote,\n context: s.context\n }));\n }\n /**\n * Gets the foreground session ID in TUI+server mode.\n *\n * This returns the ID of the session currently displayed in the TUI.\n * Only available when connecting to a server running in TUI+server mode (--ui-server).\n *\n * @returns A promise that resolves with the foreground session ID, or undefined if none\n * @throws Error if the client is not connected\n *\n * @example\n * ```typescript\n * const sessionId = await client.getForegroundSessionId();\n * if (sessionId) {\n * console.log(`TUI is displaying session: ${sessionId}`);\n * }\n * ```\n */\n async getForegroundSessionId() {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const response = await this.connection.sendRequest(\"session.getForeground\", {});\n return response.sessionId;\n }\n /**\n * Sets the foreground session in TUI+server mode.\n *\n * This requests the TUI to switch to displaying the specified session.\n * Only available when connecting to a server running in TUI+server mode (--ui-server).\n *\n * @param sessionId - The ID of the session to display in the TUI\n * @returns A promise that resolves when the session is switched\n * @throws Error if the client is not connected or if the operation fails\n *\n * @example\n * ```typescript\n * // Switch the TUI to display a specific session\n * await client.setForegroundSessionId(\"session-123\");\n * ```\n */\n async setForegroundSessionId(sessionId) {\n if (!this.connection) {\n throw new Error(\"Client not connected\");\n }\n const response = await this.connection.sendRequest(\"session.setForeground\", { sessionId });\n const result = response;\n if (!result.success) {\n throw new Error(result.error || \"Failed to set foreground session\");\n }\n }\n on(eventTypeOrHandler, handler) {\n if (typeof eventTypeOrHandler === \"string\" && handler) {\n const eventType = eventTypeOrHandler;\n if (!this.typedLifecycleHandlers.has(eventType)) {\n this.typedLifecycleHandlers.set(eventType, /* @__PURE__ */ new Set());\n }\n const storedHandler = handler;\n this.typedLifecycleHandlers.get(eventType).add(storedHandler);\n return () => {\n const handlers = this.typedLifecycleHandlers.get(eventType);\n if (handlers) {\n handlers.delete(storedHandler);\n }\n };\n }\n const wildcardHandler = eventTypeOrHandler;\n this.sessionLifecycleHandlers.add(wildcardHandler);\n return () => {\n this.sessionLifecycleHandlers.delete(wildcardHandler);\n };\n }\n /**\n * Start the CLI server process\n */\n async startCLIServer() {\n return new Promise((resolve, reject) => {\n this.stderrBuffer = \"\";\n const args = [\n ...this.options.cliArgs,\n \"--headless\",\n \"--no-auto-update\",\n \"--log-level\",\n this.options.logLevel\n ];\n if (this.options.useStdio) {\n args.push(\"--stdio\");\n } else if (this.options.port > 0) {\n args.push(\"--port\", this.options.port.toString());\n }\n if (this.options.githubToken) {\n args.push(\"--auth-token-env\", \"COPILOT_SDK_AUTH_TOKEN\");\n }\n if (!this.options.useLoggedInUser) {\n args.push(\"--no-auto-login\");\n }\n const envWithoutNodeDebug = { ...this.options.env };\n delete envWithoutNodeDebug.NODE_DEBUG;\n if (this.options.githubToken) {\n envWithoutNodeDebug.COPILOT_SDK_AUTH_TOKEN = this.options.githubToken;\n }\n if (!existsSync(this.options.cliPath)) {\n throw new Error(\n `Copilot CLI not found at ${this.options.cliPath}. Ensure @github/copilot is installed.`\n );\n }\n const stdioConfig = this.options.useStdio ? [\"pipe\", \"pipe\", \"pipe\"] : [\"ignore\", \"pipe\", \"pipe\"];\n const isJsFile = this.options.cliPath.endsWith(\".js\");\n if (isJsFile) {\n this.cliProcess = spawn(getNodeExecPath(), [this.options.cliPath, ...args], {\n stdio: stdioConfig,\n cwd: this.options.cwd,\n env: envWithoutNodeDebug,\n windowsHide: true\n });\n } else {\n this.cliProcess = spawn(this.options.cliPath, args, {\n stdio: stdioConfig,\n cwd: this.options.cwd,\n env: envWithoutNodeDebug,\n windowsHide: true\n });\n }\n let stdout = \"\";\n let resolved = false;\n if (this.options.useStdio) {\n resolved = true;\n resolve();\n } else {\n this.cliProcess.stdout?.on(\"data\", (data) => {\n stdout += data.toString();\n const match = stdout.match(/listening on port (\\d+)/i);\n if (match && !resolved) {\n this.actualPort = parseInt(match[1], 10);\n resolved = true;\n resolve();\n }\n });\n }\n this.cliProcess.stderr?.on(\"data\", (data) => {\n this.stderrBuffer += data.toString();\n const lines = data.toString().split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n process.stderr.write(`[CLI subprocess] ${line}\n`);\n }\n }\n });\n this.cliProcess.on(\"error\", (error) => {\n if (!resolved) {\n resolved = true;\n const stderrOutput = this.stderrBuffer.trim();\n if (stderrOutput) {\n reject(\n new Error(\n `Failed to start CLI server: ${error.message}\nstderr: ${stderrOutput}`\n )\n );\n } else {\n reject(new Error(`Failed to start CLI server: ${error.message}`));\n }\n }\n });\n this.processExitPromise = new Promise((_, rejectProcessExit) => {\n this.cliProcess.on(\"exit\", (code) => {\n setTimeout(() => {\n const stderrOutput = this.stderrBuffer.trim();\n if (stderrOutput) {\n rejectProcessExit(\n new Error(\n `CLI server exited with code ${code}\nstderr: ${stderrOutput}`\n )\n );\n } else {\n rejectProcessExit(\n new Error(`CLI server exited unexpectedly with code ${code}`)\n );\n }\n }, 50);\n });\n });\n this.processExitPromise.catch(() => {\n });\n this.cliProcess.on(\"exit\", (code) => {\n if (!resolved) {\n resolved = true;\n const stderrOutput = this.stderrBuffer.trim();\n if (stderrOutput) {\n reject(\n new Error(\n `CLI server exited with code ${code}\nstderr: ${stderrOutput}`\n )\n );\n } else {\n reject(new Error(`CLI server exited with code ${code}`));\n }\n } else if (this.options.autoRestart && this.state === \"connected\") {\n void this.reconnect();\n }\n });\n setTimeout(() => {\n if (!resolved) {\n resolved = true;\n reject(new Error(\"Timeout waiting for CLI server to start\"));\n }\n }, 1e4);\n });\n }\n /**\n * Connect to the CLI server (via socket or stdio)\n */\n async connectToServer() {\n if (this.options.isChildProcess) {\n return this.connectToParentProcessViaStdio();\n } else if (this.options.useStdio) {\n return this.connectToChildProcessViaStdio();\n } else {\n return this.connectViaTcp();\n }\n }\n /**\n * Connect to child via stdio pipes\n */\n async connectToChildProcessViaStdio() {\n if (!this.cliProcess) {\n throw new Error(\"CLI process not started\");\n }\n this.cliProcess.stdin?.on(\"error\", (err) => {\n if (!this.forceStopping) {\n throw err;\n }\n });\n this.connection = createMessageConnection(\n new StreamMessageReader(this.cliProcess.stdout),\n new StreamMessageWriter(this.cliProcess.stdin)\n );\n this.attachConnectionHandlers();\n this.connection.listen();\n }\n /**\n * Connect to parent via stdio pipes\n */\n async connectToParentProcessViaStdio() {\n if (this.cliProcess) {\n throw new Error(\"CLI child process was unexpectedly started in parent process mode\");\n }\n this.connection = createMessageConnection(\n new StreamMessageReader(process.stdin),\n new StreamMessageWriter(process.stdout)\n );\n this.attachConnectionHandlers();\n this.connection.listen();\n }\n /**\n * Connect to the CLI server via TCP socket\n */\n async connectViaTcp() {\n if (!this.actualPort) {\n throw new Error(\"Server port not available\");\n }\n return new Promise((resolve, reject) => {\n this.socket = new Socket();\n this.socket.connect(this.actualPort, this.actualHost, () => {\n this.connection = createMessageConnection(\n new StreamMessageReader(this.socket),\n new StreamMessageWriter(this.socket)\n );\n this.attachConnectionHandlers();\n this.connection.listen();\n resolve();\n });\n this.socket.on(\"error\", (error) => {\n reject(new Error(`Failed to connect to CLI server: ${error.message}`));\n });\n });\n }\n attachConnectionHandlers() {\n if (!this.connection) {\n return;\n }\n this.connection.onNotification(\"session.event\", (notification) => {\n this.handleSessionEventNotification(notification);\n });\n this.connection.onNotification(\"session.lifecycle\", (notification) => {\n this.handleSessionLifecycleNotification(notification);\n });\n this.connection.onRequest(\n \"tool.call\",\n async (params) => await this.handleToolCallRequestV2(params)\n );\n this.connection.onRequest(\n \"permission.request\",\n async (params) => await this.handlePermissionRequestV2(params)\n );\n this.connection.onRequest(\n \"userInput.request\",\n async (params) => await this.handleUserInputRequest(params)\n );\n this.connection.onRequest(\n \"hooks.invoke\",\n async (params) => await this.handleHooksInvoke(params)\n );\n this.connection.onClose(() => {\n if (this.state === \"connected\" && this.options.autoRestart) {\n void this.reconnect();\n }\n });\n this.connection.onError((_error) => {\n });\n }\n handleSessionEventNotification(notification) {\n if (typeof notification !== \"object\" || !notification || !(\"sessionId\" in notification) || typeof notification.sessionId !== \"string\" || !(\"event\" in notification)) {\n return;\n }\n const session = this.sessions.get(notification.sessionId);\n if (session) {\n session._dispatchEvent(notification.event);\n }\n }\n handleSessionLifecycleNotification(notification) {\n if (typeof notification !== \"object\" || !notification || !(\"type\" in notification) || typeof notification.type !== \"string\" || !(\"sessionId\" in notification) || typeof notification.sessionId !== \"string\") {\n return;\n }\n const event = notification;\n const typedHandlers = this.typedLifecycleHandlers.get(event.type);\n if (typedHandlers) {\n for (const handler of typedHandlers) {\n try {\n handler(event);\n } catch {\n }\n }\n }\n for (const handler of this.sessionLifecycleHandlers) {\n try {\n handler(event);\n } catch {\n }\n }\n }\n async handleUserInputRequest(params) {\n if (!params || typeof params.sessionId !== \"string\" || typeof params.question !== \"string\") {\n throw new Error(\"Invalid user input request payload\");\n }\n const session = this.sessions.get(params.sessionId);\n if (!session) {\n throw new Error(`Session not found: ${params.sessionId}`);\n }\n const result = await session._handleUserInputRequest({\n question: params.question,\n choices: params.choices,\n allowFreeform: params.allowFreeform\n });\n return result;\n }\n async handleHooksInvoke(params) {\n if (!params || typeof params.sessionId !== \"string\" || typeof params.hookType !== \"string\") {\n throw new Error(\"Invalid hooks invoke payload\");\n }\n const session = this.sessions.get(params.sessionId);\n if (!session) {\n throw new Error(`Session not found: ${params.sessionId}`);\n }\n const output = await session._handleHooksInvoke(params.hookType, params.input);\n return { output };\n }\n // ========================================================================\n // Protocol v2 backward-compatibility adapters\n // ========================================================================\n /**\n * Handles a v2-style tool.call RPC request from the server.\n * Looks up the session and tool handler, executes it, and returns the result\n * in the v2 response format.\n */\n async handleToolCallRequestV2(params) {\n if (!params || typeof params.sessionId !== \"string\" || typeof params.toolCallId !== \"string\" || typeof params.toolName !== \"string\") {\n throw new Error(\"Invalid tool call payload\");\n }\n const session = this.sessions.get(params.sessionId);\n if (!session) {\n throw new Error(`Unknown session ${params.sessionId}`);\n }\n const handler = session.getToolHandler(params.toolName);\n if (!handler) {\n return {\n result: {\n textResultForLlm: `Tool '${params.toolName}' is not supported by this client instance.`,\n resultType: \"failure\",\n error: `tool '${params.toolName}' not supported`,\n toolTelemetry: {}\n }\n };\n }\n try {\n const invocation = {\n sessionId: params.sessionId,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n arguments: params.arguments\n };\n const result = await handler(params.arguments, invocation);\n return { result: this.normalizeToolResultV2(result) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n result: {\n textResultForLlm: \"Invoking this tool produced an error. Detailed information is not available.\",\n resultType: \"failure\",\n error: message,\n toolTelemetry: {}\n }\n };\n }\n }\n /**\n * Handles a v2-style permission.request RPC request from the server.\n */\n async handlePermissionRequestV2(params) {\n if (!params || typeof params.sessionId !== \"string\" || !params.permissionRequest) {\n throw new Error(\"Invalid permission request payload\");\n }\n const session = this.sessions.get(params.sessionId);\n if (!session) {\n throw new Error(`Session not found: ${params.sessionId}`);\n }\n try {\n const result = await session._handlePermissionRequestV2(params.permissionRequest);\n return { result };\n } catch (_error) {\n return {\n result: {\n kind: \"denied-no-approval-rule-and-could-not-request-from-user\"\n }\n };\n }\n }\n normalizeToolResultV2(result) {\n if (result === void 0 || result === null) {\n return {\n textResultForLlm: \"Tool returned no result\",\n resultType: \"failure\",\n error: \"tool returned no result\",\n toolTelemetry: {}\n };\n }\n if (this.isToolResultObject(result)) {\n return result;\n }\n const textResult = typeof result === \"string\" ? result : JSON.stringify(result);\n return {\n textResultForLlm: textResult,\n resultType: \"success\",\n toolTelemetry: {}\n };\n }\n isToolResultObject(value) {\n return typeof value === \"object\" && value !== null && \"textResultForLlm\" in value && typeof value.textResultForLlm === \"string\" && \"resultType\" in value;\n }\n /**\n * Attempt to reconnect to the server\n */\n async reconnect() {\n this.state = \"disconnected\";\n try {\n await this.stop();\n await this.start();\n } catch (_error) {\n }\n }\n}\nexport {\n CopilotClient\n};\n","function defineTool(name, config) {\n return { name, ...config };\n}\nconst approveAll = () => ({ kind: \"approved\" });\nexport {\n approveAll,\n defineTool\n};\n","import { CopilotClient } from \"./client.js\";\nimport { CopilotSession } from \"./session.js\";\nimport { defineTool, approveAll } from \"./types.js\";\nexport {\n CopilotClient,\n CopilotSession,\n approveAll,\n defineTool\n};\n","/**\n * GitHub Copilot provider — wraps the @github/copilot-sdk to conform\n * to the generic ProviderInstance interface.\n *\n * Requires the `copilot` CLI to be installed and available on PATH\n * (or specify the path via COPILOT_CLI_PATH).\n *\n * Authentication options:\n * - Logged-in Copilot CLI user (default)\n * - COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN env vars\n */\n\nimport type { AssistantMessageEvent, CopilotSession } from \"@github/copilot-sdk\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { withTimeout } from \"../helpers/timeout.js\";\n\n/** Maximum time (ms) to wait for a copilot session to become idle after sending a prompt. */\nconst SESSION_READY_TIMEOUT_MS = 600_000;\n\n/**\n * Lazily load the Copilot SDK.\n *\n * Using a dynamic import defers resolution to runtime so that only code\n * paths that actually exercise the Copilot provider pay the cost of loading\n * the SDK, keeping startup fast for users of other providers.\n */\nasync function loadCopilotSdk(): Promise<typeof import(\"@github/copilot-sdk\")> {\n return import(\"@github/copilot-sdk\");\n}\n\n/**\n * List available Copilot models.\n *\n * Starts a temporary client, fetches the model list, then stops it.\n * Returns bare model IDs (e.g. \"claude-sonnet-4-5\").\n */\nexport async function listModels(opts?: ProviderBootOptions): Promise<string[]> {\n const { CopilotClient } = await loadCopilotSdk();\n const client = new CopilotClient({\n ...(opts?.url ? { cliUrl: opts.url } : {}),\n });\n try {\n await client.start();\n const models = await client.listModels();\n return models.map((m) => m.id).sort();\n } finally {\n await client.stop().catch(() => {});\n }\n}\n\n/**\n * Boot a Copilot provider instance — starts or connects to a Copilot CLI server.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n log.debug(opts?.url ? `Connecting to Copilot CLI at ${opts.url}` : \"Starting Copilot CLI...\");\n\n const { CopilotClient, approveAll } = await loadCopilotSdk();\n\n const client = new CopilotClient({\n ...(opts?.url ? { cliUrl: opts.url } : {}),\n ...(opts?.cwd ? { cwd: opts.cwd } : {}),\n });\n\n try {\n await client.start();\n log.debug(\"Copilot CLI started successfully\");\n } catch (err) {\n log.debug(`Failed to start Copilot CLI: ${log.formatErrorChain(err)}`);\n throw err;\n }\n\n // Model is detected lazily after the first session is created\n let model: string | undefined;\n let modelDetected = false;\n\n // Track live sessions for prompt routing and cleanup\n const sessions = new Map<string, CopilotSession>();\n\n return {\n name: \"copilot\",\n get model() {\n return model;\n },\n\n async createSession(): Promise<string> {\n log.debug(\"Creating Copilot session...\");\n try {\n const session = await client.createSession({\n ...(opts?.model ? { model: opts.model } : {}),\n ...(opts?.cwd ? { workingDirectory: opts.cwd } : {}),\n onPermissionRequest: approveAll,\n });\n sessions.set(session.sessionId, session);\n log.debug(`Session created: ${session.sessionId}`);\n\n // Detect actual default model from the first session (best-effort, once only)\n if (!modelDetected) {\n modelDetected = true;\n try {\n const result = await session.rpc.model.getCurrent();\n if (result.modelId) {\n model = result.modelId;\n log.debug(`Detected model: ${model}`);\n }\n } catch (err) {\n log.debug(`Failed to detect model from session: ${log.formatErrorChain(err)}`);\n }\n }\n\n return session.sessionId;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n const session = sessions.get(sessionId);\n if (!session) {\n throw new Error(`Copilot session ${sessionId} not found`);\n }\n\n log.debug(`Sending prompt to session ${sessionId} (${text.length} chars)...`);\n try {\n // ── 1. Fire-and-forget: start LLM processing ──────────────\n await session.send({ prompt: text });\n log.debug(\"Async prompt accepted, waiting for session to become idle...\");\n\n // ── 2. Wait for session.idle or session.error ─────────────\n let unsubIdle: (() => void) | undefined;\n let unsubErr: (() => void) | undefined;\n try {\n await withTimeout(\n new Promise<void>((resolve, reject) => {\n unsubIdle = session.on(\"session.idle\", () => {\n resolve();\n });\n\n unsubErr = session.on(\"session.error\", (event) => {\n reject(new Error(`Copilot session error: ${event.data.message}`));\n });\n }),\n SESSION_READY_TIMEOUT_MS,\n \"copilot session ready\",\n );\n } finally {\n unsubIdle?.();\n unsubErr?.();\n }\n\n log.debug(\"Session went idle, fetching result...\");\n\n // ── 3. Fetch the completed messages ───────────────────────\n const events = await session.getMessages();\n const last = [...events]\n .reverse()\n .find((e): e is AssistantMessageEvent => e.type === \"assistant.message\");\n\n const result = last?.data?.content ?? null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n log.debug(\"Cleaning up Copilot provider...\");\n // Destroy all active sessions before stopping the server\n const destroyOps = [...sessions.values()].map((s) =>\n s.destroy().catch((err) => {\n log.debug(`Failed to destroy Copilot session: ${log.formatErrorChain(err)}`);\n })\n );\n await Promise.all(destroyOps);\n sessions.clear();\n\n await client.stop().catch((err) => {\n log.debug(`Failed to stop Copilot client: ${log.formatErrorChain(err)}`);\n });\n },\n };\n}\n","/**\n * Claude provider — wraps the @anthropic-ai/claude-agent-sdk V2 preview\n * to conform to the generic ProviderInstance interface.\n *\n * Uses the V2 session-based API: `unstable_v2_createSession` for session\n * creation, `session.send()`/`session.stream()` for prompting, and manual\n * `session.close()` for cleanup (the project targets ES2022 which does not\n * include the Disposable lib required for `await using`).\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { unstable_v2_createSession, type SDKSession, type SDKMessage } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\n\n/**\n * List available Claude models.\n *\n * The Claude Agent SDK does not expose a model listing API, so this returns\n * a hardcoded list of known Claude model identifiers.\n */\nexport async function listModels(_opts?: ProviderBootOptions): Promise<string[]> {\n return [\n \"claude-haiku-3-5\",\n \"claude-opus-4-6\",\n \"claude-sonnet-4\",\n \"claude-sonnet-4-5\",\n ];\n}\n\n/**\n * Boot a Claude provider instance using the V2 preview API.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n const model = opts?.model ?? \"claude-sonnet-4\";\n const cwd = opts?.cwd;\n log.debug(`Booting Claude provider with model ${model}`);\n\n const sessions = new Map<string, SDKSession>();\n\n return {\n name: \"claude\",\n model,\n\n async createSession(): Promise<string> {\n log.debug(\"Creating Claude session...\");\n try {\n const sessionOpts = { model, permissionMode: 'acceptEdits' as const, ...(cwd ? { cwd } : {}) };\n const session = unstable_v2_createSession(sessionOpts);\n const sessionId = randomUUID();\n sessions.set(sessionId, session);\n log.debug(`Session created: ${sessionId}`);\n return sessionId;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n const session = sessions.get(sessionId);\n if (!session) {\n throw new Error(`Claude session ${sessionId} not found`);\n }\n\n log.debug(`Sending prompt to session ${sessionId} (${text.length} chars)...`);\n try {\n await session.send(text);\n\n const parts: string[] = [];\n for await (const msg of session.stream()) {\n if (msg.type === \"assistant\") {\n const msgText = msg.message.content\n .filter((block: { type: string }) => block.type === \"text\")\n .map((block: { type: string; text: string }) => block.text)\n .join(\"\");\n if (msgText) parts.push(msgText);\n }\n }\n\n const result = parts.join(\"\") || null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n log.debug(\"Cleaning up Claude provider...\");\n for (const session of sessions.values()) {\n try { session.close(); } catch {}\n }\n sessions.clear();\n },\n };\n}\n","/**\n * Codex provider — wraps the @openai/codex SDK to conform to the\n * generic ProviderInstance interface.\n *\n * Uses the AgentLoop class for session management. Each session creates\n * its own AgentLoop instance with \"full-auto\" approval policy so that\n * file edits and shell commands are auto-approved.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { log } from \"../helpers/logger.js\";\n\n/**\n * Lazily load the @openai/codex SDK.\n *\n * The package ships as a CLI bundle without a proper library entry-point\n * (no `main` / `module` / `exports` in its package.json). A top-level\n * static `import` would cause Vite's import analysis to fail at test time\n * for every test file that transitively touches the provider registry.\n * Using a dynamic import defers resolution to runtime so that only code\n * paths that actually exercise the Codex provider pay the cost.\n */\nasync function loadAgentLoop(): Promise<typeof import(\"@openai/codex\")> {\n return import(\"@openai/codex\");\n}\n\n/**\n * List available Codex models.\n *\n * The Codex SDK does not expose a model listing API, so this returns\n * a hardcoded list of known compatible model identifiers.\n */\nexport async function listModels(_opts?: ProviderBootOptions): Promise<string[]> {\n return [\n \"codex-mini-latest\",\n \"o3-mini\",\n \"o4-mini\",\n ];\n}\n\n/**\n * Boot a Codex provider instance.\n */\nexport async function boot(opts?: ProviderBootOptions): Promise<ProviderInstance> {\n const model = opts?.model ?? \"o4-mini\";\n log.debug(`Booting Codex provider with model ${model}`);\n\n const { AgentLoop } = await loadAgentLoop();\n\n type AgentLoopInstance = InstanceType<typeof AgentLoop>;\n const sessions = new Map<string, AgentLoopInstance>();\n\n return {\n name: \"codex\",\n model,\n\n async createSession(): Promise<string> {\n log.debug(\"Creating Codex session...\");\n try {\n const sessionId = randomUUID();\n const agent = new AgentLoop({\n model,\n config: { model, instructions: \"\" },\n approvalPolicy: \"full-auto\",\n ...(opts?.cwd ? { rootDir: opts.cwd } : {}),\n additionalWritableRoots: [],\n getCommandConfirmation: async () => ({ approved: true }),\n onItem: () => {},\n onLoading: () => {},\n onLastResponseId: () => {},\n });\n sessions.set(sessionId, agent);\n log.debug(`Session created: ${sessionId}`);\n return sessionId;\n } catch (err) {\n log.debug(`Session creation failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async prompt(sessionId: string, text: string): Promise<string | null> {\n const agent = sessions.get(sessionId);\n if (!agent) {\n throw new Error(`Codex session ${sessionId} not found`);\n }\n\n log.debug(`Sending prompt to session ${sessionId} (${text.length} chars)...`);\n try {\n const items = await agent.run([text]);\n\n const parts: string[] = [];\n for (const item of items) {\n if (item.type === \"message\" && \"content\" in item) {\n const content = (item as { type: string; content: Array<{ type: string; text?: string }> }).content;\n const itemText = content\n .filter((block: { type: string }) => block.type === \"output_text\")\n .map((block: { type: string; text?: string }) => block.text ?? \"\")\n .join(\"\");\n if (itemText) parts.push(itemText);\n }\n }\n\n const result = parts.join(\"\") || null;\n log.debug(`Prompt response received (${result?.length ?? 0} chars)`);\n return result;\n } catch (err) {\n log.debug(`Prompt failed: ${log.formatErrorChain(err)}`);\n throw err;\n }\n },\n\n async cleanup(): Promise<void> {\n log.debug(\"Cleaning up Codex provider...\");\n for (const agent of sessions.values()) {\n try { agent.terminate(); } catch {}\n }\n sessions.clear();\n },\n };\n}\n","/**\n * Provider binary detection — checks whether each provider's CLI binary\n * is available on PATH.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport type { ProviderName } from \"./interface.js\";\n\nconst exec = promisify(execFile);\n\n/** Kill provider binary detection after this many milliseconds. */\nconst DETECTION_TIMEOUT_MS = 5000;\n\n/**\n * Maps each provider name to its expected CLI binary.\n */\nexport const PROVIDER_BINARIES: Record<ProviderName, string> = {\n opencode: \"opencode\",\n copilot: \"copilot\",\n claude: \"claude\",\n codex: \"codex\",\n};\n\n/**\n * Check whether a provider's CLI binary is available on PATH.\n *\n * Attempts to execute the binary with `--version`. Resolves `true` if the\n * binary is found, `false` otherwise. Never rejects.\n */\nexport async function checkProviderInstalled(\n name: ProviderName,\n): Promise<boolean> {\n try {\n await exec(PROVIDER_BINARIES[name], [\"--version\"], {\n shell: process.platform === \"win32\",\n timeout: DETECTION_TIMEOUT_MS,\n });\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Provider registry — maps provider names to their boot functions.\n *\n * To add a new agent backend:\n * 1. Create `src/providers/<name>.ts` exporting an async `boot()` function\n * 2. Import and register it in the `PROVIDERS` map below\n * 3. Add the name to the `ProviderName` union in `src/providers/interface.ts`\n */\n\nimport type { ProviderName, ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nimport { boot as bootOpencode, listModels as listOpencodeModels } from \"./opencode.js\";\nimport { boot as bootCopilot, listModels as listCopilotModels } from \"./copilot.js\";\nimport { boot as bootClaude, listModels as listClaudeModels } from \"./claude.js\";\nimport { boot as bootCodex, listModels as listCodexModels } from \"./codex.js\";\n\ntype BootFn = (opts?: ProviderBootOptions) => Promise<ProviderInstance>;\ntype ListModelsFn = (opts?: ProviderBootOptions) => Promise<string[]>;\n\nconst PROVIDERS: Record<ProviderName, BootFn> = {\n opencode: bootOpencode,\n copilot: bootCopilot,\n claude: bootClaude,\n codex: bootCodex,\n};\n\nconst LIST_MODELS: Record<ProviderName, ListModelsFn> = {\n opencode: listOpencodeModels,\n copilot: listCopilotModels,\n claude: listClaudeModels,\n codex: listCodexModels,\n};\n\n/**\n * All registered provider names — useful for CLI help text and validation.\n */\nexport const PROVIDER_NAMES = Object.keys(PROVIDERS) as ProviderName[];\n\n/**\n * Boot a provider by name.\n *\n * @throws if the provider name is not registered.\n */\nexport async function bootProvider(\n name: ProviderName,\n opts?: ProviderBootOptions\n): Promise<ProviderInstance> {\n const bootFn = PROVIDERS[name];\n if (!bootFn) {\n throw new Error(\n `Unknown provider \"${name}\". Available: ${PROVIDER_NAMES.join(\", \")}`\n );\n }\n return bootFn(opts);\n}\n\n/**\n * List available models for a provider by name.\n *\n * Starts a temporary provider instance (or connects to an existing server),\n * fetches the model list, and tears down. Returns model IDs as strings.\n * Throws if the provider is unavailable (caller should handle gracefully).\n *\n * @throws if the provider name is not registered or the provider is unavailable.\n */\nexport async function listProviderModels(\n name: ProviderName,\n opts?: ProviderBootOptions\n): Promise<string[]> {\n const fn = LIST_MODELS[name];\n if (!fn) {\n throw new Error(\n `Unknown provider \"${name}\". Available: ${PROVIDER_NAMES.join(\", \")}`\n );\n }\n return fn(opts);\n}\n\nexport type { ProviderName, ProviderInstance, ProviderBootOptions } from \"./interface.js\";\nexport { PROVIDER_BINARIES, checkProviderInstalled } from \"./detect.js\";\n","/**\n * Process-level cleanup registry.\n *\n * Sub-modules (orchestrator, spec-generator) register their provider's\n * `cleanup()` here when the provider boots. The CLI signal handlers and\n * error handler drain the registry before exiting.\n *\n * All registered functions are invoked once; the registry is cleared\n * after each drain so repeated calls are harmless.\n */\n\nconst cleanups: Array<() => Promise<void>> = [];\n\n/**\n * Register an async cleanup function to be called on process shutdown.\n */\nexport function registerCleanup(fn: () => Promise<void>): void {\n cleanups.push(fn);\n}\n\n/**\n * Run all registered cleanup functions, then clear the registry.\n * Errors are swallowed to prevent cleanup failures from masking the\n * original error or blocking process exit.\n */\nexport async function runCleanup(): Promise<void> {\n const fns = cleanups.splice(0);\n for (const fn of fns) {\n try {\n await fn();\n } catch {\n // swallow — cleanup must not throw\n }\n }\n}\n","/**\n * Runtime environment detection for OS-aware agent prompts.\n *\n * Detects the host operating system and produces a formatted text block\n * that can be injected into agent system prompts so they know to run\n * commands directly instead of writing intermediate scripts.\n */\n\nexport interface EnvironmentInfo {\n /** Raw Node.js platform string (e.g. \"win32\", \"linux\", \"darwin\"). */\n platform: string;\n /** Human-readable OS name. */\n os: string;\n /** Default shell description for the platform. */\n shell: string;\n}\n\n/**\n * Detect the runtime environment from `process.platform`.\n */\nexport function getEnvironmentInfo(): EnvironmentInfo {\n const platform = process.platform;\n switch (platform) {\n case \"win32\":\n return { platform, os: \"Windows\", shell: \"cmd.exe/PowerShell\" };\n case \"darwin\":\n return { platform, os: \"macOS\", shell: \"zsh/bash\" };\n default:\n return { platform, os: \"Linux\", shell: \"bash\" };\n }\n}\n\n/**\n * Format environment information as a prompt text block.\n *\n * Returns a multi-line string describing the host OS, default shell,\n * and an instruction to run commands directly.\n */\nexport function formatEnvironmentPrompt(): string {\n const env = getEnvironmentInfo();\n return [\n `## Environment`,\n `- **Operating System:** ${env.os}`,\n `- **Default Shell:** ${env.shell}`,\n `- Always run commands directly in the shell. Do NOT write intermediate scripts (e.g. .bat, .ps1, .py files) unless the task explicitly requires creating a script.`,\n ].join(\"\\n\");\n}\n\n/** Alias used by the dispatcher module. */\nexport const getEnvironmentBlock = formatEnvironmentPrompt;\n","/**\n * Fix-tests pipeline — detects the project's test command, runs the test\n * suite, captures failure output, dispatches an AI agent to fix the broken\n * tests, and optionally re-runs tests to verify the fix.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { execFile as execFileCb } from \"node:child_process\";\nimport type { FixTestsSummary } from \"./runner.js\";\nimport type { ProviderName } from \"../providers/interface.js\";\nimport { bootProvider } from \"../providers/index.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { FileLogger, fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/* ------------------------------------------------------------------ */\n/* Types */\n/* ------------------------------------------------------------------ */\n\nexport interface FixTestsPipelineOptions {\n cwd: string;\n provider: string;\n serverUrl?: string;\n verbose: boolean;\n dryRun?: boolean;\n testTimeout?: number;\n}\n\nexport interface TestRunResult {\n exitCode: number | null;\n stdout: string;\n stderr: string;\n command: string;\n}\n\n/* ------------------------------------------------------------------ */\n/* Test runner utilities */\n/* ------------------------------------------------------------------ */\n\n/** Detect the test command from package.json in the given directory. */\nexport async function detectTestCommand(cwd: string): Promise<string | null> {\n try {\n const raw = await readFile(join(cwd, \"package.json\"), \"utf-8\");\n let pkg: any;\n try {\n pkg = JSON.parse(raw);\n } catch {\n log.debug(\n `Failed to parse package.json: ${raw.slice(0, 200)}`,\n );\n return null;\n }\n const testScript: unknown = pkg?.scripts?.test;\n if (\n typeof testScript === \"string\" &&\n testScript !== 'echo \"Error: no test specified\" && exit 1'\n ) {\n return \"npm test\";\n }\n return null;\n } catch {\n return null;\n }\n}\n\n/** Run a shell command and capture its output. Does NOT throw on non-zero exit. */\nexport function runTestCommand(\n command: string,\n cwd: string,\n): Promise<TestRunResult> {\n return new Promise((resolve) => {\n const [cmd, ...args] = command.split(\" \");\n execFileCb(\n cmd,\n args,\n { cwd, maxBuffer: 10 * 1024 * 1024, shell: process.platform === \"win32\" },\n (error, stdout, stderr) => {\n const exitCode =\n error && \"code\" in error\n ? ((error as { code?: number }).code ?? 1)\n : error\n ? 1\n : 0;\n resolve({ exitCode, stdout, stderr, command });\n },\n );\n });\n}\n\n/* ------------------------------------------------------------------ */\n/* Prompt builder */\n/* ------------------------------------------------------------------ */\n\n/** Build a focused AI prompt from test failure output. */\nexport function buildFixTestsPrompt(\n testResult: TestRunResult,\n cwd: string,\n): string {\n const output = [testResult.stdout, testResult.stderr]\n .filter(Boolean)\n .join(\"\\n\");\n return [\n `You are fixing failing tests in a project.`,\n ``,\n `**Working directory:** ${cwd}`,\n `**Test command:** ${testResult.command}`,\n `**Exit code:** ${testResult.exitCode}`,\n ``,\n formatEnvironmentPrompt(),\n ``,\n `## Test Output`,\n ``,\n \"```\",\n output,\n \"```\",\n ``,\n `## Instructions`,\n ``,\n `- Read the failing test files and the source code they test.`,\n `- Understand why the tests are failing.`,\n `- Make minimal fixes — fix the tests or fix the source code, whichever is appropriate.`,\n `- Do NOT commit changes — the developer controls commits.`,\n `- Do NOT modify tests to simply skip or ignore failures.`,\n `- When finished, confirm by saying \"Tests fixed.\"`,\n ].join(\"\\n\");\n}\n\n/* ------------------------------------------------------------------ */\n/* Main pipeline */\n/* ------------------------------------------------------------------ */\n\n/** Run the fix-tests pipeline end-to-end. */\nexport async function runFixTestsPipeline(\n opts: FixTestsPipelineOptions,\n): Promise<FixTestsSummary> {\n const { cwd } = opts;\n const testTimeoutMs = (opts.testTimeout ?? 5) * 60_000;\n const start = Date.now();\n\n // Detect test command\n const testCommand = await detectTestCommand(cwd);\n if (!testCommand) {\n log.error(\n 'No test command found. Ensure package.json has a \"test\" script.',\n );\n return { mode: \"fix-tests\", success: false, error: \"No test command found\" };\n }\n log.info(`Detected test command: ${testCommand}`);\n\n // Dry-run mode\n if (opts.dryRun) {\n log.info(`Dry run — would execute: ${testCommand}`);\n log.dim(` Working directory: ${cwd}`);\n return { mode: \"fix-tests\", success: false };\n }\n\n const fileLogger = opts.verbose ? new FileLogger(\"fix-tests\", cwd) : null;\n\n const pipelineBody = async (): Promise<FixTestsSummary> => {\n try {\n // Run the test suite\n log.info(\"Running test suite...\");\n const testResult = await runTestCommand(testCommand, cwd);\n fileLoggerStorage.getStore()?.info(`Test run complete (exit code: ${testResult.exitCode})`);\n\n // Check if tests already pass\n if (testResult.exitCode === 0) {\n log.success(\"All tests pass — nothing to fix.\");\n return { mode: \"fix-tests\", success: true };\n }\n log.warn(\n `Tests failed (exit code ${testResult.exitCode}). Dispatching AI to fix...`,\n );\n\n // Boot the provider\n const provider = (opts.provider ?? \"opencode\") as ProviderName;\n const instance = await bootProvider(provider, { url: opts.serverUrl, cwd });\n registerCleanup(() => instance.cleanup());\n\n // Build prompt and dispatch\n const prompt = buildFixTestsPrompt(testResult, cwd);\n log.debug(`Prompt built (${prompt.length} chars)`);\n fileLoggerStorage.getStore()?.prompt(\"fix-tests\", prompt);\n const sessionId = await instance.createSession();\n const response = await instance.prompt(sessionId, prompt);\n\n if (response === null) {\n fileLoggerStorage.getStore()?.error(\"No response from AI agent.\");\n log.error(\"No response from AI agent.\");\n await instance.cleanup();\n return { mode: \"fix-tests\", success: false, error: \"No response from agent\" };\n }\n if (response) fileLoggerStorage.getStore()?.response(\"fix-tests\", response);\n log.success(\"AI agent completed fixes.\");\n\n // Re-run tests to verify\n fileLoggerStorage.getStore()?.phase(\"Verification\");\n log.info(\"Re-running tests to verify fixes...\");\n const verifyResult = await runTestCommand(testCommand, cwd);\n await instance.cleanup();\n fileLoggerStorage.getStore()?.info(`Verification result: exit code ${verifyResult.exitCode}`);\n\n if (verifyResult.exitCode === 0) {\n log.success(\"All tests pass after fixes!\");\n return { mode: \"fix-tests\", success: true };\n }\n\n log.warn(\n `Tests still failing after fix attempt (exit code ${verifyResult.exitCode}).`,\n );\n return { mode: \"fix-tests\", success: false, error: \"Tests still failing after fix attempt\" };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`Fix-tests pipeline failed: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n log.error(`Fix-tests pipeline failed: ${log.formatErrorChain(err)}`);\n return { mode: \"fix-tests\", success: false, error: message };\n }\n };\n\n if (fileLogger) {\n return fileLoggerStorage.run(fileLogger, async () => {\n try {\n return await pipelineBody();\n } finally {\n fileLogger.close();\n }\n });\n }\n return pipelineBody();\n}\n","/**\n * CLI entry point for `dispatch`.\n *\n * This module is a thin argument-parsing shell. It parses CLI arguments,\n * boots the orchestrator, delegates all workflow logic (config loading,\n * validation, pipeline selection) to the orchestrator's `runFromCli()`\n * method, and exits based on the result.\n *\n * Process-level concerns (signal handlers, config subcommand) remain here.\n */\n\nimport { resolve, join } from \"node:path\";\nimport { Command, Option, CommanderError } from \"commander\";\nimport { boot as bootOrchestrator, type RawCliArgs } from \"./orchestrator/runner.js\";\nimport { log } from \"./helpers/logger.js\";\nimport { runCleanup } from \"./helpers/cleanup.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\nimport { PROVIDER_NAMES } from \"./providers/index.js\";\nimport { DATASOURCE_NAMES } from \"./datasources/index.js\";\nimport { handleConfigCommand, CONFIG_BOUNDS } from \"./config.js\";\n\nexport const MAX_CONCURRENCY = CONFIG_BOUNDS.concurrency.max;\n\nexport const HELP = `\n dispatch — AI agent orchestration CLI\n\n Usage:\n dispatch [issue-id...] Dispatch specific issues (or all open issues if none given)\n dispatch --spec <ids> Generate spec files from issues\n dispatch --spec <glob> Generate specs from local markdown files in the configured datasource\n dispatch --respec Regenerate all existing specs\n dispatch --respec <ids> Regenerate specs for specific issues\n dispatch --respec <glob> Regenerate specs matching a glob pattern\n dispatch --spec \"description\" Generate a spec from an inline text description\n dispatch --fix-tests [issue-id...] Run tests and fix failures via AI agent (optionally on specific issue branches)\n\n Options:\n --dry-run List tasks without dispatching (also works with --spec)\n --no-plan Skip the planner agent, dispatch directly\n --no-branch Skip branch creation, push, and PR lifecycle\n --no-worktree Skip git worktree isolation for parallel issues\n --feature [name] Group issues into a single feature branch and PR\n --force Ignore prior run state and re-run all tasks\n --concurrency <n> Max parallel dispatches (default: min(cpus, freeMB/500), max: ${MAX_CONCURRENCY})\n --provider <name> Agent backend: ${PROVIDER_NAMES.join(\", \")} (default: opencode)\n --source <name> Issue source: ${DATASOURCE_NAMES.join(\", \")} (optional; auto-detected from git remote)\n --server-url <url> URL of a running provider server\n --plan-timeout <min> Planning timeout in minutes (default: 10)\n --retries <n> Retry attempts for all agents (default: 2)\n --plan-retries <n> Retry attempts after planning timeout (overrides --retries for planner)\n --test-timeout <min> Test timeout in minutes (default: 5)\n --cwd <dir> Working directory (default: cwd)\n\n Spec options:\n --spec <value> Comma-separated issue numbers, glob pattern for .md files, or inline text description\n --respec [value] Regenerate specs: issue numbers, glob, or omit to regenerate all existing specs\n --output-dir <dir> Output directory for specs (default: .dispatch/specs)\n\n Azure DevOps options:\n --org <url> Azure DevOps organization URL\n --project <name> Azure DevOps project name\n\n General:\n --verbose Show detailed debug output for troubleshooting\n -h, --help Show this help\n -v, --version Show version\n\n Config:\n dispatch config Launch interactive configuration wizard\n\n Examples:\n dispatch 14\n dispatch 14,15,16\n dispatch 14 15 16\n dispatch\n dispatch 14 --dry-run\n dispatch 14 --provider copilot\n dispatch --spec 42,43,44\n dispatch --spec 42,43 --source github --provider copilot\n dispatch --spec 100,200 --source azdevops --org https://dev.azure.com/myorg --project MyProject\n dispatch --spec \"drafts/*.md\"\n dispatch --spec \"drafts/*.md\" --source github\n dispatch --spec \"./my-feature.md\" --provider copilot\n dispatch --respec\n dispatch --respec 42,43,44\n dispatch --respec \"specs/*.md\"\n dispatch --spec \"add dark mode toggle to settings page\"\n dispatch --spec \"feature A should do x\" --provider copilot\n dispatch --feature\n dispatch --feature my-feature\n dispatch --fix-tests\n dispatch --fix-tests 14\n dispatch --fix-tests 14 15 16\n dispatch --fix-tests 14,15,16\n dispatch config\n`.trimStart();\n\n/** Parsed CLI arguments including shell-only flags (help, version). */\nexport interface ParsedArgs extends Omit<RawCliArgs, \"explicitFlags\"> {\n help: boolean;\n version: boolean;\n feature?: string | boolean;\n}\n\n/**\n * Maps Commander option attribute names to their corresponding `explicitFlags`\n * key names. This is the single source of truth for all CLI options.\n *\n * Keys are Commander's camelCase attribute names (derived from the flag string).\n * Values are the flag names used in `explicitFlags` and downstream code.\n *\n * Exported so tests can verify help-text completeness.\n */\nexport const CLI_OPTIONS_MAP: Record<string, string> = {\n help: \"help\",\n version: \"version\",\n dryRun: \"dryRun\",\n plan: \"noPlan\",\n branch: \"noBranch\",\n worktree: \"noWorktree\",\n force: \"force\",\n verbose: \"verbose\",\n spec: \"spec\",\n respec: \"respec\",\n fixTests: \"fixTests\",\n feature: \"feature\",\n source: \"issueSource\",\n provider: \"provider\",\n concurrency: \"concurrency\",\n serverUrl: \"serverUrl\",\n planTimeout: \"planTimeout\",\n retries: \"retries\",\n planRetries: \"planRetries\",\n testTimeout: \"testTimeout\",\n cwd: \"cwd\",\n org: \"org\",\n project: \"project\",\n outputDir: \"outputDir\",\n};\n\nexport function parseArgs(argv: string[]): [ParsedArgs, Set<string>] {\n const program = new Command();\n\n program\n .exitOverride()\n .configureOutput({\n writeOut: () => {},\n writeErr: () => {},\n })\n .helpOption(false)\n .argument(\"[issueIds...]\")\n .option(\"-h, --help\", \"Show help\")\n .option(\"-v, --version\", \"Show version\")\n .option(\"--dry-run\", \"List tasks without dispatching\")\n .option(\"--no-plan\", \"Skip the planner agent\")\n .option(\"--no-branch\", \"Skip branch creation\")\n .option(\"--no-worktree\", \"Skip git worktree isolation\")\n .option(\"--feature [name]\", \"Group issues into a single feature branch\")\n .option(\"--force\", \"Ignore prior run state\")\n .option(\"--verbose\", \"Show detailed debug output\")\n .option(\"--fix-tests\", \"Run tests and fix failures (optionally pass issue IDs to target specific branches)\")\n .option(\"--spec <values...>\", \"Spec mode: issue numbers, glob, or text\")\n .option(\"--respec [values...]\", \"Regenerate specs\")\n .addOption(\n new Option(\"--provider <name>\", \"Agent backend\").choices(PROVIDER_NAMES),\n )\n .addOption(\n new Option(\"--source <name>\", \"Issue source\").choices(\n DATASOURCE_NAMES as string[],\n ),\n )\n .option(\n \"--concurrency <n>\",\n \"Max parallel dispatches\",\n (val: string): number => {\n const n = parseInt(val, 10);\n if (isNaN(n) || n < 1) throw new CommanderError(1, \"commander.invalidArgument\", \"--concurrency must be a positive integer\");\n if (n > MAX_CONCURRENCY) throw new CommanderError(1, \"commander.invalidArgument\", `--concurrency must not exceed ${MAX_CONCURRENCY}`);\n return n;\n },\n )\n .option(\n \"--plan-timeout <min>\",\n \"Planning timeout in minutes\",\n (val: string): number => {\n const n = parseFloat(val);\n if (isNaN(n) || n < CONFIG_BOUNDS.planTimeout.min) throw new CommanderError(1, \"commander.invalidArgument\", \"--plan-timeout must be a positive number (minutes)\");\n if (n > CONFIG_BOUNDS.planTimeout.max) throw new CommanderError(1, \"commander.invalidArgument\", `--plan-timeout must not exceed ${CONFIG_BOUNDS.planTimeout.max}`);\n return n;\n },\n )\n .option(\n \"--retries <n>\",\n \"Retry attempts\",\n (val: string): number => {\n const n = parseInt(val, 10);\n if (isNaN(n) || n < 0) throw new CommanderError(1, \"commander.invalidArgument\", \"--retries must be a non-negative integer\");\n return n;\n },\n )\n .option(\n \"--plan-retries <n>\",\n \"Planner retry attempts\",\n (val: string): number => {\n const n = parseInt(val, 10);\n if (isNaN(n) || n < 0) throw new CommanderError(1, \"commander.invalidArgument\", \"--plan-retries must be a non-negative integer\");\n return n;\n },\n )\n .option(\n \"--test-timeout <min>\",\n \"Test timeout in minutes\",\n (val: string): number => {\n const n = parseFloat(val);\n if (isNaN(n) || n <= 0) throw new CommanderError(1, \"commander.invalidArgument\", \"--test-timeout must be a positive number (minutes)\");\n return n;\n },\n )\n .option(\"--cwd <dir>\", \"Working directory\", (val: string) => resolve(val))\n .option(\"--output-dir <dir>\", \"Output directory\", (val: string) => resolve(val))\n .option(\"--org <url>\", \"Azure DevOps organization URL\")\n .option(\"--project <name>\", \"Azure DevOps project name\")\n .option(\"--server-url <url>\", \"Provider server URL\");\n\n try {\n program.parse(argv, { from: \"user\" });\n } catch (err) {\n if (err instanceof CommanderError) {\n log.error(err.message);\n process.exit(1);\n }\n throw err;\n }\n\n const opts = program.opts();\n\n // ── Build ParsedArgs ────────────────────────────────────────\n const args: ParsedArgs = {\n issueIds: program.args,\n dryRun: opts.dryRun ?? false,\n noPlan: !opts.plan,\n noBranch: !opts.branch,\n noWorktree: !opts.worktree,\n force: opts.force ?? false,\n provider: opts.provider ?? \"opencode\",\n cwd: opts.cwd ?? process.cwd(),\n help: opts.help ?? false,\n version: opts.version ?? false,\n verbose: opts.verbose ?? false,\n };\n\n // Optional fields — only set when explicitly provided\n if (opts.spec !== undefined) {\n args.spec = opts.spec.length === 1 ? opts.spec[0] : opts.spec;\n }\n if (opts.respec !== undefined) {\n if (opts.respec === true) {\n args.respec = [];\n } else {\n args.respec = opts.respec.length === 1 ? opts.respec[0] : opts.respec;\n }\n }\n if (opts.fixTests) args.fixTests = true;\n if (opts.feature) args.feature = opts.feature;\n if (opts.source !== undefined) args.issueSource = opts.source;\n if (opts.concurrency !== undefined) args.concurrency = opts.concurrency;\n if (opts.serverUrl !== undefined) args.serverUrl = opts.serverUrl;\n if (opts.planTimeout !== undefined) args.planTimeout = opts.planTimeout;\n if (opts.retries !== undefined) args.retries = opts.retries;\n if (opts.planRetries !== undefined) args.planRetries = opts.planRetries;\n if (opts.testTimeout !== undefined) args.testTimeout = opts.testTimeout;\n if (opts.org !== undefined) args.org = opts.org;\n if (opts.project !== undefined) args.project = opts.project;\n if (opts.outputDir !== undefined) args.outputDir = opts.outputDir;\n\n // ── Derive explicitFlags from Commander option sources ─────\n const explicitFlags = new Set<string>();\n\n for (const [attr, flag] of Object.entries(CLI_OPTIONS_MAP)) {\n if (program.getOptionValueSource(attr) === \"cli\") {\n explicitFlags.add(flag);\n }\n }\n\n return [args, explicitFlags];\n}\n\nasync function main() {\n const rawArgv = process.argv.slice(2);\n\n // ── Config subcommand via Commander ────────────────────────\n if (rawArgv[0] === \"config\") {\n const configProgram = new Command(\"dispatch-config\")\n .exitOverride()\n .configureOutput({ writeOut: () => {}, writeErr: () => {} })\n .helpOption(false)\n .allowUnknownOption(true)\n .allowExcessArguments(true)\n .option(\"--cwd <dir>\", \"Working directory\", (v: string) => resolve(v));\n\n try {\n configProgram.parse(rawArgv.slice(1), { from: \"user\" });\n } catch (err) {\n if (err instanceof CommanderError) {\n log.error(err.message);\n process.exit(1);\n }\n throw err;\n }\n\n const configDir = join(configProgram.opts().cwd ?? process.cwd(), \".dispatch\");\n await handleConfigCommand(rawArgv.slice(1), configDir);\n process.exit(0);\n }\n\n const [args, explicitFlags] = parseArgs(rawArgv);\n\n // Enable verbose logging before anything else\n log.verbose = args.verbose;\n\n // ── Graceful shutdown on signals ───────────────────────────\n process.on(\"SIGINT\", async () => {\n log.debug(\"Received SIGINT, cleaning up...\");\n await runCleanup();\n process.exit(130);\n });\n\n process.on(\"SIGTERM\", async () => {\n log.debug(\"Received SIGTERM, cleaning up...\");\n await runCleanup();\n process.exit(143);\n });\n\n if (args.help) {\n console.log(HELP);\n process.exit(0);\n }\n\n if (args.version) {\n console.log(`dispatch v${__VERSION__}`);\n process.exit(0);\n }\n\n // ── Delegate to orchestrator ───────────────────────────────\n const orchestrator = await bootOrchestrator({ cwd: args.cwd });\n const { help: _, version: __, ...rawArgs } = args;\n const summary = await orchestrator.runFromCli({ ...rawArgs, explicitFlags });\n\n // Determine exit code from summary\n const failed = \"failed\" in summary ? summary.failed : (\"success\" in summary && !summary.success ? 1 : 0);\n process.exit(failed > 0 ? 1 : 0);\n}\n\nmain().catch(async (err) => {\n log.error(log.formatErrorChain(err));\n await runCleanup();\n process.exit(1);\n});\n","/**\n * Spec generator — fetches issue details from a configured datasource\n * (GitHub, Azure DevOps, or local markdown files), sends them to the AI\n * provider along with instructions to explore the codebase and research\n * the approach, then writes high-level markdown spec files.\n *\n * Pipeline:\n * 1. Resolve the datasource (explicit or auto-detected)\n * 2. Fetch issue/file details via the datasource\n * 3. Boot the AI provider\n * 4. For each item, tell the AI agent the target filepath and prompt it\n * to explore the codebase and write the spec directly to disk\n * 5. Verify the spec file was written\n * 6. Push spec content back to the datasource via update()\n *\n * The generated specs stay high-level (WHAT, WHY, HOW) because the\n * planner agent in the dispatch pipeline handles detailed, line-level\n * implementation planning for each individual task.\n */\n\nimport { cpus, freemem } from \"node:os\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\nimport { getDatasource, detectDatasource, DATASOURCE_NAMES } from \"./datasources/index.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport { log } from \"./helpers/logger.js\";\n\n/** Estimated memory (in MB) required per concurrent spec-generation task. */\nexport const MB_PER_CONCURRENT_TASK = 500;\n\n/** Recognized H2 section headings used to detect spec structure boundaries. */\nexport const RECOGNIZED_H2 = new Set([\n \"## Context\",\n \"## Why\",\n \"## Approach\",\n \"## Integration Points\",\n \"## Tasks\",\n \"## References\",\n \"## Key Guidelines\",\n]);\n\nexport interface SpecOptions {\n /** Comma-separated issue numbers, glob pattern(s), or \"list\" to use datasource.list() */\n issues: string | string[];\n /** Explicit datasource override (auto-detected if omitted) */\n issueSource?: DatasourceName;\n /** AI agent backend */\n provider: ProviderName;\n /** Model override to pass to the provider (provider-specific format). */\n model?: string;\n /** URL of a running provider server */\n serverUrl?: string;\n /** Working directory */\n cwd: string;\n /** Output directory for spec files (default: .dispatch/specs) */\n outputDir?: string;\n /** Azure DevOps organization URL */\n org?: string;\n /** Azure DevOps project name */\n project?: string;\n /** Azure DevOps work item type (e.g. \"User Story\", \"Product Backlog Item\") */\n workItemType?: string;\n /** Azure DevOps iteration path filter (e.g. \"MyProject\\\\Sprint 1\" or \"@CurrentIteration\") */\n iteration?: string;\n /** Azure DevOps area path filter (e.g. \"MyProject\\\\Team A\") */\n area?: string;\n /** Max parallel fetches/generations (default: min(cpuCount, freeMB/500)) */\n concurrency?: number;\n /** When true, log a preview of what would be generated without booting the provider or writing files. */\n dryRun?: boolean;\n /** Number of retry attempts for spec generation (default: 2) */\n retries?: number;\n}\n\n/**\n * Returns a safe default concurrency: min(cpuCount, freeMB/500), at least 1.\n *\n * Each concurrent agent process (provider runtime) is estimated to consume\n * roughly 500 MB of resident memory. The formula caps parallelism at the\n * lesser of the available CPU count and the number of 500 MB slots that fit\n * in current free memory, ensuring the host is not over-committed. The\n * result is floored to at least 1 so that the pipeline always makes progress.\n *\n * Users can override this computed value via the `--concurrency` CLI flag\n * or the `concurrency` key in `.dispatch/config.json`.\n */\nexport function defaultConcurrency(): number {\n return Math.max(1, Math.min(cpus().length, Math.floor(freemem() / 1024 / 1024 / MB_PER_CONCURRENT_TASK)));\n}\n\n/**\n * Returns `true` when the input string consists solely of comma-separated\n * issue numbers (digits, commas, and optional whitespace). Anything else\n * — paths, globs, filenames — returns `false`.\n *\n * This is the branching point for the two spec-generation code paths:\n * issue-tracker mode vs. local-file/glob mode.\n */\nexport function isIssueNumbers(input: string | string[]): input is string {\n if (Array.isArray(input)) return false;\n return /^\\d+(,\\s*\\d+)*$/.test(input);\n}\n\n/**\n * Returns `true` when the input looks like a glob pattern or file path\n * rather than free-form inline text.\n *\n * Checks for:\n * - Glob metacharacters: `*`, `?`, `[`, `{`\n * - Path separators: `/`, `\\`\n * - Dot-prefix relative paths: `./`, `../`\n * - Common file extensions: `.md`, `.txt`, `.yaml`, `.yml`, `.json`, `.ts`,\n * `.js`, `.tsx`, `.jsx`\n *\n * This is a pure function intended to be called *after* `isIssueNumbers()`\n * has already returned `false`, providing the second level of input\n * discrimination for the spec pipeline.\n */\nexport function isGlobOrFilePath(input: string | string[]): boolean {\n if (Array.isArray(input)) return true;\n // Glob metacharacters\n if (/[*?\\[{]/.test(input)) return true;\n\n // Path separators (forward slash or backslash)\n if (/[/\\\\]/.test(input)) return true;\n\n // Dot-prefix relative paths (./something, ../something, .\\something, ..\\something)\n if (/^\\.\\.?[\\/\\\\]/.test(input)) return true;\n\n // Common file extensions at end of string\n if (/\\.(md|txt|yaml|yml|json|ts|js|tsx|jsx)$/i.test(input)) return true;\n\n return false;\n}\n\n/**\n * Post-process raw spec file content written by the AI agent.\n *\n * Strips code-fence wrapping, preamble text before the first H1 heading,\n * and postamble text after the last recognized spec section. Returns the\n * content unchanged when no recognizable spec structure is found.\n *\n * Pure function — no I/O, no side-effects.\n */\nexport function extractSpecContent(raw: string): string {\n let content = raw;\n\n // 1. Strip code-fence wrapping (``` or ```markdown around entire content)\n // The fence may wrap the entire input or may appear after preamble text,\n // so we search for a fenced block containing an H1 heading.\n const fenceMatch = content.match(/^\\s*```(?:markdown)?\\s*\\n([\\s\\S]*?)\\n\\s*```\\s*$/);\n if (fenceMatch) {\n content = fenceMatch[1];\n } else {\n // Try to find a fenced block that contains an H1, even with surrounding text\n const innerFenceMatch = content.match(/```(?:markdown)?\\s*\\n([\\s\\S]*?)\\n\\s*```/);\n if (innerFenceMatch && /^# /m.test(innerFenceMatch[1])) {\n content = innerFenceMatch[1];\n }\n }\n\n // 2. Remove preamble — everything before the first H1 heading\n const h1Index = content.search(/^# /m);\n if (h1Index === -1) {\n // No H1 found — return original content unchanged\n return raw;\n }\n content = content.slice(h1Index);\n\n // 3. Remove postamble — trim after the last recognized H2 section's content\n const lines = content.split(\"\\n\");\n let lastRecognizedSectionEnd = lines.length;\n\n // Walk backwards to find the last recognized H2 and its content extent\n let foundLastRecognized = false;\n for (let i = lines.length - 1; i >= 0; i--) {\n const trimmed = lines[i].trimEnd();\n if (trimmed.startsWith(\"## \")) {\n if (RECOGNIZED_H2.has(trimmed)) {\n // This is the last recognized H2 — everything up to end is the section content\n foundLastRecognized = true;\n break;\n } else {\n // Unrecognized H2 — this and everything after it is postamble\n lastRecognizedSectionEnd = i;\n }\n }\n }\n\n if (foundLastRecognized || lastRecognizedSectionEnd < lines.length) {\n // Trim trailing blank lines from the kept portion\n let end = lastRecognizedSectionEnd;\n while (end > 0 && lines[end - 1].trim() === \"\") {\n end--;\n }\n content = lines.slice(0, end).join(\"\\n\");\n }\n\n // Ensure trailing newline\n if (!content.endsWith(\"\\n\")) {\n content += \"\\n\";\n }\n\n return content;\n}\n\nexport interface ValidationResult {\n /** Whether the spec content has valid structure */\n valid: boolean;\n /** Human-readable reason when validation fails */\n reason?: string;\n}\n\n/**\n * Validate that spec content has the expected structural markers.\n *\n * Checks:\n * 1. Content starts with an H1 heading (`# `)\n * 2. Contains a `## Tasks` section with at least one `- [ ]` checkbox\n *\n * This is a guardrail, not a gate — validation failures are warned but\n * do not block the pipeline. Returns a structured result so callers can\n * act on it.\n */\nexport function validateSpecStructure(content: string): ValidationResult {\n const trimmed = content.trimStart();\n\n // Check 1: Must start with an H1 heading\n if (!trimmed.startsWith(\"# \")) {\n const reason = \"Spec does not start with an H1 heading (expected \\\"# \\\")\";\n log.warn(reason);\n return { valid: false, reason };\n }\n\n // Check 2: Must contain a ## Tasks section\n const tasksIndex = content.search(/^## Tasks\\s*$/m);\n if (tasksIndex === -1) {\n const reason = \"Spec is missing a \\\"## Tasks\\\" section\";\n log.warn(reason);\n return { valid: false, reason };\n }\n\n // Check 3: Must have at least one checkbox after ## Tasks\n const afterTasks = content.slice(tasksIndex);\n if (!/- \\[ \\]/.test(afterTasks)) {\n const reason = \"\\\"## Tasks\\\" section contains no unchecked tasks (expected at least one \\\"- [ ]\\\")\";\n log.warn(reason);\n return { valid: false, reason };\n }\n\n return { valid: true };\n}\n\n/**\n * Resolve the datasource name for a spec-generation run.\n *\n * Priority:\n * 1. Explicit `issueSource` (from --source flag or config) — always wins.\n * 2. Auto-detect from the git remote URL.\n * 3. For glob/file inputs, fall back to `\"md\"` when auto-detection fails.\n * 4. For issue-number inputs, return `null` when auto-detection fails (caller should abort).\n */\nexport async function resolveSource(\n issues: string | string[],\n issueSource: DatasourceName | undefined,\n cwd: string\n): Promise<DatasourceName | null> {\n if (issueSource) {\n return issueSource;\n }\n log.info(\"Detecting datasource from git remote...\");\n const detected = await detectDatasource(cwd);\n if (detected) {\n log.info(`Detected datasource: ${detected}`);\n return detected;\n }\n if (!isIssueNumbers(issues)) {\n return \"md\";\n }\n log.error(\n `Could not detect datasource from the repository remote URL.\\n` +\n ` Supported sources: ${DATASOURCE_NAMES.join(\", \")}\\n` +\n ` Use --source <name> to specify explicitly, or ensure the git remote\\n` +\n ` points to a supported platform (github.com, dev.azure.com).`\n );\n return null;\n}\n\nexport interface SpecSummary {\n /** Total issues requested */\n total: number;\n /** Successfully generated spec files */\n generated: number;\n /** Failed to generate */\n failed: number;\n /** Paths of generated spec files */\n files: string[];\n /** Issue numbers created or updated during spec generation (empty when datasource is md) */\n issueNumbers: string[];\n /** Dispatch identifiers for the \"Run these specs with\" hint (issue numbers or file paths) */\n identifiers?: string[];\n /** Total pipeline wall-clock duration in milliseconds */\n durationMs: number;\n /** Per-file generation durations in milliseconds (filepath → ms) */\n fileDurationsMs: Record<string, number>;\n}\n\n","/**\n * Datasource registry — maps datasource names to their implementations\n * and provides auto-detection of the datasource from the git remote URL.\n *\n * To add a new datasource:\n * 1. Create `src/datasources/<name>.ts` exporting a `datasource` object\n * 2. Import and register it in the `DATASOURCES` map below\n * 3. Add the name to the `DatasourceName` type in `src/datasources/interface.ts`\n * 4. Add a URL pattern to `detectDatasource` if auto-detection is possible\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { Datasource, DatasourceName } from \"./interface.js\";\nimport { datasource as githubDatasource } from \"./github.js\";\nimport { datasource as azdevopsDatasource } from \"./azdevops.js\";\nimport { datasource as mdDatasource } from \"./md.js\";\nexport type { Datasource, DatasourceName, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\n\nconst exec = promisify(execFile);\n\nconst DATASOURCES: Partial<Record<DatasourceName, Datasource>> = {\n github: githubDatasource,\n azdevops: azdevopsDatasource,\n md: mdDatasource,\n};\n\n/**\n * All registered datasource names — useful for CLI help text and validation.\n */\nexport const DATASOURCE_NAMES = Object.keys(DATASOURCES) as DatasourceName[];\n\n/**\n * Get a datasource by name.\n *\n * @throws if the datasource name is not registered.\n */\nexport function getDatasource(name: DatasourceName): Datasource {\n const datasource = DATASOURCES[name];\n if (!datasource) {\n throw new Error(\n `Unknown datasource \"${name}\". Available: ${DATASOURCE_NAMES.join(\", \")}`\n );\n }\n return datasource;\n}\n\n/**\n * Get the git remote URL for the `origin` remote.\n *\n * @param cwd - Working directory to run the git command in\n * @returns The remote URL string, or `null` if unavailable\n */\nexport async function getGitRemoteUrl(cwd: string): Promise<string | null> {\n try {\n const { stdout } = await exec(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd,\n shell: process.platform === \"win32\",\n });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/**\n * URL patterns used to detect the datasource from a git remote.\n *\n * Each entry maps a regex (tested against the remote URL) to the\n * corresponding `DatasourceName`. Patterns are tested in order;\n * the first match wins.\n */\nconst SOURCE_PATTERNS: { pattern: RegExp; source: DatasourceName }[] = [\n { pattern: /github\\.com/i, source: \"github\" },\n { pattern: /dev\\.azure\\.com/i, source: \"azdevops\" },\n { pattern: /visualstudio\\.com/i, source: \"azdevops\" },\n];\n\n/**\n * Auto-detect the datasource by inspecting the `origin` remote URL.\n *\n * Returns the detected `DatasourceName`, or `null` if the remote URL\n * does not match any known pattern.\n */\nexport async function detectDatasource(\n cwd: string\n): Promise<DatasourceName | null> {\n const url = await getGitRemoteUrl(cwd);\n if (!url) return null;\n\n for (const { pattern, source } of SOURCE_PATTERNS) {\n if (pattern.test(url)) {\n return source;\n }\n }\n\n return null;\n}\n\n/**\n * Parse an Azure DevOps git remote URL and extract the organization URL and project name.\n *\n * Supports all three Azure DevOps remote URL formats:\n * - **HTTPS:** `https://dev.azure.com/{org}/{project}/_git/{repo}`\n * - **SSH:** `git@ssh.dev.azure.com:v3/{org}/{project}/{repo}`\n * - **Legacy HTTPS:** `https://{org}.visualstudio.com/{project}/_git/{repo}`\n *\n * The org URL is always normalized to `https://dev.azure.com/{org}`.\n *\n * @param url - The git remote URL to parse\n * @returns The parsed org URL and project name, or `null` if the URL is not a recognized Azure DevOps format\n */\nexport function parseAzDevOpsRemoteUrl(\n url: string\n): { orgUrl: string; project: string } | null {\n // HTTPS: https://[user@]dev.azure.com/{org}/{project}/_git/{repo}\n const httpsMatch = url.match(\n /^https?:\\/\\/(?:[^@]+@)?dev\\.azure\\.com\\/([^/]+)\\/([^/]+)\\/_git\\//i\n );\n if (httpsMatch) {\n return {\n orgUrl: `https://dev.azure.com/${decodeURIComponent(httpsMatch[1])}`,\n project: decodeURIComponent(httpsMatch[2]),\n };\n }\n\n // SSH: git@ssh.dev.azure.com:v3/{org}/{project}/{repo}\n const sshMatch = url.match(\n /^git@ssh\\.dev\\.azure\\.com:v3\\/([^/]+)\\/([^/]+)\\//i\n );\n if (sshMatch) {\n return {\n orgUrl: `https://dev.azure.com/${decodeURIComponent(sshMatch[1])}`,\n project: decodeURIComponent(sshMatch[2]),\n };\n }\n\n // Legacy: https://{org}.visualstudio.com/[DefaultCollection/]{project}/_git/{repo}\n const legacyMatch = url.match(\n /^https?:\\/\\/([^.]+)\\.visualstudio\\.com\\/(?:DefaultCollection\\/)?([^/]+)\\/_git\\//i\n );\n if (legacyMatch) {\n return {\n orgUrl: `https://dev.azure.com/${decodeURIComponent(legacyMatch[1])}`,\n project: decodeURIComponent(legacyMatch[2]),\n };\n }\n\n return null;\n}\n\n/**\n * Parse a GitHub git remote URL and extract the owner and repository name.\n *\n * Supports both GitHub remote URL formats:\n * - **HTTPS:** `https://github.com/{owner}/{repo}[.git]`\n * - **SSH:** `git@github.com:{owner}/{repo}[.git]`\n *\n * @param url - The git remote URL to parse\n * @returns The parsed owner and repo, or `null` if the URL is not a recognized GitHub format\n */\nexport function parseGitHubRemoteUrl(\n url: string\n): { owner: string; repo: string } | null {\n // HTTPS: https://[user@]github.com/{owner}/{repo}[.git]\n const httpsMatch = url.match(\n /^https?:\\/\\/(?:[^@]+@)?github\\.com\\/([^/]+)\\/([^/]+?)\\/?$/i\n );\n if (httpsMatch) {\n const owner = decodeURIComponent(httpsMatch[1]);\n const rawRepo = decodeURIComponent(httpsMatch[2]);\n const repo = rawRepo.endsWith(\".git\") ? rawRepo.slice(0, -4) : rawRepo;\n return { owner, repo };\n }\n\n // SSH (scp-style): git@github.com:{owner}/{repo}[.git]\n const sshMatch = url.match(\n /^git@github\\.com:([^/]+)\\/([^/]+?)\\/?$/i\n );\n if (sshMatch) {\n const owner = decodeURIComponent(sshMatch[1]);\n const rawRepo = decodeURIComponent(sshMatch[2]);\n const repo = rawRepo.endsWith(\".git\") ? rawRepo.slice(0, -4) : rawRepo;\n return { owner, repo };\n }\n\n // SSH (url-style): ssh://git@github.com/{owner}/{repo}[.git]\n const sshUrlMatch = url.match(\n /^ssh:\\/\\/git@github\\.com\\/([^/]+)\\/([^/]+?)\\/?$/i\n );\n if (sshUrlMatch) {\n const owner = decodeURIComponent(sshUrlMatch[1]);\n const rawRepo = decodeURIComponent(sshUrlMatch[2]);\n const repo = rawRepo.endsWith(\".git\") ? rawRepo.slice(0, -4) : rawRepo;\n return { owner, repo };\n }\n\n return null;\n}\n","/**\n * GitHub datasource — reads and writes issues using the Octokit SDK.\n *\n * Requires:\n * - A GitHub OAuth token (obtained via device flow on first use)\n * - Working directory inside a GitHub repository with an `origin` remote\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { Datasource, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\nimport { slugify } from \"../helpers/slugify.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { InvalidBranchNameError, isValidBranchName } from \"../helpers/branch-validation.js\";\nimport { getGithubOctokit } from \"../helpers/auth.js\";\nimport { getGitRemoteUrl, parseGitHubRemoteUrl } from \"./index.js\";\n\nexport { InvalidBranchNameError } from \"../helpers/branch-validation.js\";\n\nconst exec = promisify(execFile);\n\n/** Execute a git command and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/**\n * Redact userinfo (credentials) from a URL for safe inclusion in error messages.\n */\nfunction redactUrl(url: string): string {\n return url.replace(/\\/\\/[^@/]+@/, \"//***@\");\n}\n\n/** Resolve the GitHub owner and repo from the git remote URL. */\nasync function getOwnerRepo(cwd: string): Promise<{ owner: string; repo: string }> {\n const remoteUrl = await getGitRemoteUrl(cwd);\n if (!remoteUrl) {\n throw new Error(\"Could not determine git remote URL. Is this a git repository with an origin remote?\");\n }\n const parsed = parseGitHubRemoteUrl(remoteUrl);\n if (!parsed) {\n throw new Error(`Could not parse GitHub owner/repo from remote URL: ${redactUrl(remoteUrl)}`);\n }\n return parsed;\n}\n\n/**\n * Build a branch name from an issue number, title, and username.\n * Produces: `<username>/dispatch/<number>-<slugified-title>`\n *\n * @param issueNumber - The issue number/ID\n * @param title - The issue title (will be slugified)\n * @param username - The slugified git username to namespace the branch\n */\nfunction buildBranchName(issueNumber: string, title: string, username: string = \"unknown\"): string {\n const slug = slugify(title, 50);\n return `${username}/dispatch/${issueNumber}-${slug}`;\n}\n\n/**\n * Detect the default branch of the repository.\n * Tries `git symbolic-ref refs/remotes/origin/HEAD` first,\n * falls back to checking if \"main\" or \"master\" exists.\n */\nasync function getDefaultBranch(cwd: string): Promise<string> {\n const PREFIX = \"refs/remotes/origin/\";\n try {\n const ref = await git([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], cwd);\n // ref looks like \"refs/remotes/origin/main\" or \"refs/remotes/origin/release/2024\"\n const trimmed = ref.trim();\n const branch = trimmed.startsWith(PREFIX)\n ? trimmed.slice(PREFIX.length)\n : trimmed;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch, \"from symbolic-ref output\");\n }\n return branch;\n } catch (err) {\n if (err instanceof InvalidBranchNameError) {\n throw err;\n }\n // Fallback: check if \"main\" branch exists\n try {\n await git([\"rev-parse\", \"--verify\", \"main\"], cwd);\n return \"main\";\n } catch {\n return \"master\";\n }\n }\n}\n\n/**\n * Gather commit messages from the current branch relative to the default branch.\n * Uses `git log` to list commits that exist on the current branch but not on\n * the default branch, returning each commit's subject line.\n *\n * @param defaultBranch - The default branch name to compare against (e.g. \"main\")\n * @param cwd - The working directory (git repo root)\n * @returns An array of commit message subject lines\n */\nexport async function getCommitMessages(defaultBranch: string, cwd: string): Promise<string[]> {\n try {\n const output = await git(\n [\"log\", `origin/${defaultBranch}..HEAD`, \"--pretty=format:%s\"],\n cwd,\n );\n return output.trim().split(\"\\n\").filter(Boolean);\n } catch {\n return [];\n }\n}\n\nexport const datasource: Datasource = {\n name: \"github\",\n\n supportsGit(): boolean {\n return true;\n },\n\n async list(opts: IssueFetchOptions = {}): Promise<IssueDetails[]> {\n const cwd = opts.cwd || process.cwd();\n const { owner, repo } = await getOwnerRepo(cwd);\n const octokit = await getGithubOctokit();\n\n const issues = await octokit.paginate(\n octokit.rest.issues.listForRepo,\n {\n owner,\n repo,\n state: \"open\",\n },\n );\n\n return issues\n .filter((issue) => !issue.pull_request)\n .map((issue): IssueDetails => ({\n number: String(issue.number),\n title: issue.title ?? \"\",\n body: issue.body ?? \"\",\n labels: (issue.labels ?? []).map((l) => (typeof l === \"string\" ? l : l.name ?? \"\")).filter(Boolean),\n state: issue.state ?? \"open\",\n url: issue.html_url ?? \"\",\n comments: [],\n acceptanceCriteria: \"\",\n }));\n },\n\n async fetch(issueId: string, opts: IssueFetchOptions = {}): Promise<IssueDetails> {\n const cwd = opts.cwd || process.cwd();\n const { owner, repo } = await getOwnerRepo(cwd);\n const octokit = await getGithubOctokit();\n\n const { data: issue } = await octokit.rest.issues.get({\n owner,\n repo,\n issue_number: Number(issueId),\n });\n\n const issueComments = await octokit.paginate(\n octokit.rest.issues.listComments,\n {\n owner,\n repo,\n issue_number: Number(issueId),\n },\n );\n\n const comments: string[] = issueComments.map(\n (c) => `**${c.user?.login ?? \"unknown\"}:** ${c.body ?? \"\"}`\n );\n\n return {\n number: String(issue.number),\n title: issue.title ?? \"\",\n body: issue.body ?? \"\",\n labels: (issue.labels ?? []).map((l) => (typeof l === \"string\" ? l : l.name ?? \"\")).filter(Boolean),\n state: issue.state ?? \"open\",\n url: issue.html_url ?? \"\",\n comments,\n acceptanceCriteria: \"\",\n };\n },\n\n async update(issueId: string, title: string, body: string, opts: IssueFetchOptions = {}): Promise<void> {\n const cwd = opts.cwd || process.cwd();\n const { owner, repo } = await getOwnerRepo(cwd);\n const octokit = await getGithubOctokit();\n\n await octokit.rest.issues.update({\n owner,\n repo,\n issue_number: Number(issueId),\n title,\n body,\n });\n },\n\n async close(issueId: string, opts: IssueFetchOptions = {}): Promise<void> {\n const cwd = opts.cwd || process.cwd();\n const { owner, repo } = await getOwnerRepo(cwd);\n const octokit = await getGithubOctokit();\n\n await octokit.rest.issues.update({\n owner,\n repo,\n issue_number: Number(issueId),\n state: \"closed\",\n });\n },\n\n async create(title: string, body: string, opts: IssueFetchOptions = {}): Promise<IssueDetails> {\n const cwd = opts.cwd || process.cwd();\n const { owner, repo } = await getOwnerRepo(cwd);\n const octokit = await getGithubOctokit();\n\n const { data: issue } = await octokit.rest.issues.create({\n owner,\n repo,\n title,\n body,\n });\n\n return {\n number: String(issue.number),\n title: issue.title ?? \"\",\n body: issue.body ?? \"\",\n labels: (issue.labels ?? []).map((l) => (typeof l === \"string\" ? l : l.name ?? \"\")).filter(Boolean),\n state: issue.state ?? \"open\",\n url: issue.html_url ?? \"\",\n comments: [],\n acceptanceCriteria: \"\",\n };\n },\n\n async getUsername(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const name = await git([\"config\", \"user.name\"], opts.cwd);\n const slug = slugify(name.trim());\n return slug || \"unknown\";\n } catch {\n return \"unknown\";\n }\n },\n\n getDefaultBranch(opts) {\n return getDefaultBranch(opts.cwd);\n },\n\n async getCurrentBranch(opts) {\n try {\n const branch = (await git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"], opts.cwd)).trim();\n // Detached HEAD returns the literal string \"HEAD\"\n if (branch && branch !== \"HEAD\") return branch;\n } catch { /* fall through */ }\n return this.getDefaultBranch(opts);\n },\n\n buildBranchName(issueNumber: string, title: string, username?: string): string {\n return buildBranchName(issueNumber, title, username ?? \"unknown\");\n },\n\n async createAndSwitchBranch(branchName, opts) {\n const cwd = opts.cwd;\n try {\n await git([\"checkout\", \"-b\", branchName], cwd);\n } catch (err) {\n // Branch may already exist — switch to it instead\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n try {\n await git([\"checkout\", branchName], cwd);\n } catch (checkoutErr) {\n const checkoutMessage = log.extractMessage(checkoutErr);\n if (checkoutMessage.includes(\"already used by worktree\")) {\n await git([\"worktree\", \"prune\"], cwd);\n await git([\"checkout\", branchName], cwd);\n } else {\n throw checkoutErr;\n }\n }\n } else {\n throw err;\n }\n }\n },\n\n async switchBranch(branchName, opts) {\n await git([\"checkout\", branchName], opts.cwd);\n },\n\n async pushBranch(branchName, opts) {\n await git([\"push\", \"--set-upstream\", \"origin\", branchName], opts.cwd);\n },\n\n async commitAllChanges(message, opts) {\n const cwd = opts.cwd;\n await git([\"add\", \"-A\"], cwd);\n const status = await git([\"diff\", \"--cached\", \"--stat\"], cwd);\n if (!status.trim()) {\n return; // nothing to commit\n }\n await git([\"commit\", \"-m\", message], cwd);\n },\n\n async createPullRequest(branchName, issueNumber, title, body, opts, baseBranch?) {\n const cwd = opts.cwd;\n const { owner, repo } = await getOwnerRepo(cwd);\n const octokit = await getGithubOctokit();\n const prBody = body || `Closes #${issueNumber}`;\n\n try {\n const target = baseBranch ?? await getDefaultBranch(cwd);\n const { data: pr } = await octokit.rest.pulls.create({\n owner,\n repo,\n title,\n body: prBody,\n head: branchName,\n base: target,\n });\n return pr.html_url;\n } catch (err: unknown) {\n // If a PR already exists for this branch, retrieve its URL.\n // Octokit throws a RequestError with status 422 for validation\n // failures, including \"A pull request already exists\".\n const isValidationError =\n typeof err === \"object\" &&\n err !== null &&\n \"status\" in err &&\n (err as { status: number }).status === 422;\n\n if (isValidationError) {\n const { data: prs } = await octokit.rest.pulls.list({\n owner,\n repo,\n head: `${owner}:${branchName}`,\n state: \"open\",\n });\n if (prs.length > 0) {\n return prs[0].html_url;\n }\n }\n throw err;\n }\n },\n};\n","/**\n * Shared slug generation utility.\n *\n * Converts an arbitrary string into a URL/filename-safe slug by lowercasing,\n * replacing non-alphanumeric runs with hyphens, stripping leading/trailing\n * hyphens, and optionally truncating to a maximum length.\n *\n * Consolidates the identical slugification pattern previously duplicated\n * across datasource and orchestrator modules.\n */\n\n/** Default max slug length for filenames. */\nexport const MAX_SLUG_LENGTH = 60;\n\n/**\n * Convert a string into a lowercase, hyphen-separated slug.\n *\n * Applies the following transformations in order:\n * 1. Lowercase the entire string\n * 2. Replace runs of non-alphanumeric characters with a single hyphen\n * 3. Strip leading and trailing hyphens\n * 4. Truncate to `maxLength` characters (if provided)\n *\n * @param input - The string to slugify\n * @param maxLength - Optional maximum length of the resulting slug\n * @returns The slugified string\n */\nexport function slugify(input: string, maxLength?: number): string {\n const slug = input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n return maxLength != null ? slug.slice(0, maxLength) : slug;\n}\n","/**\n * Shared branch-name validation utilities.\n *\n * Provides a strict validator (`isValidBranchName`) and a typed error class\n * (`InvalidBranchNameError`) that enforce git refname rules. Extracted from\n * the GitHub datasource so every datasource can share the same logic.\n */\n\n/**\n * Thrown when a branch name fails validation.\n * Provides reliable `instanceof` detection instead of brittle message-string checks.\n */\nexport class InvalidBranchNameError extends Error {\n constructor(branch: string, reason?: string) {\n const detail = reason ? ` (${reason})` : \"\";\n super(`Invalid branch name: \"${branch}\"${detail}`);\n this.name = \"InvalidBranchNameError\";\n }\n}\n\n/** Strict pattern for valid git branch name character set. */\nexport const VALID_BRANCH_NAME_RE = /^[a-zA-Z0-9._\\-/]+$/;\n\n/**\n * Check whether a branch name is safe to use in git/gh commands.\n * Enforces git refname rules beyond simple character validation:\n * - Must be 1–255 characters of allowed characters\n * - Cannot start or end with \"/\"\n * - Cannot contain \"..\" (parent traversal)\n * - Cannot end with \".lock\"\n * - Cannot contain \"@{\" (reflog syntax)\n * - Cannot contain \"//\" (empty path component)\n */\nexport function isValidBranchName(name: string): boolean {\n if (name.length === 0 || name.length > 255) return false;\n if (!VALID_BRANCH_NAME_RE.test(name)) return false;\n if (name.startsWith(\"/\") || name.endsWith(\"/\")) return false;\n if (name.includes(\"..\")) return false;\n if (name.endsWith(\".lock\")) return false;\n if (name.includes(\"@{\")) return false;\n if (name.includes(\"//\")) return false;\n return true;\n}\n","/**\n * OAuth device-flow authentication helpers for GitHub and Azure DevOps.\n *\n * Tokens are cached at ~/.dispatch/auth.json (mode 0o600) so users only\n * need to authenticate once per platform until tokens expire.\n */\n\nimport { readFile, writeFile, mkdir, chmod } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nimport { Octokit } from \"@octokit/rest\";\nimport { createOAuthDeviceAuth } from \"@octokit/auth-oauth-device\";\nimport { DeviceCodeCredential } from \"@azure/identity\";\nimport * as azdev from \"azure-devops-node-api\";\nimport open from \"open\";\n\nimport { log } from \"./logger.js\";\nimport {\n GITHUB_CLIENT_ID,\n AZURE_CLIENT_ID,\n AZURE_TENANT_ID,\n AZURE_DEVOPS_SCOPE,\n} from \"../constants.js\";\n\ninterface AuthCache {\n github?: { token: string };\n azure?: { token: string; expiresAt: string };\n}\n\nconst AUTH_PATH = join(homedir(), \".dispatch\", \"auth.json\");\n\n/** Five-minute buffer (ms) used to refresh Azure tokens before they expire. */\nconst EXPIRY_BUFFER_MS = 5 * 60 * 1000;\n\n/** Optional callback for routing auth prompts into the TUI. */\nlet authPromptHandler: ((message: string) => void) | null = null;\n\n/**\n * Register a handler for auth device-code prompts.\n * When set, prompts are routed to this handler instead of `log.info()`.\n * Pass `null` to clear the handler.\n */\nexport function setAuthPromptHandler(handler: ((message: string) => void) | null): void {\n authPromptHandler = handler;\n}\n\nasync function loadAuthCache(): Promise<AuthCache> {\n try {\n const raw = await readFile(AUTH_PATH, \"utf-8\");\n return JSON.parse(raw) as AuthCache;\n } catch {\n return {};\n }\n}\n\nasync function saveAuthCache(cache: AuthCache): Promise<void> {\n await mkdir(dirname(AUTH_PATH), { recursive: true });\n await writeFile(AUTH_PATH, JSON.stringify(cache, null, 2) + \"\\n\", \"utf-8\");\n if (process.platform !== \"win32\") {\n try {\n await chmod(AUTH_PATH, 0o600);\n } catch {\n // chmod may fail on restricted filesystems; token was already written\n }\n }\n}\n\n/**\n * Return an authenticated Octokit instance for the GitHub API.\n *\n * On first use the user is guided through the OAuth device-flow; the\n * resulting token is cached for subsequent calls.\n */\nexport async function getGithubOctokit(): Promise<Octokit> {\n const cache = await loadAuthCache();\n\n if (cache.github?.token) {\n return new Octokit({ auth: cache.github.token });\n }\n\n const auth = createOAuthDeviceAuth({\n clientId: GITHUB_CLIENT_ID,\n clientType: \"oauth-app\",\n scopes: [\"repo\"],\n onVerification(verification) {\n const msg = `Enter code ${verification.user_code} at ${verification.verification_uri}`;\n if (authPromptHandler) {\n authPromptHandler(msg);\n } else {\n log.info(msg);\n }\n open(verification.verification_uri).catch(() => {});\n },\n });\n\n const authentication = await auth({ type: \"oauth\" });\n\n cache.github = { token: authentication.token };\n await saveAuthCache(cache);\n\n return new Octokit({ auth: authentication.token });\n}\n\n/**\n * Return an authenticated Azure DevOps `WebApi` connection for the given org.\n *\n * On first use (or when the cached token is about to expire) the user is\n * guided through the Azure device-code flow; the token is cached for\n * subsequent calls.\n */\nexport async function getAzureConnection(\n orgUrl: string,\n): Promise<azdev.WebApi> {\n const cache = await loadAuthCache();\n\n if (cache.azure?.token && cache.azure.expiresAt) {\n const expiresAt = new Date(cache.azure.expiresAt).getTime();\n if (expiresAt - Date.now() > EXPIRY_BUFFER_MS) {\n return new azdev.WebApi(\n orgUrl,\n azdev.getBearerHandler(cache.azure.token),\n );\n }\n }\n\n const credential = new DeviceCodeCredential({\n tenantId: AZURE_TENANT_ID,\n clientId: AZURE_CLIENT_ID,\n userPromptCallback(deviceCodeInfo) {\n // Azure DevOps only supports work/school accounts — prepend a note\n // so users don't attempt to sign in with a personal Microsoft account.\n const note = \"Azure DevOps requires a work or school account (personal Microsoft accounts are not supported).\";\n const msg = `${note}\\n${deviceCodeInfo.message}`;\n if (authPromptHandler) {\n authPromptHandler(msg);\n } else {\n log.info(msg);\n }\n open(deviceCodeInfo.verificationUri).catch(() => {});\n },\n });\n\n const accessToken = await credential.getToken(AZURE_DEVOPS_SCOPE);\n if (!accessToken) {\n throw new Error(\n \"Azure device-code authentication did not return a token. Please try again.\",\n );\n }\n\n cache.azure = {\n token: accessToken.token,\n expiresAt: new Date(accessToken.expiresOnTimestamp).toISOString(),\n };\n await saveAuthCache(cache);\n\n return new azdev.WebApi(\n orgUrl,\n azdev.getBearerHandler(accessToken.token),\n );\n}\n","/**\n * OAuth client IDs and related constants for device-flow authentication.\n *\n * These are public client identifiers — not secrets — bundled so that users\n * do not need to register their own OAuth applications.\n */\n\n/** GitHub OAuth App client ID. */\nexport const GITHUB_CLIENT_ID = \"Ov23liUMP1Oyg811IF58\";\n\n/** Azure AD application (client) ID. */\nexport const AZURE_CLIENT_ID = \"150a3098-01dd-4126-8b10-5e7f77492e5c\";\n\n/**\n * Azure AD tenant ID — \"organizations\" restricts sign-in to work/school\n * (Entra ID) accounts. Azure DevOps does not support personal Microsoft\n * accounts for API access, so \"common\" cannot be used here.\n */\nexport const AZURE_TENANT_ID = \"organizations\";\n\n/** Azure DevOps default API scope. */\nexport const AZURE_DEVOPS_SCOPE = \"499b84ac-1321-427f-aa17-267ca6975798/.default\";\n","/**\n * Azure DevOps datasource — reads and writes work items using the\n * `azure-devops-node-api` SDK with OAuth device-flow authentication.\n *\n * Requires:\n * - Working directory inside an Azure DevOps git repository with an\n * `origin` remote\n * - User will be prompted to authenticate via device code on first use\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { Datasource, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\nimport { slugify } from \"../helpers/slugify.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { InvalidBranchNameError, isValidBranchName } from \"../helpers/branch-validation.js\";\nimport { getAzureConnection } from \"../helpers/auth.js\";\nimport { getGitRemoteUrl, parseAzDevOpsRemoteUrl } from \"./index.js\";\nimport type { WebApi } from \"azure-devops-node-api\";\nimport type { TeamContext } from \"azure-devops-node-api/interfaces/CoreInterfaces.js\";\nimport type { JsonPatchDocument } from \"azure-devops-node-api/interfaces/common/VSSInterfaces.js\";\nimport { PullRequestStatus } from \"azure-devops-node-api/interfaces/GitInterfaces.js\";\n\nconst exec = promisify(execFile);\nconst doneStateCache = new Map<string, string>();\n\n/** Execute a git command and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/**\n * Redact userinfo (credentials) from a URL for safe inclusion in error messages.\n * Replaces `https://user:pass@host/...` or `https://user@host/...` with `https://***@host/...`.\n */\nfunction redactUrl(url: string): string {\n return url.replace(/\\/\\/[^@/]+@/, \"//***@\");\n}\n\n/**\n * Resolve the Azure DevOps org URL, project name, and an authenticated\n * WebApi connection from the git remote URL.\n *\n * If `opts.org` and `opts.project` are already provided they are used\n * directly; otherwise they are parsed from the `origin` remote.\n */\nasync function getOrgAndProject(\n opts: IssueFetchOptions = {}\n): Promise<{ orgUrl: string; project: string; connection: WebApi }> {\n let orgUrl = opts.org;\n let project = opts.project;\n\n if (!orgUrl || !project) {\n const cwd = opts.cwd || process.cwd();\n const remoteUrl = await getGitRemoteUrl(cwd);\n if (!remoteUrl) {\n throw new Error(\n \"Could not determine git remote URL. Is this a git repository with an origin remote?\"\n );\n }\n const parsed = parseAzDevOpsRemoteUrl(remoteUrl);\n if (!parsed) {\n throw new Error(\n `Could not parse Azure DevOps org/project from remote URL: ${redactUrl(remoteUrl)}`\n );\n }\n orgUrl = orgUrl || parsed.orgUrl;\n project = project || parsed.project;\n }\n\n const connection = await getAzureConnection(orgUrl);\n return { orgUrl, project, connection };\n}\n\n/**\n * Map a raw Azure DevOps work item JSON object to an IssueDetails.\n */\nfunction mapWorkItemToIssueDetails(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n item: any,\n id: string,\n comments: string[],\n defaults?: { title?: string; body?: string; state?: string; workItemType?: string }\n): IssueDetails {\n const fields = item.fields ?? {};\n return {\n number: String(item.id ?? id),\n title: fields[\"System.Title\"] ?? defaults?.title ?? \"\",\n body: fields[\"System.Description\"] ?? defaults?.body ?? \"\",\n labels: (fields[\"System.Tags\"] ?? \"\")\n .split(\";\")\n .map((t: string) => t.trim())\n .filter(Boolean),\n state: fields[\"System.State\"] ?? defaults?.state ?? \"\",\n url: item._links?.html?.href ?? item.url ?? \"\",\n comments,\n acceptanceCriteria:\n fields[\"Microsoft.VSTS.Common.AcceptanceCriteria\"] ?? \"\",\n iterationPath: fields[\"System.IterationPath\"] || undefined,\n areaPath: fields[\"System.AreaPath\"] || undefined,\n assignee: fields[\"System.AssignedTo\"]?.displayName || undefined,\n priority: fields[\"Microsoft.VSTS.Common.Priority\"] ?? undefined,\n storyPoints:\n fields[\"Microsoft.VSTS.Scheduling.StoryPoints\"] ??\n fields[\"Microsoft.VSTS.Scheduling.Effort\"] ??\n fields[\"Microsoft.VSTS.Scheduling.Size\"] ??\n undefined,\n workItemType: fields[\"System.WorkItemType\"] || defaults?.workItemType || undefined,\n };\n}\n\nexport async function detectWorkItemType(\n opts: IssueFetchOptions = {}\n): Promise<string | null> {\n try {\n const { project, connection } = await getOrgAndProject(opts);\n const witApi = await connection.getWorkItemTrackingApi();\n const types = await witApi.getWorkItemTypes(project);\n\n if (!Array.isArray(types) || types.length === 0) return null;\n\n const names = types.map((t) => t.name).filter((n): n is string => !!n);\n const preferred = [\"User Story\", \"Product Backlog Item\", \"Requirement\", \"Issue\"];\n for (const p of preferred) {\n if (names.includes(p)) return p;\n }\n return names[0] ?? null;\n } catch {\n return null;\n }\n}\n\nexport async function detectDoneState(\n workItemType: string,\n opts: IssueFetchOptions = {}\n): Promise<string> {\n const { orgUrl, project, connection } = await getOrgAndProject(opts);\n const cacheKey = `${orgUrl}|${project}|${workItemType}`;\n const cached = doneStateCache.get(cacheKey);\n if (cached) return cached;\n\n try {\n const witApi = await connection.getWorkItemTrackingApi();\n const states = await witApi.getWorkItemTypeStates(project, workItemType);\n\n // Primary: find state with \"Completed\" category\n if (Array.isArray(states)) {\n const completed = states.find((s) => s.category === \"Completed\");\n if (completed?.name) {\n doneStateCache.set(cacheKey, completed.name);\n return completed.name;\n }\n\n // Fallback: check for known terminal states in priority order\n const names = states.map((s) => s.name).filter((n): n is string => !!n);\n const fallbacks = [\"Done\", \"Closed\", \"Resolved\", \"Completed\"];\n for (const f of fallbacks) {\n if (names.includes(f)) {\n doneStateCache.set(cacheKey, f);\n return f;\n }\n }\n }\n } catch {\n // Fall through to default\n }\n\n // Don't cache the default — a transient error should not\n // prevent subsequent calls from retrying the detection.\n return \"Closed\";\n}\n\n/**\n * Fetch comments for an Azure DevOps work item.\n * Non-fatal — returns empty array on failure.\n */\nasync function fetchComments(\n workItemId: number,\n project: string,\n connection: WebApi\n): Promise<string[]> {\n try {\n const witApi = await connection.getWorkItemTrackingApi();\n const commentList = await witApi.getComments(project, workItemId);\n\n if (commentList.comments && Array.isArray(commentList.comments)) {\n return commentList.comments.map((c) => {\n const author = c.createdBy?.displayName ?? \"unknown\";\n return `**${author}:** ${c.text ?? \"\"}`;\n });\n }\n return [];\n } catch {\n return [];\n }\n}\n\nexport const datasource: Datasource = {\n name: \"azdevops\",\n\n supportsGit(): boolean {\n return true;\n },\n\n async list(opts: IssueFetchOptions = {}): Promise<IssueDetails[]> {\n const { project, connection } = await getOrgAndProject(opts);\n const witApi = await connection.getWorkItemTrackingApi();\n\n const conditions = [\n \"[System.State] <> 'Closed'\",\n \"[System.State] <> 'Done'\",\n \"[System.State] <> 'Removed'\",\n ];\n\n if (opts.iteration) {\n const iterValue = String(opts.iteration).trim();\n if (iterValue === \"@CurrentIteration\") {\n conditions.push(`[System.IterationPath] UNDER @CurrentIteration`);\n } else {\n const escaped = iterValue.replace(/'/g, \"''\");\n if (escaped) conditions.push(`[System.IterationPath] UNDER '${escaped}'`);\n }\n }\n\n if (opts.area) {\n const area = String(opts.area).trim().replace(/'/g, \"''\");\n if (area) {\n conditions.push(`[System.AreaPath] UNDER '${area}'`);\n }\n }\n\n const wiql = `SELECT [System.Id] FROM workitems WHERE ${conditions.join(\" AND \")} ORDER BY [System.CreatedDate] DESC`;\n\n const queryResult = await witApi.queryByWiql({ query: wiql }, { project } as TeamContext);\n const workItemRefs = queryResult.workItems ?? [];\n if (workItemRefs.length === 0) return [];\n\n const ids = workItemRefs\n .map((ref) => ref.id)\n .filter((id): id is number => id != null);\n\n if (ids.length === 0) return [];\n\n try {\n const items = await witApi.getWorkItems(ids);\n const itemsArray = Array.isArray(items) ? items : [items];\n\n // Fetch comments with bounded concurrency (batches of 5)\n const commentsArray: string[][] = [];\n const CONCURRENCY = 5;\n for (let i = 0; i < itemsArray.length; i += CONCURRENCY) {\n const batch = itemsArray.slice(i, i + CONCURRENCY);\n const batchResults = await Promise.all(\n batch.map((item) => fetchComments(item.id!, project, connection))\n );\n commentsArray.push(...batchResults);\n }\n\n return itemsArray.map((item, i) =>\n mapWorkItemToIssueDetails(item, String(item.id), commentsArray[i])\n );\n } catch (err) {\n log.debug(`Batch getWorkItems failed, falling back to individual fetches: ${log.extractMessage(err)}`);\n // Fallback: fetch items individually in parallel\n const results = await Promise.all(\n ids.map((id) => datasource.fetch(String(id), opts))\n );\n return results;\n }\n },\n\n async fetch(\n issueId: string,\n opts: IssueFetchOptions = {}\n ): Promise<IssueDetails> {\n const { project, connection } = await getOrgAndProject(opts);\n const witApi = await connection.getWorkItemTrackingApi();\n\n const item = await witApi.getWorkItem(Number(issueId));\n const comments = await fetchComments(Number(issueId), project, connection);\n\n return mapWorkItemToIssueDetails(item, issueId, comments);\n },\n\n async update(\n issueId: string,\n title: string,\n body: string,\n opts: IssueFetchOptions = {}\n ): Promise<void> {\n const { connection } = await getOrgAndProject(opts);\n const witApi = await connection.getWorkItemTrackingApi();\n\n const document = [\n { op: \"add\", path: \"/fields/System.Title\", value: title },\n { op: \"add\", path: \"/fields/System.Description\", value: body },\n ];\n // customHeaders is the first arg (pass null), document second, id third\n await witApi.updateWorkItem(null as any, document as JsonPatchDocument, Number(issueId));\n },\n\n async close(\n issueId: string,\n opts: IssueFetchOptions = {}\n ): Promise<void> {\n const { connection } = await getOrgAndProject(opts);\n const witApi = await connection.getWorkItemTrackingApi();\n\n let workItemType = opts.workItemType;\n if (!workItemType) {\n const item = await witApi.getWorkItem(Number(issueId));\n workItemType = item.fields?.[\"System.WorkItemType\"] ?? undefined;\n }\n\n const state = workItemType\n ? await detectDoneState(workItemType, opts)\n : \"Closed\";\n\n const document = [\n { op: \"add\", path: \"/fields/System.State\", value: state },\n ];\n await witApi.updateWorkItem(null as any, document as JsonPatchDocument, Number(issueId));\n },\n\n async create(\n title: string,\n body: string,\n opts: IssueFetchOptions = {}\n ): Promise<IssueDetails> {\n const workItemType =\n opts.workItemType ?? (await detectWorkItemType(opts));\n\n if (!workItemType) {\n throw new Error(\n \"Could not determine work item type. Set workItemType in your config (for example via `dispatch config`).\"\n );\n }\n\n const { project, connection } = await getOrgAndProject(opts);\n const witApi = await connection.getWorkItemTrackingApi();\n\n const document = [\n { op: \"add\", path: \"/fields/System.Title\", value: title },\n { op: \"add\", path: \"/fields/System.Description\", value: body },\n ];\n\n const item = await witApi.createWorkItem(\n null as any,\n document as JsonPatchDocument,\n project,\n workItemType\n );\n\n return mapWorkItemToIssueDetails(item, String(item.id), [], {\n title,\n body,\n state: \"New\",\n workItemType,\n });\n },\n\n async getDefaultBranch(opts: DispatchLifecycleOptions): Promise<string> {\n const PREFIX = \"refs/remotes/origin/\";\n try {\n const ref = await git([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], opts.cwd);\n const trimmed = ref.trim();\n const branch = trimmed.startsWith(PREFIX)\n ? trimmed.slice(PREFIX.length)\n : trimmed;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch, \"from symbolic-ref output\");\n }\n return branch;\n } catch (err) {\n if (err instanceof InvalidBranchNameError) {\n throw err;\n }\n try {\n await git([\"rev-parse\", \"--verify\", \"main\"], opts.cwd);\n return \"main\";\n } catch {\n return \"master\";\n }\n }\n },\n\n async getCurrentBranch(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const branch = (await git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"], opts.cwd)).trim();\n if (branch && branch !== \"HEAD\") return branch;\n } catch { /* fall through */ }\n return this.getDefaultBranch(opts);\n },\n\n async getUsername(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const name = await git([\"config\", \"user.name\"], opts.cwd);\n const slug = slugify(name.trim());\n if (slug) return slug;\n } catch {\n // fall through\n }\n\n return \"unknown\";\n },\n\n buildBranchName(issueNumber: string, title: string, username: string): string {\n const slug = slugify(title, 50);\n const branch = `${username}/dispatch/${issueNumber}-${slug}`;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch);\n }\n return branch;\n },\n\n async createAndSwitchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n if (!isValidBranchName(branchName)) {\n throw new InvalidBranchNameError(branchName);\n }\n try {\n await git([\"checkout\", \"-b\", branchName], opts.cwd);\n } catch (err) {\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n try {\n await git([\"checkout\", branchName], opts.cwd);\n } catch (checkoutErr) {\n const checkoutMessage = log.extractMessage(checkoutErr);\n if (checkoutMessage.includes(\"already used by worktree\")) {\n await git([\"worktree\", \"prune\"], opts.cwd);\n await git([\"checkout\", branchName], opts.cwd);\n } else {\n throw checkoutErr;\n }\n }\n } else {\n throw err;\n }\n }\n },\n\n async switchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n await git([\"checkout\", branchName], opts.cwd);\n },\n\n async pushBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n await git([\"push\", \"--set-upstream\", \"origin\", branchName], opts.cwd);\n },\n\n async commitAllChanges(message: string, opts: DispatchLifecycleOptions): Promise<void> {\n await git([\"add\", \"-A\"], opts.cwd);\n const status = await git([\"diff\", \"--cached\", \"--stat\"], opts.cwd);\n if (!status.trim()) {\n return; // nothing to commit\n }\n await git([\"commit\", \"-m\", message], opts.cwd);\n },\n\n async createPullRequest(\n branchName: string,\n issueNumber: string,\n title: string,\n body: string,\n opts: DispatchLifecycleOptions,\n baseBranch?: string,\n ): Promise<string> {\n const cwd = opts.cwd;\n const { orgUrl, project, connection } = await getOrgAndProject(opts);\n const gitApi = await connection.getGitApi();\n\n // Resolve the remote URL for repo matching\n const remoteUrl = await getGitRemoteUrl(cwd);\n if (!remoteUrl) {\n throw new Error(\"Could not determine git remote URL.\");\n }\n\n // Find the repository by matching remote URL\n const repos = await gitApi.getRepositories(project);\n const normalizeUrl = (u: string) => u.replace(/\\/\\/[^@/]+@/, \"//\").replace(/\\.git$/, \"\").replace(/\\/$/, \"\").toLowerCase();\n const normalizedRemote = normalizeUrl(remoteUrl);\n const repo = repos.find(\n (r) =>\n (r.remoteUrl && normalizeUrl(r.remoteUrl) === normalizedRemote) ||\n (r.sshUrl && normalizeUrl(r.sshUrl) === normalizedRemote) ||\n (r.webUrl && normalizeUrl(r.webUrl) === normalizedRemote)\n );\n\n if (!repo || !repo.id) {\n throw new Error(`Could not find Azure DevOps repository matching remote URL: ${redactUrl(remoteUrl)}`);\n }\n\n const target = baseBranch ?? await this.getDefaultBranch(opts);\n\n try {\n const pr = await gitApi.createPullRequest(\n {\n sourceRefName: `refs/heads/${branchName}`,\n targetRefName: `refs/heads/${target}`,\n title,\n description: body || `Resolves AB#${issueNumber}`,\n workItemRefs: [{ id: issueNumber }],\n },\n repo.id,\n project\n );\n\n // Construct web UI URL (SDK url is REST API URL, not browser URL)\n const webUrl = repo.webUrl\n ? `${repo.webUrl}/pullrequest/${pr.pullRequestId}`\n : pr.url ?? \"\";\n return webUrl;\n } catch (err) {\n // If a PR already exists for this branch, retrieve its URL\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n const prs = await gitApi.getPullRequests(\n repo.id,\n {\n sourceRefName: `refs/heads/${branchName}`,\n status: PullRequestStatus.Active,\n },\n project\n );\n if (Array.isArray(prs) && prs.length > 0) {\n const existingPr = prs[0];\n const webUrl = repo.webUrl\n ? `${repo.webUrl}/pullrequest/${existingPr.pullRequestId}`\n : existingPr.url ?? \"\";\n return webUrl;\n }\n return \"\";\n }\n throw err;\n }\n },\n};\n","/**\n * Local markdown datasource — reads and writes `.md` files from a configurable\n * directory, treating each file as a work item / spec.\n *\n * Default directory: `.dispatch/specs/` (relative to the working directory).\n *\n * This datasource enables fully offline operation and local-first workflows\n * where markdown files serve as the source of truth.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { readFile, writeFile, readdir, mkdir, rename } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, parse as parsePath, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { glob } from \"glob\";\nimport type { Datasource, IssueDetails, IssueFetchOptions, DispatchLifecycleOptions } from \"./interface.js\";\nimport { slugify } from \"../helpers/slugify.js\";\nimport { loadConfig, saveConfig } from \"../config.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { InvalidBranchNameError, isValidBranchName } from \"../helpers/branch-validation.js\";\n\nconst exec = promisify(execFile);\n\n/** Execute a git command and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/** Default directory for markdown specs, relative to cwd. */\nconst DEFAULT_DIR = \".dispatch/specs\";\n\n/**\n * Resolve the specs directory from options.\n * Uses `opts.cwd` joined with `DEFAULT_DIR`, or just `DEFAULT_DIR`\n * relative to `process.cwd()`.\n */\nfunction resolveDir(opts?: IssueFetchOptions): string {\n const cwd = opts?.cwd ?? process.cwd();\n return join(cwd, DEFAULT_DIR);\n}\n\n/**\n * Normalize an issue ID to a `.md` filename and resolve its full path.\n * - Absolute paths → returned as-is\n * - Relative paths (contain `/`, `\\`, or start with `./` / `../`) → resolved\n * relative to `opts.cwd` (or `process.cwd()`)\n * - Plain filenames → joined with the specs directory (existing behavior)\n */\nfunction resolveFilePath(issueId: string, opts?: IssueFetchOptions): string {\n const filename = issueId.endsWith(\".md\") ? issueId : `${issueId}.md`;\n if (isAbsolute(filename)) return filename;\n if (/[/\\\\]/.test(filename)) {\n const cwd = opts?.cwd ?? process.cwd();\n return resolve(cwd, filename);\n }\n return join(resolveDir(opts), filename);\n}\n\n/**\n * Resolve a potentially numeric issue ID to its full file path.\n * If `issueId` is purely numeric (e.g. \"1\"), scans the specs directory for\n * a file matching `{id}-*.md` and returns its path. Falls back to the\n * standard `resolveFilePath` when no match is found or the ID is not numeric.\n */\nasync function resolveNumericFilePath(issueId: string, opts?: IssueFetchOptions): Promise<string> {\n if (/^\\d+$/.test(issueId)) {\n const dir = resolveDir(opts);\n const entries = await readdir(dir);\n const match = entries.find((f) => f.startsWith(`${issueId}-`) && f.endsWith(\".md\"));\n if (match) {\n return join(dir, match);\n }\n }\n return resolveFilePath(issueId, opts);\n}\n\n/**\n * Extract a title from markdown content.\n * Looks for the first `# Heading` line; if not found, derives a title from the\n * first meaningful line of content (stripping markdown formatting and truncating\n * to ~80 characters at a word boundary). Falls back to the filename when the\n * content has no usable text.\n */\nexport function extractTitle(content: string, filename: string): string {\n // Primary: H1 heading\n const match = content.match(/^#\\s+(.+)$/m);\n if (match) return match[1].trim();\n\n // Secondary: first meaningful content line\n const lines = content.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n // Strip leading markdown prefixes (##, -, *, >, or combinations)\n const cleaned = trimmed.replace(/^[#>*\\-]+\\s*/, \"\").trim();\n if (!cleaned) continue;\n\n // Truncate to ~80 chars at a word boundary\n if (cleaned.length <= 80) return cleaned;\n const truncated = cleaned.slice(0, 80);\n const lastSpace = truncated.lastIndexOf(\" \");\n return lastSpace > 0 ? truncated.slice(0, lastSpace) : truncated;\n }\n\n // Fallback: filename without extension\n return parsePath(filename).name;\n}\n\n/**\n * Build an `IssueDetails` object from a markdown file's content and filename.\n */\nfunction toIssueDetails(filename: string, content: string, dir: string): IssueDetails {\n const idMatch = /^(\\d+)-/.exec(filename);\n return {\n number: idMatch ? idMatch[1] : filename,\n title: extractTitle(content, filename),\n body: content,\n labels: [],\n state: \"open\",\n url: join(dir, filename),\n comments: [],\n acceptanceCriteria: \"\",\n };\n}\n\nexport const datasource: Datasource = {\n name: \"md\",\n\n supportsGit(): boolean {\n return true;\n },\n\n async list(opts?: IssueFetchOptions): Promise<IssueDetails[]> {\n if (opts?.pattern) {\n const cwd = opts.cwd ?? process.cwd();\n const files = await glob(opts.pattern, { cwd, absolute: true });\n const mdFiles = files.filter((f) => f.endsWith(\".md\")).sort();\n const results: IssueDetails[] = [];\n\n for (const filePath of mdFiles) {\n const content = await readFile(filePath, \"utf-8\");\n const filename = basename(filePath);\n const dir = dirname(filePath);\n results.push(toIssueDetails(filename, content, dir));\n }\n\n return results;\n }\n\n const dir = resolveDir(opts);\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n\n const mdFiles = entries.filter((f) => f.endsWith(\".md\")).sort();\n const results: IssueDetails[] = [];\n\n for (const filename of mdFiles) {\n const filePath = join(dir, filename);\n const content = await readFile(filePath, \"utf-8\");\n results.push(toIssueDetails(filename, content, dir));\n }\n\n return results;\n },\n\n async fetch(issueId: string, opts?: IssueFetchOptions): Promise<IssueDetails> {\n if (/^\\d+$/.test(issueId)) {\n const dir = resolveDir(opts);\n const entries = await readdir(dir);\n const match = entries.find((f) => f.startsWith(`${issueId}-`) && f.endsWith(\".md\"));\n if (match) {\n const content = await readFile(join(dir, match), \"utf-8\");\n return toIssueDetails(match, content, dir);\n }\n }\n const filePath = resolveFilePath(issueId, opts);\n const content = await readFile(filePath, \"utf-8\");\n const filename = basename(filePath);\n const dir = dirname(filePath);\n return toIssueDetails(filename, content, dir);\n },\n\n async update(issueId: string, _title: string, body: string, opts?: IssueFetchOptions): Promise<void> {\n const filePath = await resolveNumericFilePath(issueId, opts);\n await writeFile(filePath, body, \"utf-8\");\n },\n\n async close(issueId: string, opts?: IssueFetchOptions): Promise<void> {\n const filePath = await resolveNumericFilePath(issueId, opts);\n const filename = basename(filePath);\n const archiveDir = join(dirname(filePath), \"archive\");\n await mkdir(archiveDir, { recursive: true });\n await rename(filePath, join(archiveDir, filename));\n },\n\n async create(title: string, body: string, opts?: IssueFetchOptions): Promise<IssueDetails> {\n const cwd = opts?.cwd ?? process.cwd();\n const configDir = join(cwd, \".dispatch\");\n const config = await loadConfig(configDir);\n const id = config.nextIssueId ?? 1;\n\n const dir = resolveDir(opts);\n await mkdir(dir, { recursive: true });\n const filename = `${id}-${slugify(title)}.md`;\n const filePath = join(dir, filename);\n await writeFile(filePath, body, \"utf-8\");\n\n config.nextIssueId = id + 1;\n await saveConfig(config, configDir);\n\n return {\n ...toIssueDetails(filename, body, dir),\n number: String(id),\n };\n },\n\n async getDefaultBranch(opts: DispatchLifecycleOptions): Promise<string> {\n const PREFIX = \"refs/remotes/origin/\";\n try {\n const ref = await git([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], opts.cwd);\n const trimmed = ref.trim();\n const branch = trimmed.startsWith(PREFIX)\n ? trimmed.slice(PREFIX.length)\n : trimmed;\n if (!isValidBranchName(branch)) {\n throw new InvalidBranchNameError(branch, \"from symbolic-ref output\");\n }\n return branch;\n } catch (err) {\n if (err instanceof InvalidBranchNameError) {\n throw err;\n }\n try {\n await git([\"rev-parse\", \"--verify\", \"main\"], opts.cwd);\n return \"main\";\n } catch {\n return \"master\";\n }\n }\n },\n\n async getCurrentBranch(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"], {\n cwd: opts.cwd,\n shell: process.platform === \"win32\",\n });\n const branch = stdout.trim();\n if (branch && branch !== \"HEAD\") return branch;\n } catch { /* fall through */ }\n return this.getDefaultBranch(opts);\n },\n\n async getUsername(opts: DispatchLifecycleOptions): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", [\"config\", \"user.name\"], { cwd: opts.cwd, shell: process.platform === \"win32\" });\n const name = stdout.trim();\n if (!name) return \"local\";\n return slugify(name);\n } catch {\n return \"local\";\n }\n },\n\n buildBranchName(issueNumber: string, title: string, username: string): string {\n const slug = slugify(title, 50);\n\n // When issueNumber is a file path, extract a clean identifier from the filename\n if (issueNumber.includes(\"/\") || issueNumber.includes(\"\\\\\")) {\n // Normalize backslashes so basename() works correctly on POSIX\n const normalized = issueNumber.replaceAll(\"\\\\\", \"/\");\n const filename = basename(normalized);\n const idMatch = /^(\\d+)-(.+)\\.md$/.exec(filename);\n if (idMatch) {\n return `${username}/dispatch/file-${idMatch[1]}-${slug}`;\n }\n // Fallback: use slugified basename without extension\n const nameWithoutExt = parsePath(filename).name;\n const slugifiedName = slugify(nameWithoutExt, 50);\n return `${username}/dispatch/file-${slugifiedName}-${slug}`;\n }\n\n return `${username}/dispatch/${issueNumber}-${slug}`;\n },\n\n async createAndSwitchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n try {\n await git([\"checkout\", \"-b\", branchName], opts.cwd);\n } catch (err) {\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n try {\n await git([\"checkout\", branchName], opts.cwd);\n } catch (checkoutErr) {\n const checkoutMessage = log.extractMessage(checkoutErr);\n if (checkoutMessage.includes(\"already used by worktree\")) {\n await git([\"worktree\", \"prune\"], opts.cwd);\n await git([\"checkout\", branchName], opts.cwd);\n } else {\n throw checkoutErr;\n }\n }\n } else {\n throw err;\n }\n }\n },\n\n async switchBranch(branchName: string, opts: DispatchLifecycleOptions): Promise<void> {\n await git([\"checkout\", branchName], opts.cwd);\n },\n\n async pushBranch(_branchName: string, _opts: DispatchLifecycleOptions): Promise<void> {\n // No-op: MD datasource does not push to a remote\n },\n\n async commitAllChanges(message: string, opts: DispatchLifecycleOptions): Promise<void> {\n const cwd = opts.cwd;\n await git([\"add\", \"-A\"], cwd);\n const status = await git([\"diff\", \"--cached\", \"--stat\"], cwd);\n if (!status.trim()) {\n return;\n }\n await git([\"commit\", \"-m\", message], cwd);\n },\n\n async createPullRequest(\n _branchName: string,\n _issueNumber: string,\n _title: string,\n _body: string,\n _opts: DispatchLifecycleOptions,\n _baseBranch?: string,\n ): Promise<string> {\n // No-op: MD datasource does not create pull requests\n return \"\";\n },\n};\n","/**\n * Configuration data layer for Dispatch.\n *\n * Manages persistent user configuration stored in {CWD}/.dispatch/config.json.\n * Provides functions for loading, saving, and validating config values.\n */\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { PROVIDER_NAMES } from \"./providers/index.js\";\nimport { DATASOURCE_NAMES } from \"./datasources/index.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\nimport { runInteractiveConfigWizard } from \"./config-prompts.js\";\n\n/**\n * Persistent configuration options for Dispatch.\n * All fields are optional since the config file may contain any subset.\n */\nexport interface DispatchConfig {\n provider?: ProviderName;\n /**\n * Model to use when spawning agents, in provider-specific format.\n * - Copilot: bare model ID (e.g. \"claude-sonnet-4-5\")\n * - OpenCode: \"provider/model\" (e.g. \"anthropic/claude-sonnet-4\")\n * When omitted the provider uses its auto-detected default.\n */\n model?: string;\n source?: DatasourceName;\n testTimeout?: number;\n planTimeout?: number;\n concurrency?: number;\n org?: string;\n project?: string;\n workItemType?: string;\n iteration?: string;\n area?: string;\n /** Internal auto-increment counter for MD datasource issue IDs. Defaults to 1 when absent. */\n nextIssueId?: number;\n}\n\n/** Minimum and maximum bounds for numeric configuration values. */\nexport const CONFIG_BOUNDS = {\n testTimeout: { min: 1, max: 120 },\n planTimeout: { min: 1, max: 120 },\n concurrency: { min: 1, max: 64 },\n} as const;\n\n/** Valid configuration key names. */\nexport const CONFIG_KEYS = [\"provider\", \"model\", \"source\", \"testTimeout\", \"planTimeout\", \"concurrency\", \"org\", \"project\", \"workItemType\", \"iteration\", \"area\"] as const;\n\n/** A valid configuration key name. */\nexport type ConfigKey = (typeof CONFIG_KEYS)[number];\n\n/**\n * Get the path to the config file.\n * Accepts an optional `configDir` override for testing.\n */\nexport function getConfigPath(configDir?: string): string {\n const dir = configDir ?? join(process.cwd(), \".dispatch\");\n return join(dir, \"config.json\");\n}\n\n/**\n * Load the config from disk.\n * Returns `{}` if the file doesn't exist or contains invalid JSON.\n * Accepts an optional `configDir` override for testing.\n */\nexport async function loadConfig(configDir?: string): Promise<DispatchConfig> {\n const configPath = getConfigPath(configDir);\n try {\n const raw = await readFile(configPath, \"utf-8\");\n return JSON.parse(raw) as DispatchConfig;\n } catch {\n return {};\n }\n}\n\n/**\n * Save the config to disk as pretty-printed JSON.\n * Creates the parent directory if it doesn't exist.\n * Accepts an optional `configDir` override for testing.\n */\nexport async function saveConfig(\n config: DispatchConfig,\n configDir?: string,\n): Promise<void> {\n const configPath = getConfigPath(configDir);\n await mkdir(dirname(configPath), { recursive: true });\n await writeFile(configPath, JSON.stringify(config, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Validate a value for a given config key.\n * Returns `null` if valid, or an error message string if invalid.\n */\nexport function validateConfigValue(key: ConfigKey, value: string): string | null {\n switch (key) {\n case \"provider\":\n if (!PROVIDER_NAMES.includes(value as ProviderName)) {\n return `Invalid provider \"${value}\". Available: ${PROVIDER_NAMES.join(\", \")}`;\n }\n return null;\n\n case \"model\":\n if (!value || value.trim() === \"\") {\n return `Invalid model: value must not be empty`;\n }\n return null;\n\n case \"source\":\n if (!DATASOURCE_NAMES.includes(value as DatasourceName)) {\n return `Invalid source \"${value}\". Available: ${DATASOURCE_NAMES.join(\", \")}`;\n }\n return null;\n\n case \"testTimeout\": {\n const num = Number(value);\n if (!Number.isFinite(num) || num < CONFIG_BOUNDS.testTimeout.min || num > CONFIG_BOUNDS.testTimeout.max) {\n return `Invalid testTimeout \"${value}\". Must be a number between ${CONFIG_BOUNDS.testTimeout.min} and ${CONFIG_BOUNDS.testTimeout.max} (minutes)`;\n }\n return null;\n }\n\n case \"planTimeout\": {\n const num = Number(value);\n if (!Number.isFinite(num) || num < CONFIG_BOUNDS.planTimeout.min || num > CONFIG_BOUNDS.planTimeout.max) {\n return `Invalid planTimeout \"${value}\". Must be a number between ${CONFIG_BOUNDS.planTimeout.min} and ${CONFIG_BOUNDS.planTimeout.max} (minutes)`;\n }\n return null;\n }\n\n case \"concurrency\": {\n const num = Number(value);\n if (!Number.isInteger(num) || num < CONFIG_BOUNDS.concurrency.min || num > CONFIG_BOUNDS.concurrency.max) {\n return `Invalid concurrency \"${value}\". Must be an integer between ${CONFIG_BOUNDS.concurrency.min} and ${CONFIG_BOUNDS.concurrency.max}`;\n }\n return null;\n }\n\n case \"org\":\n case \"project\":\n case \"workItemType\":\n case \"iteration\":\n case \"area\":\n if (!value || value.trim() === \"\") {\n return `Invalid ${key}: value must not be empty`;\n }\n return null;\n\n default:\n return `Unknown config key \"${key}\"`;\n }\n}\n\n/**\n * Handle the `dispatch config` subcommand.\n *\n * Launches the interactive configuration wizard.\n */\nexport async function handleConfigCommand(_argv: string[], configDir?: string): Promise<void> {\n await runInteractiveConfigWizard(configDir);\n}\n","/**\n * Interactive configuration wizard for Dispatch.\n *\n * Guides users through provider, datasource, and model selection\n * via an interactive terminal flow.\n */\n\nimport { select, confirm, input } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { log } from \"./helpers/logger.js\";\nimport {\n loadConfig,\n saveConfig,\n type DispatchConfig,\n} from \"./config.js\";\nimport { PROVIDER_NAMES, listProviderModels, checkProviderInstalled } from \"./providers/index.js\";\nimport type { ProviderName } from \"./providers/interface.js\";\nimport {\n DATASOURCE_NAMES,\n detectDatasource,\n getGitRemoteUrl,\n parseAzDevOpsRemoteUrl,\n} from \"./datasources/index.js\";\nimport type { DatasourceName } from \"./datasources/interface.js\";\n\n/**\n * Run the interactive configuration wizard.\n *\n * Loads existing config, walks the user through provider, model, and\n * datasource selection, displays a summary, and saves on confirmation.\n */\nexport async function runInteractiveConfigWizard(configDir?: string): Promise<void> {\n console.log();\n log.info(chalk.bold(\"Dispatch Configuration Wizard\"));\n console.log();\n\n // ── Load existing config ───────────────────────────────────\n const existing = await loadConfig(configDir);\n const hasExisting = Object.keys(existing).length > 0;\n\n if (hasExisting) {\n log.dim(\"Current configuration:\");\n for (const [key, value] of Object.entries(existing)) {\n if (value !== undefined) {\n log.dim(` ${key} = ${value}`);\n }\n }\n console.log();\n\n const reconfigure = await confirm({\n message: \"Do you want to reconfigure?\",\n default: true,\n });\n\n if (!reconfigure) {\n log.dim(\"Configuration unchanged.\");\n return;\n }\n console.log();\n }\n\n // ── Provider selection ─────────────────────────────────────\n const installStatuses = await Promise.all(\n PROVIDER_NAMES.map((name) => checkProviderInstalled(name)),\n );\n\n const provider = await select<ProviderName>({\n message: \"Select a provider:\",\n choices: PROVIDER_NAMES.map((name, i) => ({\n name: `${installStatuses[i] ? chalk.green(\"●\") : chalk.red(\"●\")} ${name}`,\n value: name,\n })),\n default: existing.provider,\n });\n\n // ── Model selection ────────────────────────────────────────\n let selectedModel: string | undefined = existing.model;\n try {\n log.dim(\"Fetching available models...\");\n const models = await listProviderModels(provider);\n if (models.length > 0) {\n const modelChoice = await select<string>({\n message: \"Select a model:\",\n choices: [\n { name: \"default (provider decides)\", value: \"\" },\n ...models.map((m) => ({ name: m, value: m })),\n ],\n default: existing.model ?? \"\",\n });\n selectedModel = modelChoice || undefined;\n } else {\n log.dim(\"No models returned by provider — skipping model selection.\");\n selectedModel = existing.model;\n }\n } catch {\n log.dim(\"Could not list models (provider may not be running) — skipping model selection.\");\n selectedModel = existing.model;\n }\n\n // ── Auto-detect datasource from git remote ─────────────────\n const detectedSource = await detectDatasource(process.cwd());\n const datasourceDefault: DatasourceName | \"auto\" = existing.source ?? \"auto\";\n if (detectedSource) {\n log.info(\n `Detected datasource ${chalk.cyan(detectedSource)} from git remote`,\n );\n }\n\n // ── Datasource selection ───────────────────────────────────\n const selectedSource = await select<DatasourceName | \"auto\">({\n message: \"Select a datasource:\",\n choices: [\n {\n name: \"auto\",\n value: \"auto\" as const,\n description: \"detect from git remote at runtime\",\n },\n ...DATASOURCE_NAMES.map((name) => ({ name, value: name })),\n ],\n default: datasourceDefault,\n });\n const source: DatasourceName | undefined =\n selectedSource === \"auto\" ? undefined : selectedSource;\n\n // ── Azure DevOps-specific fields ───────────────────────────\n let org: string | undefined;\n let project: string | undefined;\n let workItemType: string | undefined;\n let iteration: string | undefined;\n let area: string | undefined;\n\n const effectiveSource = source ?? detectedSource;\n if (effectiveSource === \"azdevops\") {\n // Try to pre-fill org and project from git remote\n let defaultOrg = existing.org ?? \"\";\n let defaultProject = existing.project ?? \"\";\n try {\n const remoteUrl = await getGitRemoteUrl(process.cwd());\n if (remoteUrl) {\n const parsed = parseAzDevOpsRemoteUrl(remoteUrl);\n if (parsed) {\n if (!defaultOrg) defaultOrg = parsed.orgUrl;\n if (!defaultProject) defaultProject = parsed.project;\n }\n }\n } catch {\n // ignore — pre-fill is best-effort\n }\n\n console.log();\n log.info(chalk.bold(\"Azure DevOps settings\") + chalk.dim(\" (leave empty to skip):\"));\n\n const orgInput = await input({\n message: \"Organization URL:\",\n default: defaultOrg || undefined,\n });\n if (orgInput.trim()) org = orgInput.trim();\n\n const projectInput = await input({\n message: \"Project name:\",\n default: defaultProject || undefined,\n });\n if (projectInput.trim()) project = projectInput.trim();\n\n const workItemTypeInput = await input({\n message: \"Work item type (e.g. User Story, Bug):\",\n default: existing.workItemType ?? undefined,\n });\n if (workItemTypeInput.trim()) workItemType = workItemTypeInput.trim();\n\n const iterationInput = await input({\n message: \"Iteration path (e.g. MyProject\\\\Sprint 1, or @CurrentIteration):\",\n default: existing.iteration ?? undefined,\n });\n if (iterationInput.trim()) iteration = iterationInput.trim();\n\n const areaInput = await input({\n message: \"Area path (e.g. MyProject\\\\Team A):\",\n default: existing.area ?? undefined,\n });\n if (areaInput.trim()) area = areaInput.trim();\n }\n\n // ── Build new config ───────────────────────────────────────\n const newConfig: DispatchConfig = {\n provider,\n source,\n };\n\n if (selectedModel !== undefined) {\n newConfig.model = selectedModel;\n }\n if (org !== undefined) newConfig.org = org;\n if (project !== undefined) newConfig.project = project;\n if (workItemType !== undefined) newConfig.workItemType = workItemType;\n if (iteration !== undefined) newConfig.iteration = iteration;\n if (area !== undefined) newConfig.area = area;\n\n // ── Summary ────────────────────────────────────────────────\n console.log();\n log.info(chalk.bold(\"Configuration summary:\"));\n for (const [key, value] of Object.entries(newConfig)) {\n if (value !== undefined) {\n console.log(` ${chalk.cyan(key)} = ${value}`);\n }\n }\n if (selectedSource === \"auto\") {\n console.log(\n ` ${chalk.cyan(\"source\")} = auto (detect from git remote at runtime)`,\n );\n }\n console.log();\n\n // ── Confirm and save ───────────────────────────────────────\n const shouldSave = await confirm({\n message: \"Save this configuration?\",\n default: true,\n });\n\n if (shouldSave) {\n await saveConfig(newConfig, configDir);\n log.success(\"Configuration saved.\");\n } else {\n log.dim(\"Configuration not saved.\");\n }\n}\n","import { basename, join } from \"node:path\";\nimport { mkdtemp, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { log } from \"../helpers/logger.js\";\nimport type { Datasource, DatasourceName, IssueDetails, IssueFetchOptions } from \"../datasources/interface.js\";\nimport type { Task } from \"../parser.js\";\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport { slugify, MAX_SLUG_LENGTH } from \"../helpers/slugify.js\";\n\nconst exec = promisify(execFile);\n\n/** Result of writing issue items to a temp directory. */\nexport interface WriteItemsResult {\n /** Sorted list of written file paths */\n files: string[];\n /** Mapping from file path to the original IssueDetails */\n issueDetailsByFile: Map<string, IssueDetails>;\n}\n\n/**\n * Parse an issue ID and slug from a `<id>-<slug>.md` filename.\n *\n * Returns the numeric issue ID and slug, or `null` if the filename\n * does not match the expected `<id>-<slug>.md` pattern.\n */\nexport function parseIssueFilename(filePath: string): { issueId: string; slug: string } | null {\n const filename = basename(filePath);\n const match = /^(\\d+)-(.+)\\.md$/.exec(filename);\n if (!match) return null;\n return { issueId: match[1], slug: match[2] };\n}\n\n/**\n * Fetch specific issues by ID from a datasource.\n * Logs a warning and skips any ID that fails to fetch.\n */\nexport async function fetchItemsById(\n issueIds: string[],\n datasource: Datasource,\n fetchOpts: IssueFetchOptions,\n): Promise<IssueDetails[]> {\n const ids = issueIds.flatMap((id) =>\n id.split(\",\").map((s) => s.trim()).filter(Boolean)\n );\n const items = [];\n for (const id of ids) {\n try {\n const item = await datasource.fetch(id, fetchOpts);\n items.push(item);\n } catch (err) {\n const prefix = id.includes(\"/\") || id.includes(\"\\\\\") || id.endsWith(\".md\") ? \"\" : \"#\";\n log.warn(`Could not fetch issue ${prefix}${id}: ${log.formatErrorChain(err)}`);\n }\n }\n return items;\n}\n\n/**\n * Write a list of IssueDetails to a temp directory as `{number}-{slug}.md` files.\n * Returns the sorted file paths and a mapping from each path to its original IssueDetails.\n */\nexport async function writeItemsToTempDir(items: IssueDetails[]): Promise<WriteItemsResult> {\n const tempDir = await mkdtemp(join(tmpdir(), \"dispatch-\"));\n const files: string[] = [];\n const issueDetailsByFile = new Map<string, IssueDetails>();\n\n for (const item of items) {\n const slug = slugify(item.title, MAX_SLUG_LENGTH);\n // When item.number is a file path, extract just the basename without extension\n const id = item.number.includes(\"/\") || item.number.includes(\"\\\\\")\n ? basename(item.number, \".md\")\n : item.number;\n const filename = `${id}-${slug}.md`;\n const filepath = join(tempDir, filename);\n await writeFile(filepath, item.body, \"utf-8\");\n files.push(filepath);\n issueDetailsByFile.set(filepath, item);\n }\n\n files.sort((a, b) => {\n const numA = parseInt(basename(a).match(/^(\\d+)/)?.[1] ?? \"0\", 10);\n const numB = parseInt(basename(b).match(/^(\\d+)/)?.[1] ?? \"0\", 10);\n if (numA !== numB) return numA - numB;\n return a.localeCompare(b);\n });\n\n return { files, issueDetailsByFile };\n}\n\n/**\n * Retrieve one-line commit summaries for commits on the current branch\n * that are not on the given default branch.\n *\n * @param defaultBranch - The base branch to compare against (e.g. \"main\")\n * @param cwd - Working directory (git repo root)\n * @returns Array of commit summary strings, one per commit\n */\nasync function getCommitSummaries(defaultBranch: string, cwd: string): Promise<string[]> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", `${defaultBranch}..HEAD`, \"--pretty=format:%s\"],\n { cwd, shell: process.platform === \"win32\" },\n );\n return stdout\n .trim()\n .split(\"\\n\")\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Retrieve the full diff of the current branch relative to the default branch.\n *\n * @param defaultBranch - The base branch to compare against (e.g. \"main\")\n * @param cwd - Working directory (git repo root)\n * @returns The diff output as a string, or an empty string on failure\n */\nexport async function getBranchDiff(defaultBranch: string, cwd: string): Promise<string> {\n try {\n const { stdout } = await exec(\n \"git\",\n [\"diff\", `${defaultBranch}..HEAD`],\n { cwd, maxBuffer: 10 * 1024 * 1024, shell: process.platform === \"win32\" },\n );\n return stdout;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Amend the most recent commit's message without changing its content.\n *\n * @param message - The new commit message\n * @param cwd - Working directory (git repo root)\n */\nexport async function amendCommitMessage(message: string, cwd: string): Promise<void> {\n await exec(\n \"git\",\n [\"commit\", \"--amend\", \"-m\", message],\n { cwd, shell: process.platform === \"win32\" },\n );\n}\n\n/**\n * Squash all commits on the current branch (relative to the default branch)\n * into a single commit with the given message.\n *\n * Uses a soft reset to the merge-base followed by a fresh commit, which\n * avoids interactive rebase complexity.\n *\n * @param defaultBranch - The base branch to compare against (e.g. \"main\")\n * @param message - The commit message for the squashed commit\n * @param cwd - Working directory (git repo root)\n */\nexport async function squashBranchCommits(\n defaultBranch: string,\n message: string,\n cwd: string,\n): Promise<void> {\n const { stdout } = await exec(\n \"git\",\n [\"merge-base\", defaultBranch, \"HEAD\"],\n { cwd, shell: process.platform === \"win32\" },\n );\n const mergeBase = stdout.trim();\n await exec(\"git\", [\"reset\", \"--soft\", mergeBase], { cwd, shell: process.platform === \"win32\" });\n await exec(\"git\", [\"commit\", \"-m\", message], { cwd, shell: process.platform === \"win32\" });\n}\n\n/**\n * Assemble a descriptive pull request body from pipeline data.\n *\n * Includes:\n * - A summary section with commit messages from the branch\n * - The list of completed tasks\n * - Labels from the issue (if any)\n * - An issue-close reference appropriate for the datasource\n *\n * @param details - The issue details (title, body, labels, number)\n * @param tasks - The tasks that were dispatched for this issue\n * @param results - The dispatch results for all tasks\n * @param defaultBranch - The base branch to compare commits against\n * @param datasourceName - The datasource backend name (\"github\", \"azdevops\", \"md\")\n * @param cwd - Working directory (git repo root)\n * @returns The assembled PR body as a markdown string\n */\nexport async function buildPrBody(\n details: IssueDetails,\n tasks: Task[],\n results: DispatchResult[],\n defaultBranch: string,\n datasourceName: DatasourceName,\n cwd: string,\n): Promise<string> {\n const sections: string[] = [];\n\n // ── Commit summary section ──────────────────────────────────\n const commits = await getCommitSummaries(defaultBranch, cwd);\n if (commits.length > 0) {\n sections.push(\"## Summary\\n\");\n for (const commit of commits) {\n sections.push(`- ${commit}`);\n }\n sections.push(\"\");\n }\n\n // ── Completed tasks section ─────────────────────────────────\n const taskResults = new Map(\n results\n .filter((r) => tasks.includes(r.task))\n .map((r) => [r.task, r]),\n );\n\n const completedTasks = tasks.filter((t) => taskResults.get(t)?.success);\n const failedTasks = tasks.filter((t) => {\n const r = taskResults.get(t);\n return r && !r.success;\n });\n\n if (completedTasks.length > 0 || failedTasks.length > 0) {\n sections.push(\"## Tasks\\n\");\n for (const task of completedTasks) {\n sections.push(`- [x] ${task.text}`);\n }\n for (const task of failedTasks) {\n sections.push(`- [ ] ${task.text}`);\n }\n sections.push(\"\");\n }\n\n // ── Labels section ──────────────────────────────────────────\n if (details.labels.length > 0) {\n sections.push(`**Labels:** ${details.labels.join(\", \")}\\n`);\n }\n\n // ── Issue-close reference ───────────────────────────────────\n if (datasourceName === \"github\") {\n sections.push(`Closes #${details.number}`);\n } else if (datasourceName === \"azdevops\") {\n sections.push(`Resolves AB#${details.number}`);\n }\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Generate a descriptive PR title from commit messages on the branch.\n *\n * If a single commit exists, its message is used as the title.\n * If multiple commits exist, a summary title is generated that\n * captures the scope, prefixed with the issue title.\n * Falls back to the issue title if no commits are found.\n *\n * @param issueTitle - The original issue title (used as fallback)\n * @param defaultBranch - The base branch to compare commits against\n * @param cwd - Working directory (git repo root)\n * @returns A descriptive PR title string\n */\nexport async function buildPrTitle(\n issueTitle: string,\n defaultBranch: string,\n cwd: string,\n): Promise<string> {\n const commits = await getCommitSummaries(defaultBranch, cwd);\n\n if (commits.length === 0) {\n return issueTitle;\n }\n\n if (commits.length === 1) {\n return commits[0];\n }\n\n // Multiple commits — use the first commit message with a count suffix\n return `${commits[commits.length - 1]} (+${commits.length - 1} more)`;\n}\n\n/**\n * Build an aggregated PR title for feature mode.\n *\n * When a single issue is processed, the PR title is just that issue's title.\n * For multiple issues, the title includes the feature branch name and\n * references to all issues.\n *\n * @param featureBranchName - The feature branch name (e.g. \"dispatch/feature-a1b2c3d4\")\n * @param issues - All issue details processed in this feature run\n * @returns An aggregated PR title string\n */\nexport function buildFeaturePrTitle(featureBranchName: string, issues: IssueDetails[]): string {\n if (issues.length === 1) {\n return issues[0].title;\n }\n const issueRefs = issues.map((d) => `#${d.number}`).join(\", \");\n return `feat: ${featureBranchName} (${issueRefs})`;\n}\n\n/**\n * Build an aggregated PR body for feature mode that references all issues,\n * their tasks, and completion status.\n *\n * Includes:\n * - An issues section listing all issues addressed\n * - A tasks section with completion checkboxes\n * - Issue-close references appropriate for the datasource\n *\n * @param issues - All issue details processed in this feature run\n * @param tasks - All tasks dispatched across all issues\n * @param results - The dispatch results for all tasks\n * @param datasourceName - The datasource backend name (\"github\", \"azdevops\", \"md\")\n * @returns The assembled aggregated PR body as a markdown string\n */\nexport function buildFeaturePrBody(\n issues: IssueDetails[],\n tasks: Task[],\n results: DispatchResult[],\n datasourceName: DatasourceName,\n): string {\n const sections: string[] = [];\n\n sections.push(\"## Issues\\n\");\n for (const issue of issues) {\n sections.push(`- #${issue.number}: ${issue.title}`);\n }\n sections.push(\"\");\n\n const taskResults = new Map(results.map((r) => [r.task, r]));\n const completedTasks = tasks.filter((t) => taskResults.get(t)?.success);\n const failedTasks = tasks.filter((t) => {\n const r = taskResults.get(t);\n return r && !r.success;\n });\n\n if (completedTasks.length > 0 || failedTasks.length > 0) {\n sections.push(\"## Tasks\\n\");\n for (const task of completedTasks) {\n sections.push(`- [x] ${task.text}`);\n }\n for (const task of failedTasks) {\n sections.push(`- [ ] ${task.text}`);\n }\n sections.push(\"\");\n }\n\n for (const issue of issues) {\n if (datasourceName === \"github\") {\n sections.push(`Closes #${issue.number}`);\n } else if (datasourceName === \"azdevops\") {\n sections.push(`Resolves AB#${issue.number}`);\n }\n }\n\n return sections.join(\"\\n\");\n}\n","/**\n * Git worktree lifecycle manager.\n *\n * Creates, removes, and lists git worktrees in `.dispatch/worktrees/`.\n * Worktree directory names are derived from the leading numeric ID of the\n * issue filename (e.g., `123-fix-auth-bug.md` → `issue-123`).\n */\n\nimport { join, basename } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { slugify } from \"./slugify.js\";\nimport { log } from \"./logger.js\";\n\nconst exec = promisify(execFile);\n\n/** Base directory for worktrees, relative to the repository root. */\nconst WORKTREE_DIR = \".dispatch/worktrees\";\n\n/** Execute a git command in the given working directory and return stdout. */\nasync function git(args: string[], cwd: string): Promise<string> {\n const { stdout } = await exec(\"git\", args, { cwd, shell: process.platform === \"win32\" });\n return stdout;\n}\n\n/**\n * Derive a worktree directory name from an issue filename.\n *\n * Extracts the leading numeric ID and returns `issue-{id}`.\n * Example: `123-fix-auth-bug.md` → `issue-123`\n *\n * @param issueFilename - The issue filename (basename or full path)\n * @returns A directory name suitable for a worktree\n */\nexport function worktreeName(issueFilename: string): string {\n const base = basename(issueFilename);\n const withoutExt = base.replace(/\\.md$/i, \"\");\n const match = withoutExt.match(/^(\\d+)/);\n return match ? `issue-${match[1]}` : slugify(withoutExt);\n}\n\n/**\n * Create a git worktree for the given issue file.\n *\n * The worktree is placed at `.dispatch/worktrees/<name>` (relative to `repoRoot`)\n * and checks out a new branch with the specified `branchName`.\n *\n * @param repoRoot - Absolute path to the repository root\n * @param issueFilename - The issue filename used to derive the worktree directory name\n * @param branchName - The branch name to create and check out in the worktree\n * @returns The absolute path to the created worktree directory\n */\nexport async function createWorktree(\n repoRoot: string,\n issueFilename: string,\n branchName: string,\n startPoint?: string,\n): Promise<string> {\n const name = worktreeName(issueFilename);\n const worktreePath = join(repoRoot, WORKTREE_DIR, name);\n\n if (existsSync(worktreePath)) {\n log.debug(`Reusing existing worktree at ${worktreePath}`);\n return worktreePath;\n }\n\n try {\n const args = [\"worktree\", \"add\", worktreePath, \"-b\", branchName];\n if (startPoint) args.push(startPoint);\n await git(args, repoRoot);\n log.debug(`Created worktree at ${worktreePath} on branch ${branchName}`);\n } catch (err) {\n const message = log.extractMessage(err);\n if (message.includes(\"already exists\")) {\n // Branch already exists — retry without -b to use the existing branch.\n // If this also fails (e.g. worktree path conflict), fall through to\n // prune-and-retry before giving up.\n try {\n await git([\"worktree\", \"add\", worktreePath, branchName], repoRoot);\n log.debug(`Created worktree at ${worktreePath} using existing branch ${branchName}`);\n return worktreePath;\n } catch (retryErr) {\n const retryMsg = log.extractMessage(retryErr);\n if (retryMsg.includes(\"already used by worktree\")) {\n await git([\"worktree\", \"prune\"], repoRoot);\n await git([\"worktree\", \"add\", worktreePath, branchName], repoRoot);\n log.debug(`Created worktree at ${worktreePath} after pruning stale ref`);\n } else {\n throw retryErr;\n }\n }\n } else if (message.includes(\"already used by worktree\")) {\n // Branch is locked to a stale worktree ref — prune and retry\n await git([\"worktree\", \"prune\"], repoRoot);\n await git([\"worktree\", \"add\", worktreePath, branchName], repoRoot);\n log.debug(`Created worktree at ${worktreePath} after pruning stale ref`);\n } else {\n throw err;\n }\n }\n\n return worktreePath;\n}\n\n/**\n * Remove a git worktree.\n *\n * Attempts a normal removal first, falling back to `--force` if needed.\n * Runs `git worktree prune` afterwards to clean up stale references.\n * Logs a warning instead of throwing on failure so execution can continue.\n *\n * @param repoRoot - Absolute path to the repository root\n * @param issueFilename - The issue filename used to derive the worktree directory name\n */\nexport async function removeWorktree(\n repoRoot: string,\n issueFilename: string,\n): Promise<void> {\n const name = worktreeName(issueFilename);\n const worktreePath = join(repoRoot, WORKTREE_DIR, name);\n\n try {\n await git([\"worktree\", \"remove\", worktreePath], repoRoot);\n } catch {\n // Force removal as fallback\n try {\n await git([\"worktree\", \"remove\", \"--force\", worktreePath], repoRoot);\n } catch (err) {\n log.warn(`Could not remove worktree ${name}: ${log.formatErrorChain(err)}`);\n return;\n }\n }\n\n // Prune stale worktree references\n try {\n await git([\"worktree\", \"prune\"], repoRoot);\n } catch (err) {\n log.warn(`Could not prune worktrees: ${log.formatErrorChain(err)}`);\n }\n}\n\n/**\n * List all current git worktrees in the repository.\n *\n * Returns the raw `git worktree list` output for diagnostic purposes.\n *\n * @param repoRoot - Absolute path to the repository root\n * @returns The worktree list output string\n */\nexport async function listWorktrees(repoRoot: string): Promise<string> {\n try {\n return await git([\"worktree\", \"list\"], repoRoot);\n } catch (err) {\n log.warn(`Could not list worktrees: ${log.formatErrorChain(err)}`);\n return \"\";\n }\n}\n\n/**\n * Generate a unique feature branch name.\n *\n * Produces a name in the format `dispatch/feature-{octet}`, where `{octet}`\n * is the first 8 hex characters of a random UUID.\n *\n * @returns A feature branch name like `dispatch/feature-a1b2c3d4`\n */\nexport function generateFeatureBranchName(): string {\n const uuid = randomUUID();\n const octet = uuid.split(\"-\")[0];\n return `dispatch/feature-${octet}`;\n}\n","/**\n * Runner — thin coordinator that delegates to extracted pipeline modules.\n */\n\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport type { AgentBootOptions } from \"../agents/interface.js\";\nimport type { ProviderName } from \"../providers/interface.js\";\nimport type { DatasourceName } from \"../datasources/interface.js\";\nimport type { SpecOptions, SpecSummary } from \"../spec-generator.js\";\nimport { defaultConcurrency, resolveSource } from \"../spec-generator.js\";\nimport { getDatasource } from \"../datasources/index.js\";\nimport { fetchItemsById } from \"./datasource-helpers.js\";\nimport { createWorktree, removeWorktree } from \"../helpers/worktree.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { confirmLargeBatch } from \"../helpers/confirm-large-batch.js\";\nimport { checkPrereqs } from \"../helpers/prereqs.js\";\nimport { ensureGitignoreEntry } from \"../helpers/gitignore.js\";\nimport { resolveCliConfig } from \"./cli-config.js\";\nimport { runSpecPipeline } from \"./spec-pipeline.js\";\nimport { runDispatchPipeline } from \"./dispatch-pipeline.js\";\n\n/** Runtime options passed to `orchestrate()`. */\nexport interface OrchestrateRunOptions {\n issueIds: string[];\n concurrency?: number;\n dryRun: boolean;\n noPlan?: boolean;\n noBranch?: boolean;\n noWorktree?: boolean;\n force?: boolean;\n provider?: ProviderName;\n /** Model override to pass to the provider (provider-specific format). */\n model?: string;\n serverUrl?: string;\n source?: DatasourceName;\n org?: string;\n project?: string;\n workItemType?: string;\n iteration?: string;\n area?: string;\n planTimeout?: number;\n planRetries?: number;\n retries?: number;\n feature?: string | boolean;\n}\n\n/** Raw CLI arguments before config resolution. */\nexport interface RawCliArgs {\n issueIds: string[];\n dryRun: boolean;\n noPlan: boolean;\n noBranch: boolean;\n noWorktree: boolean;\n force: boolean;\n concurrency?: number;\n provider: ProviderName;\n /** Model override from config or CLI (provider-specific format). */\n model?: string;\n serverUrl?: string;\n cwd: string;\n verbose: boolean;\n spec?: string | string[];\n respec?: string | string[];\n fixTests?: boolean;\n issueSource?: DatasourceName;\n org?: string;\n project?: string;\n workItemType?: string;\n iteration?: string;\n area?: string;\n planTimeout?: number;\n planRetries?: number;\n testTimeout?: number;\n retries?: number;\n feature?: string | boolean;\n outputDir?: string;\n explicitFlags: Set<string>;\n}\n\nexport interface DispatchSummary {\n total: number;\n completed: number;\n failed: number;\n skipped: number;\n results: DispatchResult[];\n}\n\n/** Per-issue result for fix-tests runs targeting specific issues. */\nexport interface IssueResult {\n issueId: string;\n branch: string;\n success: boolean;\n error?: string;\n}\n\nexport interface FixTestsSummary {\n mode: \"fix-tests\";\n success: boolean;\n error?: string;\n issueResults?: IssueResult[];\n}\n\n/** Dispatch-mode run options with explicit mode discriminator. */\nexport interface DispatchRunOptions extends OrchestrateRunOptions {\n mode: \"dispatch\";\n}\n\n/** Spec-mode run options with explicit mode discriminator. */\nexport interface SpecRunOptions extends Omit<SpecOptions, \"cwd\"> {\n mode: \"spec\";\n}\n\n/** Fix-tests-mode run options with explicit mode discriminator. */\nexport interface FixTestsRunOptions {\n mode: \"fix-tests\";\n testTimeout?: number;\n issueIds?: string[];\n provider?: ProviderName;\n serverUrl?: string;\n verbose?: boolean;\n dryRun?: boolean;\n source?: DatasourceName;\n org?: string;\n project?: string;\n cwd?: string;\n}\n\n/** Discriminated union of all runner run options. */\nexport type UnifiedRunOptions = DispatchRunOptions | SpecRunOptions | FixTestsRunOptions;\n\n/** Unified result type — DispatchSummary or SpecSummary depending on mode. */\nexport type RunResult = DispatchSummary | SpecSummary | FixTestsSummary;\n\n/** A booted runner that coordinates dispatch and spec pipelines. */\nexport interface OrchestratorAgent {\n orchestrate(opts: OrchestrateRunOptions): Promise<DispatchSummary>;\n generateSpecs(opts: SpecOptions): Promise<SpecSummary>;\n run(opts: UnifiedRunOptions): Promise<RunResult>;\n runFromCli(args: RawCliArgs): Promise<RunResult>;\n}\n\n/** Options for the multi-issue worktree fix-tests flow. */\ninterface MultiIssueFixTestsOptions {\n cwd: string;\n issueIds: string[];\n source: DatasourceName;\n provider: ProviderName;\n serverUrl?: string;\n verbose: boolean;\n testTimeout?: number;\n org?: string;\n project?: string;\n}\n\n/**\n * Run fix-tests across multiple issues, each in its own worktree.\n *\n * Fetches the specified issues from the configured datasource,\n * creates a worktree per issue, runs `runFixTestsPipeline` inside\n * each worktree, and collects per-issue results.\n */\nasync function runMultiIssueFixTests(opts: MultiIssueFixTestsOptions): Promise<FixTestsSummary> {\n const { runFixTestsPipeline } = await import(\"./fix-tests-pipeline.js\");\n const datasource = getDatasource(opts.source);\n const fetchOpts = { cwd: opts.cwd, org: opts.org, project: opts.project };\n const items = await fetchItemsById(opts.issueIds, datasource, fetchOpts);\n\n if (items.length === 0) {\n log.warn(\"No issues found for the given IDs\");\n return { mode: \"fix-tests\", success: false, error: \"No issues found\" };\n }\n\n let username = \"\";\n try {\n username = await datasource.getUsername({ cwd: opts.cwd });\n } catch (err) {\n log.warn(`Could not resolve git username for branch naming: ${log.formatErrorChain(err)}`);\n }\n\n log.info(`Running fix-tests for ${items.length} issue(s) in worktrees`);\n\n const issueResults: IssueResult[] = [];\n\n for (const item of items) {\n const branchName = datasource.buildBranchName(item.number, item.title, username);\n const issueFilename = `${item.number}-fix-tests.md`;\n let worktreePath: string | undefined;\n\n try {\n worktreePath = await createWorktree(opts.cwd, issueFilename, branchName);\n registerCleanup(async () => { await removeWorktree(opts.cwd, issueFilename); });\n log.info(`Created worktree for issue #${item.number} at ${worktreePath}`);\n\n const result = await runFixTestsPipeline({\n cwd: worktreePath,\n provider: opts.provider,\n serverUrl: opts.serverUrl,\n verbose: opts.verbose,\n testTimeout: opts.testTimeout,\n });\n\n issueResults.push({ issueId: item.number, branch: branchName, success: result.success, error: result.error });\n } catch (err) {\n const message = log.extractMessage(err);\n log.error(`Fix-tests failed for issue #${item.number}: ${message}`);\n issueResults.push({ issueId: item.number, branch: branchName, success: false, error: message });\n } finally {\n if (worktreePath) {\n try {\n await removeWorktree(opts.cwd, issueFilename);\n } catch (err) {\n log.warn(`Could not remove worktree for issue #${item.number}: ${log.formatErrorChain(err)}`);\n }\n }\n }\n }\n\n const allSuccess = issueResults.length > 0 && issueResults.every((r) => r.success);\n return { mode: \"fix-tests\", success: allSuccess, issueResults };\n}\n\n/** Boot a runner. */\nexport async function boot(opts: AgentBootOptions): Promise<OrchestratorAgent> {\n const { cwd } = opts;\n\n const runner: OrchestratorAgent = {\n orchestrate: (runOpts) => runDispatchPipeline(runOpts, cwd),\n\n generateSpecs: (specOpts) => runSpecPipeline(specOpts),\n\n async run(opts: UnifiedRunOptions): Promise<RunResult> {\n if (opts.mode === \"spec\") {\n const { mode: _, ...rest } = opts;\n return runner.generateSpecs({ ...rest, cwd });\n }\n if (opts.mode === \"fix-tests\") {\n const { runFixTestsPipeline } = await import(\"./fix-tests-pipeline.js\");\n\n // No issue IDs — run in current cwd (existing behavior)\n if (!opts.issueIds || opts.issueIds.length === 0) {\n return runFixTestsPipeline({ cwd, provider: opts.provider ?? \"opencode\", serverUrl: opts.serverUrl, verbose: opts.verbose ?? false, testTimeout: opts.testTimeout });\n }\n\n // Multi-issue fix-tests via worktrees\n const source = opts.source;\n if (!source) {\n log.error(\"No datasource configured for multi-issue fix-tests.\");\n return { mode: \"fix-tests\" as const, success: false, error: \"No datasource configured\" };\n }\n\n return runMultiIssueFixTests({\n cwd, issueIds: opts.issueIds, source,\n provider: opts.provider ?? \"opencode\", serverUrl: opts.serverUrl,\n verbose: opts.verbose ?? false, testTimeout: opts.testTimeout,\n org: opts.org, project: opts.project,\n });\n }\n const { mode: _, ...rest } = opts;\n return runner.orchestrate(rest);\n },\n\n async runFromCli(args: RawCliArgs): Promise<RunResult> {\n const m = await resolveCliConfig(args);\n\n // ── Prerequisite checks ───────────────────────────────────\n const prereqFailures = await checkPrereqs();\n if (prereqFailures.length > 0) {\n for (const msg of prereqFailures) {\n log.error(msg);\n }\n process.exit(1);\n }\n\n // Ensure .dispatch/worktrees/ is gitignored in the main repo\n await ensureGitignoreEntry(m.cwd, \".dispatch/worktrees/\");\n\n // ── Mutual exclusion: --spec, --respec, --fix-tests ────\n const modeFlags = [\n m.spec !== undefined && \"--spec\",\n m.respec !== undefined && \"--respec\",\n m.fixTests && \"--fix-tests\",\n m.feature && \"--feature\",\n ].filter(Boolean) as string[];\n\n if (modeFlags.length > 1) {\n log.error(`${modeFlags.join(\" and \")} are mutually exclusive`);\n process.exit(1);\n }\n\n // --feature requires branching — mutually exclusive with --no-branch\n if (m.feature && m.noBranch) {\n log.error(\"--feature and --no-branch are mutually exclusive\");\n process.exit(1);\n }\n\n if (m.fixTests) {\n const { runFixTestsPipeline } = await import(\"./fix-tests-pipeline.js\");\n\n // No issue IDs — run in current cwd (existing behavior)\n if (m.issueIds.length === 0) {\n return runFixTestsPipeline({ cwd: m.cwd, provider: m.provider, serverUrl: m.serverUrl, verbose: m.verbose, testTimeout: m.testTimeout });\n }\n\n // Multi-issue fix-tests via worktrees\n const source = m.issueSource;\n if (!source) {\n log.error(\"No datasource configured. Use --source or run 'dispatch config' to set up defaults.\");\n process.exit(1);\n }\n\n return runMultiIssueFixTests({\n cwd: m.cwd, issueIds: m.issueIds, source,\n provider: m.provider, serverUrl: m.serverUrl,\n verbose: m.verbose, testTimeout: m.testTimeout,\n org: m.org, project: m.project,\n });\n }\n\n if (m.spec) {\n return this.generateSpecs({\n issues: m.spec, issueSource: m.issueSource, provider: m.provider,\n model: m.model, serverUrl: m.serverUrl, cwd: m.cwd, outputDir: m.outputDir,\n org: m.org, project: m.project, workItemType: m.workItemType, iteration: m.iteration, area: m.area, concurrency: m.concurrency,\n dryRun: m.dryRun,\n });\n }\n\n if (m.respec) {\n const respecArgs = m.respec;\n const isEmpty = Array.isArray(respecArgs) && respecArgs.length === 0;\n\n let issues: string | string[];\n if (isEmpty) {\n // No arguments: discover all existing specs via datasource.list()\n const source = await resolveSource(respecArgs, m.issueSource, m.cwd);\n if (!source) {\n process.exit(1);\n }\n const datasource = getDatasource(source);\n const existing = await datasource.list({ cwd: m.cwd, org: m.org, project: m.project, workItemType: m.workItemType, iteration: m.iteration, area: m.area });\n if (existing.length === 0) {\n log.error(\"No existing specs found to regenerate\");\n process.exit(1);\n }\n const identifiers = existing.map((item) => item.number);\n const allNumeric = identifiers.every((id) => /^\\d+$/.test(id));\n issues = allNumeric ? identifiers.join(\",\") : identifiers;\n\n const confirmed = await confirmLargeBatch(existing.length);\n if (!confirmed) {\n process.exit(0);\n }\n } else {\n // With arguments: pass directly (same as --spec)\n issues = respecArgs;\n }\n\n return this.generateSpecs({\n issues, issueSource: m.issueSource, provider: m.provider,\n model: m.model, serverUrl: m.serverUrl, cwd: m.cwd, outputDir: m.outputDir,\n org: m.org, project: m.project, workItemType: m.workItemType, iteration: m.iteration, area: m.area, concurrency: m.concurrency,\n dryRun: m.dryRun,\n });\n }\n\n return this.orchestrate({\n issueIds: m.issueIds, concurrency: m.concurrency ?? defaultConcurrency(),\n dryRun: m.dryRun, noPlan: m.noPlan, noBranch: m.noBranch, noWorktree: m.noWorktree, provider: m.provider,\n model: m.model, serverUrl: m.serverUrl, source: m.issueSource, org: m.org, project: m.project,\n workItemType: m.workItemType, iteration: m.iteration, area: m.area, planTimeout: m.planTimeout, planRetries: m.planRetries, retries: m.retries,\n force: m.force, feature: m.feature,\n });\n },\n };\n\n return runner;\n}\n\nexport { parseIssueFilename } from \"./datasource-helpers.js\";\n","/**\n * Large-batch confirmation prompt.\n *\n * Asks the user to explicitly type \"yes\" before proceeding when a\n * spec or respec operation targets more items than the safety threshold.\n * Extracted into its own module so both the runner and spec-pipeline\n * call sites can share the logic and tests can mock it via `vi.mock()`.\n */\n\nimport { input } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport { log } from \"./logger.js\";\n\n/** Default threshold above which confirmation is required. */\nexport const LARGE_BATCH_THRESHOLD = 100;\n\n/**\n * Prompt the user to confirm a large batch operation.\n *\n * If `count` is at or below `threshold`, returns `true` immediately.\n * Otherwise, warns the user and requires them to type \"yes\" to proceed.\n *\n * @param count - Number of specs that will be processed\n * @param threshold - Minimum count that triggers the prompt (default {@link LARGE_BATCH_THRESHOLD})\n * @returns `true` if the user confirmed (or count ≤ threshold), `false` otherwise\n */\nexport async function confirmLargeBatch(\n count: number,\n threshold: number = LARGE_BATCH_THRESHOLD,\n): Promise<boolean> {\n if (count <= threshold) return true;\n\n log.warn(\n `This operation will process ${chalk.bold(String(count))} specs, which exceeds the safety threshold of ${threshold}.`,\n );\n\n const answer = await input({\n message: `Type ${chalk.bold('\"yes\"')} to proceed:`,\n });\n\n return answer.trim().toLowerCase() === \"yes\";\n}\n","/**\n * Startup prerequisite checker.\n *\n * Verifies that required external tools and runtime versions are available\n * before any pipeline logic runs. Returns an array of human-readable failure\n * messages — an empty array means all checks pass.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\n/** Minimum supported Node.js version (matches package.json engines field). */\nconst MIN_NODE_VERSION = \"20.12.0\";\n\n/**\n * Parse a semver-style version string into [major, minor, patch] numbers.\n */\nfunction parseSemver(version: string): [number, number, number] {\n const [major, minor, patch] = version.split(\".\").map(Number);\n return [major ?? 0, minor ?? 0, patch ?? 0];\n}\n\n/**\n * Return true if `current` is greater than or equal to `minimum`\n * using major.minor.patch comparison.\n */\nfunction semverGte(current: string, minimum: string): boolean {\n const [cMaj, cMin, cPat] = parseSemver(current);\n const [mMaj, mMin, mPat] = parseSemver(minimum);\n if (cMaj !== mMaj) return cMaj > mMaj;\n if (cMin !== mMin) return cMin > mMin;\n return cPat >= mPat;\n}\n\n/**\n * Verify that required external tools and runtime versions are available.\n *\n * Checks performed:\n * 1. `git` is available on PATH (via `git --version`)\n * 2. Node.js version meets the `>=20.12.0` minimum\n *\n * @returns An array of human-readable failure message strings.\n * An empty array means all checks passed.\n */\nexport async function checkPrereqs(): Promise<string[]> {\n const failures: string[] = [];\n\n // Check git availability\n try {\n await exec(\"git\", [\"--version\"], { shell: process.platform === \"win32\" });\n } catch {\n failures.push(\"git is required but was not found on PATH. Install it from https://git-scm.com\");\n }\n\n // Check Node.js version\n const nodeVersion = process.versions.node;\n if (!semverGte(nodeVersion, MIN_NODE_VERSION)) {\n failures.push(\n `Node.js >= ${MIN_NODE_VERSION} is required but found ${nodeVersion}. Please upgrade Node.js`,\n );\n }\n\n return failures;\n}\n","/**\n * Utility for ensuring entries exist in a repository's .gitignore file.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { log } from \"./logger.js\";\n\n/**\n * Ensure `entry` appears as a line in `<repoRoot>/.gitignore`.\n *\n * Creates the file if it doesn't exist. No-ops if the entry (with or without\n * a trailing slash) is already present. Logs a warning and continues on\n * failure — this is non-fatal so a permissions issue won't abort the run.\n *\n * @param repoRoot - Absolute path to the repository root\n * @param entry - The gitignore pattern to add (e.g. `.dispatch/worktrees/`)\n */\nexport async function ensureGitignoreEntry(repoRoot: string, entry: string): Promise<void> {\n const gitignorePath = join(repoRoot, \".gitignore\");\n\n let contents = \"\";\n try {\n contents = await readFile(gitignorePath, \"utf8\");\n } catch (err: unknown) {\n if (err instanceof Error && \"code\" in err && (err as NodeJS.ErrnoException).code === \"ENOENT\") {\n // File doesn't exist — will be created below\n } else {\n log.warn(`Could not read .gitignore: ${String(err)}`);\n return;\n }\n }\n\n const lines = contents.split(/\\r?\\n/);\n // Match with or without trailing slash to avoid adding a duplicate when\n // the user already has the bare form (e.g. `.dispatch/worktrees`) or the\n // slash form (e.g. `.dispatch/worktrees/`).\n const bare = entry.replace(/\\/$/, \"\");\n const withSlash = bare + \"/\";\n if (lines.includes(entry) || lines.includes(bare) || lines.includes(withSlash)) {\n return;\n }\n\n try {\n const separator = contents.length > 0 && !contents.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await writeFile(gitignorePath, `${contents}${separator}${entry}\\n`, \"utf8\");\n log.debug(`Added '${entry}' to .gitignore`);\n } catch (err) {\n log.warn(`Could not update .gitignore: ${String(err)}`);\n }\n}\n","/**\n * CLI config resolution — loads the config file, merges config defaults\n * beneath CLI flags, validates mandatory configuration, and enables\n * verbose logging.\n *\n * Extracted from the orchestrator's `runFromCli()` method to keep the\n * coordinator thin and this logic independently testable.\n */\n\nimport { join } from \"node:path\";\nimport { access } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { log } from \"../helpers/logger.js\";\nimport { loadConfig, CONFIG_KEYS, type DispatchConfig, type ConfigKey } from \"../config.js\";\nimport type { RawCliArgs } from \"./runner.js\";\nimport { detectDatasource, DATASOURCE_NAMES } from \"../datasources/index.js\";\n\n/**\n * Config key → RawCliArgs field mapping.\n *\n * Maps persistent config keys (from `{cwd}/.dispatch/config.json`) to their\n * corresponding field names on `RawCliArgs`. Used during the merge step\n * to fill in CLI flag defaults from the config file.\n */\nconst CONFIG_TO_CLI: Record<ConfigKey, keyof RawCliArgs> = {\n provider: \"provider\",\n model: \"model\",\n source: \"issueSource\",\n testTimeout: \"testTimeout\",\n planTimeout: \"planTimeout\",\n concurrency: \"concurrency\",\n org: \"org\",\n project: \"project\",\n workItemType: \"workItemType\",\n iteration: \"iteration\",\n area: \"area\",\n};\n\n/** Type-safe indexed write into a RawCliArgs object. */\nfunction setCliField<K extends keyof RawCliArgs>(\n target: RawCliArgs,\n key: K,\n value: RawCliArgs[K],\n): void {\n target[key] = value;\n}\n\n/**\n * Resolve raw CLI arguments into a fully-merged and validated options\n * object, ready for pipeline delegation.\n *\n * 1. Loads the persistent config file (`{cwd}/.dispatch/config.json`)\n * 2. Merges config defaults beneath CLI flags (CLI wins when explicit)\n * 3. Validates that mandatory configuration (provider + source) is present\n * — calls `process.exit(1)` on validation failure, matching current behavior\n * 4. Auto-detects the datasource from the git remote when not explicitly set\n * — skipped for spec/respec modes, which defer source resolution to the\n * pipeline's own `resolveSource()` (context-aware fallback logic)\n * 5. Enables verbose logging if requested\n *\n * @param args - Raw CLI arguments as parsed by the CLI entry point\n * @returns The merged `RawCliArgs` with config defaults applied\n */\nexport async function resolveCliConfig(args: RawCliArgs): Promise<RawCliArgs> {\n const { explicitFlags } = args;\n\n // ── Load and merge config-file defaults beneath CLI flags ───\n const configDir = join(args.cwd, \".dispatch\");\n const config = await loadConfig(configDir);\n\n const merged = { ...args };\n for (const configKey of CONFIG_KEYS) {\n const cliField = CONFIG_TO_CLI[configKey];\n const configValue = config[configKey];\n if (configValue !== undefined && !explicitFlags.has(cliField)) {\n setCliField(merged, cliField, configValue);\n }\n }\n\n // ── Mandatory config validation ────────────────────────────\n const providerConfigured =\n explicitFlags.has(\"provider\") || config.provider !== undefined;\n\n if (!providerConfigured) {\n log.error(\"Missing required configuration: provider\");\n log.dim(\" Run 'dispatch config' to configure defaults interactively.\");\n log.dim(\" Or pass it as a CLI flag: --provider <name>\");\n process.exit(1);\n }\n\n // ── Output-dir validation ─────────────────────────────────\n if (merged.outputDir) {\n try {\n await access(merged.outputDir, constants.W_OK);\n } catch {\n log.error(\n `--output-dir path does not exist or is not writable: ${merged.outputDir}`,\n );\n process.exit(1);\n }\n }\n\n // ── Auto-detect datasource when not explicitly set ─────────\n const sourceConfigured =\n explicitFlags.has(\"issueSource\") || config.source !== undefined;\n const needsSource = !(merged.fixTests && merged.issueIds.length === 0) && !merged.spec && !merged.respec;\n\n if (needsSource && !sourceConfigured) {\n const detected = await detectDatasource(merged.cwd);\n if (detected) {\n log.info(`Auto-detected datasource from git remote: ${detected}`);\n merged.issueSource = detected;\n } else {\n log.error(\"Datasource auto-detection failed — could not determine issue source from git remote.\");\n log.dim(` Available datasources: ${DATASOURCE_NAMES.join(\", \")}`);\n log.dim(\" Run 'dispatch config' to configure defaults interactively.\");\n log.dim(\" Or pass it as a CLI flag: --source <name>\");\n process.exit(1);\n }\n }\n\n // ── Enable verbose logging ─────────────────────────────────\n log.verbose = merged.verbose;\n\n return merged;\n}\n","/**\n * Spec generation pipeline — extracted from the orchestrator to keep the\n * coordinator thin and this pipeline independently testable.\n *\n * Handles: datasource resolution, issue fetching (tracker and file/glob\n * modes), provider/agent booting, batch spec generation, datasource sync\n * (update existing issues or create new ones), and cleanup.\n */\n\nimport { join } from \"node:path\";\nimport { mkdir, readFile, rename, unlink } from \"node:fs/promises\";\nimport { glob } from \"glob\";\nimport type { SpecOptions, SpecSummary } from \"../spec-generator.js\";\nimport { isIssueNumbers, isGlobOrFilePath, resolveSource, defaultConcurrency } from \"../spec-generator.js\";\nimport type { IssueDetails, IssueFetchOptions, Datasource, DatasourceName } from \"../datasources/interface.js\";\nimport { getDatasource } from \"../datasources/index.js\";\nimport { extractTitle } from \"../datasources/md.js\";\nimport type { ProviderInstance, ProviderName } from \"../providers/interface.js\";\nimport { bootProvider } from \"../providers/index.js\";\nimport type { SpecAgent } from \"../agents/spec.js\";\nimport { boot as bootSpecAgent } from \"../agents/spec.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { FileLogger, fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { confirmLargeBatch } from \"../helpers/confirm-large-batch.js\";\nimport chalk from \"chalk\";\nimport { elapsed, renderHeaderLines } from \"../helpers/format.js\";\nimport { withRetry } from \"../helpers/retry.js\";\nimport { withTimeout } from \"../helpers/timeout.js\";\nimport { slugify, MAX_SLUG_LENGTH } from \"../helpers/slugify.js\";\nimport { parseIssueFilename } from \"./datasource-helpers.js\";\n\n/** Per-item timeout for datasource fetch calls (ms). */\nconst FETCH_TIMEOUT_MS = 30_000;\n\n// ── Shared types for pipeline stages ──────────────────────────\n\n/** An item resolved from any input mode (tracker, file, or inline text). */\ninterface ResolvedItem {\n id: string;\n details: IssueDetails | null;\n error?: string;\n}\n\n/** A successfully resolved item with non-null details. */\ninterface ValidItem {\n id: string;\n details: IssueDetails;\n error?: string;\n}\n\n/** Result of the datasource resolution stage. */\ninterface ResolvedSource {\n source: DatasourceName;\n datasource: Datasource;\n fetchOpts: IssueFetchOptions;\n}\n\n/** Accumulated state from the batch generation loop. */\ninterface GenerationResults {\n generatedFiles: string[];\n issueNumbers: string[];\n dispatchIdentifiers: string[];\n failed: number;\n fileDurationsMs: Record<string, number>;\n}\n\n// ── Pipeline stage functions ──────────────────────────────────\n\n/**\n * Resolve the datasource from options.\n * Returns null when resolution fails (caller should return early).\n */\nasync function resolveDatasource(\n issues: string | string[],\n issueSource: DatasourceName | undefined,\n specCwd: string,\n org?: string,\n project?: string,\n workItemType?: string,\n iteration?: string,\n area?: string,\n): Promise<ResolvedSource | null> {\n const source = await resolveSource(issues, issueSource, specCwd);\n if (!source) return null;\n\n const datasource = getDatasource(source);\n const fetchOpts: IssueFetchOptions = { cwd: specCwd, org, project, workItemType, iteration, area };\n return { source, datasource, fetchOpts };\n}\n\n/**\n * Fetch items from an issue tracker by number.\n * Returns an empty array if no issue numbers were provided.\n */\nasync function fetchTrackerItems(\n issues: string,\n datasource: Datasource,\n fetchOpts: IssueFetchOptions,\n concurrency: number,\n source: DatasourceName,\n): Promise<ResolvedItem[]> {\n const issueNumbers = issues\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (issueNumbers.length === 0) {\n log.error(\"No issue numbers provided. Use --spec 1,2,3\");\n return [];\n }\n\n const fetchStart = Date.now();\n log.info(`Fetching ${issueNumbers.length} issue(s) from ${source} (concurrency: ${concurrency})...`);\n\n const items: ResolvedItem[] = [];\n const fetchQueue = [...issueNumbers];\n\n while (fetchQueue.length > 0) {\n const batch = fetchQueue.splice(0, concurrency);\n log.debug(`Fetching batch of ${batch.length}: #${batch.join(\", #\")}`);\n const batchResults = await Promise.all(\n batch.map(async (id) => {\n try {\n const details = await withTimeout(datasource.fetch(id, fetchOpts), FETCH_TIMEOUT_MS, \"datasource fetch\");\n log.success(`Fetched #${id}: ${details.title}`);\n log.debug(`Body: ${details.body?.length ?? 0} chars, Labels: ${details.labels.length}, Comments: ${details.comments.length}`);\n return { id, details };\n } catch (err) {\n const message = log.extractMessage(err);\n log.error(`Failed to fetch #${id}: ${log.formatErrorChain(err)}`);\n log.debug(log.formatErrorChain(err));\n return { id, details: null, error: message };\n }\n })\n );\n items.push(...batchResults);\n }\n log.debug(`Issue fetching completed in ${elapsed(Date.now() - fetchStart)}`);\n return items;\n}\n\n/** Construct a single item from inline text input. */\nfunction buildInlineTextItem(\n issues: string | string[],\n outputDir: string,\n): ResolvedItem[] {\n const text = Array.isArray(issues) ? issues.join(\" \") : issues;\n const title = text.length > 80 ? text.slice(0, 80).trimEnd() + \"…\" : text;\n const slug = slugify(text, MAX_SLUG_LENGTH);\n const filename = `${slug}.md`;\n const filepath = join(outputDir, filename);\n\n const details: IssueDetails = {\n number: filepath,\n title,\n body: text,\n labels: [],\n state: \"open\",\n url: filepath,\n comments: [],\n acceptanceCriteria: \"\",\n };\n\n log.info(`Inline text spec: \"${title}\"`);\n return [{ id: filepath, details }];\n}\n\n/** Resolve items from a glob pattern or file paths. */\nasync function resolveFileItems(\n issues: string | string[],\n specCwd: string,\n concurrency: number,\n): Promise<ResolvedItem[] | null> {\n const files = await glob(issues, { cwd: specCwd, absolute: true });\n\n if (files.length === 0) {\n log.error(`No files matched the pattern \"${Array.isArray(issues) ? issues.join(\", \") : issues}\".`);\n return null;\n }\n\n log.info(`Matched ${files.length} file(s) for spec generation (concurrency: ${concurrency})...`);\n\n const items: ResolvedItem[] = [];\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, \"utf-8\");\n const title = extractTitle(content, filePath);\n const details: IssueDetails = {\n number: filePath,\n title,\n body: content,\n labels: [],\n state: \"open\",\n url: filePath,\n comments: [],\n acceptanceCriteria: \"\",\n };\n items.push({ id: filePath, details });\n } catch (err) {\n items.push({ id: filePath, details: null, error: log.extractMessage(err) });\n }\n }\n return items;\n}\n\n/** Filter items to those with non-null details. */\nfunction filterValidItems(\n items: ResolvedItem[],\n isTrackerMode: boolean,\n isInlineText: boolean,\n): ValidItem[] | null {\n const validItems = items.filter(\n (i): i is ValidItem => i.details !== null,\n );\n if (validItems.length === 0) {\n const noun = isTrackerMode ? \"issues\" : isInlineText ? \"inline specs\" : \"files\";\n log.error(`No ${noun} could be loaded. Aborting spec generation.`);\n return null;\n }\n return validItems;\n}\n\n/** Log a dry-run preview of what would be generated. */\nfunction previewDryRun(\n validItems: ValidItem[],\n items: ResolvedItem[],\n isTrackerMode: boolean,\n isInlineText: boolean,\n outputDir: string,\n pipelineStart: number,\n): SpecSummary {\n const mode = isTrackerMode ? \"tracker\" : isInlineText ? \"inline\" : \"file\";\n log.info(`[DRY RUN] Would generate ${validItems.length} spec(s) (mode: ${mode}):\\n`);\n\n for (const { id, details } of validItems) {\n let filepath: string;\n if (isTrackerMode) {\n const slug = slugify(details.title, 60);\n filepath = join(outputDir, `${id}-${slug}.md`);\n } else {\n filepath = id;\n }\n\n const label = isTrackerMode ? `#${id}` : filepath;\n log.info(`[DRY RUN] Would generate spec for ${label}: \"${details.title}\"`);\n log.dim(` → ${filepath}`);\n }\n\n return {\n total: items.length,\n generated: 0,\n failed: items.filter((i) => i.details === null).length,\n files: [],\n issueNumbers: [],\n durationMs: Date.now() - pipelineStart,\n fileDurationsMs: {},\n };\n}\n\n/** Boot the AI provider and spec agent, render the header banner. */\nasync function bootPipeline(\n provider: ProviderName,\n serverUrl: string | undefined,\n specCwd: string,\n model: string | undefined,\n source: DatasourceName,\n): Promise<{ specAgent: SpecAgent; instance: ProviderInstance }> {\n const bootStart = Date.now();\n log.info(`Booting ${provider} provider...`);\n log.debug(serverUrl ? `Using server URL: ${serverUrl}` : \"No --server-url, will spawn local server\");\n const instance = await bootProvider(provider, { url: serverUrl, cwd: specCwd, model });\n registerCleanup(() => instance.cleanup());\n log.debug(`Provider booted in ${elapsed(Date.now() - bootStart)}`);\n\n const headerLines = renderHeaderLines({\n provider,\n model: instance.model,\n source,\n });\n console.log(\"\");\n for (const line of headerLines) {\n console.log(line);\n }\n console.log(chalk.dim(\" ─\".repeat(24)));\n console.log(\"\");\n\n const specAgent = await bootSpecAgent({ provider: instance, cwd: specCwd });\n\n return { specAgent, instance };\n}\n\n/** Generate specs in parallel batches, sync to datasource, and track results. */\nasync function generateSpecsBatch(\n validItems: ValidItem[],\n items: ResolvedItem[],\n specAgent: SpecAgent,\n instance: ProviderInstance,\n isTrackerMode: boolean,\n isInlineText: boolean,\n datasource: Datasource,\n fetchOpts: IssueFetchOptions,\n outputDir: string,\n specCwd: string,\n concurrency: number,\n retries: number,\n): Promise<GenerationResults> {\n await mkdir(outputDir, { recursive: true });\n\n const generatedFiles: string[] = [];\n const issueNumbers: string[] = [];\n const dispatchIdentifiers: string[] = [];\n let failed = items.filter((i) => i.details === null).length;\n const fileDurationsMs: Record<string, number> = {};\n\n const genQueue = [...validItems];\n let modelLoggedInBanner = !!instance.model;\n\n while (genQueue.length > 0) {\n const batch = genQueue.splice(0, concurrency);\n log.info(`Generating specs for batch of ${batch.length} (${generatedFiles.length + failed}/${items.length} done)...`);\n\n const batchResults = await Promise.all(\n batch.map(async ({ id, details }) => {\n const specStart = Date.now();\n\n if (!details) {\n log.error(`Skipping item ${id}: missing issue details`);\n return null;\n }\n\n const itemBody = async (): Promise<{ filepath: string; identifier: string } | null> => {\n let filepath: string;\n if (isTrackerMode) {\n const slug = slugify(details.title, MAX_SLUG_LENGTH);\n const filename = `${id}-${slug}.md`;\n filepath = join(outputDir, filename);\n } else if (isInlineText) {\n filepath = id;\n } else {\n filepath = id;\n }\n\n fileLoggerStorage.getStore()?.info(`Output path: ${filepath}`);\n\n try {\n fileLoggerStorage.getStore()?.info(`Starting spec generation for ${isTrackerMode ? `#${id}` : filepath}`);\n log.info(`Generating spec for ${isTrackerMode ? `#${id}` : filepath}: ${details.title}...`);\n\n const result = await withRetry(\n () => specAgent.generate({\n issue: isTrackerMode ? details : undefined,\n filePath: isTrackerMode ? undefined : id,\n fileContent: isTrackerMode ? undefined : details.body,\n cwd: specCwd,\n outputPath: filepath,\n }),\n retries,\n { label: `specAgent.generate(${isTrackerMode ? `#${id}` : filepath})` },\n );\n\n if (!result.success) {\n throw new Error(result.error ?? \"Spec generation failed\");\n }\n\n fileLoggerStorage.getStore()?.info(`Spec generated successfully`);\n\n if (isTrackerMode || isInlineText) {\n const h1Title = extractTitle(result.data.content, filepath);\n const h1Slug = slugify(h1Title, MAX_SLUG_LENGTH);\n const finalFilename = isTrackerMode ? `${id}-${h1Slug}.md` : `${h1Slug}.md`;\n const finalFilepath = join(outputDir, finalFilename);\n if (finalFilepath !== filepath) {\n await rename(filepath, finalFilepath);\n filepath = finalFilepath;\n }\n }\n\n const specDuration = Date.now() - specStart;\n fileDurationsMs[filepath] = specDuration;\n log.success(`Spec written: ${filepath} (${elapsed(specDuration)})`);\n\n let identifier = filepath;\n\n fileLoggerStorage.getStore()?.phase(\"Datasource sync\");\n try {\n if (isTrackerMode) {\n await datasource.update(id, details.title, result.data.content, fetchOpts);\n log.success(`Updated issue #${id} with spec content`);\n await unlink(filepath);\n log.success(`Deleted local spec ${filepath} (now tracked as issue #${id})`);\n identifier = id;\n issueNumbers.push(id);\n } else if (datasource.name === \"md\") {\n const parsed = parseIssueFilename(filepath);\n if (parsed) {\n await datasource.update(parsed.issueId, details.title, result.data.content, fetchOpts);\n log.success(`Updated spec #${parsed.issueId} in-place`);\n identifier = parsed.issueId;\n issueNumbers.push(parsed.issueId);\n } else {\n const created = await datasource.create(details.title, result.data.content, fetchOpts);\n log.success(`Created spec #${created.number} from ${filepath}`);\n identifier = created.number;\n issueNumbers.push(created.number);\n try {\n await unlink(filepath);\n log.success(`Deleted local spec ${filepath} (now tracked as spec #${created.number})`);\n } catch (unlinkErr) {\n log.warn(`Could not delete local spec ${filepath}: ${log.formatErrorChain(unlinkErr)}`);\n }\n // Update filepath to the newly created spec so\n // generatedFiles / fileDurationsMs reference the\n // correct (existing) file, not the deleted original.\n const oldDuration = fileDurationsMs[filepath];\n delete fileDurationsMs[filepath];\n filepath = created.url;\n fileDurationsMs[filepath] = oldDuration;\n }\n } else {\n const created = await datasource.create(details.title, result.data.content, fetchOpts);\n log.success(`Created issue #${created.number} from ${filepath}`);\n await unlink(filepath);\n log.success(`Deleted local spec ${filepath} (now tracked as issue #${created.number})`);\n identifier = created.number;\n issueNumbers.push(created.number);\n }\n } catch (err) {\n const label = isTrackerMode ? `issue #${id}` : filepath;\n log.warn(`Could not sync ${label} to datasource: ${log.formatErrorChain(err)}`);\n }\n\n return { filepath, identifier };\n } catch (err) {\n fileLoggerStorage.getStore()?.error(`Spec generation failed for ${id}: ${log.extractMessage(err)}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n log.error(`Failed to generate spec for ${isTrackerMode ? `#${id}` : filepath}: ${log.formatErrorChain(err)}`);\n log.debug(log.formatErrorChain(err));\n return null;\n }\n };\n\n const fileLogger = log.verbose ? new FileLogger(id, specCwd) : null;\n if (fileLogger) {\n return fileLoggerStorage.run(fileLogger, async () => {\n try {\n fileLogger.phase(`Spec generation: ${id}`);\n return await itemBody();\n } finally {\n fileLogger.close();\n }\n });\n }\n return itemBody();\n }));\n\n for (const result of batchResults) {\n if (result !== null) {\n generatedFiles.push(result.filepath);\n dispatchIdentifiers.push(result.identifier);\n } else {\n failed++;\n }\n }\n\n if (!modelLoggedInBanner && instance.model) {\n log.info(`Detected model: ${instance.model}`);\n modelLoggedInBanner = true;\n }\n }\n\n return { generatedFiles, issueNumbers, dispatchIdentifiers, failed, fileDurationsMs };\n}\n\n/** Clean up spec agent and provider, logging warnings on failure. */\nasync function cleanupPipeline(\n specAgent: SpecAgent,\n instance: ProviderInstance,\n): Promise<void> {\n try {\n await specAgent.cleanup();\n } catch (err) {\n log.warn(`Spec agent cleanup failed: ${log.formatErrorChain(err)}`);\n }\n try {\n await instance.cleanup();\n } catch (err) {\n log.warn(`Provider cleanup failed: ${log.formatErrorChain(err)}`);\n }\n}\n\n/** Log the final summary and dispatch hint. */\nfunction logSummary(\n generatedFiles: string[],\n dispatchIdentifiers: string[],\n failed: number,\n totalDuration: number,\n): void {\n log.info(\n `Spec generation complete: ${generatedFiles.length} generated, ${failed} failed in ${elapsed(totalDuration)}`\n );\n\n if (generatedFiles.length > 0) {\n log.dim(`\\n Run these specs with:`);\n const allNumeric = dispatchIdentifiers.every((id) => /^\\d+$/.test(id));\n if (allNumeric) {\n log.dim(` dispatch ${dispatchIdentifiers.join(\",\")}\\n`);\n } else {\n log.dim(` dispatch ${dispatchIdentifiers.map((f) => '\"' + f + '\"').join(\" \")}\\n`);\n }\n }\n}\n\n// ── Public API ────────────────────────────────────────────────\n\n/**\n * Run the spec-generation pipeline end-to-end.\n *\n * This is the extracted core of the orchestrator's `generateSpecs()` method.\n * It accepts `SpecOptions` and returns a `SpecSummary`.\n */\nexport async function runSpecPipeline(opts: SpecOptions): Promise<SpecSummary> {\n const {\n issues,\n provider,\n model,\n serverUrl,\n cwd: specCwd,\n outputDir = join(specCwd, \".dispatch\", \"specs\"),\n org,\n project,\n workItemType,\n iteration,\n area,\n concurrency = defaultConcurrency(),\n dryRun,\n retries = 2,\n } = opts;\n\n const pipelineStart = Date.now();\n\n // ── Resolve datasource ─────────────────────────────────────\n const resolved = await resolveDatasource(issues, opts.issueSource, specCwd, org, project, workItemType, iteration, area);\n if (!resolved) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n const { source, datasource, fetchOpts } = resolved;\n\n // ── Determine items to process ─────────────────────────────\n const isTrackerMode = isIssueNumbers(issues);\n const isInlineText = !isTrackerMode && !isGlobOrFilePath(issues);\n let items: ResolvedItem[];\n\n if (isTrackerMode) {\n items = await fetchTrackerItems(issues, datasource, fetchOpts, concurrency, source);\n if (items.length === 0) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n } else if (isInlineText) {\n items = buildInlineTextItem(issues, outputDir);\n } else {\n const fileItems = await resolveFileItems(issues, specCwd, concurrency);\n if (!fileItems) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n items = fileItems;\n }\n\n // ── Filter valid items ─────────────────────────────────────\n const validItems = filterValidItems(items, isTrackerMode, isInlineText);\n if (!validItems) {\n return { total: items.length, generated: 0, failed: items.length, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n\n // ── Dry-run preview ────────────────────────────────────────\n if (dryRun) {\n return previewDryRun(validItems, items, isTrackerMode, isInlineText, outputDir, pipelineStart);\n }\n\n // ── Confirm large batch ────────────────────────────────────\n const confirmed = await confirmLargeBatch(validItems.length);\n if (!confirmed) {\n return { total: 0, generated: 0, failed: 0, files: [], issueNumbers: [], durationMs: Date.now() - pipelineStart, fileDurationsMs: {} };\n }\n\n // ── Boot provider and spec agent ───────────────────────────\n const { specAgent, instance } = await bootPipeline(provider, serverUrl, specCwd, model, source);\n\n // ── Generate specs in batches ──────────────────────────────\n const results = await generateSpecsBatch(\n validItems, items, specAgent, instance,\n isTrackerMode, isInlineText,\n datasource, fetchOpts, outputDir, specCwd,\n concurrency, retries,\n );\n\n // ── Cleanup ────────────────────────────────────────────────\n await cleanupPipeline(specAgent, instance);\n\n // ── Summary ────────────────────────────────────────────────\n const totalDuration = Date.now() - pipelineStart;\n logSummary(results.generatedFiles, results.dispatchIdentifiers, results.failed, totalDuration);\n\n return {\n total: items.length,\n generated: results.generatedFiles.length,\n failed: results.failed,\n files: results.generatedFiles,\n issueNumbers: results.issueNumbers,\n identifiers: results.dispatchIdentifiers,\n durationMs: totalDuration,\n fileDurationsMs: results.fileDurationsMs,\n };\n}\n","/**\n * Spec agent — generates high-level markdown spec files from issue details\n * or file content by interacting with an AI provider.\n *\n * The spec agent follows the same pattern as the planner agent: it receives\n * a provider instance at boot time and exposes a `generate()` method for\n * producing specs. It writes to a temp file in `.dispatch/tmp/`, post-processes\n * and validates the content, then writes the cleaned result to the final\n * output path.\n */\n\nimport { mkdir, readFile, writeFile, unlink } from \"node:fs/promises\";\nimport { join, resolve, sep } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { AgentResult, SpecData } from \"./types.js\";\nimport type { IssueDetails } from \"../datasources/interface.js\";\nimport { extractSpecContent, validateSpecStructure } from \"../spec-generator.js\";\nimport { extractTitle } from \"../datasources/md.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/**\n * Options passed to the spec agent's `generate()` method.\n */\nexport interface SpecGenerateOptions {\n /** Issue details (for tracker mode) — mutually exclusive with fileContent */\n issue?: IssueDetails;\n /** File path (for file/glob mode) — used as source file reference */\n filePath?: string;\n /** File content (for file/glob mode) — mutually exclusive with issue */\n fileContent?: string;\n /** Inline text (for inline text mode) — mutually exclusive with issue and fileContent */\n inlineText?: string;\n /** Working directory */\n cwd: string;\n /** Final output path where the spec should be written */\n outputPath: string;\n /** Worktree root directory for isolation, if operating in a worktree */\n worktreeRoot?: string;\n}\n\n/**\n * A booted spec agent that can generate spec files.\n */\nexport interface SpecAgent extends Agent {\n /**\n * Generate a single spec. Creates an isolated session, instructs the AI\n * to write to a temp file, post-processes and validates the content,\n * writes the cleaned result to the final output path, and cleans up.\n */\n generate(opts: SpecGenerateOptions): Promise<AgentResult<SpecData>>;\n}\n\n/**\n * Boot a spec agent backed by the given provider.\n *\n * @throws if `opts.provider` is not supplied — the spec agent requires a\n * provider to create sessions and send prompts.\n */\nexport async function boot(opts: AgentBootOptions): Promise<SpecAgent> {\n const { provider } = opts;\n\n if (!provider) {\n throw new Error(\"Spec agent requires a provider instance in boot options\");\n }\n\n return {\n name: \"spec\",\n\n async generate(genOpts: SpecGenerateOptions): Promise<AgentResult<SpecData>> {\n const { issue, filePath, fileContent, inlineText, cwd: workingDir, outputPath } = genOpts;\n const startTime = Date.now();\n\n try {\n // 0. Normalize cwd and validate outputPath stays within it\n const resolvedCwd = resolve(workingDir);\n const resolvedOutput = resolve(outputPath);\n if (\n resolvedOutput !== resolvedCwd &&\n !resolvedOutput.startsWith(resolvedCwd + sep)\n ) {\n return {\n data: null,\n success: false,\n error: `Output path \"${outputPath}\" escapes the working directory \"${workingDir}\"`,\n durationMs: Date.now() - startTime,\n };\n }\n\n // 1. Create .dispatch/tmp/ on demand\n const tmpDir = join(resolvedCwd, \".dispatch\", \"tmp\");\n await mkdir(tmpDir, { recursive: true });\n\n // 2. Generate a unique temp file path\n const tmpFilename = `spec-${randomUUID()}.md`;\n const tmpPath = join(tmpDir, tmpFilename);\n\n // 3. Build the appropriate prompt, pointing at the temp file path\n let prompt: string;\n if (issue) {\n prompt = buildSpecPrompt(issue, workingDir, tmpPath);\n } else if (inlineText) {\n prompt = buildInlineTextSpecPrompt(inlineText, workingDir, tmpPath);\n } else if (filePath && fileContent !== undefined) {\n prompt = buildFileSpecPrompt(filePath, fileContent, workingDir, tmpPath);\n } else {\n return {\n data: null,\n success: false,\n error: \"Either issue, inlineText, or filePath+fileContent must be provided\",\n durationMs: Date.now() - startTime,\n };\n }\n\n fileLoggerStorage.getStore()?.prompt(\"spec\", prompt);\n\n // 4. Create a session via the provider and send the prompt\n const sessionId = await provider.createSession();\n log.debug(`Spec prompt built (${prompt.length} chars)`);\n const response = await provider.prompt(sessionId, prompt);\n\n if (response === null) {\n return {\n data: null,\n success: false,\n error: \"AI agent returned no response\",\n durationMs: Date.now() - startTime,\n };\n }\n\n log.debug(`Spec agent response (${response.length} chars)`);\n fileLoggerStorage.getStore()?.response(\"spec\", response);\n\n // 5. Read the temp file\n let rawContent: string;\n try {\n rawContent = await readFile(tmpPath, \"utf-8\");\n } catch {\n return {\n data: null,\n success: false,\n error: `Spec agent did not write the file to ${tmpPath}. Agent response: ${response.slice(0, 300)}`,\n durationMs: Date.now() - startTime,\n };\n }\n\n // 6. Apply extractSpecContent post-processing\n const cleanedContent = extractSpecContent(rawContent);\n log.debug(`Post-processed spec (${rawContent.length} → ${cleanedContent.length} chars)`);\n\n // 7. Run validateSpecStructure\n const validation = validateSpecStructure(cleanedContent);\n if (!validation.valid) {\n log.warn(`Spec validation warning for ${outputPath}: ${validation.reason}`);\n }\n\n // 8. Write the cleaned content to the final output path\n await writeFile(resolvedOutput, cleanedContent, \"utf-8\");\n log.debug(`Wrote cleaned spec to ${resolvedOutput}`);\n\n // 9. Clean up the temp file\n try {\n await unlink(tmpPath);\n } catch {\n // Ignore cleanup errors — temp file may already be gone\n }\n\n fileLoggerStorage.getStore()?.agentEvent(\"spec\", \"completed\", `${Date.now() - startTime}ms`);\n return {\n data: {\n content: cleanedContent,\n valid: validation.valid,\n validationReason: validation.reason,\n },\n success: true,\n durationMs: Date.now() - startTime,\n };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`spec error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return {\n data: null,\n success: false,\n error: message,\n durationMs: Date.now() - startTime,\n };\n }\n },\n\n async cleanup(): Promise<void> {\n // Spec agent has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n\n/**\n * Build the source-specific section for tracker/issue mode.\n */\nfunction buildIssueSourceSection(issue: IssueDetails): string[] {\n const lines: string[] = [\n ``,\n `## Issue Details`,\n ``,\n `- **Number:** #${issue.number}`,\n `- **Title:** ${issue.title}`,\n `- **State:** ${issue.state}`,\n `- **URL:** ${issue.url}`,\n ];\n\n if (issue.labels.length > 0) {\n lines.push(`- **Labels:** ${issue.labels.join(\", \")}`);\n }\n\n if (issue.body) {\n lines.push(``, `### Description`, ``, issue.body);\n }\n\n if (issue.acceptanceCriteria) {\n lines.push(``, `### Acceptance Criteria`, ``, issue.acceptanceCriteria);\n }\n\n if (issue.comments.length > 0) {\n lines.push(``, `### Discussion`, ``);\n for (const comment of issue.comments) {\n lines.push(comment, ``);\n }\n }\n\n return lines;\n}\n\n/**\n * Build the source-specific section for file/glob mode.\n */\nfunction buildFileSourceSection(filePath: string, content: string, title: string): string[] {\n const lines: string[] = [\n ``,\n `## File Details`,\n ``,\n `- **Title:** ${title}`,\n `- **Source file:** ${filePath}`,\n ];\n\n if (content) {\n lines.push(``, `### Content`, ``, content);\n }\n\n return lines;\n}\n\n/**\n * Build the source-specific section for inline text mode.\n */\nfunction buildInlineTextSourceSection(title: string, text: string): string[] {\n return [\n ``,\n `## Inline Text`,\n ``,\n `- **Title:** ${title}`,\n ``,\n `### Description`,\n ``,\n text,\n ];\n}\n\n/**\n * Build the full spec prompt by assembling role preamble, pipeline explanation,\n * output constraints, source-specific section, working directory, instructions,\n * output template, task tagging rules, references, and key guidelines.\n *\n * All three public prompt builders delegate to this function with their\n * source-specific parameters.\n */\nfunction buildCommonSpecInstructions(params: {\n /** Subject phrase for the role preamble (e.g., \"the issue below\"). */\n subject: string;\n /** Source-specific section lines to insert after output constraints. */\n sourceSection: string[];\n /** Working directory path. */\n cwd: string;\n /** Output file path. */\n outputPath: string;\n /** Full text of instruction step 2. */\n understandStep: string;\n /** Title template line for the spec structure. */\n titleTemplate: string;\n /** One-line summary template line. */\n summaryTemplate: string;\n /** Variable ending lines for the \"Why\" section template. */\n whyLines: string[];\n}): string[] {\n const {\n subject,\n sourceSection,\n cwd,\n outputPath,\n understandStep,\n titleTemplate,\n summaryTemplate,\n whyLines,\n } = params;\n\n return [\n `You are a **spec agent**. Your job is to explore the codebase, understand ${subject}, and write a high-level **markdown spec file** to disk that will drive an automated implementation pipeline.`,\n ``,\n `**Important:** This file will be consumed by a two-stage pipeline:`,\n `1. A **planner agent** reads each task together with the prose context in this file, then explores the codebase to produce a detailed, line-level implementation plan.`,\n `2. A **coder agent** follows that detailed plan to make the actual code changes.`,\n ``,\n `Because the planner agent handles low-level details, your spec must stay **high-level and strategic**. Focus on the WHAT, WHY, and HOW — not exact code or line numbers.`,\n ``,\n `**CRITICAL — Output constraints (read carefully):**`,\n `The file you write must contain ONLY the structured spec content described below. You MUST NOT include:`,\n `- **No preamble:** Do not add any text before the H1 heading (e.g., \"Here's the spec:\", \"I've written the spec file to...\")`,\n `- **No postamble:** Do not add any text after the last spec section (e.g., \"Let me know if you'd like changes\", \"Here's a summary of...\")`,\n `- **No summaries:** Do not append a summary or recap of what you wrote`,\n `- **No code fences:** Do not wrap the spec content in \\`\\`\\`markdown ... \\`\\`\\` or any other code fence`,\n `- **No conversational text:** Do not include any explanations, commentary, or dialogue — the file is consumed by an automated pipeline, not a human`,\n `The file content must start with \\`# \\` (the H1 heading) and contain nothing before or after the structured spec sections.`,\n ...sourceSection,\n ``,\n `## Working Directory`,\n ``,\n `\\`${cwd}\\``,\n ``,\n formatEnvironmentPrompt(),\n ``,\n `## Instructions`,\n ``,\n `1. **Explore the codebase** — read relevant files, search for symbols, understand the project structure, language, frameworks, conventions, and patterns. Identify the tech stack (languages, package managers, frameworks, test runners) so your spec aligns with the project's actual standards.`,\n ``,\n understandStep,\n ``,\n `3. **Research the approach** — look up relevant documentation, libraries, and patterns. Consider how the change integrates with the existing architecture, standards, and technologies already in use. For example, if the project is TypeScript, do not propose a Python solution; if it uses Vitest, do not suggest Jest.`,\n ``,\n `4. **Identify integration points** — determine which existing modules, interfaces, patterns, and conventions the implementation must align with. Note the key files and modules involved, but do NOT prescribe exact code changes — the planner agent will handle that.`,\n ``,\n `5. **DO NOT make any code changes** — you are only producing a spec, not implementing.`,\n ``,\n `## Output`,\n ``,\n `Write the complete spec as a markdown file to this exact path:`,\n ``,\n `\\`${outputPath}\\``,\n ``,\n `Use your Write tool to save the file. The file content MUST begin with the H1 heading — no preamble, no code fences, no conversational text before it. Do not add any text after the final spec section — no postamble, no summary, no commentary. The file must follow this structure exactly:`,\n ``,\n titleTemplate,\n ``,\n summaryTemplate,\n ``,\n `## Context`,\n ``,\n `<Describe the relevant parts of the codebase: key modules, directory structure,`,\n `language/framework, and architectural patterns. Name specific files and modules`,\n `that are involved so the planner agent knows where to look, but do not include`,\n `code snippets or line-level details.>`,\n ``,\n `## Why`,\n ``,\n `<Explain the motivation — why this change is needed, what problem it solves,`,\n ...whyLines,\n ``,\n `## Approach`,\n ``,\n `<High-level description of the implementation strategy. Explain the overall`,\n `approach, which patterns to follow, what to extend vs. create new, and how`,\n `the change fits into the existing architecture. Mention relevant standards,`,\n `technologies, and conventions the implementation MUST align with.>`,\n ``,\n `## Integration Points`,\n ``,\n `<List the specific modules, interfaces, configurations, and conventions that`,\n `the implementation must integrate with. For example: existing provider`,\n `interfaces to implement, CLI argument patterns to follow, test framework`,\n `and conventions to match, build system requirements, etc.>`,\n ``,\n `## Tasks`,\n ``,\n `Each task MUST be prefixed with an execution-mode tag:`,\n ``,\n `- \\`(P)\\` — **Parallel-safe.** This task has no dependency on the output of a prior task and can run concurrently with other \\`(P)\\` tasks.`,\n `- \\`(S)\\` — **Serial / dependent.** This task depends on a prior task's output or modifies shared state that conflicts with concurrent work. It acts as a barrier: all preceding tasks complete before it starts, and it completes before subsequent tasks begin.`,\n `- \\`(I)\\` — **Isolated / barrier.** This task must run alone after all preceding tasks complete and before any subsequent tasks begin. Use for validation tasks like running tests, linting, or builds that read the output of prior tasks.`,\n ``,\n `**Default to \\`(P)\\`.** Most tasks are independent (e.g., adding a function in one module, writing tests in another). Only use \\`(S)\\` when a task genuinely depends on the result of a prior task (e.g., \"refactor module X\" followed by \"update callers of module X\"). Use \\`(I)\\` for validation or barrier tasks that must run alone after all prior work completes (e.g., \"run tests\", \"run linting\", \"build the project\").`,\n ``,\n `If a task has no \\`(P)\\`, \\`(S)\\`, or \\`(I)\\` prefix, the system treats it as serial, so always tag explicitly.`,\n ``,\n `Example:`,\n ``,\n `- [ ] (P) Add validation helper to the form utils module`,\n `- [ ] (P) Add unit tests for the new validation helper`,\n `- [ ] (S) Refactor the form component to use the new validation helper`,\n `- [ ] (P) Update documentation for the form utils module`,\n `- [ ] (I) Run the full test suite to verify all changes pass`,\n ``,\n ``,\n `## References`,\n ``,\n `- <Links to relevant docs, related issues, or external resources>`,\n ``,\n `## Key Guidelines`,\n ``,\n `- **Stay high-level.** Do NOT include code snippets, exact line numbers, diffs, or step-by-step coding instructions. A dedicated planner agent will produce those details for each task at execution time.`,\n `- **Respect the project's stack.** Your spec must align with the languages, frameworks, libraries, test tools, and conventions already in use. Never suggest technologies that conflict with the existing project.`,\n `- **Explain WHAT, WHY, and HOW (strategically).** Each task should say what needs to happen, why it's needed, and which part of the codebase it touches — but leave the tactical \"how\" to the planner agent.`,\n `- **Detail integration points.** The prose sections (Context, Approach, Integration Points) are critical — they tell the planner agent where to look and what constraints to respect.`,\n `- **Keep tasks atomic and ordered.** Each \\`- [ ]\\` task must be a single, clear unit of work. Order them so dependencies come first.`,\n `- **Tag every task with \\`(P)\\`, \\`(S)\\`, or \\`(I)\\`.** Default to \\`(P)\\` (parallel) unless the task depends on a prior task's output. Use \\`(I)\\` for validation/barrier tasks. Group related serial dependencies together and prefer parallelism to maximize throughput.`,\n `- **Embed commit instructions within task descriptions.** You control when commits happen. Instead of creating standalone commit tasks (which would fail — each task runs in an isolated agent session), include commit instructions at the end of implementation task descriptions at logical boundaries. For example: \"Implement the validation helper and commit with a conventional commit message.\" Group related changes into a single commit where it makes logical sense, and use the project's conventional commit types: \\`feat\\`, \\`fix\\`, \\`docs\\`, \\`refactor\\`, \\`test\\`, \\`chore\\`, \\`style\\`, \\`perf\\`, \\`ci\\`. Not every task needs a commit instruction — use your judgment to place them at logical boundaries.`,\n `- **Keep the markdown clean** — it will be parsed by an automated tool.`,\n ];\n}\n\n/**\n * Build the prompt that instructs the AI agent to explore the codebase,\n * understand the issue, and write a high-level markdown spec file to disk.\n *\n * The agent is responsible for writing the file — this is not a completion\n * API call. The output emphasises WHAT needs to change, WHY it needs to\n * change, and HOW it fits into the existing project — but deliberately\n * avoids low-level implementation specifics (exact code, line numbers,\n * diffs). A dedicated planner agent handles that granularity per-task at\n * dispatch time.\n */\nexport function buildSpecPrompt(issue: IssueDetails, cwd: string, outputPath: string): string {\n return buildCommonSpecInstructions({\n subject: \"the issue below\",\n sourceSection: buildIssueSourceSection(issue),\n cwd,\n outputPath,\n understandStep: `2. **Understand the issue** — analyze the issue description, acceptance criteria, and discussion comments to fully understand what needs to be done and why.`,\n titleTemplate: `# <Issue title> (#<number>)`,\n summaryTemplate: `> <One-line summary: what this issue achieves and why it matters>`,\n whyLines: [\n `what user or system benefit it provides. Pull from the issue description,`,\n `acceptance criteria, and discussion.>`,\n ],\n }).join(\"\\n\");\n}\n\n/**\n * Build a spec prompt from a local markdown file instead of an issue-tracker\n * issue. The title is extracted from the first `# Heading` in the content,\n * falling back to the filename without extension. The file content serves as\n * the description.\n *\n * When `outputPath` is provided, the prompt instructs the AI to write to that\n * path instead of the source file. When omitted, the source `filePath` is\n * used as the output target (in-place overwrite), preserving backward\n * compatibility with existing callers.\n *\n * The output-format instructions, spec structure template, (P)/(S) tagging\n * rules, and agent guidelines are identical to those in `buildSpecPrompt()`.\n */\nexport function buildFileSpecPrompt(filePath: string, content: string, cwd: string, outputPath?: string): string {\n const title = extractTitle(content, filePath);\n const writePath = outputPath ?? filePath;\n\n return buildCommonSpecInstructions({\n subject: \"the content below\",\n sourceSection: buildFileSourceSection(filePath, content, title),\n cwd,\n outputPath: writePath,\n understandStep: `2. **Understand the content** — analyze the file content to fully understand what needs to be done and why.`,\n titleTemplate: `# <Title>`,\n summaryTemplate: `> <One-line summary: what this achieves and why it matters>`,\n whyLines: [\n `what user or system benefit it provides. Pull from the file content.>`,\n ],\n }).join(\"\\n\");\n}\n\n/**\n * Build a spec prompt from inline text provided directly on the command line.\n *\n * Unlike `buildFileSpecPrompt()`, there is no source file — the user's text\n * serves as both the title and the description. The output-format\n * instructions, spec structure template, (P)/(S) tagging rules, and agent\n * guidelines are identical to those in `buildSpecPrompt()` and\n * `buildFileSpecPrompt()`.\n */\nexport function buildInlineTextSpecPrompt(text: string, cwd: string, outputPath: string): string {\n const title = text.length > 80 ? text.slice(0, 80).trimEnd() + \"…\" : text;\n\n return buildCommonSpecInstructions({\n subject: \"the request below\",\n sourceSection: buildInlineTextSourceSection(title, text),\n cwd,\n outputPath,\n understandStep: `2. **Understand the request** — analyze the inline text to fully understand what needs to be done and why. Since this is a brief description rather than a detailed issue or document, you may need to infer details from the codebase.`,\n titleTemplate: `# <Title>`,\n summaryTemplate: `> <One-line summary: what this achieves and why it matters>`,\n whyLines: [\n `what user or system benefit it provides. Pull from the inline text description.>`,\n ],\n }).join(\"\\n\");\n}\n","/**\n * Shared formatting utilities used across the CLI.\n */\n\nimport chalk from \"chalk\";\n\n/**\n * Format a duration in milliseconds into a human-readable string.\n *\n * Examples:\n * elapsed(0) → \"0s\"\n * elapsed(45000) → \"45s\"\n * elapsed(133000) → \"2m 13s\"\n */\nexport function elapsed(ms: number): string {\n const s = Math.floor(ms / 1000);\n const m = Math.floor(s / 60);\n const sec = s % 60;\n if (m > 0) return `${m}m ${sec}s`;\n return `${sec}s`;\n}\n\n/** Options for the shared header renderer. */\nexport interface HeaderInfo {\n provider?: string;\n model?: string;\n source?: string;\n}\n\n/**\n * Build the standard dispatch header lines used by both the TUI and\n * the spec-generation banner.\n *\n * Returns an array of chalk-formatted strings (one per line).\n * Each metadata field (provider, model, source) is rendered on its own line.\n */\nexport function renderHeaderLines(info: HeaderInfo): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold.white(\" ⚡ dispatch\") + chalk.dim(` — AI task orchestration`));\n if (info.provider) {\n lines.push(chalk.dim(` provider: ${info.provider}`));\n }\n if (info.model) {\n lines.push(chalk.dim(` model: ${info.model}`));\n }\n if (info.source) {\n lines.push(chalk.dim(` source: ${info.source}`));\n }\n return lines;\n}\n","/**\n * Generic retry utility.\n *\n * Provides a reusable `withRetry` wrapper that retries an async function\n * on any thrown error up to a configurable number of times. Used by the\n * dispatch pipeline to add resilience to agent calls.\n */\n\nimport { log } from \"./logger.js\";\n\n/** Options for `withRetry`. */\nexport interface RetryOptions {\n /** Label for log messages identifying the operation being retried. */\n label?: string;\n}\n\n/**\n * Retry an async function up to `maxRetries` times on failure.\n *\n * Calls `fn` and returns its result on the first success. If `fn` throws,\n * it is retried up to `maxRetries` additional times. If all attempts fail,\n * the last error is re-thrown.\n *\n * @param fn - Async function to execute (called with no arguments)\n * @param maxRetries - Number of retry attempts (0 = no retries, 1 = one retry, etc.)\n * @param options - Optional label for log output\n * @returns The resolved value of `fn`\n * @throws The last error if all attempts are exhausted\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n maxRetries: number,\n options?: RetryOptions,\n): Promise<T> {\n const maxAttempts = maxRetries + 1;\n const label = options?.label;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (err) {\n lastError = err;\n const suffix = label ? ` [${label}]` : \"\";\n if (attempt < maxAttempts) {\n log.warn(\n `Attempt ${attempt}/${maxAttempts} failed${suffix}: ${log.extractMessage(err)}`,\n );\n log.debug(`Retrying${suffix} (attempt ${attempt + 1}/${maxAttempts})`);\n }\n }\n }\n\n throw lastError;\n}\n","/**\n * Dispatch pipeline — the core execution pipeline that discovers tasks,\n * optionally plans them via the planner agent, executes them via the\n * executor agent, syncs completion state back to the datasource, and\n * cleans up resources.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { readFile } from \"node:fs/promises\";\nimport { glob } from \"glob\";\nimport { parseTaskFile, buildTaskContext, groupTasksByMode, type TaskFile, type Task } from \"../parser.js\";\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport { boot as bootPlanner, type PlannerAgent } from \"../agents/planner.js\";\nimport type { AgentResult, PlannerData, ExecutorData } from \"../agents/types.js\";\nimport { boot as bootExecutor, type ExecutorAgent } from \"../agents/executor.js\";\nimport { boot as bootCommit, type CommitAgent } from \"../agents/commit.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { registerCleanup } from \"../helpers/cleanup.js\";\nimport { createWorktree, removeWorktree, worktreeName, generateFeatureBranchName } from \"../helpers/worktree.js\";\nimport { isValidBranchName } from \"../helpers/branch-validation.js\";\nimport { createTui, type TuiState } from \"../tui.js\";\nimport type { ProviderName, ProviderInstance } from \"../providers/interface.js\";\nimport { bootProvider } from \"../providers/index.js\";\nimport { getDatasource, getGitRemoteUrl, parseAzDevOpsRemoteUrl, parseGitHubRemoteUrl } from \"../datasources/index.js\";\nimport type { DatasourceName, DispatchLifecycleOptions, IssueDetails, IssueFetchOptions } from \"../datasources/interface.js\";\nimport { getGithubOctokit, getAzureConnection, setAuthPromptHandler } from \"../helpers/auth.js\";\nimport type { OrchestrateRunOptions, DispatchSummary } from \"./runner.js\";\nimport {\n fetchItemsById,\n writeItemsToTempDir,\n parseIssueFilename,\n buildPrBody,\n buildPrTitle,\n buildFeaturePrTitle,\n buildFeaturePrBody,\n getBranchDiff,\n squashBranchCommits,\n} from \"./datasource-helpers.js\";\nimport { withTimeout, TimeoutError } from \"../helpers/timeout.js\";\nimport { withRetry } from \"../helpers/retry.js\";\nimport { isGlobOrFilePath } from \"../spec-generator.js\";\nimport { extractTitle } from \"../datasources/md.js\";\nimport chalk from \"chalk\";\nimport { elapsed, renderHeaderLines } from \"../helpers/format.js\";\nimport { FileLogger, fileLoggerStorage } from \"../helpers/file-logger.js\";\n\nconst exec = promisify(execFile);\n\n/**\n * Expand glob patterns / file paths into IssueDetails[].\n * Mirrors resolveFileItems() from the spec pipeline.\n */\nasync function resolveGlobItems(\n patterns: string[],\n cwd: string,\n): Promise<IssueDetails[]> {\n const files = await glob(patterns, { cwd, absolute: true });\n\n if (files.length === 0) {\n log.warn(`No files matched the pattern(s): ${patterns.join(\", \")}`);\n return [];\n }\n\n log.info(`Matched ${files.length} file(s) from glob pattern(s)`);\n\n const items: IssueDetails[] = [];\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, \"utf-8\");\n const title = extractTitle(content, filePath);\n items.push({\n number: filePath,\n title,\n body: content,\n labels: [],\n state: \"open\",\n url: filePath,\n comments: [],\n acceptanceCriteria: \"\",\n });\n } catch (err) {\n log.warn(`Could not read file ${filePath}: ${log.formatErrorChain(err)}`);\n }\n }\n return items;\n}\n\n/** Default planning timeout in minutes when not specified by the user. */\nconst DEFAULT_PLAN_TIMEOUT_MIN = 10;\n\n/** Default number of planning retries when not specified by the user. */\nconst DEFAULT_PLAN_RETRIES = 1;\n\n/**\n * Run the full dispatch pipeline: discover tasks from a datasource,\n * optionally plan them via the planner agent, execute via the executor\n * agent, sync completion state, and clean up.\n */\nexport async function runDispatchPipeline(\n opts: OrchestrateRunOptions,\n cwd: string,\n): Promise<DispatchSummary> {\n const {\n issueIds,\n concurrency,\n dryRun,\n serverUrl,\n noPlan,\n noBranch: noBranchOpt,\n noWorktree,\n feature,\n provider = \"opencode\",\n model,\n source,\n org,\n project,\n workItemType,\n iteration,\n area,\n planTimeout,\n planRetries,\n retries,\n } = opts;\n let noBranch = noBranchOpt;\n\n // Planning timeout/retry defaults\n const planTimeoutMs = (planTimeout ?? DEFAULT_PLAN_TIMEOUT_MIN) * 60_000;\n const maxPlanAttempts = (planRetries ?? retries ?? DEFAULT_PLAN_RETRIES) + 1; // retries + initial attempt\n\n log.debug(`Plan timeout: ${planTimeout ?? DEFAULT_PLAN_TIMEOUT_MIN}m (${planTimeoutMs}ms), max attempts: ${maxPlanAttempts}`);\n\n // Dry-run mode uses simple log output\n if (dryRun) {\n return dryRunMode(issueIds, cwd, source, org, project, workItemType, iteration, area);\n }\n\n // Pre-authenticate before TUI starts so device codes are visible in the terminal.\n // For cached tokens this is instant; for new auth it runs the device flow\n // while stdout is still free.\n // Validate the remote URL first to fail fast before triggering device auth.\n if (source === \"github\") {\n const remoteUrl = await getGitRemoteUrl(cwd);\n if (remoteUrl && parseGitHubRemoteUrl(remoteUrl)) {\n await getGithubOctokit();\n } else if (!remoteUrl) {\n log.warn(\"No git remote found — skipping GitHub pre-authentication\");\n } else {\n log.warn(\"Remote URL is not a GitHub repository — skipping GitHub pre-authentication\");\n }\n } else if (source === \"azdevops\") {\n let orgUrl = org;\n if (!orgUrl) {\n const remoteUrl = await getGitRemoteUrl(cwd);\n if (remoteUrl) {\n const parsed = parseAzDevOpsRemoteUrl(remoteUrl);\n if (parsed) orgUrl = parsed.orgUrl;\n }\n }\n if (orgUrl) await getAzureConnection(orgUrl);\n }\n\n // ── Start TUI (or inline logging for verbose mode) ──────────\n const verbose = log.verbose;\n let tui: ReturnType<typeof createTui>;\n\n if (verbose) {\n // Print inline header banner (same pattern as spec pipeline)\n const headerLines = renderHeaderLines({ provider, source });\n console.log(\"\");\n for (const line of headerLines) console.log(line);\n console.log(chalk.dim(\" ─\".repeat(24)));\n console.log(\"\");\n log.info(\"Discovering task files...\");\n\n // Silent state container — no animated rendering\n const state: TuiState = {\n tasks: [],\n phase: \"discovering\",\n startTime: Date.now(),\n filesFound: 0,\n provider,\n source,\n };\n tui = { state, update: () => {}, stop: () => {} };\n } else {\n tui = createTui();\n tui.state.provider = provider;\n tui.state.source = source;\n\n // Route auth device-code prompts into the TUI notification banner\n setAuthPromptHandler((msg) => {\n tui.state.notification = msg;\n tui.update();\n });\n }\n\n try {\n // ── 1. Discover task files ──────────────────────────────────\n tui.state.phase = \"discovering\";\n\n if (!source) {\n tui.state.phase = \"done\";\n setAuthPromptHandler(null);\n tui.stop();\n log.error(\"No datasource configured. Use --source or run 'dispatch config' to set up defaults.\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const datasource = getDatasource(source);\n\n // When using the md datasource, git operations are optional — they only\n // work when dispatch is run from inside a git repository. If no repo is\n // found, disable branching so the pipeline can still complete its work.\n if (source === \"md\" && !noBranch) {\n try {\n await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd, shell: process.platform === \"win32\" });\n } catch {\n noBranch = true;\n if (verbose) log.debug(\"No git repository found — skipping git operations for md datasource\");\n }\n }\n\n const fetchOpts: IssueFetchOptions = { cwd, org, project, workItemType, iteration, area };\n let items: IssueDetails[];\n if (issueIds.length > 0 && source === \"md\" && issueIds.some(id => isGlobOrFilePath(id))) {\n items = await resolveGlobItems(issueIds, cwd);\n } else if (issueIds.length > 0) {\n items = await fetchItemsById(issueIds, datasource, fetchOpts);\n } else {\n items = await datasource.list(fetchOpts);\n }\n\n // Auth is complete — clear the notification banner and handler\n tui.state.notification = undefined;\n setAuthPromptHandler(null);\n\n if (items.length === 0) {\n tui.state.phase = \"done\";\n setAuthPromptHandler(null);\n tui.stop();\n const label = issueIds.length > 0 ? `issue(s) ${issueIds.join(\", \")}` : `datasource: ${source}`;\n log.warn(\"No work items found from \" + label);\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const { files, issueDetailsByFile } = await writeItemsToTempDir(items);\n tui.state.filesFound = files.length;\n if (verbose) log.debug(`Found ${files.length} task file(s)`);\n\n // ── 2. Parse all tasks ──────────────────────────────────────\n tui.state.phase = \"parsing\";\n if (verbose) log.info(\"Parsing tasks...\");\n const taskFiles: TaskFile[] = [];\n\n for (const file of files) {\n const tf = await parseTaskFile(file);\n if (tf.tasks.length > 0) {\n taskFiles.push(tf);\n }\n }\n\n const allTasks = taskFiles.flatMap((tf) => tf.tasks);\n\n // Build a lookup from file path → raw content for filtered planner context\n const fileContentMap = new Map<string, string>();\n for (const tf of taskFiles) {\n fileContentMap.set(tf.path, tf.content);\n }\n\n if (allTasks.length === 0) {\n tui.state.phase = \"done\";\n setAuthPromptHandler(null);\n tui.stop();\n log.warn(\"No unchecked tasks found\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n // Populate TUI task list\n tui.state.tasks = allTasks.map((task) => ({\n task,\n status: \"pending\" as const,\n }));\n\n // Group tasks by their source file (each file = one issue)\n const tasksByFile = new Map<string, typeof allTasks>();\n for (const task of allTasks) {\n const list = tasksByFile.get(task.file) ?? [];\n list.push(task);\n tasksByFile.set(task.file, list);\n }\n\n // Determine whether to use worktree-based parallel execution.\n // Worktrees are used when: not opted out, branching is enabled, and\n // there are multiple issues to process (single-issue runs use serial\n // mode to avoid unnecessary worktree overhead).\n const useWorktrees = !noWorktree && (feature || (!noBranch && tasksByFile.size > 1));\n\n // ── 3. Boot provider ────────────────────────────────────────\n tui.state.phase = \"booting\";\n if (verbose) log.info(`Booting ${provider} provider...`);\n if (serverUrl) {\n tui.state.serverUrl = serverUrl;\n }\n if (verbose && serverUrl) log.debug(`Server URL: ${serverUrl}`);\n\n // When using worktrees, providers are booted per-worktree inside\n // processIssueFile. Otherwise, boot a single shared provider.\n let instance: ProviderInstance | undefined;\n let planner: PlannerAgent | null = null;\n let executor: ExecutorAgent | undefined;\n let commitAgent: CommitAgent | undefined;\n\n if (!useWorktrees) {\n instance = await bootProvider(provider, { url: serverUrl, cwd, model });\n registerCleanup(() => instance!.cleanup());\n if (instance.model) {\n tui.state.model = instance.model;\n }\n if (verbose && instance.model) log.debug(`Model: ${instance.model}`);\n\n // ── 4. Boot planner agent (unless --no-plan) ────────────────\n planner = noPlan ? null : await bootPlanner({ provider: instance, cwd });\n executor = await bootExecutor({ provider: instance, cwd });\n commitAgent = await bootCommit({ provider: instance, cwd });\n }\n\n // ── 5. Dispatch tasks ───────────────────────────────────────\n tui.state.phase = \"dispatching\";\n if (verbose) log.info(`Dispatching ${allTasks.length} task(s)...`);\n const results: DispatchResult[] = [];\n let completed = 0;\n let failed = 0;\n\n const lifecycleOpts: DispatchLifecycleOptions = { cwd };\n\n // ── Capture the branch the user is currently on ────────────────\n // This is used as the base for new branches, PR targets, and the\n // branch to return to after completion. When the user is on main\n // this naturally resolves to main; when on release/1.4.3 it uses\n // that branch instead.\n const startingBranch = await datasource.getCurrentBranch(lifecycleOpts);\n\n // ── Feature-branch setup (when --feature) ──────────────────────\n let featureBranchName: string | undefined;\n let featureDefaultBranch: string | undefined;\n\n if (feature) {\n // Resolve the feature branch name\n if (typeof feature === \"string\") {\n if (!isValidBranchName(feature)) {\n log.error(`Invalid feature branch name: \"${feature}\"`);\n tui.state.phase = \"done\";\n tui.stop();\n return { total: allTasks.length, completed: 0, failed: allTasks.length, skipped: 0, results: [] };\n }\n featureBranchName = feature.includes(\"/\") ? feature : `dispatch/${feature}`;\n } else {\n featureBranchName = generateFeatureBranchName();\n }\n\n try {\n featureDefaultBranch = startingBranch;\n\n // Ensure we are on the starting branch so the feature branch starts from the correct commit\n await datasource.switchBranch(featureDefaultBranch, lifecycleOpts);\n\n // Create the feature branch from the starting branch (or switch to it if it already exists)\n try {\n await datasource.createAndSwitchBranch(featureBranchName, lifecycleOpts);\n log.debug(`Created feature branch ${featureBranchName} from ${featureDefaultBranch}`);\n } catch (createErr) {\n const message = log.extractMessage(createErr);\n if (message.includes(\"already exists\")) {\n await datasource.switchBranch(featureBranchName, lifecycleOpts);\n log.debug(`Switched to existing feature branch ${featureBranchName}`);\n } else {\n throw createErr;\n }\n }\n\n // Register cleanup for the feature branch\n registerCleanup(async () => {\n try {\n await datasource.switchBranch(featureDefaultBranch!, lifecycleOpts);\n } catch { /* swallow */ }\n });\n\n // Switch back to starting branch so worktrees can be created from the main repo\n await datasource.switchBranch(featureDefaultBranch, lifecycleOpts);\n log.debug(`Switched back to ${featureDefaultBranch} for worktree creation`);\n } catch (err) {\n log.error(`Feature branch creation failed: ${log.extractMessage(err)}`);\n tui.state.phase = \"done\";\n tui.stop();\n return { total: allTasks.length, completed: 0, failed: allTasks.length, skipped: 0, results: [] };\n }\n }\n\n // Resolve git username once for branch naming\n let username = \"\";\n try {\n username = await datasource.getUsername(lifecycleOpts);\n } catch (err) {\n log.warn(`Could not resolve git username for branch naming: ${log.formatErrorChain(err)}`);\n }\n\n // Process a single issue file's tasks — handles both worktree and\n // serial branch modes, parameterised by useWorktrees.\n const processIssueFile = async (file: string, fileTasks: typeof allTasks) => {\n const details = issueDetailsByFile.get(file);\n const fileLogger = verbose && details ? new FileLogger(details.number, cwd) : null;\n\n const body = async () => {\n let defaultBranch: string | undefined;\n let branchName: string | undefined;\n let worktreePath: string | undefined;\n let issueCwd = cwd;\n\n // ── Branch / worktree setup (unless --no-branch) ────────────\n if (!noBranch && details) {\n fileLogger?.phase(\"Branch/worktree setup\");\n try {\n defaultBranch = feature ? featureBranchName! : startingBranch;\n branchName = datasource.buildBranchName(details.number, details.title, username);\n\n if (useWorktrees) {\n worktreePath = await createWorktree(cwd, file, branchName, ...(feature && featureBranchName ? [featureBranchName] : []));\n registerCleanup(async () => { await removeWorktree(cwd, file); });\n issueCwd = worktreePath;\n log.debug(`Created worktree for issue #${details.number} at ${worktreePath}`);\n fileLogger?.info(`Worktree created at ${worktreePath}`);\n\n // Tag TUI tasks with worktree name for display\n const wtName = worktreeName(file);\n for (const task of fileTasks) {\n const tuiTask = tui.state.tasks.find((t) => t.task === task);\n if (tuiTask) tuiTask.worktree = wtName;\n }\n } else if (datasource.supportsGit()) {\n await datasource.createAndSwitchBranch(branchName, lifecycleOpts);\n log.debug(`Switched to branch ${branchName}`);\n fileLogger?.info(`Switched to branch ${branchName}`);\n }\n } catch (err) {\n const errorMsg = `Branch creation failed for issue #${details.number}: ${log.extractMessage(err)}`;\n fileLogger?.error(`Branch creation failed: ${log.extractMessage(err)}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n log.error(errorMsg);\n for (const task of fileTasks) {\n const tuiTask = tui.state.tasks.find((t) => t.task === task);\n if (tuiTask) {\n tuiTask.status = \"failed\";\n tuiTask.error = errorMsg;\n }\n results.push({ task, success: false, error: errorMsg });\n }\n failed += fileTasks.length;\n return;\n }\n }\n\n const worktreeRoot = useWorktrees ? worktreePath : undefined;\n const issueLifecycleOpts: DispatchLifecycleOptions = { cwd: issueCwd };\n\n // ── Boot per-worktree provider and agents (or use shared ones) ──\n fileLogger?.phase(\"Provider/agent boot\");\n let localInstance: ProviderInstance;\n let localPlanner: PlannerAgent | null;\n let localExecutor: ExecutorAgent;\n let localCommitAgent: CommitAgent;\n\n if (useWorktrees) {\n localInstance = await bootProvider(provider, { url: serverUrl, cwd: issueCwd, model });\n registerCleanup(() => localInstance.cleanup());\n if (localInstance.model && !tui.state.model) {\n tui.state.model = localInstance.model;\n }\n if (verbose && localInstance.model) log.debug(`Model: ${localInstance.model}`);\n localPlanner = noPlan ? null : await bootPlanner({ provider: localInstance, cwd: issueCwd });\n localExecutor = await bootExecutor({ provider: localInstance, cwd: issueCwd });\n localCommitAgent = await bootCommit({ provider: localInstance, cwd: issueCwd });\n fileLogger?.info(`Provider booted: ${localInstance.model ?? provider}`);\n } else {\n localInstance = instance!;\n localPlanner = planner;\n localExecutor = executor!;\n localCommitAgent = commitAgent!;\n }\n\n // ── Dispatch file's tasks ─────────────────────────────────\n const groups = groupTasksByMode(fileTasks);\n const issueResults: DispatchResult[] = [];\n\n for (const group of groups) {\n const groupQueue = [...group];\n\n while (groupQueue.length > 0) {\n const batch = groupQueue.splice(0, concurrency);\n const batchResults = await Promise.all(\n batch.map(async (task) => {\n const tuiTask = tui.state.tasks.find((t) => t.task === task)!;\n const startTime = Date.now();\n tuiTask.elapsed = startTime;\n\n // ── Phase A: Plan (unless --no-plan) ─────────────────\n let plan: string | undefined;\n if (localPlanner) {\n tuiTask.status = \"planning\";\n fileLogger?.phase(`Planning task: ${task.text}`);\n if (verbose) log.info(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: planning — \"${task.text}\"`);\n const rawContent = fileContentMap.get(task.file);\n const fileContext = rawContent ? buildTaskContext(rawContent, task) : undefined;\n\n let planResult: AgentResult<PlannerData> | undefined;\n\n for (let attempt = 1; attempt <= maxPlanAttempts; attempt++) {\n try {\n planResult = await withTimeout(\n localPlanner.plan(task, fileContext, issueCwd, worktreeRoot),\n planTimeoutMs,\n \"planner.plan()\",\n );\n break; // success — exit retry loop\n } catch (err) {\n if (err instanceof TimeoutError) {\n log.warn(\n `Planning timed out for task \"${task.text}\" (attempt ${attempt}/${maxPlanAttempts})`,\n );\n fileLogger?.warn(`Planning timeout (attempt ${attempt}/${maxPlanAttempts})`);\n if (attempt < maxPlanAttempts) {\n log.debug(`Retrying planning (attempt ${attempt + 1}/${maxPlanAttempts})`);\n fileLogger?.info(`Retrying planning (attempt ${attempt + 1}/${maxPlanAttempts})`);\n }\n } else {\n // Non-timeout error — do not retry, surface immediately\n planResult = {\n data: null,\n success: false,\n error: log.extractMessage(err),\n durationMs: 0,\n };\n break;\n }\n }\n }\n\n // All attempts exhausted with timeout — produce failure result\n if (!planResult) {\n const timeoutMin = planTimeout ?? 10;\n planResult = {\n data: null,\n success: false,\n error: `Planning timed out after ${timeoutMin}m (${maxPlanAttempts} attempts)`,\n durationMs: 0,\n };\n }\n\n if (!planResult.success) {\n tuiTask.status = \"failed\";\n tuiTask.error = `Planning failed: ${planResult.error}`;\n fileLogger?.error(`Planning failed: ${planResult.error}`);\n tuiTask.elapsed = Date.now() - startTime;\n if (verbose) log.error(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: failed — ${tuiTask.error} (${elapsed(tuiTask.elapsed)})`);\n failed++;\n return { task, success: false, error: tuiTask.error } as DispatchResult;\n }\n\n plan = planResult.data.prompt;\n fileLogger?.info(`Planning completed (${planResult.durationMs ?? 0}ms)`);\n }\n\n // ── Phase B: Execute via executor agent ──────────────\n tuiTask.status = \"running\";\n fileLogger?.phase(`Executing task: ${task.text}`);\n if (verbose) log.info(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: executing — \"${task.text}\"`);\n const execRetries = 2;\n const execResult = await withRetry(\n async () => {\n const result = await localExecutor.execute({\n task,\n cwd: issueCwd,\n plan: plan ?? null,\n worktreeRoot,\n });\n if (!result.success) {\n throw new Error(result.error ?? \"Execution failed\");\n }\n return result;\n },\n execRetries,\n { label: `executor \"${task.text}\"` },\n ).catch((err): AgentResult<ExecutorData> => ({\n data: null,\n success: false,\n error: log.extractMessage(err),\n durationMs: 0,\n }));\n\n if (execResult.success) {\n fileLogger?.info(`Execution completed successfully (${Date.now() - startTime}ms)`);\n // Sync checked-off state back to the datasource\n try {\n const parsed = parseIssueFilename(task.file);\n const updatedContent = await readFile(task.file, \"utf-8\");\n if (parsed) {\n const issueDetails = issueDetailsByFile.get(task.file);\n const title = issueDetails?.title ?? parsed.slug;\n await datasource.update(parsed.issueId, title, updatedContent, fetchOpts);\n log.success(`Synced task completion to issue #${parsed.issueId}`);\n } else {\n const issueDetails = issueDetailsByFile.get(task.file);\n if (issueDetails) {\n await datasource.update(issueDetails.number, issueDetails.title, updatedContent, fetchOpts);\n log.success(`Synced task completion to issue #${issueDetails.number}`);\n }\n }\n } catch (err) {\n log.warn(`Could not sync task completion to datasource: ${log.formatErrorChain(err)}`);\n }\n\n tuiTask.status = \"done\";\n tuiTask.elapsed = Date.now() - startTime;\n if (verbose) log.success(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: done — \"${task.text}\" (${elapsed(tuiTask.elapsed)})`);\n completed++;\n } else {\n fileLogger?.error(`Execution failed: ${execResult.error}`);\n tuiTask.status = \"failed\";\n tuiTask.error = execResult.error;\n tuiTask.elapsed = Date.now() - startTime;\n if (verbose) log.error(`Task #${tui.state.tasks.indexOf(tuiTask) + 1}: failed — \"${task.text}\" (${elapsed(tuiTask.elapsed)})${tuiTask.error ? `: ${tuiTask.error}` : \"\"}`);\n failed++;\n }\n\n const dispatchResult: DispatchResult = execResult.success\n ? execResult.data.dispatchResult\n : {\n task,\n success: false,\n error: execResult.error ?? \"Executor failed without returning a dispatch result.\",\n };\n return dispatchResult;\n })\n );\n\n issueResults.push(...batchResults);\n\n // Update TUI once the provider detects the actual model (lazy detection)\n if (!tui.state.model && localInstance.model) {\n tui.state.model = localInstance.model;\n }\n }\n }\n\n results.push(...issueResults);\n\n // ── Safety-net commit (stage any uncommitted changes) ─────\n if (!noBranch && branchName && defaultBranch && details && datasource.supportsGit()) {\n try {\n await datasource.commitAllChanges(\n `chore: stage uncommitted changes for issue #${details.number}`,\n issueLifecycleOpts,\n );\n log.debug(`Staged uncommitted changes for issue #${details.number}`);\n } catch (err) {\n log.warn(`Could not commit uncommitted changes for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n }\n\n // ── Commit agent (rewrite commits + generate PR metadata) ───\n fileLogger?.phase(\"Commit generation\");\n let commitAgentResult: import(\"../agents/commit.js\").CommitResult | undefined;\n if (!noBranch && branchName && defaultBranch && details && datasource.supportsGit()) {\n try {\n const branchDiff = await getBranchDiff(defaultBranch, issueCwd);\n if (branchDiff) {\n const result = await localCommitAgent.generate({\n branchDiff,\n issue: details,\n taskResults: issueResults,\n cwd: issueCwd,\n worktreeRoot,\n });\n if (result.success) {\n commitAgentResult = result;\n fileLogger?.info(`Commit message generated for issue #${details.number}`);\n // Rewrite commit history with the generated message\n try {\n await squashBranchCommits(defaultBranch, result.commitMessage, issueCwd);\n log.debug(`Rewrote commit message for issue #${details.number}`);\n fileLogger?.info(`Rewrote commit history for issue #${details.number}`);\n } catch (err) {\n log.warn(`Could not rewrite commit message for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n } else {\n log.warn(`Commit agent failed for issue #${details.number}: ${result.error}`);\n fileLogger?.warn(`Commit agent failed: ${result.error}`);\n }\n }\n } catch (err) {\n log.warn(`Commit agent error for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n }\n\n // ── Branch teardown (push, PR, cleanup) ──────────────────\n fileLogger?.phase(\"PR lifecycle\");\n if (!noBranch && branchName && defaultBranch && details) {\n if (feature && featureBranchName) {\n // ── Feature mode: merge working branch into feature branch ──\n if (worktreePath) {\n try {\n await removeWorktree(cwd, file);\n } catch (err) {\n log.warn(`Could not remove worktree for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n }\n\n try {\n await datasource.switchBranch(featureBranchName, lifecycleOpts);\n await exec(\"git\", [\"merge\", branchName, \"--no-ff\", \"-m\", `merge: issue #${details.number}`], { cwd, shell: process.platform === \"win32\" });\n log.debug(`Merged ${branchName} into ${featureBranchName}`);\n } catch (err) {\n const mergeError = `Could not merge ${branchName} into feature branch: ${log.formatErrorChain(err)}`;\n log.warn(mergeError);\n // Abort the failed merge so the repo is left in a clean state\n try {\n await exec(\"git\", [\"merge\", \"--abort\"], { cwd, shell: process.platform === \"win32\" });\n } catch { /* merge --abort may fail if there's nothing to abort */ }\n // Record every task in this issue as failed\n for (const task of fileTasks) {\n const tuiTask = tui.state.tasks.find((t) => t.task === task);\n if (tuiTask) {\n tuiTask.status = \"failed\";\n tuiTask.error = mergeError;\n }\n const existingResult = results.find((r) => r.task === task);\n if (existingResult) {\n existingResult.success = false;\n existingResult.error = mergeError;\n }\n }\n return;\n }\n\n try {\n await exec(\"git\", [\"branch\", \"-d\", branchName], { cwd, shell: process.platform === \"win32\" });\n log.debug(`Deleted local branch ${branchName}`);\n } catch (err) {\n log.warn(`Could not delete local branch ${branchName}: ${log.formatErrorChain(err)}`);\n }\n\n try {\n await datasource.switchBranch(featureDefaultBranch!, lifecycleOpts);\n } catch (err) {\n log.warn(`Could not switch back to ${featureDefaultBranch}: ${log.formatErrorChain(err)}`);\n }\n } else {\n // ── Normal mode: push and create per-issue PR ──\n if (datasource.supportsGit()) {\n try {\n await datasource.pushBranch(branchName, issueLifecycleOpts);\n log.debug(`Pushed branch ${branchName}`);\n fileLogger?.info(`Pushed branch ${branchName}`);\n } catch (err) {\n log.warn(`Could not push branch ${branchName}: ${log.formatErrorChain(err)}`);\n }\n }\n\n if (datasource.supportsGit()) {\n try {\n const prTitle = commitAgentResult?.prTitle\n || await buildPrTitle(details.title, defaultBranch, issueLifecycleOpts.cwd);\n const prBody = commitAgentResult?.prDescription\n || await buildPrBody(\n details,\n fileTasks,\n issueResults,\n defaultBranch,\n datasource.name,\n issueLifecycleOpts.cwd,\n );\n const prUrl = await datasource.createPullRequest(\n branchName,\n details.number,\n prTitle,\n prBody,\n issueLifecycleOpts,\n startingBranch,\n );\n if (prUrl) {\n log.success(`Created PR for issue #${details.number}: ${prUrl}`);\n fileLogger?.info(`Created PR: ${prUrl}`);\n }\n } catch (err) {\n log.warn(`Could not create PR for issue #${details.number}: ${log.formatErrorChain(err)}`);\n fileLogger?.warn(`PR creation failed: ${log.extractMessage(err)}`);\n }\n }\n\n if (useWorktrees && worktreePath) {\n try {\n await removeWorktree(cwd, file);\n } catch (err) {\n log.warn(`Could not remove worktree for issue #${details.number}: ${log.formatErrorChain(err)}`);\n }\n } else if (!useWorktrees && datasource.supportsGit()) {\n try {\n await datasource.switchBranch(defaultBranch, lifecycleOpts);\n log.debug(`Switched back to ${defaultBranch}`);\n } catch (err) {\n log.warn(`Could not switch back to ${defaultBranch}: ${log.formatErrorChain(err)}`);\n }\n }\n }\n }\n\n // ── Per-worktree resource cleanup ───────────────────────────\n fileLogger?.phase(\"Resource cleanup\");\n if (useWorktrees) {\n await localExecutor.cleanup();\n await localPlanner?.cleanup();\n await localInstance.cleanup();\n }\n };\n\n if (fileLogger) {\n await fileLoggerStorage.run(fileLogger, async () => {\n try {\n await body();\n } finally {\n fileLogger.close();\n }\n });\n } else {\n await body();\n }\n };\n\n // Execute issues: parallel via worktrees, or serial fallback\n // Feature mode forces serial execution to avoid merge conflicts\n if (useWorktrees && !feature) {\n await Promise.all(\n Array.from(tasksByFile).map(([file, fileTasks]) =>\n processIssueFile(file, fileTasks)\n )\n );\n } else {\n for (const [file, fileTasks] of tasksByFile) {\n await processIssueFile(file, fileTasks);\n }\n }\n\n // ── Feature branch finalization (push + aggregated PR) ──────\n if (feature && featureBranchName && featureDefaultBranch) {\n try {\n await datasource.switchBranch(featureBranchName, lifecycleOpts);\n log.debug(`Switched to feature branch ${featureBranchName}`);\n } catch (err) {\n log.warn(`Could not switch to feature branch: ${log.formatErrorChain(err)}`);\n }\n\n try {\n await datasource.pushBranch(featureBranchName, lifecycleOpts);\n log.debug(`Pushed feature branch ${featureBranchName}`);\n } catch (err) {\n log.warn(`Could not push feature branch: ${log.formatErrorChain(err)}`);\n }\n\n try {\n const allIssueDetails = Array.from(issueDetailsByFile.values());\n const prTitle = buildFeaturePrTitle(featureBranchName, allIssueDetails);\n const prBody = buildFeaturePrBody(allIssueDetails, allTasks, results, source!);\n const primaryIssue = allIssueDetails[0]?.number ?? \"\";\n const prUrl = await datasource.createPullRequest(\n featureBranchName,\n primaryIssue,\n prTitle,\n prBody,\n lifecycleOpts,\n startingBranch,\n );\n if (prUrl) {\n log.success(`Created feature PR: ${prUrl}`);\n }\n } catch (err) {\n log.warn(`Could not create feature PR: ${log.formatErrorChain(err)}`);\n }\n\n try {\n await datasource.switchBranch(featureDefaultBranch, lifecycleOpts);\n } catch (err) {\n log.warn(`Could not switch back to ${featureDefaultBranch}: ${log.formatErrorChain(err)}`);\n }\n }\n\n // ── 6. Cleanup ──────────────────────────────────────────────\n // Per-worktree resources are cleaned up inside processIssueFile.\n // Shared resources (when !useWorktrees) are cleaned up here.\n await commitAgent?.cleanup();\n await executor?.cleanup();\n await planner?.cleanup();\n await instance?.cleanup();\n\n tui.state.phase = \"done\";\n tui.stop();\n if (verbose) log.success(`Done — ${completed} completed, ${failed} failed (${elapsed(Date.now() - tui.state.startTime)})`);\n\n return { total: allTasks.length, completed, failed, skipped: 0, results };\n } catch (err) {\n setAuthPromptHandler(null);\n tui.stop();\n throw err;\n }\n}\n\n/**\n * Dry-run mode — discovers and parses tasks, logs them, but does not\n * execute anything.\n */\nexport async function dryRunMode(\n issueIds: string[],\n cwd: string,\n source?: DatasourceName,\n org?: string,\n project?: string,\n workItemType?: string,\n iteration?: string,\n area?: string,\n): Promise<DispatchSummary> {\n if (!source) {\n log.error(\"No datasource configured. Use --source or run 'dispatch config' to set up defaults.\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const datasource = getDatasource(source);\n const fetchOpts: IssueFetchOptions = { cwd, org, project, workItemType, iteration, area };\n\n const lifecycleOpts = { cwd };\n let username = \"\";\n try {\n username = await datasource.getUsername(lifecycleOpts);\n } catch {\n // Fall back to empty prefix if username resolution fails\n }\n\n let items: IssueDetails[];\n if (issueIds.length > 0 && source === \"md\" && issueIds.some(id => isGlobOrFilePath(id))) {\n items = await resolveGlobItems(issueIds, cwd);\n } else if (issueIds.length > 0) {\n items = await fetchItemsById(issueIds, datasource, fetchOpts);\n } else {\n items = await datasource.list(fetchOpts);\n }\n\n if (items.length === 0) {\n const label = issueIds.length > 0 ? `issue(s) ${issueIds.join(\", \")}` : `datasource: ${source}`;\n log.warn(\"No work items found from \" + label);\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n const { files, issueDetailsByFile } = await writeItemsToTempDir(items);\n\n const taskFiles: TaskFile[] = [];\n for (const file of files) {\n const tf = await parseTaskFile(file);\n if (tf.tasks.length > 0) {\n taskFiles.push(tf);\n }\n }\n\n const allTasks = taskFiles.flatMap((tf) => tf.tasks);\n\n if (allTasks.length === 0) {\n log.warn(\"No unchecked tasks found\");\n return { total: 0, completed: 0, failed: 0, skipped: 0, results: [] };\n }\n\n log.info(`Dry run — ${allTasks.length} task(s) across ${taskFiles.length} file(s):\\n`);\n for (const task of allTasks) {\n const parsed = parseIssueFilename(task.file);\n const details = parsed\n ? items.find((item) => item.number === parsed.issueId)\n : issueDetailsByFile.get(task.file);\n const branchInfo = details\n ? ` [branch: ${datasource.buildBranchName(details.number, details.title, username)}]`\n : \"\";\n log.task(allTasks.indexOf(task), allTasks.length, `${task.file}:${task.line} — ${task.text}${branchInfo}`);\n }\n\n return {\n total: allTasks.length,\n completed: 0,\n failed: 0,\n skipped: allTasks.length,\n results: [],\n };\n}\n","/**\n * Markdown task parser — extracts unchecked `[ ]` tasks from markdown files\n * and provides utilities to mark them as complete `[x]`.\n *\n * Non-task content (headings, prose, notes) is preserved in `TaskFile.context`\n * so the planner agent can use it for implementation guidance.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\n\nexport interface Task {\n /** Zero-based index within the file */\n index: number;\n /** The raw text after `- [ ] `, with any (P)/(S) prefix stripped */\n text: string;\n /** Line number in the file (1-based) */\n line: number;\n /** Full original line content */\n raw: string;\n /** The source file path */\n file: string;\n /** Execution mode — \"parallel\", \"serial\", or \"isolated\". Defaults to \"serial\" when unspecified. */\n mode?: \"parallel\" | \"serial\" | \"isolated\";\n}\n\nexport interface TaskFile {\n path: string;\n tasks: Task[];\n /** Full file content — includes non-task prose, headings, and notes */\n content: string;\n}\n\n/** Matches an unchecked markdown task item, e.g. `- [ ] Implement feature` */\nconst UNCHECKED_RE = /^(\\s*[-*]\\s)\\[ \\]\\s+(.+)$/;\n/** Matches a checked markdown task item, e.g. `- [x] Implement feature` */\nconst CHECKED_RE = /^(\\s*[-*]\\s)\\[[xX]\\]\\s+/;\n/** Replacement string used with UNCHECKED_RE to mark a task complete, e.g. `- [ ] task` → `- [x] task` */\nconst CHECKED_SUB = \"$1[x] $2\";\n/** Matches a mode prefix at the start of task text, e.g. `(P) Run tests in parallel` */\nconst MODE_PREFIX_RE = /^\\(([PSI])\\)\\s+/;\n\n/**\n * Build a filtered view of the file content for a single task's planner context.\n * Keeps:\n * - All non-task lines (headings, prose, notes, blank lines, checked tasks)\n * - The specific unchecked task line being planned\n * Removes:\n * - All *other* unchecked `[ ]` task lines\n *\n * This prevents the planner (and downstream executor) from being confused\n * by sibling tasks that belong to different agents.\n */\nexport function buildTaskContext(content: string, task: Task): string {\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n\n const filtered = lines.filter((line, i) => {\n // Always keep the line that matches the current task\n if (i + 1 === task.line) return true;\n // Remove other unchecked task lines\n if (UNCHECKED_RE.test(line)) return false;\n // Keep everything else (headings, prose, checked tasks, blank lines)\n return true;\n });\n\n return filtered.join(\"\\n\");\n}\n\n/**\n * Parse markdown content (string) and return all unchecked tasks.\n * Pure function — no file I/O. Useful for testing and reuse.\n */\nexport function parseTaskContent(content: string, filePath: string): TaskFile {\n // Normalize CRLF → LF so the regex anchors work consistently\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n const tasks: Task[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const match = lines[i].match(UNCHECKED_RE);\n if (match) {\n let text = match[2].trim();\n let mode: \"parallel\" | \"serial\" | \"isolated\" = \"serial\";\n\n const modeMatch = text.match(MODE_PREFIX_RE);\n if (modeMatch) {\n const modeMap: Record<string, \"parallel\" | \"serial\" | \"isolated\"> = {\n P: \"parallel\",\n S: \"serial\",\n I: \"isolated\",\n };\n mode = modeMap[modeMatch[1]] ?? \"serial\";\n text = text.slice(modeMatch[0].length);\n }\n\n tasks.push({\n index: tasks.length,\n text,\n line: i + 1,\n raw: lines[i],\n file: filePath,\n mode,\n });\n }\n }\n\n return { path: filePath, tasks, content };\n}\n\n/**\n * Parse a single markdown file and return all unchecked tasks.\n */\nexport async function parseTaskFile(filePath: string): Promise<TaskFile> {\n const content = await readFile(filePath, \"utf-8\");\n return parseTaskContent(content, filePath);\n}\n\n/**\n * Mark a specific task as complete in its source file by replacing `[ ]` with `[x]`.\n */\nexport async function markTaskComplete(task: Task): Promise<void> {\n const content = await readFile(task.file, \"utf-8\");\n const eol = content.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n const lineIndex = task.line - 1;\n\n if (lineIndex < 0 || lineIndex >= lines.length) {\n throw new Error(\n `Line ${task.line} out of range in ${task.file} (${lines.length} lines)`\n );\n }\n\n const original = lines[lineIndex];\n const updated = original.replace(UNCHECKED_RE, CHECKED_SUB);\n\n if (original === updated) {\n throw new Error(\n `Line ${task.line} in ${task.file} does not match expected unchecked pattern: \"${original}\"`\n );\n }\n\n lines[lineIndex] = updated;\n await writeFile(task.file, lines.join(eol), \"utf-8\");\n}\n\n/**\n * Group a flat task list into ordered execution groups.\n *\n * - Consecutive parallel tasks accumulate into the current group.\n * - A serial task caps the current group (is appended to it), then a new group begins.\n * - A lone serial task (no preceding parallel tasks) forms a solo group.\n * - An isolated task flushes the current group (if non-empty) as its own group,\n * then creates a solo group containing only the isolated task, then resets\n * the accumulator. This guarantees the isolated task runs alone.\n *\n * The orchestrator runs each group concurrently, waiting for the group to\n * complete before starting the next one.\n */\nexport function groupTasksByMode(tasks: Task[]): Task[][] {\n if (tasks.length === 0) return [];\n\n const groups: Task[][] = [];\n let current: Task[] = [];\n\n for (const task of tasks) {\n const mode = task.mode ?? \"serial\";\n\n if (mode === \"parallel\") {\n current.push(task);\n } else if (mode === \"isolated\") {\n // Flush accumulated tasks as their own group\n if (current.length > 0) {\n groups.push(current);\n current = [];\n }\n // Push a solo group for the isolated task\n groups.push([task]);\n } else {\n // Serial task caps the current group\n current.push(task);\n groups.push(current);\n current = [];\n }\n }\n\n // Flush any remaining parallel tasks that weren't capped by a serial task\n if (current.length > 0) {\n groups.push(current);\n }\n\n return groups;\n}\n","/**\n * Planner agent — explores the codebase and researches the implementation\n * for a task, then produces a focused system prompt for the executor agent.\n *\n * The planner runs in its own session with read-only intent: it reads files,\n * searches symbols, and reasons about the task without making any changes.\n * Its output is a rich, context-aware prompt that the executor can follow\n * to make precise edits.\n */\n\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { Task } from \"../parser.js\";\nimport type { AgentResult, PlannerData } from \"./types.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/**\n * A booted planner agent that can produce execution plans for tasks.\n *\n * To add a new planner implementation:\n * 1. Create `src/agents/<name>.ts`\n * 2. Export an async `boot` function that returns a `PlannerAgent`\n * 3. Register it in `src/agents/index.ts`\n */\nexport interface PlannerAgent extends Agent {\n /**\n * Run the planner for a single task. Creates an isolated session,\n * sends the planning prompt, and extracts the resulting execution plan.\n *\n * When `fileContext` is provided (filtered markdown from the task file),\n * it is included so the planner can use non-task prose (headings, notes,\n * implementation details) as additional guidance.\n *\n * When `cwd` is provided, it overrides the boot-time working directory\n * in the planning prompt — use this for worktree tasks.\n *\n * When `worktreeRoot` is provided, the prompt includes directory-restriction\n * instructions that confine the agent to that worktree directory.\n */\n plan(task: Task, fileContext?: string, cwd?: string, worktreeRoot?: string): Promise<AgentResult<PlannerData>>;\n}\n\n/**\n * Boot a planner agent backed by the given provider.\n *\n * @throws if `opts.provider` is not supplied — the planner requires a\n * provider to create sessions and send prompts.\n */\nexport async function boot(opts: AgentBootOptions): Promise<PlannerAgent> {\n const { provider, cwd } = opts;\n\n if (!provider) {\n throw new Error(\"Planner agent requires a provider instance in boot options\");\n }\n\n return {\n name: \"planner\",\n\n async plan(task: Task, fileContext?: string, cwdOverride?: string, worktreeRoot?: string): Promise<AgentResult<PlannerData>> {\n const startTime = Date.now();\n try {\n const sessionId = await provider.createSession();\n const prompt = buildPlannerPrompt(task, cwdOverride ?? cwd, fileContext, worktreeRoot);\n fileLoggerStorage.getStore()?.prompt(\"planner\", prompt);\n\n const plan = await provider.prompt(sessionId, prompt);\n if (plan) fileLoggerStorage.getStore()?.response(\"planner\", plan);\n\n if (!plan?.trim()) {\n return { data: null, success: false, error: \"Planner returned empty plan\", durationMs: Date.now() - startTime };\n }\n\n fileLoggerStorage.getStore()?.agentEvent(\"planner\", \"completed\", `${Date.now() - startTime}ms`);\n return { data: { prompt: plan }, success: true, durationMs: Date.now() - startTime };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`planner error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return { data: null, success: false, error: message, durationMs: Date.now() - startTime };\n }\n },\n\n async cleanup(): Promise<void> {\n // Planner has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n\n/**\n * Build the prompt that instructs the planner to explore the codebase,\n * understand the task, and produce an execution plan.\n *\n * When file context is provided, it is included as a \"Task File Contents\"\n * section so the planner can use headings, prose, and notes from the\n * markdown file as implementation guidance.\n *\n * When `worktreeRoot` is provided, directory-restriction instructions are\n * appended to confine all agent operations within the worktree boundary.\n */\nfunction buildPlannerPrompt(task: Task, cwd: string, fileContext?: string, worktreeRoot?: string): string {\n const sections: string[] = [\n `You are a **planning agent**. Your job is to explore the codebase, understand the task below, and produce a detailed execution prompt that another agent will follow to implement the changes.`,\n ``,\n `## Task`,\n `- **Working directory:** ${cwd}`,\n `- **Source file:** ${task.file}`,\n `- **Task (line ${task.line}):** ${task.text}`,\n ];\n\n if (fileContext) {\n sections.push(\n ``,\n `## Task File Contents`,\n ``,\n `The task comes from a markdown file that may contain important implementation`,\n `details, requirements, and context in its non-task content (headings, prose,`,\n `notes). Review this carefully — it may describe conventions, constraints, or`,\n `technical details that are critical for the implementation.`,\n ``,\n `\\`\\`\\`markdown`,\n fileContext,\n `\\`\\`\\``,\n );\n }\n\n if (worktreeRoot) {\n sections.push(\n ``,\n `## Worktree Isolation`,\n ``,\n `You are operating inside a git worktree. All file operations MUST be confined`,\n `to the following directory tree:`,\n ``,\n ` ${worktreeRoot}`,\n ``,\n `- Do NOT read, write, or execute commands that access files outside this directory.`,\n `- Do NOT reference or modify files in the main repository working tree or other worktrees.`,\n `- All relative paths must resolve within the worktree root above.`,\n );\n }\n\n sections.push(\n ``,\n formatEnvironmentPrompt(),\n );\n\n sections.push(\n ``,\n `## Instructions`,\n ``,\n `1. **Explore the codebase** — read relevant files, search for symbols, and understand the project structure, conventions, and patterns.`,\n `2. **Review the task file contents above** — pay close attention to non-task text (headings, prose, notes) as it often contains important implementation details, requirements, and constraints.`,\n `3. **Identify the files** that need to be created or modified to complete this task.`,\n `4. **Research the implementation** — understand the existing code patterns, imports, types, and APIs involved.`,\n `5. **DO NOT make any changes** — you are only planning, not executing.`,\n ``,\n `## Output Format`,\n ``,\n `Produce your response as a **system prompt for an executor agent**. The executor will receive your output verbatim as its instructions. Write it in second person (\"You will...\", \"Modify the file...\").`,\n ``,\n `Your output MUST include:`,\n ``,\n `1. **Context** — A brief summary of the relevant project structure, conventions, and patterns the executor needs to know. Include any important details from the task file's non-task content.`,\n `2. **Files to modify** — The exact file paths that need to be created or changed, with the rationale for each.`,\n `3. **Step-by-step implementation** — Precise, ordered steps the executor should follow. Include:`,\n ` - Exact file paths`,\n ` - What to add, change, or remove`,\n ` - Code snippets, type signatures, or patterns to follow (based on existing code you read)`,\n ` - Import statements needed`,\n `4. **Constraints** — Any important constraints:`,\n ` - If the task description includes a commit instruction, include a final step in the plan to commit the changes using conventional commit conventions (supported types: feat, fix, docs, refactor, test, chore, style, perf, ci). If the task does not mention committing, instruct the executor to NOT commit changes.`,\n ` - Make minimal, correct changes — do not refactor unrelated code.`,\n ` - Follow existing code style and conventions found in the project.`,\n ``,\n `Be specific and concrete. Reference actual code you found during exploration. The executor has no prior context about this codebase — your prompt is all it gets.`,\n );\n\n return sections.join(\"\\n\");\n}\n","/**\n * Task dispatcher — creates a fresh session per task to keep contexts\n * isolated and avoid context rot. Works with any registered provider.\n */\n\nimport type { ProviderInstance } from \"./providers/interface.js\";\nimport type { Task } from \"./parser.js\";\nimport { log } from \"./helpers/logger.js\";\nimport { fileLoggerStorage } from \"./helpers/file-logger.js\";\nimport { getEnvironmentBlock } from \"./helpers/environment.js\";\n\nexport interface DispatchResult {\n task: Task;\n success: boolean;\n error?: string;\n}\n\n/**\n * Dispatch a single task to the provider in its own session.\n * Each task gets a fresh session for context isolation.\n *\n * When a `plan` is provided (from the planner agent), it replaces the\n * generic prompt with the planner's context-rich execution instructions.\n */\nexport async function dispatchTask(\n instance: ProviderInstance,\n task: Task,\n cwd: string,\n plan?: string,\n worktreeRoot?: string,\n): Promise<DispatchResult> {\n try {\n log.debug(`Dispatching task: ${task.file}:${task.line} — ${task.text.slice(0, 80)}`);\n const sessionId = await instance.createSession();\n const prompt = plan ? buildPlannedPrompt(task, cwd, plan, worktreeRoot) : buildPrompt(task, cwd, worktreeRoot);\n log.debug(`Prompt built (${prompt.length} chars, ${plan ? \"with plan\" : \"no plan\"})`);\n fileLoggerStorage.getStore()?.prompt(\"dispatchTask\", prompt);\n\n const response = await instance.prompt(sessionId, prompt);\n\n if (response === null) {\n log.debug(\"Task dispatch returned null response\");\n fileLoggerStorage.getStore()?.warn(\"dispatchTask: null response\");\n return { task, success: false, error: \"No response from agent\" };\n }\n\n log.debug(`Task dispatch completed (${response.length} chars response)`);\n fileLoggerStorage.getStore()?.response(\"dispatchTask\", response);\n return { task, success: true };\n } catch (err) {\n const message = log.extractMessage(err);\n log.debug(`Task dispatch failed: ${log.formatErrorChain(err)}`);\n fileLoggerStorage.getStore()?.error(`dispatchTask error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return { task, success: false, error: message };\n }\n}\n\n/**\n * Build a focused prompt for a single task. Includes context about the\n * project but scopes the work to just this one unit.\n */\nfunction buildPrompt(task: Task, cwd: string, worktreeRoot?: string): string {\n return [\n `You are completing a task from a markdown task file.`,\n ``,\n `**Working directory:** ${cwd}`,\n `**Source file:** ${task.file}`,\n `**Task (line ${task.line}):** ${task.text}`,\n ``,\n getEnvironmentBlock(),\n ``,\n `Instructions:`,\n `- Complete ONLY this specific task — do not work on other tasks.`,\n `- Make the minimal, correct changes needed.`,\n buildCommitInstruction(task.text),\n ...buildWorktreeIsolation(worktreeRoot),\n `- When finished, confirm by saying \"Task complete.\"`,\n ].join(\"\\n\");\n}\n\n/**\n * Build a prompt for the executor when a planner has already explored\n * the codebase and produced a detailed execution plan.\n */\nfunction buildPlannedPrompt(task: Task, cwd: string, plan: string, worktreeRoot?: string): string {\n return [\n `You are an **executor agent** completing a task that has been pre-planned by a planner agent.`,\n `The planner has already explored the codebase and produced detailed instructions below.`,\n ``,\n `**Working directory:** ${cwd}`,\n `**Source file:** ${task.file}`,\n `**Task (line ${task.line}):** ${task.text}`,\n ``,\n getEnvironmentBlock(),\n ``,\n `---`,\n ``,\n `## Execution Plan`,\n ``,\n plan,\n ``,\n `---`,\n ``,\n `## Executor Constraints`,\n `- Follow the plan above precisely — do not deviate, skip steps, or reorder.`,\n `- Complete ONLY this specific task — do not work on other tasks.`,\n `- Make the minimal, correct changes needed — do not refactor unrelated code.`,\n `- Do NOT explore the codebase. The planner has already done all necessary research. Only read or modify the files explicitly referenced in the plan.`,\n `- Do NOT re-plan, question, or revise the plan. Trust it as given and execute it faithfully.`,\n `- Do NOT search for additional context using grep, find, or similar tools unless the plan explicitly instructs you to.`,\n buildCommitInstruction(task.text),\n ...buildWorktreeIsolation(worktreeRoot),\n `- When finished, confirm by saying \"Task complete.\"`,\n ].join(\"\\n\");\n}\n\n/**\n * Check whether a task description includes an instruction to commit.\n */\nfunction taskRequestsCommit(taskText: string): boolean {\n return /\\bcommit\\b/i.test(taskText);\n}\n\n/**\n * Build a commit instruction line based on whether the task requests a commit.\n */\nfunction buildCommitInstruction(taskText: string): string {\n if (taskRequestsCommit(taskText)) {\n return (\n `- The task description includes a commit instruction. After completing the implementation, ` +\n `stage all changes and create a conventional commit. Use one of these types: ` +\n `feat, fix, docs, refactor, test, chore, style, perf, ci.`\n );\n }\n return `- Do NOT commit changes — the orchestrator handles commits.`;\n}\n\n/**\n * Build worktree isolation instructions when operating inside a git worktree.\n * Returns an empty array when no worktreeRoot is provided (non-worktree mode).\n */\nfunction buildWorktreeIsolation(worktreeRoot?: string): string[] {\n if (!worktreeRoot) return [];\n return [\n `- **Worktree isolation:** You are operating inside a git worktree at \\`${worktreeRoot}\\`. ` +\n `You MUST NOT read, write, or execute commands that access files outside this directory. ` +\n `All file paths must resolve within \\`${worktreeRoot}\\`.`,\n ];\n}\n","/**\n * Executor agent — executes a single task by dispatching it to the AI\n * provider and marking it complete on success.\n *\n * The executor consumes a plan produced by the planner (or null when\n * planning is disabled). It never calls the planner itself — the plan\n * is treated as authoritative input from the orchestrator.\n */\n\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { AgentResult, ExecutorData } from \"./types.js\";\nimport type { Task } from \"../parser.js\";\nimport { markTaskComplete } from \"../parser.js\";\nimport { dispatchTask } from \"../dispatcher.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\n\n/**\n * Input to the executor for a single task.\n *\n * `plan` is the planner's output prompt string, or `null` when planning\n * was skipped (--no-plan). The executor uses this to decide whether to\n * build a planned prompt or a generic prompt via the dispatcher.\n */\nexport interface ExecuteInput {\n /** The task to execute */\n task: Task;\n /** Working directory */\n cwd: string;\n /** Planner output prompt, or null if planning was skipped */\n plan: string | null;\n /** Worktree root directory for isolation, if operating in a worktree */\n worktreeRoot?: string;\n}\n\n/**\n * A booted executor agent that can execute planned (or unplanned) tasks.\n */\nexport interface ExecutorAgent extends Agent {\n /**\n * Execute a single task. Dispatches to the provider, marks the task\n * complete on success, and returns a structured result.\n */\n execute(input: ExecuteInput): Promise<AgentResult<ExecutorData>>;\n}\n\n/**\n * Boot an executor agent backed by the given provider.\n *\n * @throws if `opts.provider` is not supplied — the executor requires a\n * provider to create sessions and send prompts.\n */\nexport async function boot(opts: AgentBootOptions): Promise<ExecutorAgent> {\n const { provider } = opts;\n\n if (!provider) {\n throw new Error(\"Executor agent requires a provider instance in boot options\");\n }\n\n return {\n name: \"executor\",\n\n async execute(input: ExecuteInput): Promise<AgentResult<ExecutorData>> {\n const { task, cwd, plan, worktreeRoot } = input;\n const startTime = Date.now();\n\n try {\n fileLoggerStorage.getStore()?.agentEvent(\"executor\", \"started\", task.text);\n // Dispatch the task — plan being non-null triggers the planned prompt path\n // in dispatchTask, otherwise the generic prompt is used\n const result = await dispatchTask(provider, task, cwd, plan ?? undefined, worktreeRoot);\n\n if (result.success) {\n await markTaskComplete(task);\n fileLoggerStorage.getStore()?.agentEvent(\"executor\", \"completed\", `${Date.now() - startTime}ms`);\n return { data: { dispatchResult: result }, success: true, durationMs: Date.now() - startTime };\n }\n\n fileLoggerStorage.getStore()?.agentEvent(\"executor\", \"failed\", result.error ?? \"unknown error\");\n return { data: null, success: false, error: result.error, durationMs: Date.now() - startTime };\n } catch (err) {\n const message = log.extractMessage(err);\n fileLoggerStorage.getStore()?.error(`executor error: ${message}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n return { data: null, success: false, error: message, durationMs: Date.now() - startTime };\n }\n },\n\n async cleanup(): Promise<void> {\n // Executor has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n","/**\n * Commit agent — analyzes branch changes and generates meaningful\n * conventional-commit-compliant commit messages, PR titles, and PR\n * descriptions using an AI provider.\n *\n * The commit agent runs after all tasks complete but before the PR is\n * created. It receives the branch diff, issue context, and task results,\n * prompts the AI provider, parses the structured response, and writes\n * the results to a temporary markdown file.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Agent, AgentBootOptions } from \"./interface.js\";\nimport type { IssueDetails } from \"../datasources/interface.js\";\nimport type { DispatchResult } from \"../dispatcher.js\";\nimport { log } from \"../helpers/logger.js\";\nimport { fileLoggerStorage } from \"../helpers/file-logger.js\";\nimport { formatEnvironmentPrompt } from \"../helpers/environment.js\";\n\n/** Options for the commit agent's `generate()` method. */\nexport interface CommitGenerateOptions {\n /** Git diff of the branch relative to the default branch */\n branchDiff: string;\n /** Issue details for context */\n issue: IssueDetails;\n /** Task dispatch results */\n taskResults: DispatchResult[];\n /** Working directory */\n cwd: string;\n /** Worktree root directory for isolation, if operating in a worktree */\n worktreeRoot?: string;\n}\n\n/** Structured result returned by the commit agent. */\nexport interface CommitResult {\n /** The generated conventional commit message */\n commitMessage: string;\n /** The generated PR title */\n prTitle: string;\n /** The generated PR description */\n prDescription: string;\n /** Whether generation succeeded */\n success: boolean;\n /** Error message if generation failed */\n error?: string;\n /** Path to the temp markdown file with the full output */\n outputPath?: string;\n}\n\n/** Commit agent — extends `Agent` with a `generate()` method. */\nexport interface CommitAgent extends Agent {\n /**\n * Generate commit message, PR title, and PR description from branch\n * changes and context. Writes results to a temp markdown file.\n */\n generate(opts: CommitGenerateOptions): Promise<CommitResult>;\n}\n\n/**\n * Boot the commit agent.\n *\n * @throws if `opts.provider` is not supplied.\n */\nexport async function boot(opts: AgentBootOptions): Promise<CommitAgent> {\n const { provider } = opts;\n\n if (!provider) {\n throw new Error(\n \"Commit agent requires a provider instance in boot options\"\n );\n }\n\n return {\n name: \"commit\",\n\n async generate(genOpts: CommitGenerateOptions): Promise<CommitResult> {\n try {\n const resolvedCwd = resolve(genOpts.cwd);\n const tmpDir = join(resolvedCwd, \".dispatch\", \"tmp\");\n await mkdir(tmpDir, { recursive: true });\n\n const tmpFilename = `commit-${randomUUID()}.md`;\n const tmpPath = join(tmpDir, tmpFilename);\n\n const prompt = buildCommitPrompt(genOpts);\n fileLoggerStorage.getStore()?.prompt(\"commit\", prompt);\n\n const sessionId = await provider.createSession();\n log.debug(`Commit prompt built (${prompt.length} chars)`);\n const response = await provider.prompt(sessionId, prompt);\n if (response) fileLoggerStorage.getStore()?.response(\"commit\", response);\n\n if (!response?.trim()) {\n return {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n success: false,\n error: \"Commit agent returned empty response\",\n };\n }\n\n log.debug(`Commit agent response (${response.length} chars)`);\n\n const parsed = parseCommitResponse(response);\n\n if (!parsed.commitMessage && !parsed.prTitle) {\n return {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n success: false,\n error:\n \"Failed to parse commit agent response: no commit message or PR title found\",\n };\n }\n\n const outputContent = formatOutputFile(parsed);\n await writeFile(tmpPath, outputContent, \"utf-8\");\n log.debug(`Wrote commit agent output to ${tmpPath}`);\n\n fileLoggerStorage.getStore()?.agentEvent(\"commit\", \"completed\", `message: ${parsed.commitMessage.slice(0, 80)}`);\n return {\n ...parsed,\n success: true,\n outputPath: tmpPath,\n };\n } catch (err) {\n fileLoggerStorage.getStore()?.error(`commit error: ${log.extractMessage(err)}${err instanceof Error && err.stack ? `\\n${err.stack}` : \"\"}`);\n const message = log.extractMessage(err);\n return {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n success: false,\n error: message,\n };\n }\n },\n\n async cleanup(): Promise<void> {\n // Commit agent has no owned resources — provider lifecycle is managed externally\n },\n };\n}\n\n/**\n * Build the prompt that instructs the AI to analyze the branch diff and\n * generate a conventional commit message, PR title, and PR description.\n */\nexport function buildCommitPrompt(opts: CommitGenerateOptions): string {\n const { branchDiff, issue, taskResults } = opts;\n\n const sections: string[] = [\n `You are a **commit message agent**. Your job is to analyze the git diff below and generate a meaningful, conventional-commit-compliant commit message, a PR title, and a PR description.`,\n ``,\n formatEnvironmentPrompt(),\n ``,\n `## Conventional Commit Guidelines`,\n ``,\n `Follow the Conventional Commits specification (https://www.conventionalcommits.org/):`,\n `- Format: \\`<type>(<optional scope>): <description>\\``,\n `- Types: \\`feat\\`, \\`fix\\`, \\`docs\\`, \\`refactor\\`, \\`test\\`, \\`chore\\`, \\`style\\`, \\`perf\\`, \\`ci\\``,\n `- The description should be concise, imperative mood, lowercase first letter, no period at the end`,\n `- If the change includes breaking changes, add \\`!\\` after the type/scope (e.g., \\`feat!: ...\\`)`,\n ``,\n `## Issue Context`,\n ``,\n `- **Issue #${issue.number}:** ${issue.title}`,\n ];\n\n if (issue.body) {\n sections.push(\n `- **Description:** ${issue.body.slice(0, 500)}${issue.body.length > 500 ? \"...\" : \"\"}`\n );\n }\n\n if (issue.labels.length > 0) {\n sections.push(`- **Labels:** ${issue.labels.join(\", \")}`);\n }\n\n const completed = taskResults.filter((r) => r.success);\n const failed = taskResults.filter((r) => !r.success);\n\n if (taskResults.length > 0) {\n sections.push(``, `## Tasks`);\n if (completed.length > 0) {\n sections.push(``, `### Completed`);\n for (const r of completed) {\n sections.push(`- ${r.task.text}`);\n }\n }\n if (failed.length > 0) {\n sections.push(``, `### Failed`);\n for (const r of failed) {\n sections.push(\n `- ${r.task.text}${r.error ? ` (error: ${r.error})` : \"\"}`\n );\n }\n }\n }\n\n const maxDiffLength = 50_000;\n const truncatedDiff =\n branchDiff.length > maxDiffLength\n ? branchDiff.slice(0, maxDiffLength) +\n \"\\n\\n... (diff truncated due to size)\"\n : branchDiff;\n\n sections.push(\n ``,\n `## Git Diff`,\n ``,\n `\\`\\`\\`diff`,\n truncatedDiff,\n `\\`\\`\\``,\n ``,\n `## Required Output Format`,\n ``,\n `You MUST respond with exactly the following three sections, using these exact headers:`,\n ``,\n `### COMMIT_MESSAGE`,\n `<your conventional commit message here>`,\n ``,\n `### PR_TITLE`,\n `<your PR title here>`,\n ``,\n `### PR_DESCRIPTION`,\n `<your PR description in markdown here>`,\n ``,\n `**Rules:**`,\n `- The commit message MUST follow conventional commit format`,\n `- The PR title should be a concise, descriptive summary of the overall change`,\n `- The PR description should explain what changed and why, referencing the issue context`,\n `- Do NOT include any text outside these three sections`\n );\n\n return sections.join(\"\\n\");\n}\n\n/**\n * Parse the AI agent's structured response into commit message, PR title,\n * and PR description. Uses robust matching to handle minor formatting\n * variations.\n */\nexport function parseCommitResponse(response: string): {\n commitMessage: string;\n prTitle: string;\n prDescription: string;\n} {\n const result = {\n commitMessage: \"\",\n prTitle: \"\",\n prDescription: \"\",\n };\n\n const commitMatch = response.match(\n /###\\s*COMMIT_MESSAGE\\s*\\n([\\s\\S]*?)(?=###\\s*PR_TITLE|$)/i\n );\n const titleMatch = response.match(\n /###\\s*PR_TITLE\\s*\\n([\\s\\S]*?)(?=###\\s*PR_DESCRIPTION|$)/i\n );\n const descMatch = response.match(\n /###\\s*PR_DESCRIPTION\\s*\\n([\\s\\S]*?)$/i\n );\n\n if (commitMatch?.[1]) {\n result.commitMessage = commitMatch[1].trim();\n }\n if (titleMatch?.[1]) {\n result.prTitle = titleMatch[1].trim();\n }\n if (descMatch?.[1]) {\n result.prDescription = descMatch[1].trim();\n }\n\n return result;\n}\n\n/**\n * Format the parsed results into a markdown file for pipeline consumption.\n */\nfunction formatOutputFile(parsed: {\n commitMessage: string;\n prTitle: string;\n prDescription: string;\n}): string {\n const sections: string[] = [\n `# Commit Agent Output`,\n ``,\n `## Commit Message`,\n ``,\n parsed.commitMessage,\n ``,\n `## PR Title`,\n ``,\n parsed.prTitle,\n ``,\n `## PR Description`,\n ``,\n parsed.prDescription,\n ``,\n ];\n return sections.join(\"\\n\");\n}\n","/**\n * TUI renderer — draws a real-time dashboard to the terminal showing\n * dispatch progress, current task, and results.\n */\n\nimport chalk from \"chalk\";\nimport { elapsed, renderHeaderLines } from \"./helpers/format.js\";\nimport type { Task } from \"./parser.js\";\n\nexport type TaskStatus = \"pending\" | \"planning\" | \"running\" | \"done\" | \"failed\";\n\nexport interface TaskState {\n task: Task;\n status: TaskStatus;\n elapsed?: number;\n error?: string;\n /** Worktree directory name when running in a worktree (e.g. \"123-fix-auth-bug\") */\n worktree?: string;\n}\n\nexport interface TuiState {\n tasks: TaskState[];\n phase: \"discovering\" | \"parsing\" | \"booting\" | \"dispatching\" | \"done\";\n startTime: number;\n filesFound: number;\n serverUrl?: string;\n /** Active provider name — shown in the booting phase */\n provider?: string;\n /** Model identifier reported by the provider, if available */\n model?: string;\n /** Datasource name (e.g. \"github\", \"azdevops\", \"md\") */\n source?: string;\n /** Currently-processing issue context (number + title) */\n currentIssue?: { number: string; title: string };\n /** Persistent notification banner (e.g. auth device-code prompt) */\n notification?: string;\n}\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nconst BAR_WIDTH = 30;\n\nlet spinnerIndex = 0;\nlet interval: ReturnType<typeof setInterval> | null = null;\nlet lastLineCount = 0;\n\nfunction spinner(): string {\n return chalk.cyan(SPINNER_FRAMES[spinnerIndex % SPINNER_FRAMES.length]);\n}\n\nfunction progressBar(done: number, total: number): string {\n if (total === 0) return chalk.dim(\"░\".repeat(BAR_WIDTH));\n const filled = Math.round((done / total) * BAR_WIDTH);\n const empty = BAR_WIDTH - filled;\n const pct = Math.round((done / total) * 100);\n return (\n chalk.green(\"█\".repeat(filled)) +\n chalk.dim(\"░\".repeat(empty)) +\n chalk.white(` ${pct}%`)\n );\n}\n\nfunction statusIcon(status: TaskStatus): string {\n switch (status) {\n case \"pending\":\n return chalk.dim(\"○\");\n case \"planning\":\n return spinner();\n case \"running\":\n return spinner();\n case \"done\":\n return chalk.green(\"●\");\n case \"failed\":\n return chalk.red(\"✖\");\n }\n}\n\nfunction statusLabel(status: TaskStatus): string {\n switch (status) {\n case \"pending\":\n return chalk.dim(\"pending\");\n case \"planning\":\n return chalk.magenta(\"planning\");\n case \"running\":\n return chalk.cyan(\"executing\");\n case \"done\":\n return chalk.green(\"done\");\n case \"failed\":\n return chalk.red(\"failed\");\n }\n}\n\nfunction phaseLabel(phase: TuiState[\"phase\"], provider?: string): string {\n switch (phase) {\n case \"discovering\":\n return `${spinner()} Discovering task files...`;\n case \"parsing\":\n return `${spinner()} Parsing tasks...`;\n case \"booting\": {\n const name = provider ?? \"provider\";\n return `${spinner()} Connecting to ${name}...`;\n }\n case \"dispatching\":\n return `${spinner()} Dispatching tasks...`;\n case \"done\":\n return chalk.green(\"✔\") + \" Complete\";\n }\n}\n\nfunction countVisualRows(text: string, cols: number): number {\n const stripped = text.replace(/\\x1B\\[[0-9;]*m/g, \"\");\n const safeCols = Math.max(1, cols);\n return stripped.split(\"\\n\").reduce((sum, line) => {\n return sum + Math.max(1, Math.ceil(line.length / safeCols));\n }, 0);\n}\n\nfunction render(state: TuiState): string {\n const lines: string[] = [];\n const now = Date.now();\n const totalElapsed = elapsed(now - state.startTime);\n\n const done = state.tasks.filter((t) => t.status === \"done\").length;\n const failed = state.tasks.filter((t) => t.status === \"failed\").length;\n const total = state.tasks.length;\n\n // ── Header ──────────────────────────────────────────────────\n lines.push(\"\");\n lines.push(\n ...renderHeaderLines({\n provider: state.provider,\n model: state.model,\n source: state.source,\n })\n );\n\n if (state.currentIssue) {\n lines.push(\n chalk.dim(` issue: `) + chalk.white(`#${state.currentIssue.number}`) + chalk.dim(` — ${state.currentIssue.title}`)\n );\n }\n\n lines.push(chalk.dim(\" ─\".repeat(24)));\n\n // ── Notification banner (auth prompts, etc.) ─────────────\n if (state.notification) {\n lines.push(\"\");\n for (const notifLine of state.notification.split(\"\\n\")) {\n lines.push(\" \" + chalk.yellowBright(\"⚠ \") + chalk.yellow(notifLine));\n }\n }\n\n // ── Phase + Timer ───────────────────────────────────────────\n lines.push(` ${phaseLabel(state.phase, state.provider)}` + chalk.dim(` ${totalElapsed}`));\n\n if (state.phase === \"dispatching\" || state.phase === \"done\") {\n // ── Progress bar ────────────────────────────────────────\n lines.push(\"\");\n lines.push(` ${progressBar(done + failed, total)} ${chalk.dim(`${done + failed}/${total} tasks`)}`);\n lines.push(\"\");\n\n // ── Task list ───────────────────────────────────────────\n // Determine if multiple worktrees are active (show indicator only when >1)\n const activeWorktrees = new Set(\n state.tasks.map((t) => t.worktree).filter(Boolean)\n );\n const showWorktree = activeWorktrees.size > 1;\n\n const cols = process.stdout.columns || 80;\n const maxTextLen = cols - 30;\n\n const running = state.tasks.filter((t) => t.status === \"running\" || t.status === \"planning\");\n const completed = state.tasks.filter(\n (t) => t.status === \"done\" || t.status === \"failed\"\n );\n const pending = state.tasks.filter((t) => t.status === \"pending\");\n\n if (showWorktree) {\n // ── Grouped-by-worktree display ───────────────────────\n const groups = new Map<string, TaskState[]>();\n const ungrouped: TaskState[] = [];\n for (const ts of state.tasks) {\n if (ts.worktree) {\n const arr = groups.get(ts.worktree) ?? [];\n arr.push(ts);\n groups.set(ts.worktree, arr);\n } else {\n ungrouped.push(ts);\n }\n }\n\n const doneGroups: [string, TaskState[]][] = [];\n const activeGroups: [string, TaskState[]][] = [];\n for (const [wt, tasks] of groups) {\n const allDone = tasks.every((t) => t.status === \"done\" || t.status === \"failed\");\n if (allDone) {\n doneGroups.push([wt, tasks]);\n } else {\n activeGroups.push([wt, tasks]);\n }\n }\n\n // Done groups (collapsed, last 3)\n if (doneGroups.length > 3) {\n lines.push(chalk.dim(` ··· ${doneGroups.length - 3} earlier issue(s) completed`));\n }\n for (const [wt, tasks] of doneGroups.slice(-3)) {\n const issueNum = wt.match(/^(\\d+)/)?.[1] ?? wt.slice(0, 12);\n const anyFailed = tasks.some((t) => t.status === \"failed\");\n const icon = anyFailed ? chalk.red(\"✖\") : chalk.green(\"●\");\n const doneCount = tasks.filter((t) => t.status === \"done\").length;\n const maxElapsed = Math.max(...tasks.map((t) => t.elapsed ?? 0));\n lines.push(` ${icon} ${chalk.dim(`#${issueNum}`)} ${chalk.dim(`${doneCount}/${tasks.length} tasks`)} ${chalk.dim(elapsed(maxElapsed))}`);\n }\n\n // Active groups (one row per group)\n for (const [wt, tasks] of activeGroups) {\n const issueNum = wt.match(/^(\\d+)/)?.[1] ?? wt.slice(0, 12);\n const activeTasks = tasks.filter((t) => t.status === \"running\" || t.status === \"planning\");\n const activeCount = activeTasks.length;\n const firstActive = activeTasks[0];\n const truncLen = Math.min(cols - 26, 60);\n let text = firstActive?.task.text ?? \"\";\n if (text.length > truncLen) {\n text = text.slice(0, truncLen - 1) + \"…\";\n }\n const earliest = Math.min(...activeTasks.map((t) => t.elapsed ?? now));\n const elapsedStr = elapsed(now - earliest);\n lines.push(` ${spinner()} ${chalk.white(`#${issueNum}`)} ${activeCount} active ${text} ${chalk.dim(elapsedStr)}`);\n }\n\n // Ungrouped tasks (only running/planning, flat)\n for (const ts of ungrouped) {\n if (ts.status !== \"running\" && ts.status !== \"planning\") continue;\n const icon = statusIcon(ts.status);\n const idx = chalk.dim(`#${state.tasks.indexOf(ts) + 1}`);\n let text = ts.task.text;\n if (text.length > maxTextLen) {\n text = text.slice(0, maxTextLen - 1) + \"…\";\n }\n const elapsedStr = chalk.dim(` ${elapsed(now - (ts.elapsed || now))}`);\n const label = statusLabel(ts.status);\n lines.push(` ${icon} ${idx} ${text} ${label}${elapsedStr}`);\n if (ts.error) {\n lines.push(chalk.red(` └─ ${ts.error}`));\n }\n }\n } else {\n // ── Flat display with running cap ─────────────────────\n const visibleRunning = running.slice(0, 8);\n const visible: TaskState[] = [\n ...completed.slice(-3),\n ...visibleRunning,\n ...pending.slice(0, 3),\n ];\n\n if (completed.length > 3) {\n lines.push(chalk.dim(` ··· ${completed.length - 3} earlier task(s) completed`));\n }\n\n for (const ts of visible) {\n const icon = statusIcon(ts.status);\n const idx = chalk.dim(`#${state.tasks.indexOf(ts) + 1}`);\n let text = ts.task.text;\n if (text.length > maxTextLen) {\n text = text.slice(0, maxTextLen - 1) + \"…\";\n }\n\n const elapsedStr =\n ts.status === \"running\" || ts.status === \"planning\"\n ? chalk.dim(` ${elapsed(now - (ts.elapsed || now))}`)\n : ts.status === \"done\" && ts.elapsed\n ? chalk.dim(` ${elapsed(ts.elapsed)}`)\n : \"\";\n\n const label = statusLabel(ts.status);\n\n lines.push(` ${icon} ${idx} ${text} ${label}${elapsedStr}`);\n\n if (ts.error) {\n lines.push(chalk.red(` └─ ${ts.error}`));\n }\n }\n\n if (running.length > 8) {\n lines.push(chalk.dim(` ··· ${running.length - 8} more running`));\n }\n\n if (pending.length > 3) {\n lines.push(chalk.dim(` ··· ${pending.length - 3} more task(s) pending`));\n }\n }\n\n // ── Summary line ────────────────────────────────────────\n lines.push(\"\");\n const parts: string[] = [];\n if (done > 0) parts.push(chalk.green(`${done} passed`));\n if (failed > 0) parts.push(chalk.red(`${failed} failed`));\n if (total - done - failed > 0)\n parts.push(chalk.dim(`${total - done - failed} remaining`));\n lines.push(` ${parts.join(chalk.dim(\" · \"))}`);\n } else if (state.filesFound > 0) {\n lines.push(chalk.dim(` Found ${state.filesFound} file(s)`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Clear the previous render and draw a new frame.\n * Uses a single-write, per-line overwrite strategy to eliminate flicker.\n */\nfunction draw(state: TuiState): void {\n const output = render(state);\n const cols = process.stdout.columns || 80;\n const newLineCount = countVisualRows(output, cols);\n\n let buffer = \"\";\n\n // Move cursor up to the beginning of the previous frame\n if (lastLineCount > 0) {\n buffer += `\\x1B[${lastLineCount}A`;\n }\n\n // Append each line with \\x1B[K (Erase to End of Line)\n const lines = output.split(\"\\n\");\n buffer += lines.map((line) => line + \"\\x1B[K\").join(\"\\n\");\n\n // Clean up leftover rows if new frame is shorter than previous\n const leftover = lastLineCount - newLineCount;\n if (leftover > 0) {\n for (let i = 0; i < leftover; i++) {\n buffer += \"\\n\\x1B[K\";\n }\n buffer += `\\x1B[${leftover}A`;\n }\n\n process.stdout.write(buffer);\n lastLineCount = newLineCount;\n}\n\n/**\n * Create and start the TUI — returns a controller to update state.\n */\nexport function createTui(): {\n state: TuiState;\n update: () => void;\n stop: () => void;\n} {\n const state: TuiState = {\n tasks: [],\n phase: \"discovering\",\n startTime: Date.now(),\n filesFound: 0,\n };\n\n // Animate spinner at ~80ms\n interval = setInterval(() => {\n spinnerIndex++;\n draw(state);\n }, 80);\n\n const update = () => draw(state);\n\n const stop = () => {\n if (interval) {\n clearInterval(interval);\n interval = null;\n }\n draw(state);\n };\n\n draw(state);\n\n return { state, update, stop };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,WAAW,eAAe,sBAAsB;AACzD,SAAS,MAAM,eAAe;AAC9B,SAAS,yBAAyB;AAflC,IAiBa,mBAEA;AAnBb;AAAA;AAAA;AAiBO,IAAM,oBAAoB,IAAI,kBAA8B;AAE5D,IAAM,aAAN,MAAM,YAAW;AAAA,MACb;A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WAAW,EAAE,GAAG,SAAS,cAAc,CAAC;AAG3E,QAAM,SAAS,YAAY,UAAU,QAAQ,SAAU,aAAa,WAAW,CAAC,QAAQ,UAAU,IAAI;AACtG,UAAQ,KAAK,SAAS,IAAI,IAAI,CAAC;AACjC;AAEA,KAAK,EAAE,MAAM,OAAO,QAAQ;AAC1B,MAAI,MAAM,IAAI,iBAAiB,GAAG,CAAC;AACnC,QAAM,WAAW;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["resolve","ErrorCodes","ResponseError","Message","Touch","Disposable","RAL","Event","CancellationToken","CancellationState","resolve","MessageReader","ResolvedMessageReaderOptions","MessageWriter","ResolvedMessageWriterOptions","result","CancelNotification","ProgressToken","ProgressNotification","StarRequestHandler","Trace","TraceValues","TraceFormat","SetTraceNotification","LogTraceNotification","ConnectionErrors","ConnectionError","ConnectionStrategy","IdCancellationReceiverStrategy","RequestCancellationReceiverStrategy","CancellationReceiverStrategy","CancellationSenderStrategy","CancellationStrategy","MessageStrategy","ConnectionOptions","ConnectionState","createMessageConnection","startTime","resolve","resolve","RIL","exports","process","StreamMessageReader","StreamMessageWriter","resolve","createMessageConnection","input","resolve","input","dirname","join","import_node","resolve","listModels","CopilotClient","boot","approveAll","resolve","listModels","boot","randomUUID","listModels","boot","execFile","promisify","exec","boot","listModels","readFile","join","resolve","resolve","join","execFile","promisify","input","join","dirname","join","dirname","execFile","promisify","exec","promisify","execFile","git","redactUrl","datasource","execFile","readFile","writeFile","mkdir","dirname","join","promisify","readFile","writeFile","mkdir","join","dirname","chalk","chalk","join","readFile","mkdir","dirname","writeFile","exec","promisify","execFile","git","join","datasource","mdFiles","results","readFile","dir","dirname","content","writeFile","mkdir","exec","promisify","execFile","datasource","input","basename","join","writeFile","execFile","promisify","exec","promisify","execFile","basename","datasource","join","writeFile","exec","join","basename","execFile","promisify","randomUUID","existsSync","exec","promisify","execFile","git","basename","join","existsSync","randomUUID","input","chalk","execFile","promisify","exec","readFile","writeFile","join","join","join","join","mkdir","readFile","rename","unlink","glob","mkdir","readFile","writeFile","join","resolve","randomUUID","boot","resolve","join","mkdir","randomUUID","readFile","writeFile","chalk","chalk","datasource","join","glob","readFile","chalk","boot","mkdir","rename","unlink","execFile","promisify","readFile","glob","readFile","writeFile","readFile","writeFile","boot","boot","input","mkdir","writeFile","join","resolve","randomUUID","boot","chalk","chalk","chalk","exec","promisify","execFile","glob","readFile","chalk","datasource","boot","runFixTestsPipeline","datasource","boot","opts","_","rest","resolve","join","boot"]}