@wonderwhy-er/desktop-commander 0.2.46 → 0.2.48

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.
@@ -41,10 +41,12 @@ try {
41
41
  process.exit(3); // Exit code 3 for auth error
42
42
  }
43
43
 
44
- // Update device status to offline
44
+ // Update device status to offline, stamping the exact shutdown moment so
45
+ // "last seen X ago" is precise for clean shutdowns (the periodic
46
+ // bookkeeping write only runs on the slow capable cadence).
45
47
  const { error } = await client
46
48
  .from('mcp_devices')
47
- .update({ status: 'offline' })
49
+ .update({ status: 'offline', last_seen: new Date().toISOString() })
48
50
  .eq('id', deviceId);
49
51
 
50
52
  clearTimeout(timeoutHandle);
@@ -166,7 +166,7 @@ const getVersion = async () => {
166
166
  }
167
167
  };
168
168
 
169
- // Function to detect shell environmen
169
+ // Function to detect shell environment
170
170
  function detectShell() {
171
171
  // Check for Windows shells
172
172
  if (process.platform === 'win32') {
@@ -1,3 +1,17 @@
1
- import { ServerResult } from '../types.js';
1
+ import { ProcessInfo, ServerResult } from '../types.js';
2
+ /**
3
+ * Parse `tasklist /fo csv /nh` output (#662). Fields per row, all quoted:
4
+ * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
5
+ * default table: image names can contain spaces and Mem Usage contains
6
+ * thousands separators, so positional whitespace splitting can't work.
7
+ * tasklist has no live per-process CPU%, so cpu is reported as n/a.
8
+ */
9
+ export declare function parseWindowsTasklistCsv(stdout: string): ProcessInfo[];
10
+ /**
11
+ * Parse `ps aux` output: 11 whitespace-separated columns, COMMAND from
12
+ * column 10 onward (it can contain spaces, so it must be rejoined, not
13
+ * taken as the last token).
14
+ */
15
+ export declare function parsePsAux(stdout: string): ProcessInfo[];
2
16
  export declare function listProcesses(): Promise<ServerResult>;
3
17
  export declare function killProcess(args: unknown): Promise<ServerResult>;
@@ -3,22 +3,53 @@ import { promisify } from 'util';
3
3
  import os from 'os';
4
4
  import { KillProcessArgsSchema } from './schemas.js';
5
5
  const execAsync = promisify(exec);
6
+ /**
7
+ * Parse `tasklist /fo csv /nh` output (#662). Fields per row, all quoted:
8
+ * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
9
+ * default table: image names can contain spaces and Mem Usage contains
10
+ * thousands separators, so positional whitespace splitting can't work.
11
+ * tasklist has no live per-process CPU%, so cpu is reported as n/a.
12
+ */
13
+ export function parseWindowsTasklistCsv(stdout) {
14
+ return stdout.split(/\r?\n/)
15
+ .filter(Boolean)
16
+ .map(line => {
17
+ const fields = (line.match(/"([^"]*)"/g) || []).map(f => f.slice(1, -1));
18
+ return {
19
+ pid: parseInt(fields[1], 10),
20
+ command: fields[0] ?? '',
21
+ cpu: 'n/a',
22
+ memory: fields[4] ?? '',
23
+ };
24
+ })
25
+ .filter(p => !Number.isNaN(p.pid));
26
+ }
27
+ /**
28
+ * Parse `ps aux` output: 11 whitespace-separated columns, COMMAND from
29
+ * column 10 onward (it can contain spaces, so it must be rejoined, not
30
+ * taken as the last token).
31
+ */
32
+ export function parsePsAux(stdout) {
33
+ return stdout.split(/\r?\n/)
34
+ .slice(1)
35
+ .filter(Boolean)
36
+ .map(line => {
37
+ const parts = line.trim().split(/\s+/);
38
+ return {
39
+ pid: parseInt(parts[1], 10),
40
+ command: parts.slice(10).join(' ') || parts[parts.length - 1],
41
+ cpu: parts[2],
42
+ memory: parts[3],
43
+ };
44
+ })
45
+ .filter(p => !Number.isNaN(p.pid));
46
+ }
6
47
  export async function listProcesses() {
7
- const command = os.platform() === 'win32' ? 'tasklist' : 'ps aux';
48
+ const isWindows = os.platform() === 'win32';
49
+ const command = isWindows ? 'tasklist /fo csv /nh' : 'ps aux';
8
50
  try {
9
51
  const { stdout } = await execAsync(command);
10
- const processes = stdout.split('\n')
11
- .slice(1)
12
- .filter(Boolean)
13
- .map(line => {
14
- const parts = line.split(/\s+/);
15
- return {
16
- pid: parseInt(parts[1]),
17
- command: parts[parts.length - 1],
18
- cpu: parts[2],
19
- memory: parts[3],
20
- };
21
- });
52
+ const processes = isWindows ? parseWindowsTasklistCsv(stdout) : parsePsAux(stdout);
22
53
  return {
23
54
  content: [{
24
55
  type: "text",
@@ -12,6 +12,25 @@ interface FormattedToolCallRecord extends Omit<ToolCallRecord, 'timestamp'> {
12
12
  declare class ToolHistory {
13
13
  private history;
14
14
  private readonly MAX_ENTRIES;
15
+ /**
16
+ * Cap on the output kept per entry. Entries hold the FULL ServerResult, and
17
+ * get_recent_tool_calls serialises them straight back out, so without a cap
18
+ * the history is unbounded in two compounding ways:
19
+ *
20
+ * - a single large output (a big read_file, a wide list_directory) makes
21
+ * every later history dump that includes it large too, and
22
+ * - any tool whose output happens to CONTAIN a history dump — e.g.
23
+ * `cat`-ing a file a previous dump was written to — nests the whole
24
+ * history inside itself, and each nesting level roughly doubles the JSON
25
+ * escaping. Observed 2026-07-27: 83KB of arguments on disk produced a
26
+ * 1.89MB in-memory dump this way.
27
+ *
28
+ * Excluding more tool names cannot fix that, because the nesting arrives
29
+ * through ordinary tools. Capping the stored output does, and a preview is
30
+ * all this history is for — it is a "what happened recently" aid, not a
31
+ * result cache.
32
+ */
33
+ private readonly MAX_STORED_OUTPUT_BYTES;
15
34
  private readonly MAX_HISTORY_FILE_SIZE_BYTES;
16
35
  private readonly HISTORY_FILE_TRIM_TARGET_BYTES;
17
36
  private readonly historyFile;
@@ -49,6 +68,11 @@ declare class ToolHistory {
49
68
  /**
50
69
  * Add a tool call to history
51
70
  */
71
+ /**
72
+ * Replace an oversized output with a short marker. Keeps the record shape
73
+ * ({ content: [...] }) so readers and formatters need no special case.
74
+ */
75
+ private capOutput;
52
76
  addCall(toolName: string, args: any, output: ServerResult, duration?: number): void;
53
77
  /**
54
78
  * Get recent tool calls with filters
@@ -18,6 +18,25 @@ class ToolHistory {
18
18
  constructor() {
19
19
  this.history = [];
20
20
  this.MAX_ENTRIES = 1000;
21
+ /**
22
+ * Cap on the output kept per entry. Entries hold the FULL ServerResult, and
23
+ * get_recent_tool_calls serialises them straight back out, so without a cap
24
+ * the history is unbounded in two compounding ways:
25
+ *
26
+ * - a single large output (a big read_file, a wide list_directory) makes
27
+ * every later history dump that includes it large too, and
28
+ * - any tool whose output happens to CONTAIN a history dump — e.g.
29
+ * `cat`-ing a file a previous dump was written to — nests the whole
30
+ * history inside itself, and each nesting level roughly doubles the JSON
31
+ * escaping. Observed 2026-07-27: 83KB of arguments on disk produced a
32
+ * 1.89MB in-memory dump this way.
33
+ *
34
+ * Excluding more tool names cannot fix that, because the nesting arrives
35
+ * through ordinary tools. Capping the stored output does, and a preview is
36
+ * all this history is for — it is a "what happened recently" aid, not a
37
+ * result cache.
38
+ */
39
+ this.MAX_STORED_OUTPUT_BYTES = 4 * 1024;
21
40
  this.MAX_HISTORY_FILE_SIZE_BYTES = 5 * 1024 * 1024;
22
41
  // When the file exceeds the cap we trim it down to this target instead of
23
42
  // all the way to zero, so a single overflow doesn't cause every subsequent
@@ -61,8 +80,14 @@ class ToolHistory {
61
80
  // Silently skip invalid lines
62
81
  }
63
82
  }
64
- // Keep only last 1000 entries
65
- this.history = records.slice(-this.MAX_ENTRIES);
83
+ // Keep only last 1000 entries, and cap on the way IN as well as on the
84
+ // way out. Entries written before the cap existed are still on disk and
85
+ // are well under the whole-file trim threshold, so without this the cap
86
+ // does nothing for anyone upgrading with an existing history file — i.e.
87
+ // for everyone it was written for.
88
+ this.history = records
89
+ .slice(-this.MAX_ENTRIES)
90
+ .map(record => ({ ...record, output: this.capOutput(record.output) }));
66
91
  // If file is getting too large, trim it
67
92
  if (lines.length > this.MAX_ENTRIES * 2) {
68
93
  this.trimHistoryFile();
@@ -181,12 +206,39 @@ class ToolHistory {
181
206
  /**
182
207
  * Add a tool call to history
183
208
  */
209
+ /**
210
+ * Replace an oversized output with a short marker. Keeps the record shape
211
+ * ({ content: [...] }) so readers and formatters need no special case.
212
+ */
213
+ capOutput(output) {
214
+ let size;
215
+ try {
216
+ size = JSON.stringify(output)?.length ?? 0;
217
+ }
218
+ catch {
219
+ // Circular or otherwise unserialisable — it could never be returned to a
220
+ // client anyway, so don't retain it.
221
+ size = Number.POSITIVE_INFINITY;
222
+ }
223
+ if (size <= this.MAX_STORED_OUTPUT_BYTES)
224
+ return output;
225
+ const shown = Number.isFinite(size) ? `${size} bytes` : 'unserialisable';
226
+ return {
227
+ ...output,
228
+ content: [
229
+ {
230
+ type: 'text',
231
+ text: `[output omitted from history: ${shown}, over the ${this.MAX_STORED_OUTPUT_BYTES}-byte cap]`,
232
+ },
233
+ ],
234
+ };
235
+ }
184
236
  addCall(toolName, args, output, duration) {
185
237
  const record = {
186
238
  timestamp: new Date().toISOString(),
187
239
  toolName,
188
240
  arguments: args,
189
- output,
241
+ output: this.capOutput(output),
190
242
  duration
191
243
  };
192
244
  this.history.push(record);
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.2.46";
1
+ export declare const VERSION = "0.2.48";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.2.46';
1
+ export const VERSION = '0.2.48';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wonderwhy-er/desktop-commander",
3
- "version": "0.2.46",
3
+ "version": "0.2.48",
4
4
  "description": "MCP server for terminal operations and file editing",
5
5
  "mcpName": "io.github.wonderwhy-er/desktop-commander",
6
6
  "license": "MIT",
@@ -56,9 +56,8 @@
56
56
  "release:minor": "node scripts/publish-release.cjs --minor",
57
57
  "release:major": "node scripts/publish-release.cjs --major",
58
58
  "release:dry": "node scripts/publish-release.cjs --dry-run",
59
- "release:mcp": "node scripts/publish-release.cjs --mcp-only",
60
- "release:alpha": "node scripts/publish-release.cjs --npm-only --alpha",
61
- "release:skip-mcp": "node scripts/publish-release.cjs --skip-mcp",
59
+ "release:rehearsal": "node scripts/publish-release.cjs --rehearsal",
60
+ "release:alpha": "node scripts/publish-release.cjs --alpha",
62
61
  "logs:view": "npm run build && node scripts/view-fuzzy-logs.js",
63
62
  "logs:analyze": "npm run build && node scripts/analyze-fuzzy-logs.js",
64
63
  "logs:clear": "npm run build && node scripts/clear-fuzzy-logs.js",
@@ -1,34 +0,0 @@
1
- /**
2
- * Pure fuzzy-search algorithm, shared by the main thread (fuzzySearch.ts)
3
- * and the worker thread (fuzzySearchWorker.ts). This is the single source
4
- * of truth for the algorithm — do not fork it.
5
- *
6
- * Must stay side-effect free with no imports beyond fastest-levenshtein:
7
- * telemetry lives in the caller (metrics are returned, not captured here),
8
- * and a small module graph keeps worker spawn cheap.
9
- */
10
- export interface FuzzyMatch {
11
- start: number;
12
- end: number;
13
- value: string;
14
- distance: number;
15
- }
16
- export interface FuzzySearchMetrics {
17
- /** Total wall time of the search in ms */
18
- executionTimeMs: number;
19
- /** Wall time of the final iterative refinement phase in ms */
20
- iterativeTimeMs: number;
21
- /** Iterations spent in the iterative refinement phase */
22
- iterations: number;
23
- /** Length of the segment handed to iterative refinement */
24
- segmentLength: number;
25
- }
26
- export interface FuzzySearchResult {
27
- match: FuzzyMatch;
28
- metrics: FuzzySearchMetrics;
29
- }
30
- /**
31
- * Finds the closest match to a query string within text using fuzzy matching.
32
- * Returns the match plus timing/iteration metrics for the caller to report.
33
- */
34
- export declare function fuzzyIndexOf(text: string, query: string): FuzzySearchResult;
@@ -1,85 +0,0 @@
1
- /**
2
- * Pure fuzzy-search algorithm, shared by the main thread (fuzzySearch.ts)
3
- * and the worker thread (fuzzySearchWorker.ts). This is the single source
4
- * of truth for the algorithm — do not fork it.
5
- *
6
- * Must stay side-effect free with no imports beyond fastest-levenshtein:
7
- * telemetry lives in the caller (metrics are returned, not captured here),
8
- * and a small module graph keeps worker spawn cheap.
9
- */
10
- import { distance } from 'fastest-levenshtein';
11
- /**
12
- * Finds the closest match to a query string within text using fuzzy matching.
13
- * Returns the match plus timing/iteration metrics for the caller to report.
14
- */
15
- export function fuzzyIndexOf(text, query) {
16
- const startTime = performance.now();
17
- const metrics = { iterativeTimeMs: 0, iterations: 0, segmentLength: 0 };
18
- const match = recursiveFuzzyIndexOf(text, query, 0, text.length, Infinity, metrics);
19
- return {
20
- match,
21
- metrics: { ...metrics, executionTimeMs: performance.now() - startTime }
22
- };
23
- }
24
- /**
25
- * Recursively narrows the search to the half of the text with the better
26
- * Levenshtein distance, falling back to iterative refinement when the
27
- * segment is small or no longer improving.
28
- */
29
- function recursiveFuzzyIndexOf(text, query, start, end, parentDistance, metrics) {
30
- // For small text segments, use iterative approach
31
- if (end - start <= 2 * query.length) {
32
- return iterativeReduction(text, query, start, end, parentDistance, metrics);
33
- }
34
- let midPoint = start + Math.floor((end - start) / 2);
35
- let leftEnd = Math.min(end, midPoint + query.length); // Include query length to cover overlaps
36
- let rightStart = Math.max(start, midPoint - query.length); // Include query length to cover overlaps
37
- let leftDistance = distance(text.substring(start, leftEnd), query);
38
- let rightDistance = distance(text.substring(rightStart, end), query);
39
- let bestDistance = Math.min(leftDistance, parentDistance, rightDistance);
40
- // If parent distance is already the best, use iterative approach
41
- if (parentDistance === bestDistance) {
42
- return iterativeReduction(text, query, start, end, parentDistance, metrics);
43
- }
44
- // Recursively search the better half
45
- if (leftDistance < rightDistance) {
46
- return recursiveFuzzyIndexOf(text, query, start, leftEnd, bestDistance, metrics);
47
- }
48
- else {
49
- return recursiveFuzzyIndexOf(text, query, rightStart, end, bestDistance, metrics);
50
- }
51
- }
52
- /**
53
- * Iteratively refines the best match by shrinking the segment from both ends
54
- * while the Levenshtein distance keeps improving.
55
- */
56
- function iterativeReduction(text, query, start, end, parentDistance, metrics) {
57
- const startTime = performance.now();
58
- let bestDistance = parentDistance;
59
- let bestStart = start;
60
- let bestEnd = end;
61
- // Improve start position
62
- let nextDistance = distance(text.substring(bestStart + 1, bestEnd), query);
63
- while (nextDistance < bestDistance) {
64
- bestDistance = nextDistance;
65
- bestStart++;
66
- nextDistance = distance(text.substring(bestStart + 1, bestEnd), query);
67
- metrics.iterations++;
68
- }
69
- // Improve end position
70
- nextDistance = distance(text.substring(bestStart, bestEnd - 1), query);
71
- while (nextDistance < bestDistance) {
72
- bestDistance = nextDistance;
73
- bestEnd--;
74
- nextDistance = distance(text.substring(bestStart, bestEnd - 1), query);
75
- metrics.iterations++;
76
- }
77
- metrics.iterativeTimeMs = performance.now() - startTime;
78
- metrics.segmentLength = end - start;
79
- return {
80
- start: bestStart,
81
- end: bestEnd,
82
- value: text.substring(bestStart, bestEnd),
83
- distance: bestDistance
84
- };
85
- }
@@ -1,4 +0,0 @@
1
- export declare function getDefaultEditorMetadata(filePath: string): Promise<{
2
- defaultEditorName?: string;
3
- defaultEditorPath?: string;
4
- }>;
@@ -1,36 +0,0 @@
1
- import { execFile } from 'child_process';
2
- import os from 'os';
3
- import path from 'path';
4
- import { promisify } from 'util';
5
- const execFileAsync = promisify(execFile);
6
- const defaultEditorCache = new Map();
7
- function escapeAppleScriptString(value) {
8
- return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
9
- }
10
- export async function getDefaultEditorMetadata(filePath) {
11
- if (os.platform() !== 'darwin') {
12
- return {};
13
- }
14
- const extension = path.extname(filePath).toLowerCase();
15
- const cacheKey = extension || path.basename(filePath).toLowerCase();
16
- const cached = defaultEditorCache.get(cacheKey);
17
- if (cached) {
18
- return cached;
19
- }
20
- try {
21
- const script = `set appAlias to default application of (info for POSIX file "${escapeAppleScriptString(filePath)}")\nreturn (name of (info for appAlias)) & linefeed & POSIX path of appAlias`;
22
- const { stdout } = await execFileAsync('osascript', ['-e', script], { timeout: 12000 });
23
- const lines = stdout.split('\n').map((line) => line.trim()).filter(Boolean);
24
- const defaultEditorName = lines[lines.length - 2]?.replace(/\.app$/i, '') ?? '';
25
- const defaultEditorPath = lines[lines.length - 1] ?? '';
26
- if (defaultEditorName && defaultEditorPath.startsWith('/')) {
27
- const metadata = { defaultEditorName, defaultEditorPath };
28
- defaultEditorCache.set(cacheKey, metadata);
29
- return metadata;
30
- }
31
- }
32
- catch {
33
- // Generic UI fallback is good enough if detection fails.
34
- }
35
- return {};
36
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Detect how this server instance was installed/launched, beyond what the
3
- * MCP client reports in clientInfo. A plugin is not a separate MCP client —
4
- * the host connects under its own name (e.g. the Claude Code plugin still
5
- * reports 'claude-code'), so the environment is the only place this signal
6
- * exists.
7
- *
8
- * Checked in priority order:
9
- * 1. DC_INSTALL_SOURCE — explicit marker set by our own packaging
10
- * (e.g. the Claude Code plugin manifest, or future Cowork/host configs).
11
- * 2. CLAUDE_PLUGIN_ROOT / CLAUDE_PLUGIN_DATA — set by Claude Code itself
12
- * when it spawns a plugin's MCP server, so this also covers plugin
13
- * versions installed before the explicit marker existed.
14
- */
15
- export declare function detectInstallSource(): string | undefined;
@@ -1,23 +0,0 @@
1
- /**
2
- * Detect how this server instance was installed/launched, beyond what the
3
- * MCP client reports in clientInfo. A plugin is not a separate MCP client —
4
- * the host connects under its own name (e.g. the Claude Code plugin still
5
- * reports 'claude-code'), so the environment is the only place this signal
6
- * exists.
7
- *
8
- * Checked in priority order:
9
- * 1. DC_INSTALL_SOURCE — explicit marker set by our own packaging
10
- * (e.g. the Claude Code plugin manifest, or future Cowork/host configs).
11
- * 2. CLAUDE_PLUGIN_ROOT / CLAUDE_PLUGIN_DATA — set by Claude Code itself
12
- * when it spawns a plugin's MCP server, so this also covers plugin
13
- * versions installed before the explicit marker existed.
14
- */
15
- export function detectInstallSource() {
16
- if (process.env.DC_INSTALL_SOURCE) {
17
- return process.env.DC_INSTALL_SOURCE;
18
- }
19
- if (process.env.CLAUDE_PLUGIN_ROOT || process.env.CLAUDE_PLUGIN_DATA) {
20
- return 'claude-code-plugin';
21
- }
22
- return undefined;
23
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * Capture a PostHog event. Silently no-ops if POSTHOG_API_KEY is not set
3
- * or if telemetry has been disabled by the user.
4
- */
5
- export declare function capturePostHog(distinctId: string, event: string, properties?: Record<string, any>): Promise<void>;
6
- /**
7
- * Identify a user by their distinct ID and set person properties.
8
- */
9
- export declare function identifyPostHog(distinctId: string, properties?: Record<string, any>): Promise<void>;
10
- /**
11
- * Capture an exception via PostHog error tracking.
12
- */
13
- export declare function captureExceptionPostHog(error: unknown, distinctId?: string, additionalProperties?: Record<string, any>): Promise<void>;
14
- /**
15
- * Flush all pending PostHog events. Call before process exit.
16
- */
17
- export declare function shutdownPostHog(): Promise<void>;
@@ -1,94 +0,0 @@
1
- import { PostHog } from 'posthog-node';
2
- import { platform } from 'os';
3
- let _client = null;
4
- function getClient() {
5
- if (!_client) {
6
- _client = new PostHog(process.env.POSTHOG_API_KEY ?? '', {
7
- host: process.env.POSTHOG_HOST,
8
- enableExceptionAutocapture: true,
9
- });
10
- }
11
- return _client;
12
- }
13
- /**
14
- * Capture a PostHog event. Silently no-ops if POSTHOG_API_KEY is not set
15
- * or if telemetry has been disabled by the user.
16
- */
17
- export async function capturePostHog(distinctId, event, properties) {
18
- if (!process.env.POSTHOG_API_KEY)
19
- return;
20
- try {
21
- // Respect the user's telemetry preference
22
- const { configManager, isTelemetryDisabledValue } = await import('../config-manager.js');
23
- const telemetryEnabled = await configManager.getValue('telemetryEnabled');
24
- if (isTelemetryDisabledValue(telemetryEnabled))
25
- return;
26
- let VERSION = 'unknown';
27
- try {
28
- const { VERSION: v } = await import('../version.js');
29
- VERSION = v;
30
- }
31
- catch {
32
- // Continue without version
33
- }
34
- getClient().capture({
35
- distinctId,
36
- event,
37
- properties: {
38
- platform: platform(),
39
- app_version: VERSION,
40
- ...properties,
41
- },
42
- });
43
- }
44
- catch {
45
- // Silently fail — analytics must never break functionality
46
- }
47
- }
48
- /**
49
- * Identify a user by their distinct ID and set person properties.
50
- */
51
- export async function identifyPostHog(distinctId, properties) {
52
- if (!process.env.POSTHOG_API_KEY)
53
- return;
54
- try {
55
- const { configManager, isTelemetryDisabledValue } = await import('../config-manager.js');
56
- const telemetryEnabled = await configManager.getValue('telemetryEnabled');
57
- if (isTelemetryDisabledValue(telemetryEnabled))
58
- return;
59
- getClient().identify({ distinctId, properties });
60
- }
61
- catch {
62
- // Silently fail
63
- }
64
- }
65
- /**
66
- * Capture an exception via PostHog error tracking.
67
- */
68
- export async function captureExceptionPostHog(error, distinctId, additionalProperties) {
69
- if (!process.env.POSTHOG_API_KEY)
70
- return;
71
- try {
72
- const { configManager, isTelemetryDisabledValue } = await import('../config-manager.js');
73
- const telemetryEnabled = await configManager.getValue('telemetryEnabled');
74
- if (isTelemetryDisabledValue(telemetryEnabled))
75
- return;
76
- getClient().captureException(error, distinctId, additionalProperties);
77
- }
78
- catch {
79
- // Silently fail
80
- }
81
- }
82
- /**
83
- * Flush all pending PostHog events. Call before process exit.
84
- */
85
- export async function shutdownPostHog() {
86
- if (_client) {
87
- try {
88
- await _client.shutdown();
89
- }
90
- catch {
91
- // Silently fail
92
- }
93
- }
94
- }