@echomem/mcp 1.4.62 → 1.4.64

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,7 +16,7 @@ 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";
19
+ import { formatTicketFilingPacket, formatWorkspaceTicketOverview, ticketAddressById, } from "./ticket-review-format.js";
20
20
  import { SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE, resolveCloudCoworkSessionFromToolArguments, resolveSourceSessionRequestContext, resolveSourceSessionFromBindingToken, } 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";
@@ -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();
@@ -2365,8 +2411,32 @@ Details: ${m.details || "N/A"}`)
2365
2411
  }],
2366
2412
  };
2367
2413
  }
2414
+ async handleWorkspaceTicketOverview(args) {
2415
+ const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
2416
+ const result = await this.client.listWorkspaceTicketsForOverview(parsed.workspaceId ?? parsed.groupId);
2417
+ const payload = isRecord(result.data) ? result.data : {};
2418
+ const tickets = Array.isArray(payload.tickets)
2419
+ ? payload.tickets.filter(isRecord)
2420
+ : [];
2421
+ return {
2422
+ content: [{
2423
+ type: "text",
2424
+ text: [
2425
+ `Workspace: ${result.workspaceId}`,
2426
+ ...formatWorkspaceTicketOverview({
2427
+ tickets,
2428
+ staleDays: parsed.staleDays,
2429
+ includeDescriptions: parsed.includeDescriptions,
2430
+ }),
2431
+ ].join("\n"),
2432
+ }],
2433
+ };
2434
+ }
2368
2435
  async handleReviewWorkspaceTicketSession(args) {
2369
2436
  const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
2437
+ if (parsed.operation === "overview") {
2438
+ return this.handleWorkspaceTicketOverview(args);
2439
+ }
2370
2440
  if (parsed.operation === "find_candidates") {
2371
2441
  return this.handleFindWorkspaceTicketCandidates(args);
2372
2442
  }
@@ -2649,6 +2719,108 @@ Details: ${m.details || "N/A"}`)
2649
2719
  }
2650
2720
  async handleApplyWorkspaceTicketAction(args) {
2651
2721
  const parsed = applyWorkspaceTicketActionSchema.parse(args ?? {});
2722
+ if (parsed.action === "move_ticket") {
2723
+ const moved = await this.client.moveWorkspaceTicketDirect({
2724
+ workspaceId: parsed.workspaceId,
2725
+ ticketId: parsed.ticketId,
2726
+ expectedVersion: parsed.expectedVersion,
2727
+ parentId: parsed.parentId ?? null,
2728
+ edgeKind: parsed.edgeKind,
2729
+ });
2730
+ const ticket = isRecord(moved.data) && isRecord(moved.data.ticket) ? moved.data.ticket : {};
2731
+ return {
2732
+ content: [{
2733
+ type: "text",
2734
+ text: [
2735
+ "Moved the ticket.",
2736
+ `Ticket: ${readString(ticket, "title") ?? parsed.ticketId}`,
2737
+ `New address: ${readString(ticket, "address") ?? "unknown"}`,
2738
+ `New parent: ${parsed.parentId ?? "root"}`,
2739
+ `Workspace: ${moved.workspaceId}`,
2740
+ "Descendants moved with it; their dependencies are unchanged.",
2741
+ ].join("\n"),
2742
+ }],
2743
+ };
2744
+ }
2745
+ if (parsed.action === "rebind_session") {
2746
+ const rebound = await this.client.stewardWorkspaceTickets({
2747
+ workspaceId: parsed.workspaceId,
2748
+ operation: "rebind",
2749
+ contextId: parsed.contextId,
2750
+ toTicketId: parsed.ticketId,
2751
+ reason: parsed.reason,
2752
+ });
2753
+ const data = isRecord(rebound.data) ? rebound.data : {};
2754
+ const from = Array.isArray(data.fromTicketIds) ? data.fromTicketIds : [];
2755
+ return {
2756
+ content: [{
2757
+ type: "text",
2758
+ text: [
2759
+ data.changed === true
2760
+ ? "Rebound the session to its new ticket."
2761
+ : "That session was already on this ticket; nothing changed.",
2762
+ `Session context: ${parsed.contextId}`,
2763
+ `Now on ticket: ${parsed.ticketId}`,
2764
+ from.length ? `Moved off: ${from.join(", ")}` : "It held no previous ticket.",
2765
+ `Workspace: ${rebound.workspaceId}`,
2766
+ "The session's memories stay with their source session; only ticket attribution moved.",
2767
+ ].join("\n"),
2768
+ }],
2769
+ };
2770
+ }
2771
+ if (parsed.action === "merge_tickets") {
2772
+ const merged = await this.client.stewardWorkspaceTickets({
2773
+ workspaceId: parsed.workspaceId,
2774
+ operation: "merge",
2775
+ survivorTicketId: parsed.ticketId,
2776
+ absorbedTicketId: parsed.absorbedTicketId,
2777
+ expectedSurvivorVersion: parsed.expectedVersion,
2778
+ expectedAbsorbedVersion: parsed.expectedAbsorbedVersion,
2779
+ reason: parsed.reason,
2780
+ });
2781
+ const data = isRecord(merged.data) ? merged.data : {};
2782
+ const kids = Array.isArray(data.movedChildIds) ? data.movedChildIds : [];
2783
+ const ctxs = Array.isArray(data.movedContextIds) ? data.movedContextIds : [];
2784
+ return {
2785
+ content: [{
2786
+ type: "text",
2787
+ text: [
2788
+ `Merged "${readString(data, "absorbedTitle") ?? parsed.absorbedTicketId}" into ${parsed.ticketId}.`,
2789
+ `Children reparented: ${kids.length}`,
2790
+ `Sessions moved: ${ctxs.length}`,
2791
+ "The absorbed ticket was deleted and its outcome appended to the survivor's description.",
2792
+ `The survivor carries an event naming what it absorbed. The old ID ${parsed.absorbedTicketId} now 404s.`,
2793
+ `Workspace: ${merged.workspaceId}`,
2794
+ ].join("\n"),
2795
+ }],
2796
+ };
2797
+ }
2798
+ if (parsed.action === "update_ticket") {
2799
+ const updated = await this.client.updateWorkspaceTicketDirect({
2800
+ workspaceId: parsed.workspaceId,
2801
+ ticketId: parsed.ticketId,
2802
+ expectedVersion: parsed.expectedVersion,
2803
+ title: parsed.title,
2804
+ description: parsed.description,
2805
+ ownerId: parsed.ownerId,
2806
+ dueAt: parsed.dueAt,
2807
+ });
2808
+ const ticket = isRecord(updated.data) && isRecord(updated.data.ticket)
2809
+ ? updated.data.ticket
2810
+ : {};
2811
+ return {
2812
+ content: [{
2813
+ type: "text",
2814
+ text: [
2815
+ "Updated the workspace ticket.",
2816
+ `Ticket: ${readString(ticket, "title") ?? parsed.title} · ${readString(ticket, "id") ?? parsed.ticketId}`,
2817
+ `Workspace: ${updated.workspaceId}`,
2818
+ `Version: ${numberArg(ticket, "version") ?? "unknown"} (was ${parsed.expectedVersion})`,
2819
+ "This edit did not change any session's ticket assignment.",
2820
+ ].join("\n"),
2821
+ }],
2822
+ };
2823
+ }
2652
2824
  const result = await this.client.applyWorkspaceTicketAction(parsed);
2653
2825
  if (!result) {
2654
2826
  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.";
@@ -93,6 +93,7 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
93
93
  return;
94
94
  }
95
95
  readyStage = "plan";
96
+ trackSetupEvent({ event: "step", step: "plan" });
96
97
  app.className = "planGateStage";
97
98
  app.innerHTML =
98
99
  setupJourney(2) +
@@ -168,6 +169,7 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
168
169
  if (!live) {
169
170
  extractMounted = false;
170
171
  readyStage = "sessions";
172
+ trackSetupEvent({ event: "step", step: "import" });
171
173
  app.className = "";
172
174
  // One reading line, top to bottom: the find (headline) → the value (sub) → quiet proof
173
175
  // (source strip) → the single action with its reassurances attached → optional detail.
@@ -1217,18 +1219,21 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1217
1219
  if (free) free.onclick = function () {
1218
1220
  freePlanFallbackApplied = true;
1219
1221
  rememberSetupPlanChoice("free");
1222
+ trackSetupEvent({ event: "plan_selected", plan: "free" });
1220
1223
  renderDashboard();
1221
1224
  };
1222
1225
  var pro = document.getElementById("chooseProPlan");
1223
1226
  if (pro) pro.onclick = function () {
1224
1227
  freePlanFallbackApplied = true;
1225
1228
  rememberSetupPlanChoice("pro");
1229
+ trackSetupEvent({ event: "plan_selected", plan: "pro" });
1226
1230
  openPaidPricing("pro");
1227
1231
  };
1228
1232
  var power = document.getElementById("choosePowerPlan");
1229
1233
  if (power) power.onclick = function () {
1230
1234
  freePlanFallbackApplied = true;
1231
1235
  rememberSetupPlanChoice("power");
1236
+ trackSetupEvent({ event: "plan_selected", plan: "power" });
1232
1237
  openPaidPricing("power");
1233
1238
  };
1234
1239
  }