#!/usr/bin/env node import { R as Recipe, P as PackageManager, D as DetectResult, b as buildPlan, e as executePlan, d as discoverServices, S as ServiceCandidate } from './discover-DxVLnLx-.js'; import { Stack } from 'crumbtrail-core'; import 'crumbtrail-node'; import './types-Oq-S4_9j.js'; /** Output sink — swappable in tests to capture lines instead of writing stdout. */ interface Ui { out(line?: string): void; err(line?: string): void; /** * Rewrite a transient single-line status in place (a live "Waiting… 12s" * ticker). TTY-only; calling with no argument clears the line. Callers MUST * clear before the next out()/err() or the lines collide. */ status?(line?: string): void; } /** One row of a `multiSelect` list. */ interface MultiSelectItem { /** Primary text, e.g. "apps/web". */ label: string; /** Trailing detail, e.g. "next" or "already wired — skipping". */ hint?: string; /** Whether this row starts checked (drives the empty-input default). */ checked: boolean; /** * False for rows we can list but cannot wire (no recipe matched). Rendered * greyed out and rejected if the user names them explicitly — listing them is * how we show the scan wasn't blind to the package. */ selectable: boolean; } /** Prompts the wizard needs — injectable so tests answer without a TTY. */ interface Prompter { /** Free-text with a default; empty input returns the default. */ ask(question: string, def?: string): Promise; /** Yes/no; empty input returns `def`. */ confirm(question: string, def?: boolean): Promise; /** 1-based numeric choice among labels; empty input returns `def` (0-based). */ select(question: string, labels: string[], def?: number): Promise; /** * Multi-choice; returns 0-based indices. On a real TTY this is an * interactive checkbox list (arrows move, space toggles, enter confirms); * everywhere else it falls back to the number-list prompt so piped stdin * and dumb terminals keep working. */ multiSelect(question: string, items: MultiSelectItem[]): Promise; } interface StoredAuth { token: string; expiresAt: string; /** Endpoint the token was minted against — a token is only reused for its base. */ endpoint: string; /** * Where this deployment serves its dashboard, as the server reported it. * Locally the API and the app are different ports, so it cannot be derived * from `endpoint`, and every link the wizard printed from the API base 404ed. */ appBaseUrl?: string; } declare function loadAuth(env?: NodeJS.ProcessEnv): StoredAuth | undefined; interface LoginOptions { base: string; ui: Ui; noBrowser?: boolean; fetchImpl?: typeof fetch; /** Injected browser opener (tests). */ openFn?: (url: string) => boolean | Promise; env?: NodeJS.ProcessEnv; /** Device-poll interval override for tests (ms). */ pollIntervalMs?: number; /** Sliding budget window for device polls (ms); default POLL_WINDOW_MS. */ pollWindowMs?: number; /** Device polls allowed per window; default DEVICE_POLL_BUDGET. */ pollBudget?: number; /** Browser hand-off deadline in ms (default 5 min); overridable in tests. */ browserDeadlineMs?: number; /** * False in a non-TTY shell: refuse to START an interactive login (browser * hand-off / device code) that would block on input nobody can give, and throw * an actionable error instead of hanging. Undefined/true keeps the interactive * flow (default) so a normal terminal is unaffected. A valid CRUMBTRAIL_TOKEN or * a cached token is honored regardless of this flag. */ allowInteractiveLogin?: boolean; } /** * Resolve a usable CLI token for `base`: reuse a stored token (validated by a * cheap GET /api/projects, and only if it was minted for THIS endpoint), else * run the login flow and persist the result. A stored token that 401s is * cleared and re-minted. */ declare function ensureToken(opts: LoginOptions): Promise; type StageName = "dns" | "tls" | "auth"; type StageStatus = "pass" | "fail" | "skipped"; interface StageResult { stage: StageName; status: StageStatus; /** Human reason for the status — the exact failing cause on a FAIL. */ reason: string; /** Wall-clock ms the stage took (0 for a stage that was skipped without work). */ ms: number; } interface PreflightResult { /** True iff no stage FAILED (skipped stages don't fail the run). */ ok: boolean; /** The resolved API base the probe targeted. */ endpoint: string; stages: StageResult[]; } /** * The credential the auth stage probes with. An ingest key exercises the SDK's * own ingest path (`x-crumbtrail-auth` → session/start); a bearer token is the * cached-login fallback that proves auth + endpoint via the dashboard GET. */ type AuthProbe = { kind: "ingestKey"; key: string; } | { kind: "bearer"; token: string; projectId?: string; } | { kind: "none"; }; interface PreflightIO { /** Resolve `host` to an address; reject on failure. */ resolveDns: (host: string) => Promise; /** * Open a TLS connection to host:port with SNI + full cert verification. Reject * with the cert error on a hostname/altname or trust-chain mismatch. */ checkTls: (host: string, port: number) => Promise; /** * Perform the authenticated round-trip for `probe`. Resolve with the HTTP * status on a response; throw ApiError (has `.status`) for a non-2xx, or any * other error for a transport failure (no status reached). */ authRoundTrip: (base: string, probe: AuthProbe) => Promise; /** Monotonic-ish clock for stage timing (injectable for deterministic tests). */ now: () => number; } interface RunPreflightOptions { /** Resolved, normalized API base (from resolveEndpoint). */ endpoint: string; probe: AuthProbe; io?: Partial; fetchImpl?: typeof fetch; } /** * Run the staged preflight. Stages short-circuit downward — a DNS failure skips * TLS + auth (they can't succeed), and a TLS failure skips auth — so the report * names the ROOT cause once instead of a cascade of derived failures. A * reachable host with a bad cert always reaches (and FAILS) the TLS stage. */ declare function runPreflight(opts: RunPreflightOptions): Promise; type CorsDiagnosticStatus = "pass" | "fail" | "unknown" | "not-applicable"; type CorsNetworkCategory = "http" | "redirect" | "timeout" | "dns" | "tls" | "network" | "opaque" | "not-applicable"; interface CorsDiagnosticResult { status: CorsDiagnosticStatus; endpoint: string; origin?: string; category: CorsNetworkCategory; responseStatus?: number; missingHeaders: string[]; missingMethod?: string; reason: string; nextStep: string; } interface CorsDiagnosticOptions { endpoint: string; origin?: string; applicable: boolean; /** Matches the browser request's credentials mode. Defaults to same-origin. */ credentials?: RequestCredentials; fetchImpl?: typeof fetch; timeoutMs?: number; } /** * Read-only browser preflight approximation. It deliberately sends no key or * proof: CORS decisions are made from Origin and requested header names. */ declare function diagnoseCors(opts: CorsDiagnosticOptions): Promise; interface Project { id: string; name: string; } /** * Which repository, and which directory inside it, this run is wiring. * * A project can hold one service per name, ignoring case, so `api` in one * repository and `api` in another are the same row to the cloud. Sending the * identity is what lets the two be told apart: the cloud already has a * `source_path` column for the directory, and the repository is what * distinguishes two apps whose directory is `.` in both. */ interface ServiceIdentity { /** Repository-relative app directory, e.g. `services/api` or `.`. */ sourcePath?: string; /** Stable repository name, from the git origin remote where there is one. */ repo?: string; } /** * Create a service, or adopt the one that already carries this name. * * Service names are unique per project, ignoring case, so the second run of the * wizard in a wired app used to die on a 409 before it ever reached the * already-wired check further down. Re-running is the single most natural thing * somebody does when they are not sure the first run worked, so a name that is * taken is treated as "this is the same app, carry on" rather than a failure. * * The 409 is still the source of truth for the collision: only after the server * refuses do we read the list back, which keeps the happy path one request and * makes the adopted service the real row rather than a guess. * * Adoption matches the name, because that is what the cloud's uniqueness rule * is built on. The name alone cannot tell "the same app, run again" from "a * different repository that also calls its backend api", so the identity this * run sends is compared against the identity the existing row carries, and the * three answers are reported separately: same repository, different * repository, or unknown because the row predates the CLI sending one. */ type AdoptionMatch = "same-source" | "other-source" | "unknown-source"; /** * Mint a project-scoped ingest key and return it in plaintext. * * The route is additive by default: it issues another key and leaves existing * ones live, which is the right shape here. Rotating would kill the key a * deployed app is already using, and this wizard has no business doing that to * a project it was merely pointed at. * * Plaintext is returned exactly once, by the server, and is never stored * anywhere by this process — the caller writes it straight into the app's env * file. See env-file.ts for the rules that write follows. * * The key id comes back with it because additive minting means a project can * hold several live keys, and the dashboard lists them all. Without the id the * run cannot say WHICH of those rows is the one now sitting in the app's env * file, which is the question a second run leaves behind. */ declare function createIngestKey(base: string, token: string, projectId: string, fetchImpl?: typeof fetch, identityLabel?: string): Promise<{ apiKey: string; keyId?: string; }>; /** * Turn session replay on or off for a project. * * Replay is the one capture setting a team cannot discover by using the * product: a session with no recording renders as an explanation rather than a * player, so nobody who has not read the settings page knows the switch exists. * Setup is where the question can be asked once, of the person who owns the * decision, before anyone waits on a replay that was never recorded. * * A partial patch on purpose. The route merges each field over the project's * current settings, so this changes replay and nothing a customer has already * chosen elsewhere. */ declare function setSessionReplay(base: string, token: string, projectId: string, enabled: boolean, fetchImpl?: typeof fetch, identityLabel?: string): Promise; declare function setDataReproduction(base: string, token: string, projectId: string, enabled: boolean, fetchImpl?: typeof fetch, identityLabel?: string): Promise; interface ProvisionInput { base: string; token: string; recipe: Recipe; /** * The detected non-JS backend Stack for the `otlp` recipe * (`DetectResult.otlpStack`). When set it OVERRIDES the static * `RECIPE_REGISTRY[recipe].stack` placeholder on the createService call — this * is how the single otlp recipe reports its variable Stack to the service. */ stack?: Stack | null; ui: Ui; prompter: Prompter; /** Skip prompts (non-interactive / --yes). */ assumeYes: boolean; /** --project : skip creation, attach a service to this project. */ projectId?: string; /** Inferred defaults (from detection / package.json / git). */ defaultProjectName: string; defaultServiceName: string; /** Explicit `--service ` target. Unset preserves the prompt/default path. */ serviceName?: string; /** Which repository and directory this app lives in. */ identity?: ServiceIdentity; /** Who the token belongs to, for the wrong-account message. */ identityLabel?: string; fetchImpl?: typeof fetch; } interface ProvisionResult { projectId: string; projectName: string; serviceId: string; serviceName: string; /** True when the service already existed and this run reused it. */ adopted?: boolean; /** How much of that reuse the cloud's own identity could confirm. */ adoptionMatch?: AdoptionMatch; /** Carried into the run summary when reuse could be the wrong application. */ adoptionNote?: string; } interface ResolveProjectInput { base: string; token: string; ui: Ui; prompter: Prompter; assumeYes: boolean; projectId?: string; defaultProjectName: string; /** Who the token belongs to, for the wrong-account message. */ identityLabel?: string; fetchImpl?: typeof fetch; } /** * Resolve the project a service will report to: explicit --project, an * interactive pick among existing projects, or a freshly created one. * * Split out of provisionFlow so the batch installer can resolve ONE project and * then mint many services under it. */ declare function resolveProject(input: ResolveProjectInput): Promise; interface ProvisionServiceInput { base: string; token: string; projectId: string; /** Who the token belongs to, for the wrong-account message. */ identityLabel?: string; recipe: Recipe; /** Detected otlp stack; overrides the registry placeholder. */ stack?: Stack | null; serviceName: string; /** Which repository and directory this app lives in, sent with the create. */ identity?: ServiceIdentity; /** Named targets must not adopt a verified different repository. */ rejectOtherSource?: boolean; ui: Ui; fetchImpl?: typeof fetch; } /** * Add one service to an already-resolved project. * * Still key-free, and still on purpose: one key covers the whole project, so * minting is a project-level step the wizard runs once, not something each * service repeats. Prompt-free by design too — the batch installer names * services from detection rather than asking N times. */ declare function provisionService(input: ProvisionServiceInput): Promise<{ serviceId: string; serviceName: string; adopted?: boolean; adoptionMatch?: AdoptionMatch; /** Printed by the caller's summary when adoption could be the wrong app. */ adoptionNote?: string; }>; /** * Resolve a project and add a service to it, returned to the wizard for the * summary. Composed from resolveProject + provisionService so the * single-package path keeps its exact behavior (including the interactive * "Service name" prompt). The key is minted later, by the wizard, once * env-file.ts has confirmed it has somewhere safe to go. */ declare function provisionFlow(input: ProvisionInput): Promise; /** Write boundary for the env writer — swappable in tests. */ interface EnvFileIO { exists(p: string): boolean; readFile(p: string): string | null; writeFile(p: string, content: string): void; remove(p: string): void; /** Whether git already follows this path, relative to `cwd`. */ isTracked(cwd: string, target: string): boolean; /** Whether an ignore rule already excludes this path, relative to `cwd`. */ isIgnored(cwd: string, target: string): boolean; } interface IngestPollConfig { /** Delay before the first poll, and the backoff step size. */ initialDelayMs: number; /** Upper bound on the per-attempt delay. */ maxDelayMs: number; /** Give up (→ "timedout") once cumulative waiting reaches this. */ timeoutMs: number; } type RealEventOutcome = "found" | "timedout" | "cancelled"; /** * What the wait actually observed when it ended empty. * * A wait that learned nothing and a wait that watched a quiet project are * different facts, and the note the wizard prints has to be able to tell them * apart instead of asserting a cause it never checked. */ type PollTimeoutReason = /** Every read of the sessions feed failed, so nothing was observed at all. */ "reads-failed" /** The project has no sessions, so nothing has ever reported in. */ | "no-sessions" /** Sessions exist; none was created and none captured anything new. */ | "no-new-activity"; interface PollRealEventResult { outcome: RealEventOutcome; /** Set when outcome is "found" — the session behind the first real event. */ sessionId?: string; /** Set only when outcome is "timedout" — what the wait actually saw. */ reason?: PollTimeoutReason; /** Sessions the project already had when the wait opened, when it was read. */ baselineSessionCount?: number; } interface PollRealEventOptions { base: string; token: string; projectId: string; ui: Ui; /** * Ms epoch captured at wizard entry. Only sessions started at/after this count * as "the first real event" — a session from a prior run is ignored. */ wizardStart?: number; signal?: AbortSignal; config?: IngestPollConfig; fetchImpl?: typeof fetch; /** Injected delay (tests); defaults to a real, abortable setTimeout. */ sleepFn?: (ms: number, signal?: AbortSignal) => Promise; } /** * Poll the sessions feed until a real (non-synthetic) session lands, the backoff * budget is exhausted, or the caller aborts (Ctrl-C). The timing policy is the * ported poll.ts state machine. On a TTY, a live elapsed-time status line keeps * a long wait from reading as a hang. */ declare function pollForRealEvent(opts: PollRealEventOptions): Promise; interface PollServicesOptions extends Omit { wizardStart?: number; /** The services we just wired and expect events from. */ serviceIds: string[]; /** Fired once per service, the first time its event lands. */ onFound?: (serviceId: string, sessionId: string) => void; } interface PollServicesResult { /** "found" only when EVERY serviceId reported. */ outcome: RealEventOutcome; /** serviceId → sessionId, for however many reported before we stopped. */ found: Record; } /** * Poll once for the whole batch until every wired service has reported, the * shared budget is exhausted, or the user aborts. Timeout and cancel both return * whatever arrived — stragglers never block the wizard from finishing, because * the wiring is already done by the time we get here. */ declare function pollForServices(opts: PollServicesOptions): Promise; /** Order two dotted numeric versions. A prerelease suffix sorts below its release. */ declare function compareSdkVersions(a: string, b: string): number; /** * The install spec for one SDK package, floored at THIS CLI's own version. * * `SDK_VERSION_FLOORS` is a CAPABILITY floor — the oldest SDK the recipes still * work against — and it is deliberately not raised for every release. That is * the right rule for a resolver that takes the newest matching version, and the * wrong one for pnpm 10+/11, whose release-age gate silently skips versions * published in the last few days: a run of `crumbtrail` 0.37.0 asking for * `>=0.31.0` resolved `crumbtrail-node` 0.36.0 hours after 0.37.0 shipped, and * 0.36.0's backend log capture does not work. The SDKs and the CLI are released * in lockstep, so the CLI's own version is a version that exists on the * registry, and asking for it by name is what makes pnpm's gate step aside. * The capability floor still wins when it is HIGHER (a CLI older than the * recipes it carries cannot happen, but the max costs nothing). */ declare function sdkInstallSpecForCli(pkg: string, cliVersion?: string): string; /** * The version of `pkg` as it actually sits on disk for an app at `cwd`, or * undefined when it is not there. Walks up through parent `node_modules` because * npm and yarn hoist, and a pnpm workspace links the dependency into the app's * own `node_modules` while the store lives at the root. * * This is the only honest answer to "did the install work". A package manager's * exit code is not: pnpm 10+/11 exits 1 with ERR_PNPM_IGNORED_BUILDS whenever * ANY dependency in the tree has an unapproved build script (esbuild, sharp, * prisma…), long after the packages it was asked to add are installed. */ declare function resolvedSdkVersion(cwd: string, pkg: string): string | undefined; type Command = "wizard" | "login" | "logout" | "token" | "verify" | "doctor" | "help" | "version"; interface ParsedArgs { command: Command; yes: boolean; project?: string; /** `--service `: name the application this app reports as. */ service?: string; noBrowser: boolean; skipVerify: boolean; /** * Do not mint an ingest key or write one to an env file — print the variable * to set instead. For anyone whose secrets come from a vault or a platform's * own env UI, where a key on a developer's disk is the wrong artifact. */ noWriteKey: boolean; /** * Do not mint an agent token and do not touch the coding agent's MCP * configuration — print what would have been written instead. For anyone * whose agent configuration is generated, shared, or governed elsewhere. */ noAgent: boolean; endpoint?: string; /** `doctor` only: browser origin to check. */ origin?: string; /** * Monorepo root only: wire exactly these services (repeatable `--only`, * matched against a service's package name or path). Also the non-interactive * escape hatch — a root run in CI must name its services somehow. */ only?: string[]; /** Monorepo root only: select every wireable service, no prompt. */ all: boolean; /** * Target a specific package directory instead of the detected repo root. In a * monorepo this bypasses the batch scan and wires exactly this one package * (resolved relative to cwd; must exist and hold a package.json). */ workspace?: string; /** * Turn session replay on (`--replay`) or off (`--no-replay`) for the project * without being asked. Unset means ask on a TTY and leave replay alone * otherwise, because recording a customer's end users is not a default a * non-interactive run should pick on their behalf. */ replay?: boolean; reproduction?: boolean; /** * `verify` only: the ingest key to probe with (else $CRUMBTRAIL_KEY, else the * cached login token). The primary CI credential for a pre-deploy check. */ key?: string; /** `verify` only: emit a machine-readable JSON result instead of the human table. */ json: boolean; /** Non-flag/subcommand leftover — an unknown token triggers usage help. */ unknown?: string; /** A flag that needs a value was used without one. */ parseError?: string; } declare function parseArgs(argv: string[]): ParsedArgs; interface InstallSdkInput { cwd: string; packageManager: PackageManager | null; recipe: Recipe; /** Packages selected dynamically by the injection plan. */ packagesOverride?: string[]; base: string; ui: Ui; /** Injected runner (tests); returns the child exit code. */ spawnFn?: (cmd: string, args: string[], cwd: string) => number; /** Injected fetch for the tarball-manifest fallback (tests); defaults to global. */ fetchImpl?: typeof fetch; /** Injected on-disk version reader (tests); defaults to `resolvedSdkVersion`. */ resolvedVersionFn?: (cwd: string, pkg: string) => string | undefined; /** This CLI's own version (tests); defaults to its package.json. */ cliVersion?: string; } interface InstallSdkResult { installed: boolean; packages: string[]; note?: string; } /** * A remote URL reduced to the repository it names, so the same repository * reads the same however it was cloned: `git@github.com:acme/api.git`, * `https://github.com/acme/api.git` and `ssh://git@github.com/acme/api` all * become `github.com/acme/api`. */ declare function normalizeRepoUrl(url: string): string; /** * Which repository, and which directory inside it, is being wired. * * A project holds one application per name, ignoring case, so `api` in this * repository and `api` in another are one row to the cloud and their events * arrive mixed. This is the identity that tells them apart, and it is sent with * every create. * * The repository is taken from the origin remote and from nothing else. A * directory basename would be a guess, and a wrong guess here reports two * checkouts of one repository as two different repositories. */ declare function serviceIdentity(appDir: string): ServiceIdentity; /** * Install the SDK with the detected package manager. If the registry install * fails (e.g. packages not yet public, or a self-hosted endpoint), fall back to * installing the deploy's packed tarballs — discovered via * `GET /install/manifest.json` — so a fresh deploy wires up before the * packages are on npm. Every recipe's SDK (including react-native and tauri, now * packed as optional channels by pack-local.mjs) is resolved by name prefix from * that manifest, so the fallback is uniform. Non-fatal either way, since * injection only writes import statements. */ declare function installSdk(input: InstallSdkInput): Promise; interface WizardDeps { detect: (cwd: string) => DetectResult; ensureToken: typeof ensureToken; provisionFlow: typeof provisionFlow; createIngestKey: typeof createIngestKey; /** Mints the hosted-agent token the MCP configuration carries. */ mintAgentToken: typeof mintAgentToken; /** Filesystem + git boundary for the env key write (faked in tests). */ envFileIO: EnvFileIO; installSdk: (input: InstallSdkInput) => Promise; buildPlan: typeof buildPlan; executePlan: typeof executePlan; pollForRealEvent: typeof pollForRealEvent; /** Batch path (monorepo root). */ discoverServices: typeof discoverServices; resolveProject: typeof resolveProject; provisionService: typeof provisionService; setSessionReplay: typeof setSessionReplay; setDataReproduction?: typeof setDataReproduction; pollForServices: typeof pollForServices; /** Synthetic preflight for `verify` (stub in tests). */ runPreflight: typeof runPreflight; /** Read-only CORS check for browser correlation. */ runCorsDiagnostic: typeof diagnoseCors; /** Browser opener for the end-of-wizard dashboard hand-off (stub in tests). */ openBrowserFn?: (url: string) => Promise; /** * The saved login on this machine, which decides the endpoint prompt's * default. Injectable so a test does not answer from the developer's own * ~/.config/crumbtrail/auth.json. */ loadStoredAuth?: typeof loadAuth; ui: Ui; prompter: Prompter; env: NodeJS.ProcessEnv; cwd: string; isTTY: boolean; fetchImpl?: typeof fetch; } declare function defaultDeps(): WizardDeps; /** Filesystem probes for --workspace validation; injectable so the resolver is * unit-testable without touching real directories. */ interface WorkspaceIO { isDir: (p: string) => boolean; isFile: (p: string) => boolean; } /** * Resolve `--workspace ` to an absolute package directory. The dir is taken * relative to the wizard's cwd, must exist, and must hold a package.json (the * workspace-package manifest) — otherwise detect() would run against nothing * useful, so we refuse with a concrete message rather than proceed. Pure aside * from the injected probes. */ declare function resolveWorkspaceDir(baseCwd: string, workspace: string, io?: WorkspaceIO): { dir: string; } | { error: string; }; /** * The endpoint this run will send data to, confirmed out loud. * * A run that took the hosted default in silence looked identical to one the * user had chosen: the header printed the URL, nothing ever asked, and someone * setting up against a local stack only found out after the wizard had created * a project on the wrong deployment. So when nothing stated an endpoint — * no `--endpoint`, no CRUMBTRAIL_BASE_URL — the interactive run asks, with a * default pre-filled so Enter still means something sane. * * That default is the endpoint of a saved login when this machine has one. A * run that had just done `crumbtrail login --endpoint http://127.0.0.1:19890` * was offered the hosted cloud as the default, then printed "Using your saved * Crumbtrail login for http://127.0.0.1:19890" two lines later, so pressing * Enter wired the whole app to a deployment the run had no login for. The * login this machine actually holds is the honest default; the hosted cloud is * the default only when there is no login to speak for. * `--yes` and non-interactive shells take the same default without a prompt. * * It is asked only when there is something to get wrong, which is when this * machine holds a login for a DIFFERENT endpoint than the one this run would * otherwise use. That is the case the incident above describes and the only one * where the answer is not already known. * * A first run holds no login, so the old prompt asked a stranger to choose * between the hosted cloud and nothing, fifteen seconds after they read "set it * up in one command", with no basis for answering. It cannot be deferred past * sign in either, because sign in happens against an endpoint. So it is * defaulted and stated instead: `runWizard` prints the endpoint it settled on * with the flag that changes it, before anything is created, which keeps the * protection the prompt existed for without opening on a question. */ declare function confirmEndpoint(parsed: ParsedArgs, deps: WizardDeps, base: string): Promise; declare function runWizard(parsed: ParsedArgs, deps: WizardDeps): Promise; type ServiceStatus = "wired" | "guidance" | "skipped-already-wired" | "withheld" | "declined" | "failed"; interface ServiceOutcome { name: string; relDir: string; recipe: Recipe; status: ServiceStatus; serviceId?: string; /** Env var the injected code reads its key from. */ keyEnvVar?: string; /** That variable is supplied at build time, so it has no env file to go in. */ keyIsCompileTime?: boolean; /** True when the service has a key available for the configured variable. */ keyReady?: boolean; /** * The key this service carries was presented to the endpoint and refused. * * Separate from `keyReady`, which only says a value reached the env file. A * rejected key is a service that will not report a single event, so it must * not wear the same tick, or sit in the same "wired" count, as one that will. */ keyRejected?: boolean; /** Exact setup guidance was printed and this run made no local file changes. */ nonmutatingGuidance?: true; filesTouched: string[]; notes: string[]; error?: string; errorKind?: "project-access"; sessionUrl?: string; } /** * What the run did about frontend to backend correlation, in the service's own * notes. Silence here is what made this the longest lived gap in setup: the * emitted list is the only thing that turns the shared_request_id join on, and * a wizard that never mentions it leaves the user with two unrelated piles of * evidence and no reason to suspect a setting. */ declare function correlationNotes(recipe: Recipe, origins: readonly string[], backendCount: number, outcome?: ServiceStatus): string[]; /** * Why `--all` left a package alone, in the package's own terms. * * A library that gets wired is worse than one that is skipped: the app that * imports it runs the library's capture first, and every session from that * process is then filed under the library's name while the real service reports * nothing at all. So `--all` means every service, not every directory — and the * ones it passed over are named here rather than silently dropped. */ declare function skippedByAllNote(c: ServiceCandidate): string; /** * Selected packages that one of the other selected packages imports. * * Two capture inits in one process is one capture: the first call wins and the * second is ignored, so every session from that process is filed under whichever * name loaded first. When a library and the app that imports it are both wired, * that name is the library's, and the app the user cares about reports nothing. * The wizard is the only thing in the room that can see both halves, so it says * so instead of leaving a silent misfiling to be discovered in the dashboard. */ declare function importedSelectionWarnings(selected: readonly ServiceCandidate[], readPkg: (dir: string) => { name?: string; dependencies?: unknown; } | null): string[]; /** * Resolve --only/--all into indices, or null when we should prompt. * Returns a string on a user error (unknown --only value). * * `--only` is explicit and always honoured; `--all` is a judgement call the user * delegated, so it declines the packages that look like libraries and reports * them in `skipped`. */ declare function resolveSelection(parsed: ParsedArgs, candidates: ServiceCandidate[]): { indices: number[]; skipped?: ServiceCandidate[]; } | { error: string; } | null; interface BatchContext { base: string; wizardStart: number; root: DetectResult; /** Root holds unlinked sibling services rather than declared workspaces. */ includeUnlinkedApps?: boolean; } /** * The monorepo path: scan → pick → one login → one project → wire each selected * service → one shared wait → summary. * * A failure on one service never sinks the batch (each is try/caught and * recorded), because a half-wired repo with a clear report is strictly better * than an abort that leaves the user guessing which services made it. */ declare function runBatchWizard(parsed: ParsedArgs, deps: WizardDeps, ctx: BatchContext): Promise; declare function printBatchSummary(ui: Ui, base: string, root: string, projectId: string, projectName: string, outcomes: ServiceOutcome[], batchNotes?: string[], /** False when no first-event wait ran (`--skip-verify`), so nothing was seen. */ verified?: boolean, /** What the agent-connection step did, when one ran. */ agent?: AgentConnection): boolean; interface KeyWriteOutcome { status: "written" | "already-set" | "refused-tracked" | "no-variable" | "skipped-flag" | "skipped-no-wiring" | "failed"; /** The env file involved, when there is one. */ file?: string; varName?: string; /** Extra line for the end-of-run summary's notes. */ note?: string; /** In-memory only; lets the wizard probe the key without printing it. */ probeKey?: string; } /** * The step that finishes the job: mint the project's ingest key and put it in * the app's env file. * * Sequenced deliberately. env-file.ts decides where the key would go and * whether that is safe BEFORE anything is minted, so the refusal paths * (`--no-write-key`, a git-tracked env file, a variable already pointed at a * key) cost no credential at all. Only a decision of "ready" reaches the * network. See env-file.ts for the rules the write itself follows. */ interface KeyTarget { /** Names the service in batch output; empty on the single-package path. */ label: string; /** The package being wired — where its env file lives. */ appDir: string; varName: string | undefined; } /** * Mint a hosted-agent token for one project. * * The same route the dashboard's Settings and Setup pages post to * (`/api/agent-tokens`), which accepts the CLI's own `ctcli_` bearer, so the * wizard needs nothing the dashboard has and no route of its own. Scoped to * this project alone: a token that reaches every project in an organization is * an organization-administrator decision, not a side effect of wiring one app. */ declare function mintAgentToken(args: { base: string; token: string; projectId: string; name: string; fetchImpl?: typeof fetch; }): Promise<{ secret: string; expiresAt?: string; }>; /** What the agent-connection step did, as the summary has to state it. */ interface AgentConnection { status: "connected" | "already-configured" | "no-target" | "declined" | "failed"; /** Repo-relative configuration files this run wrote. */ files: string[]; /** The summary's "Coding agent" value. */ line: string; /** Outstanding steps, printed in the summary's notes block. */ notes: string[]; } /** * Ask once, at setup, whether this project should record session replay. * * Replay is the only capture setting whose absence is invisible from the * product: a session without a recording renders as an explanation, not as a * missing feature, so a team that never opened the settings page waits for a * player that was never going to arrive. Asking here puts the question in * front of the person who owns the project on the one run where they are * already answering questions about it. * * It is never assumed. Replay records what a customer's own end users see, so * an unattended run leaves it alone and says where the switch lives; only a * person at a TTY, or an explicit `--replay` / `--no-replay`, decides it. * A failure here is reported and never fatal: the app is wired either way, and * the setting is one click away in the dashboard. */ declare function offerDataReproduction(args: { base: string; token: string; projectId: string; parsed: ParsedArgs; deps: WizardDeps; identityLabel: string; }): Promise; /** One service's key, as the run left it, for `probeServiceKeys`. */ interface KeyProbeTarget { /** Service name, and the key of the returned map. */ name: string; write: KeyWriteOutcome | undefined; /** Repo-relative env file holding the key, when there is one. */ where?: string; /** Where a replacement key is minted, named in the stale-key note. */ mintUrl?: string; } interface KeyProbeVerdict { ok: true; } interface KeyProbeRejection { ok: false; note: string; } /** * Probe the ingest key each service actually carries, one probe per DISTINCT * key, and attribute every verdict only to the services carrying that key. * * Both halves are the fix for the same defect. The wizard mints ONE key and * writes it into every service it wired, but a service whose env file already * held a key keeps that one untouched — and a leftover from an older install is * exactly the key that fails. Probing "the first key found across the run" * therefore tested a credential this run never wrote, and then broadcast that * one rejection to every service, so a single stale line in a single .env made * a nine service install report itself as nine broken services. * * Services with no key to probe are absent from the result: unknown is not a * rejection, and the event wait is what decides those. */ declare function probeServiceKeys(targets: KeyProbeTarget[], probe: (key: string) => Promise): Promise>; /** * Says nothing when the amended file loads an env file, and states the * condition when it does not. * * The fresh injection path prepends a guarded `.env` load above the init it * writes, so the key in the env file is genuinely read at startup. An amend * edits the customer's own init and adds no such loader, so a service that * loads no env file still starts with the variable unset. Telling that user a * restart is all it takes is a claim the shipped code does not support. */ declare function envLoadCaveat(plan: { content?: string | null; keyEnvVar?: string; }): string | undefined; /** * Whether this run saw the app report. * * confirmed the first event arrived while the wizard waited * none the wizard waited and nothing arrived * unverified no wait ran (`--skip-verify`, or a recipe that sends no cloud * event), so the run has no evidence either way */ type CaptureState = "confirmed" | "none" | "unverified"; /** * The verdict the summary bar prints, and the exit code that goes with it. * * "Setup complete" used to be decided by the ingest key alone, so a run that * printed "No event yet, start your app" three lines earlier still certified * itself as done. The README's promise is a confirmed first event, so the bar * now says which of the three things happened, and only a confirmed event is * allowed to be called complete. */ declare function summaryVerdict(input: { stepsOutstanding: boolean; capture: CaptureState; }): { line: string; tone: "success" | "warn"; incomplete: boolean; }; /** * Pick the credential the preflight auth stage probes with. An explicit --key * (or $CRUMBTRAIL_KEY) is the primary CI path — it exercises the SDK's ingest * path. Absent a key we fall back to the cached login token, but only if it was * minted for THIS endpoint (a token is only reused for its base). Nothing → the * auth stage reports a clear "no credential" failure. */ declare function resolveAuthProbe(base: string, key: string | undefined, projectId: string | undefined, env: NodeJS.ProcessEnv): AuthProbe; declare function wizardAliasHint(arg: string): string | undefined; declare function runCli(argv: string[], deps?: WizardDeps, nodeVersion?: string): Promise; declare function isCliEntrypoint(argv1: string | undefined): boolean; export { type AgentConnection, type CaptureState, type Command, type InstallSdkInput, type InstallSdkResult, type KeyProbeRejection, type KeyProbeTarget, type KeyProbeVerdict, type KeyTarget, type KeyWriteOutcome, type ParsedArgs, type ServiceOutcome, type ServiceStatus, type WizardDeps, type WorkspaceIO, compareSdkVersions, confirmEndpoint, correlationNotes, defaultDeps, envLoadCaveat, importedSelectionWarnings, installSdk, isCliEntrypoint, mintAgentToken, normalizeRepoUrl, offerDataReproduction, parseArgs, printBatchSummary, probeServiceKeys, resolveAuthProbe, resolveSelection, resolveWorkspaceDir, resolvedSdkVersion, runBatchWizard, runCli, runWizard, sdkInstallSpecForCli, serviceIdentity, skippedByAllNote, summaryVerdict, wizardAliasHint };