@echomem/mcp 1.4.63 → 1.4.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -16,8 +16,8 @@ import { MCP_PACKAGE_VERSION, MCP_SERVER_INSTRUCTIONS, MEMORY_CITATION_INSTRUCTI
16
16
  import { clearBillingAlert, writeBillingAlert } from "./billing-alert.js";
17
17
  import { checkLatestUpdateStatus, formatUpdateNotice, formatUpdateStatusText, startBackgroundUpdateCheck, } from "./update-check.js";
18
18
  import { autoUpdateHeadlessRuntime } from "./headless-runtime.js";
19
- import { formatTicketFilingPacket, ticketAddressById, } from "./ticket-review-format.js";
20
- import { SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE, resolveCloudCoworkSessionFromToolArguments, resolveSourceSessionRequestContext, resolveSourceSessionFromBindingToken, } from "./source-session.js";
19
+ import { formatTicketFilingPacket, formatWorkspaceTicketOverview, ticketAddressById, } from "./ticket-review-format.js";
20
+ import { SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE, resolveCloudCoworkSessionFromToolArguments, resolveSourceSessionRequestContext, resolveSourceSessionFromBindingToken, resolveSourceSessionFromBindingTokenWithRetry, } from "./source-session.js";
21
21
  const ECHO_API_BASE_URL = process.env.ECHO_API_BASE_URL || "https://echo-mem-chrome.vercel.app";
22
22
  const ECHO_PRICING_URL = process.env.ECHO_PRICING_URL || "https://echoknows.com/account";
23
23
  const ECHO_MEMORY_WEB_URL = (process.env.ECHO_MEMORY_WEB_URL || "https://echoknows.com/memory").replace(/\/$/, "");
@@ -722,6 +722,7 @@ class EchoMemApiClient {
722
722
  baseURL: ECHO_API_BASE_URL.replace(/\/$/, ""),
723
723
  headers: {
724
724
  "Content-Type": "application/json",
725
+ "X-Echo-Client": "mcp",
725
726
  },
726
727
  });
727
728
  // Read the token fresh on EVERY request (not baked in at construction) so a `login` that runs
@@ -850,6 +851,51 @@ class EchoMemApiClient {
850
851
  });
851
852
  return response.data;
852
853
  }
854
+ // Workspace stewardship reads/writes. Both endpoints authorise on workspace
855
+ // MEMBERSHIP, not on a verified source session, so these keep working when
856
+ // per-conversation identity is unavailable (FIND-112).
857
+ async resolveStewardshipWorkspaceId(explicit) {
858
+ if (explicit)
859
+ return explicit;
860
+ const response = await this.axios.get("/api/extension/social/groups/current");
861
+ const group = isRecord(response.data?.group) ? response.data.group : null;
862
+ const id = group ? readString(group, "id") : undefined;
863
+ if (!id) {
864
+ throw new Error("Could not determine which workspace to steward. Pass workspaceId explicitly.");
865
+ }
866
+ return id;
867
+ }
868
+ async moveWorkspaceTicketDirect(args) {
869
+ const id = await this.resolveStewardshipWorkspaceId(args.workspaceId);
870
+ const response = await this.axios.patch(`/api/extension/workspaces/${encodeURIComponent(id)}/tickets/${encodeURIComponent(args.ticketId)}/move`, {
871
+ expectedVersion: args.expectedVersion,
872
+ newParentId: args.parentId ?? null,
873
+ ...(args.edgeKind ? { edgeKind: args.edgeKind } : {}),
874
+ });
875
+ return { workspaceId: id, data: response.data };
876
+ }
877
+ async stewardWorkspaceTickets(args) {
878
+ const { workspaceId, ...body } = args;
879
+ const id = await this.resolveStewardshipWorkspaceId(workspaceId);
880
+ const response = await this.axios.post(`/api/extension/workspaces/${encodeURIComponent(id)}/tickets/stewardship`, body);
881
+ return { workspaceId: id, data: response.data };
882
+ }
883
+ async listWorkspaceTicketsForOverview(workspaceId) {
884
+ const id = await this.resolveStewardshipWorkspaceId(workspaceId);
885
+ const response = await this.axios.get(`/api/extension/workspaces/${encodeURIComponent(id)}/tickets`);
886
+ return { workspaceId: id, data: response.data };
887
+ }
888
+ async updateWorkspaceTicketDirect(args) {
889
+ const id = await this.resolveStewardshipWorkspaceId(args.workspaceId);
890
+ const response = await this.axios.patch(`/api/extension/workspaces/${encodeURIComponent(id)}/tickets/${encodeURIComponent(args.ticketId)}`, {
891
+ expectedVersion: args.expectedVersion,
892
+ title: args.title,
893
+ description: args.description,
894
+ ownerId: args.ownerId,
895
+ ...(args.dueAt !== undefined ? { dueAt: args.dueAt } : {}),
896
+ });
897
+ return { workspaceId: id, data: response.data };
898
+ }
853
899
  async reviewWorkspaceTicketSession(args) {
854
900
  const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
855
901
  const sourceSession = this.getRequestSourceSession();
@@ -1731,6 +1777,25 @@ class EchoMemMCPServer {
1731
1777
  if (provisionalCloudSession && sourceResolution.sourceSession) {
1732
1778
  throw new McpError(ErrorCode.InvalidParams, "This request already has a verified local source session. Omit cloudCoworkSessionId rather than mixing identities.");
1733
1779
  }
1780
+ const sourceSessionBindingToken = isRecord(toolArgs)
1781
+ && typeof toolArgs.sourceSessionBindingToken === "string"
1782
+ ? toolArgs.sourceSessionBindingToken
1783
+ : null;
1784
+ if (sourceSessionBindingToken && (sourceResolution.sourceSession || provisionalCloudSession)) {
1785
+ throw new McpError(ErrorCode.InvalidParams, "This request already has a source-session identity. Omit sourceSessionBindingToken rather than mixing identities.");
1786
+ }
1787
+ if (sourceSessionBindingToken) {
1788
+ try {
1789
+ sourceResolution = {
1790
+ sourceSession: await resolveSourceSessionFromBindingTokenWithRetry(sourceSessionBindingToken, { hostPlatform: this.getMcpClientAnalytics().host_platform }),
1791
+ isSubagent: false,
1792
+ lineageStatus: "not_applicable",
1793
+ };
1794
+ }
1795
+ catch (error) {
1796
+ throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : "Could not verify the local source session");
1797
+ }
1798
+ }
1734
1799
  if (provisionalCloudSession) {
1735
1800
  sourceResolution = {
1736
1801
  sourceSession: provisionalCloudSession,
@@ -2330,7 +2395,8 @@ Details: ${m.details || "N/A"}`)
2330
2395
  "Final: false",
2331
2396
  `Ticket ${parsed.ticketId} was accepted for verified source-session discovery.`,
2332
2397
  "This is not a failed link. Echo Desktop can finish it asynchronously from the structured ticket marker or this exact local tool invocation.",
2333
- "The agent cannot verify final completion from this shared MCP request; use the ticket Activity as the current final-state evidence.",
2398
+ "For immediate request-scoped completion, retry once with a fresh random UUID in sourceSessionBindingToken. Never reuse that token or copy one from another conversation.",
2399
+ "If the retry cannot verify exactly one local transcript, leave Desktop recovery in place and use ticket Activity as the final-state evidence.",
2334
2400
  "Do not guess a context ID or call bind_source_session on the user's behalf unless its documented compatibility fallback is actually needed.",
2335
2401
  ].join("\n"),
2336
2402
  }],
@@ -2365,8 +2431,32 @@ Details: ${m.details || "N/A"}`)
2365
2431
  }],
2366
2432
  };
2367
2433
  }
2434
+ async handleWorkspaceTicketOverview(args) {
2435
+ const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
2436
+ const result = await this.client.listWorkspaceTicketsForOverview(parsed.workspaceId ?? parsed.groupId);
2437
+ const payload = isRecord(result.data) ? result.data : {};
2438
+ const tickets = Array.isArray(payload.tickets)
2439
+ ? payload.tickets.filter(isRecord)
2440
+ : [];
2441
+ return {
2442
+ content: [{
2443
+ type: "text",
2444
+ text: [
2445
+ `Workspace: ${result.workspaceId}`,
2446
+ ...formatWorkspaceTicketOverview({
2447
+ tickets,
2448
+ staleDays: parsed.staleDays,
2449
+ includeDescriptions: parsed.includeDescriptions,
2450
+ }),
2451
+ ].join("\n"),
2452
+ }],
2453
+ };
2454
+ }
2368
2455
  async handleReviewWorkspaceTicketSession(args) {
2369
2456
  const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
2457
+ if (parsed.operation === "overview") {
2458
+ return this.handleWorkspaceTicketOverview(args);
2459
+ }
2370
2460
  if (parsed.operation === "find_candidates") {
2371
2461
  return this.handleFindWorkspaceTicketCandidates(args);
2372
2462
  }
@@ -2384,7 +2474,8 @@ Details: ${m.details || "N/A"}`)
2384
2474
  text: [
2385
2475
  "Status: source_session_unavailable",
2386
2476
  "No verified source-session identity is available for this request, so EchoMem cannot review its ticket assignment.",
2387
- "Do not guess or ask the user for a context ID. Retry after automatic source-session binding is available.",
2477
+ "Retry this exact operation once with a fresh random UUID in sourceSessionBindingToken. The bridge verifies it from this tool call in the local host JSONL and keeps the identity request-scoped.",
2478
+ "Never reuse that token, copy one from another conversation, guess a context ID, or ask the user for one.",
2388
2479
  ].join("\n"),
2389
2480
  }],
2390
2481
  };
@@ -2517,7 +2608,7 @@ Details: ${m.details || "N/A"}`)
2517
2608
  text: [
2518
2609
  "Status: source_session_unavailable",
2519
2610
  "No verified source-session identity is available, so EchoMem cannot build a filing packet for this conversation.",
2520
- "Do not guess or ask the user for a context ID. Retry after automatic source-session binding is available.",
2611
+ "Retry this exact operation once with a fresh random UUID in sourceSessionBindingToken. Never reuse the token, copy one from another conversation, guess a context ID, or ask the user for one.",
2521
2612
  ].join("\n"),
2522
2613
  }],
2523
2614
  };
@@ -2649,6 +2740,108 @@ Details: ${m.details || "N/A"}`)
2649
2740
  }
2650
2741
  async handleApplyWorkspaceTicketAction(args) {
2651
2742
  const parsed = applyWorkspaceTicketActionSchema.parse(args ?? {});
2743
+ if (parsed.action === "move_ticket") {
2744
+ const moved = await this.client.moveWorkspaceTicketDirect({
2745
+ workspaceId: parsed.workspaceId,
2746
+ ticketId: parsed.ticketId,
2747
+ expectedVersion: parsed.expectedVersion,
2748
+ parentId: parsed.parentId ?? null,
2749
+ edgeKind: parsed.edgeKind,
2750
+ });
2751
+ const ticket = isRecord(moved.data) && isRecord(moved.data.ticket) ? moved.data.ticket : {};
2752
+ return {
2753
+ content: [{
2754
+ type: "text",
2755
+ text: [
2756
+ "Moved the ticket.",
2757
+ `Ticket: ${readString(ticket, "title") ?? parsed.ticketId}`,
2758
+ `New address: ${readString(ticket, "address") ?? "unknown"}`,
2759
+ `New parent: ${parsed.parentId ?? "root"}`,
2760
+ `Workspace: ${moved.workspaceId}`,
2761
+ "Descendants moved with it; their dependencies are unchanged.",
2762
+ ].join("\n"),
2763
+ }],
2764
+ };
2765
+ }
2766
+ if (parsed.action === "rebind_session") {
2767
+ const rebound = await this.client.stewardWorkspaceTickets({
2768
+ workspaceId: parsed.workspaceId,
2769
+ operation: "rebind",
2770
+ contextId: parsed.contextId,
2771
+ toTicketId: parsed.ticketId,
2772
+ reason: parsed.reason,
2773
+ });
2774
+ const data = isRecord(rebound.data) ? rebound.data : {};
2775
+ const from = Array.isArray(data.fromTicketIds) ? data.fromTicketIds : [];
2776
+ return {
2777
+ content: [{
2778
+ type: "text",
2779
+ text: [
2780
+ data.changed === true
2781
+ ? "Rebound the session to its new ticket."
2782
+ : "That session was already on this ticket; nothing changed.",
2783
+ `Session context: ${parsed.contextId}`,
2784
+ `Now on ticket: ${parsed.ticketId}`,
2785
+ from.length ? `Moved off: ${from.join(", ")}` : "It held no previous ticket.",
2786
+ `Workspace: ${rebound.workspaceId}`,
2787
+ "The session's memories stay with their source session; only ticket attribution moved.",
2788
+ ].join("\n"),
2789
+ }],
2790
+ };
2791
+ }
2792
+ if (parsed.action === "merge_tickets") {
2793
+ const merged = await this.client.stewardWorkspaceTickets({
2794
+ workspaceId: parsed.workspaceId,
2795
+ operation: "merge",
2796
+ survivorTicketId: parsed.ticketId,
2797
+ absorbedTicketId: parsed.absorbedTicketId,
2798
+ expectedSurvivorVersion: parsed.expectedVersion,
2799
+ expectedAbsorbedVersion: parsed.expectedAbsorbedVersion,
2800
+ reason: parsed.reason,
2801
+ });
2802
+ const data = isRecord(merged.data) ? merged.data : {};
2803
+ const kids = Array.isArray(data.movedChildIds) ? data.movedChildIds : [];
2804
+ const ctxs = Array.isArray(data.movedContextIds) ? data.movedContextIds : [];
2805
+ return {
2806
+ content: [{
2807
+ type: "text",
2808
+ text: [
2809
+ `Merged "${readString(data, "absorbedTitle") ?? parsed.absorbedTicketId}" into ${parsed.ticketId}.`,
2810
+ `Children reparented: ${kids.length}`,
2811
+ `Sessions moved: ${ctxs.length}`,
2812
+ "The absorbed ticket was deleted and its outcome appended to the survivor's description.",
2813
+ `The survivor carries an event naming what it absorbed. The old ID ${parsed.absorbedTicketId} now 404s.`,
2814
+ `Workspace: ${merged.workspaceId}`,
2815
+ ].join("\n"),
2816
+ }],
2817
+ };
2818
+ }
2819
+ if (parsed.action === "update_ticket") {
2820
+ const updated = await this.client.updateWorkspaceTicketDirect({
2821
+ workspaceId: parsed.workspaceId,
2822
+ ticketId: parsed.ticketId,
2823
+ expectedVersion: parsed.expectedVersion,
2824
+ title: parsed.title,
2825
+ description: parsed.description,
2826
+ ownerId: parsed.ownerId,
2827
+ dueAt: parsed.dueAt,
2828
+ });
2829
+ const ticket = isRecord(updated.data) && isRecord(updated.data.ticket)
2830
+ ? updated.data.ticket
2831
+ : {};
2832
+ return {
2833
+ content: [{
2834
+ type: "text",
2835
+ text: [
2836
+ "Updated the workspace ticket.",
2837
+ `Ticket: ${readString(ticket, "title") ?? parsed.title} · ${readString(ticket, "id") ?? parsed.ticketId}`,
2838
+ `Workspace: ${updated.workspaceId}`,
2839
+ `Version: ${numberArg(ticket, "version") ?? "unknown"} (was ${parsed.expectedVersion})`,
2840
+ "This edit did not change any session's ticket assignment.",
2841
+ ].join("\n"),
2842
+ }],
2843
+ };
2844
+ }
2652
2845
  const result = await this.client.applyWorkspaceTicketAction(parsed);
2653
2846
  if (!result) {
2654
2847
  throw new Error("A verified source-session identity is required to apply a ticket action. Do not guess or ask the user for a context ID.");
package/dist/migrate.js CHANGED
@@ -919,7 +919,7 @@ export function isActiveMigrationSession(session, nowMs = Date.now()) {
919
919
  function authedClient(token) {
920
920
  return axios.create({
921
921
  baseURL: API_BASE,
922
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
922
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, "X-Echo-Client": "cli" },
923
923
  });
924
924
  }
925
925
  export function discoverMigratableSessions(opts = {}) {
@@ -0,0 +1,376 @@
1
+ /**
2
+ * Product analytics for the CLI install + onboarding funnel (PostHog).
3
+ *
4
+ * The backend records sign-up, saves and searches server-side. This module records only what the
5
+ * CLI alone sees: `init` / `connect` / `setup` and the localhost onboarding page steps, including
6
+ * the steps before the user has a token.
7
+ *
8
+ * - Anonymous identity is a random UUID persisted at `<config-dir>/installation-id`. After OTP
9
+ * verification one `$identify` links it to the Echo user id; later events use the user id.
10
+ * - Properties are allow-listed primitives only: never emails, paths, transcript/memory text,
11
+ * titles, queries, tokens or keys. Errors are reported as short normalized codes.
12
+ * - Fire-and-forget over HTTPS with a short timeout. Capturing never throws and never blocks;
13
+ * one-shot commands `flush()` briefly before the process exits.
14
+ *
15
+ * Disabled by ECHO_TELEMETRY=0/false/off/no, ECHO_DISABLE_TELEMETRY, DO_NOT_TRACK, the
16
+ * desktop-managed runtime (Echo Desktop tracks its own onboarding), test runs, CI machines, and
17
+ * local API doubles.
18
+ */
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import { randomUUID } from "node:crypto";
22
+ import { echoConfigDir } from "./keystore.js";
23
+ import { MCP_PACKAGE_VERSION } from "./package-metadata.js";
24
+ export const POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/";
25
+ // Public, write-only ingestion key (the website ships the same one in its browser bundle).
26
+ const DEFAULT_POSTHOG_TOKEN = "phc_mgK8tXERi58Y26DCALzVX9d7z22VLeb7BBHY7z8kvDbJ";
27
+ const DEFAULT_TIMEOUT_MS = 2000;
28
+ const INSTALLATION_ID_FILE = "installation-id";
29
+ const ANONYMOUS_ID_FILE = "analytics-anon-id";
30
+ const USER_ID_FILE = "analytics-user-id";
31
+ const TELEMETRY_OFF_VALUES = new Set(["0", "false", "off", "no"]);
32
+ const CI_ENV_KEYS = ["CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE"];
33
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
34
+ const USER_ID_RE = /^[A-Za-z0-9-]{8,64}$/;
35
+ function isTruthyFlag(value) {
36
+ if (value === undefined)
37
+ return false;
38
+ const normalized = value.trim().toLowerCase();
39
+ return normalized !== "" && normalized !== "0" && normalized !== "false";
40
+ }
41
+ function isLoopbackUrl(value) {
42
+ try {
43
+ const host = new URL(value).hostname;
44
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /** Why analytics is off for this environment, or null when it may send. */
51
+ export function productAnalyticsDisabledReason(env) {
52
+ const echoTelemetry = env.ECHO_TELEMETRY?.trim().toLowerCase();
53
+ if ((echoTelemetry && TELEMETRY_OFF_VALUES.has(echoTelemetry)) || isTruthyFlag(env.ECHO_DISABLE_TELEMETRY)) {
54
+ return "telemetry_opt_out";
55
+ }
56
+ if (isTruthyFlag(env.DO_NOT_TRACK))
57
+ return "do_not_track";
58
+ if (env.ECHO_DESKTOP_MANAGED === "1")
59
+ return "desktop_managed";
60
+ if (env.NODE_ENV === "test" || env.NODE_TEST_CONTEXT || /^test(?::|$)/.test(env.npm_lifecycle_event || "")) {
61
+ return "test";
62
+ }
63
+ // Scripted installs on build machines are not users.
64
+ if (CI_ENV_KEYS.some((key) => isTruthyFlag(env[key])))
65
+ return "ci";
66
+ // A local API double means a test or dev run; opt in explicitly with ECHO_POSTHOG_TOKEN.
67
+ if (!env.ECHO_POSTHOG_TOKEN && env.ECHO_API_BASE_URL && isLoopbackUrl(env.ECHO_API_BASE_URL))
68
+ return "local_api";
69
+ return null;
70
+ }
71
+ const BLOCKED_PROPERTY_KEY = /email|token|key|secret|passphrase|password|otp|path|dir|cwd|file|query|title|content|text|message|transcript/i;
72
+ /** Keep only short, primitive, non-identifying values. Anything that looks like PII is dropped. */
73
+ export function sanitizeAnalyticsProperties(properties) {
74
+ const safe = {};
75
+ for (const [key, value] of Object.entries(properties)) {
76
+ if (BLOCKED_PROPERTY_KEY.test(key))
77
+ continue;
78
+ if (value === null || typeof value === "boolean") {
79
+ safe[key] = value;
80
+ }
81
+ else if (typeof value === "number") {
82
+ if (Number.isFinite(value))
83
+ safe[key] = value;
84
+ }
85
+ else if (typeof value === "string") {
86
+ const trimmed = value.trim();
87
+ if (trimmed.length > 120)
88
+ continue;
89
+ if (/[@/\\]/.test(trimmed))
90
+ continue; // emails, file paths, URLs
91
+ if (/^(?:ec_|phc_|sk-|echo_grp_)/i.test(trimmed))
92
+ continue; // credentials
93
+ safe[key] = trimmed;
94
+ }
95
+ }
96
+ return safe;
97
+ }
98
+ /** Map any thrown value / HTTP failure to a short code. Never returns a raw message. */
99
+ export function analyticsErrorCode(error) {
100
+ if (!error || typeof error !== "object")
101
+ return "unknown";
102
+ const e = error;
103
+ const status = typeof e.response?.status === "number"
104
+ ? e.response.status
105
+ : typeof e.status === "number"
106
+ ? e.status
107
+ : undefined;
108
+ if (status !== undefined) {
109
+ if (status === 429)
110
+ return "rate_limited";
111
+ if (status === 410)
112
+ return "expired";
113
+ if (status >= 500)
114
+ return "server_error";
115
+ if (status === 400 || status === 401 || status === 403 || status === 422)
116
+ return "invalid_code";
117
+ return "unknown";
118
+ }
119
+ const code = typeof e.code === "string" ? e.code : "";
120
+ if (code === "ECONNABORTED" || code === "ETIMEDOUT" || code === "IMPORT_START_TIMEOUT" || e.name === "AbortError" || e.name === "TimeoutError") {
121
+ return "timeout";
122
+ }
123
+ if (code === "ERR_NETWORK" || code === "ECONNREFUSED" || code === "ECONNRESET" || code === "ENOTFOUND" || code === "EAI_AGAIN" || code === "ENETUNREACH") {
124
+ return "network";
125
+ }
126
+ return "unknown";
127
+ }
128
+ /** Stable host ids for the `hosts` property (e.g. `claude-code` → `claude_code`). */
129
+ export function analyticsHostIds(ids) {
130
+ return [...new Set(ids.map((id) => id.replace(/-/g, "_")))];
131
+ }
132
+ export class ProductAnalytics {
133
+ env;
134
+ fetchImpl;
135
+ configDirOverride;
136
+ timeoutMs;
137
+ pending = new Set();
138
+ suppressed = false;
139
+ command = "onboarding";
140
+ cachedInstallationId;
141
+ cachedAnonymousId;
142
+ userId;
143
+ userIdLoaded = false;
144
+ constructor(options = {}) {
145
+ this.env = options.env ?? process.env;
146
+ this.fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch : undefined);
147
+ this.configDirOverride = options.configDir;
148
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
149
+ }
150
+ isEnabled() {
151
+ return !this.suppressed && Boolean(this.fetchImpl) && productAnalyticsDisabledReason(this.env) === null;
152
+ }
153
+ /** Stop sending for the rest of this process (e.g. `setup --skip-login` invoked by Echo Desktop). */
154
+ suppress() {
155
+ this.suppressed = true;
156
+ }
157
+ setCommand(command) {
158
+ this.command = command;
159
+ }
160
+ configDir() {
161
+ return this.configDirOverride ?? echoConfigDir();
162
+ }
163
+ /** Persistent anonymous id for this machine profile. Created on first use; never throws. */
164
+ installationId() {
165
+ if (this.cachedInstallationId)
166
+ return this.cachedInstallationId;
167
+ const file = path.join(this.configDir(), INSTALLATION_ID_FILE);
168
+ try {
169
+ const existing = fs.readFileSync(file, "utf8").trim();
170
+ if (UUID_RE.test(existing))
171
+ return (this.cachedInstallationId = existing.toLowerCase());
172
+ }
173
+ catch {
174
+ /* first run */
175
+ }
176
+ const id = randomUUID();
177
+ try {
178
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
179
+ fs.writeFileSync(file, `${id}\n`, { mode: 0o600 });
180
+ }
181
+ catch {
182
+ /* unwritable config dir: keep a per-process id */
183
+ }
184
+ return (this.cachedInstallationId = id);
185
+ }
186
+ readIdFile(name, pattern) {
187
+ try {
188
+ const value = fs.readFileSync(path.join(this.configDir(), name), "utf8").trim();
189
+ return pattern.test(value) ? value : undefined;
190
+ }
191
+ catch {
192
+ return undefined;
193
+ }
194
+ }
195
+ writeIdFile(name, value) {
196
+ try {
197
+ fs.mkdirSync(this.configDir(), { recursive: true, mode: 0o700 });
198
+ fs.writeFileSync(path.join(this.configDir(), name), `${value}\n`, { mode: 0o600 });
199
+ }
200
+ catch {
201
+ /* unwritable config dir: keep the in-memory value */
202
+ }
203
+ }
204
+ /**
205
+ * The account this machine last identified as (persisted, since credentials.json carries no
206
+ * user id), falling back to a user id in credentials when present.
207
+ */
208
+ loadUserId() {
209
+ if (!this.userIdLoaded) {
210
+ this.userIdLoaded = true;
211
+ this.userId = this.readIdFile(USER_ID_FILE, USER_ID_RE);
212
+ if (!this.userId) {
213
+ try {
214
+ const creds = JSON.parse(fs.readFileSync(path.join(this.configDir(), "credentials.json"), "utf8"));
215
+ const candidate = creds.userId ?? creds.user_id;
216
+ if (typeof candidate === "string" && USER_ID_RE.test(candidate))
217
+ this.userId = candidate;
218
+ }
219
+ catch {
220
+ /* no credentials yet */
221
+ }
222
+ }
223
+ }
224
+ return this.userId;
225
+ }
226
+ /**
227
+ * The signed-out identity. Starts as the installation id and is replaced whenever an identified
228
+ * account signs out, because PostHog has already merged the old one into that account; reusing
229
+ * it would credit the next person's pre-sign-in events to it. `installation_id` stays stable.
230
+ */
231
+ anonymousId() {
232
+ if (!this.cachedAnonymousId) {
233
+ this.cachedAnonymousId = this.readIdFile(ANONYMOUS_ID_FILE, UUID_RE)?.toLowerCase() ?? this.installationId();
234
+ }
235
+ return this.cachedAnonymousId;
236
+ }
237
+ distinctId() {
238
+ return this.loadUserId() || this.anonymousId();
239
+ }
240
+ /** Call on logout so the next account on this machine starts from a fresh anonymous id. */
241
+ resetIdentity() {
242
+ this.userId = undefined;
243
+ this.userIdLoaded = true;
244
+ try {
245
+ fs.rmSync(path.join(this.configDir(), USER_ID_FILE), { force: true });
246
+ }
247
+ catch {
248
+ /* nothing stored */
249
+ }
250
+ if (!this.isEnabled())
251
+ return;
252
+ this.cachedAnonymousId = randomUUID();
253
+ this.writeIdFile(ANONYMOUS_ID_FILE, this.cachedAnonymousId);
254
+ }
255
+ /**
256
+ * A sign-in is starting although this machine was identified before (the account's key was
257
+ * revoked or credentials were removed without `logout`): treat it as a sign-out first, since the
258
+ * person about to sign in may be someone else.
259
+ */
260
+ resetIdentityIfIdentified() {
261
+ if (this.loadUserId())
262
+ this.resetIdentity();
263
+ }
264
+ commonProperties() {
265
+ return {
266
+ app: "cli",
267
+ cli_version: MCP_PACKAGE_VERSION,
268
+ os: process.platform,
269
+ arch: process.arch,
270
+ $lib: "echomem-cli",
271
+ installation_id: this.installationId(),
272
+ command: this.command,
273
+ };
274
+ }
275
+ capture(event, properties = {}) {
276
+ if (!this.isEnabled())
277
+ return Promise.resolve();
278
+ try {
279
+ return this.send(event, this.distinctId(), { ...this.commonProperties(), ...sanitizeAnalyticsProperties(properties) });
280
+ }
281
+ catch {
282
+ return Promise.resolve();
283
+ }
284
+ }
285
+ /** Link this installation to the verified Echo user; subsequent events use the user id. */
286
+ identify(userId) {
287
+ if (!this.isEnabled() || !userId || !USER_ID_RE.test(userId))
288
+ return Promise.resolve();
289
+ try {
290
+ if (this.distinctId() === userId)
291
+ return Promise.resolve();
292
+ const anonId = this.anonymousId();
293
+ this.userId = userId;
294
+ this.writeIdFile(USER_ID_FILE, userId);
295
+ return this.send("$identify", userId, { ...this.commonProperties(), $anon_distinct_id: anonId });
296
+ }
297
+ catch {
298
+ return Promise.resolve();
299
+ }
300
+ }
301
+ /** Wait (bounded) for in-flight events — call before a one-shot command exits. */
302
+ async flush(timeoutMs = this.timeoutMs) {
303
+ if (this.pending.size === 0)
304
+ return;
305
+ let timer;
306
+ await Promise.race([
307
+ Promise.allSettled([...this.pending]),
308
+ new Promise((resolve) => {
309
+ timer = setTimeout(resolve, timeoutMs);
310
+ }),
311
+ ]);
312
+ if (timer)
313
+ clearTimeout(timer);
314
+ }
315
+ send(event, distinctId, properties) {
316
+ const fetchImpl = this.fetchImpl;
317
+ if (!fetchImpl)
318
+ return Promise.resolve();
319
+ const body = JSON.stringify({
320
+ api_key: this.env.ECHO_POSTHOG_TOKEN || DEFAULT_POSTHOG_TOKEN,
321
+ event,
322
+ distinct_id: distinctId,
323
+ properties,
324
+ timestamp: new Date().toISOString(),
325
+ });
326
+ const controller = new AbortController();
327
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
328
+ timer.unref?.();
329
+ const request = Promise.resolve()
330
+ .then(() => fetchImpl(POSTHOG_CAPTURE_URL, {
331
+ method: "POST",
332
+ headers: { "Content-Type": "application/json" },
333
+ body,
334
+ signal: controller.signal,
335
+ }))
336
+ .then(() => undefined, () => undefined)
337
+ .finally(() => {
338
+ clearTimeout(timer);
339
+ this.pending.delete(request);
340
+ });
341
+ this.pending.add(request);
342
+ return request;
343
+ }
344
+ }
345
+ export const productAnalytics = new ProductAnalytics();
346
+ /**
347
+ * Funnel events around one install command: Started, then Completed only when the command
348
+ * finished (a configured machine that never connected an account is `not_finished`), or Failed
349
+ * with a code when it threw. `listConfiguredHostIds` is only consulted when the command didn't
350
+ * report its hosts itself.
351
+ */
352
+ export async function trackCliCommandRun(analytics, command, run, listConfiguredHostIds) {
353
+ analytics.setCommand(command);
354
+ void analytics.capture("Echo CLI Init Started", { command });
355
+ try {
356
+ const { configured, finished } = await run();
357
+ if (!finished) {
358
+ void analytics.capture("Echo CLI Init Failed", { command, error_code: "not_finished" });
359
+ }
360
+ else if (analytics.isEnabled()) {
361
+ const hostIds = analyticsHostIds(configured ? configured.map((client) => client.id) : listConfiguredHostIds());
362
+ void analytics.capture("Echo CLI Init Completed", {
363
+ command,
364
+ hosts_configured_count: hostIds.length,
365
+ hosts: hostIds.join(","),
366
+ });
367
+ }
368
+ }
369
+ catch (error) {
370
+ void analytics.capture("Echo CLI Init Failed", { command, error_code: analyticsErrorCode(error) });
371
+ throw error;
372
+ }
373
+ finally {
374
+ await analytics.flush();
375
+ }
376
+ }
@@ -178,6 +178,11 @@ export const SETUP_PAGE_CLIENT_CORE = String.raw ` var params = new URLSear
178
178
  try { data = raw ? JSON.parse(raw) : {}; } catch (_) {}
179
179
  if (!res.ok) throw new Error(data.message || data.error || raw || ("HTTP " + res.status));
180
180
  return data;
181
+ }
182
+ // Funnel analytics for page-only steps; the localhost bridge allow-lists values. Best-effort.
183
+ function trackSetupEvent(body) {
184
+ if (previewState) return;
185
+ try { postJson("/analytics", body, 3000).catch(function () {}); } catch (_) {}
181
186
  }
182
187
  function routeError(code) {
183
188
  if (code === "NO_PENDING_SESSIONS") return "There are no unprocessed local conversations to extract right now.";