The Open Framework for Building Agents
feat(cli): add telemetry (#2283)
OwenKephart97090d6fa4ac
diff --git a/.changeset/bright-pets-obey.md b/.changeset/bright-pets-obey.mdnew file mode 100644index 000000000..72460961c--- /dev/null+++ b/.changeset/bright-pets-obey.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add CLI telemetry for command usage and outcomes. Use `eve telemetry disable` to opt out permanently, or `EVE_TELEMETRY_DISABLED` for a per-command override.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 6eb18d8e7..d48461d8a 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -1,43 +1,48 @@---title: "CLI"-description: "Reference for every eve CLI command: init, set, info, build, start, dev, logs, trace, link, deploy, eval, channels, and extension."+description: "Reference for every eve CLI command: init, set, info, build, start, dev, logs, traces, link, deploy, eval, channels, extension, and telemetry."----Relevant `eve` commands can run from the application root or any directory beneath it. In an `agents/` workspace, agent-specific commands accept `--agent <name>` and otherwise open a picker when more than one agent exists. Non-interactive runs must pass `--agent`. Running `eve` with no command runs `eve init` when the current directory is not an eve project, or `eve dev` when it is.+Relevant `eve` commands can run from the application root or any directory beneath it. Running `eve` with no command runs `eve init` when the current directory is not an eve project, or `eve dev` when it is.## Commands-| Command | Description |-| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |-| `eve` | Initialize the current directory, or start development when it is already an eve project |-| `eve init [target]` | Create a new agent, or add an agent to an existing project |-| `eve info` | Print the resolved application, including static instructions and discovered capabilities, routes, artifact paths, and diagnostics |-| `eve build` | Compile `.eve/` artifacts and build the host output; prints the output directory |-| `eve start` | Serve the built `.output/` app; prints the listening URL |-| `eve dev` | Start the local dev server and open the terminal UI |-| `eve dev <url>` | Connect the UI to an existing server URL (e.g. a remote deployment) instead of booting a local server |-| `eve acp [url]` | Serve the local application or an existing eve server URL as a stable ACP v1 agent over stdio |-| `eve logs [logid]` | Print an `eve dev` diagnostic log (the most recent when `logid` is omitted) |-| `eve logs ls` | List `eve dev` diagnostic logs, most recent first |-| `eve traces ls` | List locally captured agent traces, most recent first |-| `eve traces [trace]` | Show a local span tree (the most recent when omitted) |-| `eve link` | Link the directory to a Vercel project and pull AI Gateway credentials |-| `eve deploy` | Deploy the agent to Vercel production (links first if needed) |-| `eve eval` | Run evals against the local app or a remote target |-| `eve channels list` | List user-authored channels |-| `eve extension init [target]` | Create a new extension package |-| `eve extension build` | Build the current package as an extension |-| `eve set` | Change the root agent's model and reasoning effort |-| `eve add <item>` | Install an item from the official or a configured shadcn registry |+| Command | Description |+| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |+| `eve` | Initialize the current directory, or start development when it is already an eve project |+| `eve init [target]` | Create a new agent, or add an agent to an existing project |+| `eve info` | Print the resolved application, including static instructions and discovered capabilities, routes, artifact paths, and diagnostics |+| `eve build` | Compile `.eve/` artifacts and build the host output; prints the output directory |+| `eve start` | Serve the built `.output/` app; prints the listening URL |+| `eve dev` | Start the local dev server and open the terminal UI |+| `eve dev <url>` | Connect the UI to an existing server URL (e.g. a remote deployment) instead of booting a local server |+| `eve acp [url]` | Serve the local application or an existing eve server URL as a stable ACP v1 agent over stdio |+| `eve logs [logid]` | Print an `eve dev` diagnostic log (the most recent when `logid` is omitted) |+| `eve logs ls` | List `eve dev` diagnostic logs, most recent first |+| `eve traces ls` | List locally captured agent traces, most recent first |+| `eve traces [trace]` | Show a local span tree (the most recent when omitted) |+| `eve telemetry <command>` | Show, enable, or disable CLI telemetry collection |+| `eve link` | Link the directory to a Vercel project and pull AI Gateway credentials |+| `eve deploy` | Deploy the agent to Vercel production (links first if needed) |+| `eve eval` | Run evals against the local app or a remote target |+| `eve channels list` | List user-authored channels |+| `eve extension init [target]` | Create a new extension package |+| `eve extension build` | Build the current package as an extension |+| `eve set` | Change the root agent's model and reasoning effort |+| `eve add <item>` | Install an item from the official or a configured shadcn registry || `eve integration setup <kind>` | Run a built-in setup flow directly after its registry files are installed |-| `eve registry <command>` | Add sources and list, search, or view registry catalog items |+| `eve registry <command>` | Add sources and list, search, or view registry catalog items |When `eve build` fails on discovery errors, it prints the full diagnostics report (severity, message, source path) and the diagnostics artifact path.+## CLI telemetry++eve collects CLI telemetry by default to improve the command-line interface. Run `eve telemetry disable` to disable it for this machine, or set `EVE_TELEMETRY_DISABLED=1` for one command. See [CLI telemetry](./telemetry) for the current data fields, exclusions, debug mode, notice, and local preference storage.+## `eve init````bash-eve init [target] [--agents <name,...>] [--model <provider/model-id>] [--reasoning <effort>] [--channel-web-nextjs]+eve init [target] [--model <provider/model-id>] [--reasoning <effort>] [--channel-web-nextjs]```Creates a new agent app or adds an agent to an existing app. Always installs dependencies. New directories also initialize Git.@@ -48,8 +53,6 @@ Creates a new agent app or adds an agent to an existing app. Always installs dep| `eve init` or `eve init .` in an empty directory | Creates an agent project in the current directory || `eve init` or `eve init .` in a non-empty directory without `package.json` | Asks whether to scaffold in the current directory or a named subdirectory. Using the current directory preserves unrelated files but overwrites files at generated paths || `eve init .` in an existing project | Adds `agent/` plus missing `eve`, `ai`, and `zod` dependencies. Requires `package.json` and no existing `agent/` files |-| `eve init my-project --agents foreman,researcher` | Creates a workspace with `agents/foreman/agent/` and `agents/researcher/agent/` |-| `eve init billing` from an `agents/` workspace | Adds only `agents/billing/agent/`; the workspace keeps its existing package, dependencies, and TypeScript configuration |Coding-agent launches and non-interactive terminals cannot answer the location prompt and fail before writing. Pass a new directory name, such as `eve init my-agent`, in those environments.@@ -57,7 +60,6 @@ After scaffolding, a human terminal usually continues into `eve dev`. If a codin| Flag | Type | Default | Description || ---------------------- | ------ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |-| `--agents <names>` | list | unset | Create an `agents/` workspace with one or more comma-separated agent names. || `--model <model>` | string | `openai/gpt-5.6-luna-fast` | Set the root agent's AI Gateway model ID. || `--reasoning <effort>` | enum | provider default | Set reasoning to `none`, `minimal`, `low`, `medium`, `high`, or `xhigh`. `provider-default` leaves the field unauthored. || `--channel-web-nextjs` | flag | off | Add the Web Chat app (Next.js). Not for existing projects — run `eve add channel/web` there instead. |@@ -122,8 +124,6 @@ Commands for installing and discovering [shadcn registry](https://ui.shadcn.com/eve add extension/agent-browsereve add lineareve add channel/slack --skip-install-eve add memory/file-eve integration setup file-memoryeve add https://example.com/r/my-extension.json --overwriteeve registry add @acme=https://example.com/r/{name}.jsoneve registry search browser@@ -139,8 +139,6 @@ Coding agents should use `eve add <item> --non-interactive`, adding `--yes` to aWhen setup is skipped, cancelled, or needs more input after installation, eve prints or returns the matching `eve add <item> --skip-install` continuation. It reruns the selected components' declared flows without reinstalling registry files.-`eve integration setup file-memory` runs the storage setup directly without reinstalling `agent/memory/file.ts`. It authenticates through the Vercel CLI, resolves the linked project, reconciles the private Blob store, and pulls the environment. Use it to repair or verify a previous provisioning attempt; `eve add memory/file` also offers the normal deployment handoff after setup.-`eve registry add` records configured sources in `package.json#registries`. `eve registry list` aggregates the official catalog and all configured sources by default. `eve registry search` also includes [skills.sh](https://skills.sh), available without configuration at `@skills`, and groups results by source with each source's available result count. Search returns up to 10 matches per source by default; pass `--limit <count>` to request between 1 and 100. Either command can browse one supplied URL or namespace. Official and other universal items with explicit file targets do not require shadcn project configuration.## `eve info`diff --git a/docs/reference/meta.json b/docs/reference/meta.jsonindex 8aff34420..65d284e9f 100644--- a/docs/reference/meta.json+++ b/docs/reference/meta.json@@ -1,4 +1 @@-{- "title": "Reference",- "pages": ["typescript-api", "cli"]-}+{ "title": "Reference", "pages": ["typescript-api", "cli", "telemetry"] }diff --git a/docs/reference/telemetry.md b/docs/reference/telemetry.mdnew file mode 100644index 000000000..7d34d4b0d--- /dev/null+++ b/docs/reference/telemetry.md@@ -0,0 +1,56 @@+---+title: "CLI Telemetry"+description: "Learn what eve CLI telemetry collects and how to control it."+---++# CLI telemetry++eve collects usage data from its CLI to help improve its commands and development experience. You can turn telemetry off at any time.++## What eve collects++eve sends the following information to Vercel:++- The eve version, operating system, CPU architecture, and whether stdin is a terminal.+- The command you ran and whether it succeeded, had a usage error, or failed.+- For `eve dev`, whether you connected to a local or remote agent and whether the UI was interactive or headless.+- Random identifiers for the CLI session, your eve installation, and the project.++The project identifier lets eve group usage from the same project without sending its name or location. eve derives it from the Git remote when available, otherwise `REPOSITORY_URL` or the working directory, and transforms that value before sending it.++## What eve does not collect++eve does not collect command arguments, prompts, agent files, URLs, request headers, error messages, environment variables, file paths, or file contents.++## View telemetry data++Set `EVE_TELEMETRY_DEBUG=1` to print the telemetry batch to stderr instead of sending it:++```bash+EVE_TELEMETRY_DEBUG=1 eve info+```++## Turn telemetry off++Disable telemetry for this machine:++```bash+eve telemetry disable+```++Check its status or turn it back on:++```bash+eve telemetry status+eve telemetry enable+```++To disable telemetry for one command without changing the saved setting, set `EVE_TELEMETRY_DISABLED=1`:++```bash+EVE_TELEMETRY_DISABLED=1 eve dev+```++On an interactive terminal, eve displays this information once before it collects telemetry. eve saves your preference in your platform user configuration directory. In CI and Docker environments, eve uses fresh in-memory identifiers for each invocation instead of saving them.++Vercel handles CLI telemetry under the [Vercel Privacy Notice](https://vercel.com/legal/privacy-notice).diff --git a/packages/eve/src/cli/dev/boot-progress.ts b/packages/eve/src/cli/dev/boot-progress.tsnew file mode 100644index 000000000..11f0c61b9--- /dev/null+++ b/packages/eve/src/cli/dev/boot-progress.ts@@ -0,0 +1,28 @@+import { createLogger } from "#internal/logging.js";+import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";+import { startCliLiveRow } from "#cli/ui/live-row.js";++const devBootLog = createLogger("dev.boot");++export function createDevBootProgressReporter(+ row: ReturnType<typeof startCliLiveRow> | undefined,+): DevBootProgressReporter {+ return (event) => {+ switch (event.type) {+ case "phase-started":+ row?.update("Building your agent", event.phase);+ devBootLog.debug(event.phase);+ return;+ case "phase-finished":+ devBootLog.debug(`${event.phase} finished`, { ms: event.elapsedMs });+ return;+ case "before-first-paint":+ row?.stop();+ return;+ default: {+ const exhaustive: never = event;+ return exhaustive;+ }+ }+ };+}diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.tsindex 33663ab91..ceed53fb7 100644--- a/packages/eve/src/cli/run.test.ts+++ b/packages/eve/src/cli/run.test.ts@@ -2,7 +2,8 @@ import { resolve } from "node:path";import { describe, expect, it, vi } from "vitest";-import { resolveDevUiMode, resolveTuiDisplayOptions, runCli } from "#cli/run.js";+import { createCliProgram, resolveDevUiMode, resolveTuiDisplayOptions, runCli } from "#cli/run.js";+import { cliTelemetryCommandPaths, internalCliCommandPaths } from "#cli/telemetry/index.js";import { MockScreen } from "#cli/dev/tui/test/mock-terminal.js";import type { RunDevelopmentTuiInput } from "#cli/dev/tui/tui.js";import type { DevelopmentServerOptions } from "#internal/nitro/host/types.js";@@ -66,6 +67,28 @@ async function runInteractiveDev(}describe("CLI command registration", () => {+ it("keeps telemetry's command allowlist aligned with registered commands", () => {+ const program = createCliProgram(+ { error: () => {}, log: () => {} },+ {},+ {+ resolve: async () => {},+ resolveAgent: async () => undefined as never,+ root: process.cwd(),+ },+ { trackDevContext: () => {} },+ );+ const paths: string[] = [];+ const visit = (command: (typeof program.commands)[number], parentPath = ""): void => {+ const path = [parentPath, command.name()].filter(Boolean).join(":");+ paths.push(path);+ for (const child of command.commands) visit(child, path);+ };+ for (const command of program.commands) visit(command);++ expect([...cliTelemetryCommandPaths, ...internalCliCommandPaths].sort()).toEqual(paths.sort());+ });+it("lists the current project creation and Vercel commands", async () => {const output: string[] = [];@@ -80,6 +103,7 @@ describe("CLI command registration", () => {expect(help).toContain("link");expect(help).toContain("deploy");expect(help).toContain("registry");+ expect(help).toContain("telemetry");expect(help).not.toContain("setup [options] <item>");});diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.tsindex 2ca4b554b..47243f9f8 100644--- a/packages/eve/src/cli/run.ts+++ b/packages/eve/src/cli/run.ts@@ -5,7 +5,6 @@ import {Option,} from "#compiled/commander/index.js";import { registerBuildCommand, type BuildHost } from "#cli/commands/build.js";-import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";import { resolveApplicationRoot } from "#internal/application/paths.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { isCodingAgentLaunch } from "#cli/agent-detection.js";@@ -49,9 +48,15 @@ import {import type { AgentReasoningDefinition } from "#shared/agent-definition.js";import { findEveProjectContext, resolveEveProjectContext } from "#internal/project-context.js";import { parseDevelopmentServerUrl } from "#cli/dev/url.js";+import { createDevBootProgressReporter } from "#cli/dev/boot-progress.js";import { startCliLiveRow } from "#cli/ui/live-row.js";import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";-import { createLogger } from "#internal/logging.js";+import { registerEveTelemetryCommands } from "#cli/telemetry/command.js";+import {+ canonicalCommand,+ createEveCliTelemetry,+ type EveCliTelemetry,+} from "#cli/telemetry/index.js";import type {DevelopmentServer,DevelopmentServerOptions,@@ -101,31 +106,6 @@ interface CliRuntimeDependencies {type CliRuntimeOverrides = Partial<CliRuntimeDependencies>;-const devBootLog = createLogger("dev.boot");--function createDevBootProgressReporter(- row: ReturnType<typeof startCliLiveRow> | undefined,-): DevBootProgressReporter {- return (event) => {- switch (event.type) {- case "phase-started":- row?.update("Building your agent", event.phase);- devBootLog.debug(event.phase);- return;- case "phase-finished":- devBootLog.debug(`${event.phase} finished`, { ms: event.elapsedMs });- return;- case "before-first-paint":- row?.stop();- return;- default: {- const exhaustive: never = event;- return exhaustive;- }- }- };-}-async function loadPrintApplicationInfo(): Promise<CliRuntimeDependencies["printApplicationInfo"]> {return (await import("#cli/commands/info.js")).printApplicationInfo;}@@ -153,10 +133,11 @@ function hasInteractiveTerminal(): boolean {return Boolean(process.stdin.isTTY && process.stdout.isTTY);}-function createCliProgram(+export function createCliProgram(logger: CliLogger,runtime: CliRuntimeOverrides,applicationContext: CliApplicationContext,+ telemetry: Pick<EveCliTelemetry, "trackDevContext">,): Command {const packageVersion = resolveInstalledPackageInfo().version;const program = new Command();@@ -195,6 +176,8 @@ function createCliProgram(await runChannelsListCommand(logger, applicationContext.project!, options);});+ registerEveTelemetryCommands(program, logger);+registerIntegrationCommands({ program, logger, applicationContext });const extension = program@@ -396,6 +379,7 @@ function createCliProgram(const remoteServerUrl = remoteTarget?.serverUrl;const interactive = hasInteractiveTerminal();const mode = resolveDevUiMode({ options, interactive });+ telemetry.trackDevContext({ target: remoteTarget ? "remote" : "local", ui: mode });if (mode === "headless") logger.log(eveCliBanner());if (options.input !== undefined && mode === "headless") {throw new InvalidArgumentError("--input requires the interactive UI.");@@ -651,7 +635,8 @@ export async function runCli(return resolveEveProjectContext(applicationContext.root);},};- const program = createCliProgram(logger, runtime, applicationContext);+ const telemetry = createEveCliTelemetry(resolveInstalledPackageInfo().version);+ const program = createCliProgram(logger, runtime, applicationContext, telemetry);let input = argv;if (input.length === 0) {const findApplicationRoot = runtime.findApplicationRoot ?? findCliApplicationRoot;@@ -664,17 +649,23 @@ export async function runCli(input = ["dev"];}}+ const command = canonicalCommand(input);+ telemetry.trackCommand(command);+ if (command !== "telemetry") await telemetry.notify(logger);try {await program.parseAsync(input, {from: "user",});+ telemetry.trackOutcome("success");} catch (error) {- if (error instanceof CommanderError) {- if (error.exitCode === 0) {- return;- }+ if (error instanceof CommanderError && error.exitCode === 0) {+ telemetry.trackOutcome("success");+ return;+ }+ telemetry.trackOutcome(error instanceof CommanderError ? "usage_error" : "error");+ if (error instanceof CommanderError) {// A coding agent that fumbles `eve init` can trip commander before the// init action runs, so the action's own agent detection never fires.// Commander has already written its usage error to stderr; add the setup@@ -691,5 +682,7 @@ export async function runCli(}throw error;+ } finally {+ await telemetry.flush();}}diff --git a/packages/eve/src/cli/telemetry/command.test.ts b/packages/eve/src/cli/telemetry/command.test.tsnew file mode 100644index 000000000..20769953c--- /dev/null+++ b/packages/eve/src/cli/telemetry/command.test.ts@@ -0,0 +1,38 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ disableEveTelemetry,+ enableEveTelemetry,+ showEveTelemetryStatus,+} from "#cli/telemetry/command.js";+import { readEveTelemetryPreference, setEveTelemetryEnabled } from "#cli/telemetry/preference.js";++vi.mock("#cli/telemetry/preference.js", () => ({+ readEveTelemetryPreference: vi.fn(async () => ({ enabled: true, notified: false })),+ setEveTelemetryEnabled: vi.fn(),+}));++afterEach(() => {+ vi.clearAllMocks();+});++describe("eve telemetry", () => {+ it("reports the durable preference", async () => {+ vi.mocked(readEveTelemetryPreference).mockResolvedValue({ enabled: false, notified: true });+ const logger = { log: vi.fn() };++ await showEveTelemetryStatus(logger);++ expect(logger.log).toHaveBeenCalledWith("Telemetry status: Disabled");+ });++ it("updates the durable preference", async () => {+ const logger = { log: vi.fn() };++ await enableEveTelemetry(logger);+ await disableEveTelemetry(logger);++ expect(setEveTelemetryEnabled).toHaveBeenNthCalledWith(1, true);+ expect(setEveTelemetryEnabled).toHaveBeenNthCalledWith(2, false);+ });+});diff --git a/packages/eve/src/cli/telemetry/command.ts b/packages/eve/src/cli/telemetry/command.tsnew file mode 100644index 000000000..3e9504f47--- /dev/null+++ b/packages/eve/src/cli/telemetry/command.ts@@ -0,0 +1,49 @@+import type { Command } from "#compiled/commander/index.js";+import { flushEveCliTelemetry } from "#cli/telemetry/flush.js";+import { readEveTelemetryPreference, setEveTelemetryEnabled } from "#cli/telemetry/preference.js";++type TelemetryLogger = {+ log(message: string): void;+};++export function registerEveTelemetryCommands(program: Command, logger: TelemetryLogger): void {+ const telemetry = program+ .command("telemetry")+ .description("Enable or disable CLI telemetry collection.");+ telemetry+ .command("status")+ .description("Show whether telemetry collection is enabled.")+ .action(async () => {+ await showEveTelemetryStatus(logger);+ });+ telemetry+ .command("enable")+ .description("Enable telemetry collection.")+ .action(async () => {+ await enableEveTelemetry(logger);+ });+ telemetry+ .command("disable")+ .description("Disable telemetry collection.")+ .action(async () => {+ await disableEveTelemetry(logger);+ });+ telemetry.command("flush <payload>", { hidden: true }).action(async (payload: string) => {+ await flushEveCliTelemetry(payload);+ });+}++export async function showEveTelemetryStatus(logger: TelemetryLogger): Promise<void> {+ const { enabled } = await readEveTelemetryPreference();+ logger.log(`Telemetry status: ${enabled ? "Enabled" : "Disabled"}`);+}++export async function enableEveTelemetry(logger: TelemetryLogger): Promise<void> {+ await setEveTelemetryEnabled(true);+ logger.log("Telemetry collection enabled.");+}++export async function disableEveTelemetry(logger: TelemetryLogger): Promise<void> {+ await setEveTelemetryEnabled(false);+ logger.log("Telemetry collection disabled. No data will be collected from this machine.");+}diff --git a/packages/eve/src/cli/telemetry/flush.test.ts b/packages/eve/src/cli/telemetry/flush.test.tsnew file mode 100644index 000000000..ec8c929d9--- /dev/null+++ b/packages/eve/src/cli/telemetry/flush.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from "vitest";++import { flushEveCliTelemetry } from "#cli/telemetry/flush.js";++describe("flushEveCliTelemetry", () => {+ it("posts a valid batch", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response());+ vi.stubGlobal("fetch", fetchMock);+ vi.stubEnv("EVE_TELEMETRY_ENDPOINT", "http://localhost/events");++ await flushEveCliTelemetry(+ JSON.stringify({+ sessionId: "session_123",+ events: [{ id: "event_123", event_time: 1, key: "command", value: "info" }],+ }),+ );++ expect(fetchMock).toHaveBeenCalledWith(+ "http://localhost/events",+ expect.objectContaining({+ headers: expect.objectContaining({ "x-eve-cli-session-id": "session_123" }),+ }),+ );+ });++ it("ignores an invalid payload", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);++ await flushEveCliTelemetry("not json");++ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/cli/telemetry/flush.ts b/packages/eve/src/cli/telemetry/flush.tsnew file mode 100644index 000000000..31a977f71--- /dev/null+++ b/packages/eve/src/cli/telemetry/flush.ts@@ -0,0 +1,48 @@+const DEFAULT_ENDPOINT = "https://telemetry.vercel.com/api/eve-cli/v1/events";+const REQUEST_TIMEOUT_MS = 1_000;++type TelemetryEvent = {+ readonly id: string;+ readonly event_time: number;+ readonly key: string;+ readonly value: string;+};++type FlushPayload = {+ readonly events: TelemetryEvent[];+ readonly sessionId: string;+};++function isFlushPayload(value: unknown): value is FlushPayload {+ if (!value || typeof value !== "object") return false;+ const payload = value as Partial<FlushPayload>;+ return typeof payload.sessionId === "string" && Array.isArray(payload.events);+}++/** Sends a telemetry batch from the telemetry-disabled child CLI process. */+export async function flushEveCliTelemetry(payloadJson: string): Promise<void> {+ let payload: FlushPayload;+ try {+ const parsed = JSON.parse(payloadJson) as unknown;+ if (!isFlushPayload(parsed)) return;+ payload = parsed;+ } catch {+ return;+ }++ try {+ await fetch(process.env.EVE_TELEMETRY_ENDPOINT ?? DEFAULT_ENDPOINT, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "client-id": "eve-cli",+ "x-eve-cli-topic-id": "generic",+ "x-eve-cli-session-id": payload.sessionId,+ },+ body: JSON.stringify(payload.events),+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ } catch {+ // Telemetry must never affect command output or exit status.+ }+}diff --git a/packages/eve/src/cli/telemetry/identity.test.ts b/packages/eve/src/cli/telemetry/identity.test.tsnew file mode 100644index 000000000..874550cdb--- /dev/null+++ b/packages/eve/src/cli/telemetry/identity.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";++import { hashEveTelemetryProject, resolveEveTelemetryProjectId } from "#cli/telemetry/identity.js";++const identity = { installationId: "installation_123", projectSalt: "project_salt_123" };++describe("eve CLI telemetry identity", () => {+ it("uses the Git remote before environment and working-directory fallbacks", async () => {+ const projectId = await resolveEveTelemetryProjectId({+ cwd: "/project",+ repositoryUrl: "https://example.com/environment.git",+ identity,+ getGitRemote: async () => "[email protected]:owner/project.git",+ });++ expect(projectId).toBe(hashEveTelemetryProject(identity, "[email protected]:owner/project.git"));+ expect(projectId).not.toBe("[email protected]:owner/project.git");+ });++ it("uses the repository environment variable before the working directory", async () => {+ const projectId = await resolveEveTelemetryProjectId({+ cwd: "/project",+ repositoryUrl: "https://example.com/environment.git",+ identity,+ getGitRemote: async () => undefined,+ });++ expect(projectId).toBe(+ hashEveTelemetryProject(identity, "https://example.com/environment.git"),+ );+ });++ it("uses the working directory when no repository identifier is available", async () => {+ const projectId = await resolveEveTelemetryProjectId({+ cwd: "/project",+ identity,+ getGitRemote: async () => undefined,+ });++ expect(projectId).toBe(hashEveTelemetryProject(identity, "/project"));+ });++ it("uses different hashes for different salts", () => {+ expect(hashEveTelemetryProject(identity, "project")).not.toBe(+ hashEveTelemetryProject({ ...identity, projectSalt: "other_salt" }, "project"),+ );+ });+});diff --git a/packages/eve/src/cli/telemetry/identity.ts b/packages/eve/src/cli/telemetry/identity.tsnew file mode 100644index 000000000..3705ad77d--- /dev/null+++ b/packages/eve/src/cli/telemetry/identity.ts@@ -0,0 +1,52 @@+import { execFile } from "node:child_process";+import { createHash, randomUUID } from "node:crypto";+import { existsSync } from "node:fs";+import { promisify } from "node:util";++const runFile = promisify(execFile);+const GIT_TIMEOUT_MS = 1_000;++export type EveCliTelemetryIdentity = {+ readonly installationId: string;+ readonly projectSalt: string;+};++export function createEveTelemetryIdentity(): EveCliTelemetryIdentity {+ return { installationId: randomUUID(), projectSalt: randomUUID() };+}++export function isEphemeralEveTelemetryEnvironment(): boolean {+ return Boolean(process.env.CI) || existsSync("/.dockerenv");+}++export function hashEveTelemetryProject(identity: EveCliTelemetryIdentity, value: string): string {+ return createHash("sha256").update(identity.projectSalt).update(value).digest("hex");+}++export async function resolveEveTelemetryProjectId(input: {+ readonly cwd?: string;+ readonly repositoryUrl?: string;+ readonly getGitRemote?: (cwd: string) => Promise<string | undefined>;+ readonly identity: EveCliTelemetryIdentity;+}): Promise<string> {+ const cwd = input.cwd ?? process.cwd();+ const gitRemote = await (input.getGitRemote ?? getGitRemote)(cwd);+ return hashEveTelemetryProject(+ input.identity,+ gitRemote ?? input.repositoryUrl ?? process.env.REPOSITORY_URL ?? cwd,+ );+}++async function getGitRemote(cwd: string): Promise<string | undefined> {+ try {+ const { stdout } = await runFile("git", ["config", "--local", "--get", "remote.origin.url"], {+ cwd,+ timeout: GIT_TIMEOUT_MS,+ windowsHide: true,+ });+ const value = stdout.trim();+ return value === "" ? undefined : value;+ } catch {+ return undefined;+ }+}diff --git a/packages/eve/src/cli/telemetry/index.test.ts b/packages/eve/src/cli/telemetry/index.test.tsnew file mode 100644index 000000000..25bd66c06--- /dev/null+++ b/packages/eve/src/cli/telemetry/index.test.ts@@ -0,0 +1,216 @@+import { spawn } from "node:child_process";+import { EventEmitter } from "node:events";++import { afterEach, describe, expect, it, vi } from "vitest";++vi.mock("node:child_process", async (importOriginal) => ({+ ...(await importOriginal<typeof import("node:child_process")>()),+ spawn: vi.fn(),+}));++import { canonicalCommand, createEveCliTelemetry } from "#cli/telemetry/index.js";+import {+ createEveTelemetryIdentity,+ isEphemeralEveTelemetryEnvironment,+ resolveEveTelemetryProjectId,+} from "#cli/telemetry/identity.js";+import {+ markEveTelemetryNotified,+ readEveTelemetryPreference,+ readOrCreateEveTelemetryIdentity,+} from "#cli/telemetry/preference.js";++vi.mock("#cli/telemetry/identity.js", () => ({+ createEveTelemetryIdentity: vi.fn(() => ({+ installationId: "ephemeral_installation_123",+ projectSalt: "ephemeral_project_salt_123",+ })),+ isEphemeralEveTelemetryEnvironment: vi.fn(() => false),+ resolveEveTelemetryProjectId: vi.fn(async () => "project_123"),+}));++vi.mock("#cli/telemetry/preference.js", () => ({+ markEveTelemetryNotified: vi.fn(),+ readEveTelemetryPreference: vi.fn(async () => ({ enabled: true, notified: false })),+ readOrCreateEveTelemetryIdentity: vi.fn(async () => ({+ installationId: "installation_123",+ projectSalt: "project_salt_123",+ })),+}));++afterEach(() => {+ vi.unstubAllEnvs();+ vi.clearAllMocks();+ vi.mocked(readEveTelemetryPreference)+ .mockReset()+ .mockResolvedValue({ enabled: true, notified: false });+ vi.mocked(readOrCreateEveTelemetryIdentity)+ .mockReset()+ .mockResolvedValue({ installationId: "installation_123", projectSalt: "project_salt_123" });+ vi.mocked(createEveTelemetryIdentity).mockReset().mockReturnValue({+ installationId: "ephemeral_installation_123",+ projectSalt: "ephemeral_project_salt_123",+ });+ vi.mocked(isEphemeralEveTelemetryEnvironment).mockReset().mockReturnValue(false);+});++describe("canonicalCommand", () => {+ it("records default and nested command paths without user-supplied values", () => {+ expect(canonicalCommand([])).toBe("dev");+ expect(canonicalCommand(["dev", "https://agent.example"])).toBe("dev");+ expect(canonicalCommand(["registry", "search", "private-query"])).toBe("registry:search");+ expect(canonicalCommand(["logs"])).toBe("logs:show");+ expect(canonicalCommand(["traces"])).toBe("traces:show");+ });++ it("records root help and version separately from the default command", () => {+ expect(canonicalCommand(["--help"])).toBe("help");+ expect(canonicalCommand(["-h"])).toBe("help");+ expect(canonicalCommand(["--version"])).toBe("version");+ expect(canonicalCommand(["-V"])).toBe("version");+ });++ it("records supported top-level commands and buckets unknown commands", () => {+ expect(canonicalCommand(["set", "--model", "private/model"])).toBe("set");+ expect(canonicalCommand(["not-a-command", "private-argument"])).toBe("unknown");+ });+});++describe("createEveCliTelemetry", () => {+ it("does not spawn a flush process when the environment override disables telemetry", async () => {+ vi.stubEnv("EVE_TELEMETRY_DISABLED", "1");+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("info");++ await telemetry.flush();++ expect(spawn).not.toHaveBeenCalled();+ expect(readEveTelemetryPreference).not.toHaveBeenCalled();+ expect(readOrCreateEveTelemetryIdentity).not.toHaveBeenCalled();+ });++ it("does not spawn a flush process when the durable preference disables telemetry", async () => {+ vi.mocked(readEveTelemetryPreference).mockResolvedValue({ enabled: false, notified: true });+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("info");++ await telemetry.flush();++ expect(spawn).not.toHaveBeenCalled();+ expect(readOrCreateEveTelemetryIdentity).not.toHaveBeenCalled();+ });++ it("prints and persists the first-run notice on an interactive terminal", async () => {+ vi.stubEnv("NODE_ENV", "production");+ const stderr = Object.getOwnPropertyDescriptor(process.stderr, "isTTY");+ Object.defineProperty(process.stderr, "isTTY", { configurable: true, value: true });+ const logger = { error: vi.fn() };+ try {+ await createEveCliTelemetry("1.0.0").notify(logger);+ } finally {+ if (stderr === undefined) Reflect.deleteProperty(process.stderr, "isTTY");+ else Object.defineProperty(process.stderr, "isTTY", stderr);+ }++ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining("eve telemetry disable"));+ expect(markEveTelemetryNotified).toHaveBeenCalled();+ });++ it("records resolved dev context without inspecting command arguments", async () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("EVE_TELEMETRY_DEBUG", "1");+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("dev");+ telemetry.trackDevContext({ target: "remote", ui: "headless" });++ await telemetry.flush();++ const events = JSON.parse(+ String(write.mock.calls[0]?.[0]).replace("[eve telemetry] ", ""),+ ) as Array<{+ key: string;+ value: string;+ }>;+ expect(events).toContainEqual(expect.objectContaining({ key: "target", value: "remote" }));+ expect(events).toContainEqual(expect.objectContaining({ key: "ui", value: "headless" }));+ expect(events).toContainEqual(+ expect.objectContaining({ key: "installation_id", value: "installation_123" }),+ );+ expect(events).toContainEqual(+ expect.objectContaining({ key: "project_id", value: "project_123" }),+ );+ expect(resolveEveTelemetryProjectId).toHaveBeenCalledWith({+ identity: { installationId: "installation_123", projectSalt: "project_salt_123" },+ });+ });++ it("skips telemetry when identity initialization fails", async () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.mocked(readOrCreateEveTelemetryIdentity).mockRejectedValue(new Error("read-only config"));+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("info");++ await expect(telemetry.flush()).resolves.toBeUndefined();++ expect(spawn).not.toHaveBeenCalled();+ });++ it("uses an in-memory identity in an ephemeral environment", async () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("EVE_TELEMETRY_DEBUG", "1");+ vi.mocked(isEphemeralEveTelemetryEnvironment).mockReturnValue(true);+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("info");++ await telemetry.flush();++ expect(readOrCreateEveTelemetryIdentity).not.toHaveBeenCalled();+ expect(createEveTelemetryIdentity).toHaveBeenCalledOnce();+ expect(String(write.mock.calls[0]?.[0])).toContain("ephemeral_installation_123");+ });++ it("flushes an allowlisted outcome through a telemetry-disabled child process", async () => {+ const child = Object.assign(new EventEmitter(), { unref: vi.fn() });+ vi.mocked(spawn).mockReturnValue(child as never);+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("EVE_TELEMETRY_DISABLED", "");+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("info");+ telemetry.trackOutcome("usage_error");++ await telemetry.flush();++ expect(spawn).toHaveBeenCalledWith(+ process.execPath,+ expect.arrayContaining([process.argv[1], "telemetry", "flush"]),+ expect.objectContaining({+ detached: true,+ env: expect.objectContaining({ EVE_TELEMETRY_DISABLED: "1" }),+ }),+ );+ expect(child.unref).toHaveBeenCalled();+ const payload = JSON.parse(vi.mocked(spawn).mock.calls[0]![1][3]!) as {+ events: Array<{ key: string; value: string }>;+ };+ expect(payload.events).toContainEqual(+ expect.objectContaining({ key: "outcome", value: "usage_error" }),+ );+ expect(payload.events).not.toContainEqual(expect.objectContaining({ key: "error_code" }));+ expect(payload.events).not.toContainEqual(expect.objectContaining({ key: "error_status" }));+ });++ it("ignores asynchronous child-process errors", async () => {+ const child = Object.assign(new EventEmitter(), { unref: vi.fn() });+ vi.mocked(spawn).mockReturnValue(child as never);+ vi.stubEnv("NODE_ENV", "production");+ const telemetry = createEveCliTelemetry("1.0.0");+ telemetry.trackCommand("info");++ await telemetry.flush();++ expect(() => child.emit("error", new Error("spawn failed"))).not.toThrow();+ expect(child.unref).toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/cli/telemetry/index.ts b/packages/eve/src/cli/telemetry/index.tsnew file mode 100644index 000000000..4f85d2a05--- /dev/null+++ b/packages/eve/src/cli/telemetry/index.ts@@ -0,0 +1,180 @@+import { spawn } from "node:child_process";+import { randomUUID } from "node:crypto";+import os from "node:os";++import {+ createEveTelemetryIdentity,+ isEphemeralEveTelemetryEnvironment,+ resolveEveTelemetryProjectId,+} from "#cli/telemetry/identity.js";+import {+ markEveTelemetryNotified,+ readEveTelemetryPreference,+ readOrCreateEveTelemetryIdentity,+} from "#cli/telemetry/preference.js";++export type EveCliTelemetryEvent = {+ readonly id: string;+ readonly event_time: number;+ readonly key: string;+ readonly value: string;+};++export type EveCliTelemetry = {+ trackCommand(command: string): void;+ trackDevContext(context: { target: "local" | "remote"; ui: "tui" | "headless" }): void;+ trackOutcome(outcome: "success" | "usage_error" | "error"): void;+ notify(logger: { error(message: string): void }): Promise<void>;+ flush(): Promise<void>;+};++async function isEnabled(): Promise<boolean> {+ return (+ process.env.NODE_ENV !== "test" &&+ !process.env.EVE_TELEMETRY_DISABLED &&+ (await readEveTelemetryPreference()).enabled+ );+}++function event(key: string, value: string): EveCliTelemetryEvent {+ return { id: randomUUID(), event_time: Date.now(), key, value };+}++const CLI_TELEMETRY_COMMANDS = new Map<string, string>([+ ["acp", "acp"],+ ["add", "add"],+ ["build", "build"],+ ["channels", "channels"],+ ["channels:list", "channels:list"],+ ["deploy", "deploy"],+ ["dev", "dev"],+ ["eval", "eval"],+ ["extension", "extension"],+ ["extension:build", "extension:build"],+ ["extension:init", "extension:init"],+ ["info", "info"],+ ["init", "init"],+ ["integration", "integration"],+ ["integration:connect", "integration:connect"],+ ["integration:setup", "integration:setup"],+ ["invoke", "invoke"],+ ["link", "link"],+ ["logs", "logs:show"],+ ["logs:ls", "logs:ls"],+ ["logs:show", "logs:show"],+ ["registry", "registry"],+ ["registry:add", "registry:add"],+ ["registry:list", "registry:list"],+ ["registry:search", "registry:search"],+ ["registry:view", "registry:view"],+ ["set", "set"],+ ["start", "start"],+ ["telemetry", "telemetry"],+ ["telemetry:disable", "telemetry:disable"],+ ["telemetry:enable", "telemetry:enable"],+ ["telemetry:status", "telemetry:status"],+ ["traces", "traces:show"],+ ["traces:ls", "traces:ls"],+]);++/** Explicit privacy allowlist for command values emitted by CLI telemetry. */+export const cliTelemetryCommandPaths = new Set(CLI_TELEMETRY_COMMANDS.keys());++/** Internal command paths that must never emit telemetry. */+export const internalCliCommandPaths = new Set(["telemetry:flush"]);++/** Returns only an allowlisted command path; it never includes user input. */+export function canonicalCommand(argv: readonly string[]): string {+ const firstArgument = argv[0];+ if (firstArgument === "--help" || firstArgument === "-h") return "help";+ if (firstArgument === "--version" || firstArgument === "-V") return "version";++ const commandIndex = argv.findIndex((argument) => !argument.startsWith("-"));+ const command = argv[commandIndex];+ if (command === undefined || /^https?:\/\//.test(command)) return "dev";++ const nested = argv.slice(commandIndex + 1).find((argument) => !argument.startsWith("-"));+ if (nested !== undefined) {+ const nestedCommand = CLI_TELEMETRY_COMMANDS.get(`${command}:${nested}`);+ if (nestedCommand !== undefined) return nestedCommand;+ }+ return CLI_TELEMETRY_COMMANDS.get(command) ?? "unknown";+}++export function createEveCliTelemetry(version: string): EveCliTelemetry {+ const events: EveCliTelemetryEvent[] = [+ event("version", version),+ event("platform", os.platform()),+ event("arch", os.arch()),+ event("stdin_is_tty", process.stdin.isTTY ? "true" : "false"),+ ];+ const sessionId = randomUUID();++ return {+ trackCommand(command) {+ events.push(event("command", command));+ },+ trackDevContext(context) {+ events.push(event("target", context.target), event("ui", context.ui));+ },+ trackOutcome(outcome) {+ events.push(event("outcome", outcome));+ },+ async notify(logger) {+ const preference = await readEveTelemetryPreference();+ if (+ process.env.NODE_ENV === "test" ||+ process.env.EVE_TELEMETRY_DISABLED ||+ !preference.enabled ||+ preference.notified ||+ !process.stderr.isTTY+ ) {+ return;+ }+ logger.error(+ "Attention: eve collects CLI telemetry to improve the command-line interface.\n" ++ "Disable it with `eve telemetry disable`, or for one command set EVE_TELEMETRY_DISABLED=1.\n" ++ "Learn more: https://eve.dev/docs/reference/telemetry",+ );+ try {+ await markEveTelemetryNotified();+ } catch {+ // Failing to persist the notice must not affect the command.+ }+ },+ async flush() {+ if (!(await isEnabled()) || events.length === 0) return;+ try {+ const identity = isEphemeralEveTelemetryEnvironment()+ ? createEveTelemetryIdentity()+ : await readOrCreateEveTelemetryIdentity();+ events.push(+ event("installation_id", identity.installationId),+ event("project_id", await resolveEveTelemetryProjectId({ identity })),+ );+ } catch {+ return;+ }+ if (process.env.EVE_TELEMETRY_DEBUG) {+ process.stderr.write(`[eve telemetry] ${JSON.stringify(events)}\n`);+ return;+ }+ try {+ const child = spawn(+ process.execPath,+ [process.argv[1] ?? "", "telemetry", "flush", JSON.stringify({ events, sessionId })],+ {+ detached: true,+ env: { ...process.env, EVE_TELEMETRY_DISABLED: "1" },+ stdio: "ignore",+ windowsHide: true,+ },+ );+ child.on("error", () => {});+ child.unref();+ } catch {+ // Telemetry must never affect command output or exit status.+ }+ },+ };+}diff --git a/packages/eve/src/cli/telemetry/preference.test.ts b/packages/eve/src/cli/telemetry/preference.test.tsnew file mode 100644index 000000000..b47bb8eeb--- /dev/null+++ b/packages/eve/src/cli/telemetry/preference.test.ts@@ -0,0 +1,120 @@+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++vi.mock("node:fs/promises", () => ({+ mkdir: vi.fn(),+ readFile: vi.fn(),+ rename: vi.fn(),+ rm: vi.fn(),+ writeFile: vi.fn(),+}));++import {+ markEveTelemetryNotified,+ readEveTelemetryPreference,+ readOrCreateEveTelemetryIdentity,+ setEveTelemetryEnabled,+} from "#cli/telemetry/preference.js";++afterEach(() => {+ vi.unstubAllEnvs();+ vi.clearAllMocks();+});++describe("eve telemetry preference", () => {+ it("defaults to enabled before a preference exists", async () => {+ vi.mocked(readFile).mockRejectedValue(new Error("missing"));++ await expect(readEveTelemetryPreference()).resolves.toEqual({ enabled: true, notified: false });+ });++ it("reads a persisted opt-out and current notice version", async () => {+ vi.mocked(readFile).mockResolvedValue(+ '{"telemetry":{"enabled":false,"noticeVersion":1,"notifiedAt":"now"}}',+ );++ await expect(readEveTelemetryPreference()).resolves.toEqual({ enabled: false, notified: true });+ });++ it("shows the versioned notice when only an older notice timestamp exists", async () => {+ vi.mocked(readFile).mockResolvedValue('{"telemetry":{"notifiedAt":"now"}}');++ await expect(readEveTelemetryPreference()).resolves.toEqual({ enabled: true, notified: false });+ });++ it("creates and persists a telemetry identity", async () => {+ vi.mocked(readFile).mockRejectedValue(new Error("missing"));++ const identity = await readOrCreateEveTelemetryIdentity();++ expect(identity.installationId).toMatch(/^[0-9a-f-]{36}$/);+ expect(identity.projectSalt).toMatch(/^[0-9a-f-]{36}$/);+ expect(writeFile).toHaveBeenCalledWith(+ expect.any(String),+ expect.stringContaining(identity.installationId),+ { mode: 0o600 },+ );+ expect(writeFile).toHaveBeenCalledWith(+ expect.any(String),+ expect.stringContaining(identity.projectSalt),+ { mode: 0o600 },+ );+ });++ it("ignores a relative XDG config home", async () => {+ vi.stubEnv("XDG_CONFIG_HOME", "relative-config");+ vi.mocked(readFile).mockRejectedValue(new Error("missing"));++ await setEveTelemetryEnabled(false);++ expect(mkdir).toHaveBeenCalledWith(join(homedir(), ".config", "eve"), { recursive: true });+ });++ it("merges telemetry changes into the eve config atomically", async () => {+ vi.stubEnv("XDG_CONFIG_HOME", "/eve-config");+ vi.mocked(readFile)+ .mockResolvedValueOnce('{"other":"preserved","telemetry":{"future":"preserved"}}')+ .mockResolvedValueOnce(+ '{"other":"preserved","telemetry":{"future":"preserved","enabled":false}}',+ );++ await setEveTelemetryEnabled(false);+ await markEveTelemetryNotified();++ expect(mkdir).toHaveBeenCalledWith("/eve-config/eve", { recursive: true });+ expect(writeFile).toHaveBeenNthCalledWith(+ 1,+ expect.stringMatching(/^\/eve-config\/eve\/config\.json\./),+ expect.stringContaining('"other": "preserved"'),+ { mode: 0o600 },+ );+ expect(writeFile).toHaveBeenNthCalledWith(+ 2,+ expect.stringMatching(/^\/eve-config\/eve\/config\.json\./),+ expect.stringContaining('"future": "preserved"'),+ { mode: 0o600 },+ );+ expect(writeFile).toHaveBeenNthCalledWith(+ 2,+ expect.stringMatching(/^\/eve-config\/eve\/config\.json\./),+ expect.stringContaining('"enabled": false'),+ { mode: 0o600 },+ );+ expect(writeFile).toHaveBeenNthCalledWith(+ 2,+ expect.stringMatching(/^\/eve-config\/eve\/config\.json\./),+ expect.stringContaining('"noticeVersion": 1'),+ { mode: 0o600 },+ );+ expect(writeFile).toHaveBeenNthCalledWith(+ 2,+ expect.stringMatching(/^\/eve-config\/eve\/config\.json\./),+ expect.stringContaining('"notifiedAt"'),+ { mode: 0o600 },+ );+ expect(rename).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/eve/src/cli/telemetry/preference.ts b/packages/eve/src/cli/telemetry/preference.tsnew file mode 100644index 000000000..fb06d5bdb--- /dev/null+++ b/packages/eve/src/cli/telemetry/preference.ts@@ -0,0 +1,128 @@+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import { homedir } from "node:os";++import {+ createEveTelemetryIdentity,+ type EveCliTelemetryIdentity,+} from "#cli/telemetry/identity.js";+import { dirname, isAbsolute, join } from "node:path";++import { z } from "zod";++const EVE_TELEMETRY_NOTICE_VERSION = 1;++export type EveTelemetryPreference = {+ readonly enabled: boolean;+ readonly notified: boolean;+};++function configuredDirectory(value: string | undefined, fallback: string): string {+ return value && isAbsolute(value) ? value : fallback;+}++function eveConfigPath(): string {+ const home = homedir();+ if (process.platform === "win32") {+ return join(+ configuredDirectory(process.env.APPDATA, join(home, "AppData", "Roaming")),+ "eve",+ "config.json",+ );+ }+ if (process.platform === "darwin") {+ return join(home, "Library", "Preferences", "eve", "config.json");+ }+ return join(+ configuredDirectory(process.env.XDG_CONFIG_HOME, join(home, ".config")),+ "eve",+ "config.json",+ );+}++const EveConfigSchema = z.looseObject({+ telemetry: z+ .looseObject({+ enabled: z.boolean().default(true),+ installationId: z.string().optional(),+ noticeVersion: z.number().int().positive().optional(),+ notifiedAt: z.string().optional(),+ projectSalt: z.string().optional(),+ })+ .optional(),+});++function parsePreference(value: unknown): EveTelemetryPreference {+ const telemetry = EveConfigSchema.safeParse(value).data?.telemetry;+ return {+ enabled: telemetry?.enabled ?? true,+ notified: telemetry?.noticeVersion === EVE_TELEMETRY_NOTICE_VERSION,+ };+}++export async function readEveTelemetryPreference(): Promise<EveTelemetryPreference> {+ try {+ return parsePreference(JSON.parse(await readFile(eveConfigPath(), "utf8")) as unknown);+ } catch {+ return { enabled: true, notified: false };+ }+}++export async function readOrCreateEveTelemetryIdentity(): Promise<EveCliTelemetryIdentity> {+ let telemetry: z.infer<typeof EveConfigSchema>["telemetry"];+ try {+ telemetry = EveConfigSchema.safeParse(+ JSON.parse(await readFile(eveConfigPath(), "utf8")) as unknown,+ ).data?.telemetry;+ } catch {+ // An absent or malformed config starts with a fresh telemetry identity.+ }++ const identity =+ telemetry?.installationId && telemetry.projectSalt+ ? { installationId: telemetry.installationId, projectSalt: telemetry.projectSalt }+ : createEveTelemetryIdentity();+ if (+ telemetry?.installationId !== identity.installationId ||+ telemetry?.projectSalt !== identity.projectSalt+ ) {+ await updateEveTelemetryPreference(identity);+ }+ return identity;+}++async function updateEveTelemetryPreference(+ update: Record<string, boolean | number | string>,+): Promise<void> {+ const path = eveConfigPath();+ let existing: Record<string, unknown> = {};+ try {+ const parsed = JSON.parse(await readFile(path, "utf8")) as unknown;+ if (typeof parsed === "object" && parsed !== null) existing = parsed as Record<string, unknown>;+ } catch {+ // An absent or malformed config starts with the telemetry preference.+ }++ const telemetry =+ typeof existing.telemetry === "object" && existing.telemetry !== null ? existing.telemetry : {};+ const next = { ...existing, telemetry: { ...telemetry, ...update } };+ const temporaryPath = `${path}.${process.pid}.${Date.now()}.tmp`;+ await mkdir(dirname(path), { recursive: true });+ try {+ await writeFile(temporaryPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ await rename(temporaryPath, path);+ } catch (error) {+ await rm(temporaryPath, { force: true });+ throw error;+ }+}++export async function setEveTelemetryEnabled(enabled: boolean): Promise<void> {+ await updateEveTelemetryPreference({ enabled });+}++export async function markEveTelemetryNotified(): Promise<void> {+ await updateEveTelemetryPreference({+ noticeVersion: EVE_TELEMETRY_NOTICE_VERSION,+ notifiedAt: new Date().toISOString(),+ });+}