@apso/cli 0.53.0 → 0.54.0

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.
@@ -11,6 +11,18 @@ const schema_tools_1 = require("@apso/schema-tools");
11
11
  const apsorc_parser_1 = require("../../lib/apsorc-parser");
12
12
  const generators_1 = require("../../lib/generators");
13
13
  const schema_convert_1 = require("../../lib/utils/schema-convert");
14
+ /**
15
+ * A validation error that includes the individual error messages.
16
+ * This allows telemetry to extract and report the specific validation failures.
17
+ */
18
+ class ValidationError extends Error {
19
+ constructor(message, errors) {
20
+ super(message);
21
+ this.userError = true;
22
+ this.name = "ValidationError";
23
+ this.errorMessages = errors;
24
+ }
25
+ }
14
26
  /**
15
27
  * What `apso generate` would stop on: its configuration checks and the auth,
16
28
  * permissions and mcp rules. It runs the generator's own checks
@@ -149,7 +161,12 @@ class SchemaValidate extends base_command_1.default {
149
161
  for (const err of errors) {
150
162
  this.log(` - ${err}`);
151
163
  }
152
- this.error(`Validation failed with ${errors.length} error(s).`);
164
+ // Use this.error() to maintain oclif's exit code 2 and formatting.
165
+ // Attach the error list so telemetry can still extract individual messages.
166
+ const validationError = new ValidationError(`Validation failed with ${errors.length} error(s).`, errors);
167
+ // this.error() will trigger base-command's catch(), which will extract
168
+ // errorMessages from the ValidationError and send them to telemetry.
169
+ this.error(validationError);
153
170
  }
154
171
  else {
155
172
  this.log("Validation passed.");
@@ -6,6 +6,7 @@ const core_1 = require("@oclif/core");
6
6
  const child_process_1 = require("child_process");
7
7
  const os_1 = tslib_1.__importDefault(require("os"));
8
8
  const telemetry_1 = require("./telemetry/telemetry");
9
+ const error_utils_1 = require("./telemetry/error-utils");
9
10
  /**
10
11
  * True for errors oclif raised deliberately (this.error, this.exit, parse
11
12
  * errors) and for errors that mark themselves `userError` (problems in the
@@ -28,16 +29,26 @@ class BaseCommand extends core_1.Command {
28
29
  // and arg parse failures) with an `oclif` property. Those are messages
29
30
  // we chose to show the user, e.g. "No entity named X", not crashes, so
30
31
  // they go to PostHog only. Everything else is a real bug for Sentry.
31
- const userError = isUserError(err);
32
+ //
33
+ // Config and validation errors (ApsorcNamingError, validation failures)
34
+ // are also user errors, not CLI bugs.
35
+ const isOclifError = isUserError(err);
36
+ const isConfigError = (0, error_utils_1.isConfigOrValidationError)(err);
37
+ const userError = isOclifError || isConfigError;
38
+ // Sentry: only real bugs (not user errors)
32
39
  if (!userError) {
33
40
  (0, telemetry_1.captureException)(err, { command: this.id });
34
41
  }
42
+ // PostHog: capture the exception with full context
43
+ (0, telemetry_1.capturePostHogException)(err, { command: this.id });
44
+ // Extract detailed error properties for the cli_command_failed event
45
+ const errorProps = (0, error_utils_1.extractErrorProperties)(err);
46
+ // Track the failure event with structured error properties
35
47
  (0, telemetry_1.track)("cli_command_failed", {
36
48
  command: this.id,
37
49
  duration_ms: (0, telemetry_1.elapsedMs)(),
38
- error: err === null || err === void 0 ? void 0 : err.message,
39
- error_code: err === null || err === void 0 ? void 0 : err.code,
40
50
  user_error: userError,
51
+ ...errorProps,
41
52
  });
42
53
  await (0, telemetry_1.shutdownTelemetry)();
43
54
  }
@@ -137,6 +137,11 @@ export interface GlobalConfigFile {
137
137
  * User id this install's anonymous telemetry id was last aliased to.
138
138
  */
139
139
  telemetryAliasedUserId?: string;
140
+ /**
141
+ * Mark this machine as internal (Apso team/system). Set via `apso config set internal true`.
142
+ * When true, all telemetry events are tagged as internal.
143
+ */
144
+ internal?: boolean;
140
145
  }
141
146
  /**
142
147
  * Project link stored in .apso/link.json
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Error extraction and redaction utilities for telemetry.
3
+ *
4
+ * Extracts useful error properties (class, normalized message, code, entity,
5
+ * field) while redacting sensitive data: file contents, secrets, tokens, env
6
+ * values, and absolute paths. Home-directory paths are redacted.
7
+ */
8
+ /**
9
+ * Maximum number of error messages to include in an array.
10
+ */
11
+ export declare const MAX_ERROR_MESSAGES = 10;
12
+ /**
13
+ * Redact sensitive information from a string.
14
+ */
15
+ export declare function redactSensitiveData(str: string): string;
16
+ /**
17
+ * Truncate a string to a maximum length, adding ellipsis if truncated.
18
+ */
19
+ export declare function truncate(str: string, maxLength?: number): string;
20
+ /**
21
+ * Normalize an error message by redacting sensitive data and truncating.
22
+ */
23
+ export declare function normalizeErrorMessage(message: string): string;
24
+ /**
25
+ * Extract the error class name from an error object.
26
+ */
27
+ export declare function getErrorClass(err: unknown): string | undefined;
28
+ /**
29
+ * Extract the error code from an error object (if present).
30
+ */
31
+ export declare function getErrorCode(err: unknown): string | undefined;
32
+ /**
33
+ * Extract entity name from an error object (for schema/config errors).
34
+ */
35
+ export declare function getErrorEntity(err: unknown): string | undefined;
36
+ /**
37
+ * Extract field name from an error object (for schema/config errors).
38
+ */
39
+ export declare function getErrorField(err: unknown): string | undefined;
40
+ /**
41
+ * Extract error messages array from a validation error.
42
+ * Used for errors that carry multiple individual messages (e.g. ValidationError).
43
+ */
44
+ export declare function getErrorMessages(err: unknown): string[] | undefined;
45
+ /**
46
+ * Extract structured error properties for telemetry.
47
+ *
48
+ * @param err - The error object
49
+ * @returns Object with error properties suitable for telemetry
50
+ */
51
+ export declare function extractErrorProperties(err: unknown): {
52
+ error_class?: string;
53
+ error_message?: string;
54
+ error_code?: string;
55
+ entity?: string;
56
+ field?: string;
57
+ error_messages?: string[];
58
+ };
59
+ /**
60
+ * Extract an array of error messages from multiple errors, redacted and truncated.
61
+ *
62
+ * Used for validation errors where multiple issues may be present.
63
+ *
64
+ * @param errors - Array of errors (strings or Error objects)
65
+ * @param maxCount - Maximum number of error messages to include
66
+ * @returns Array of redacted, truncated error messages
67
+ */
68
+ export declare function extractErrorMessages(errors: Array<string | Error>, maxCount?: number): string[];
69
+ /**
70
+ * Check if an error is a config or validation error (a user error).
71
+ *
72
+ * Config and validation errors should be marked as user errors, not CLI bugs.
73
+ */
74
+ export declare function isConfigOrValidationError(err: unknown): boolean;
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ /**
3
+ * Error extraction and redaction utilities for telemetry.
4
+ *
5
+ * Extracts useful error properties (class, normalized message, code, entity,
6
+ * field) while redacting sensitive data: file contents, secrets, tokens, env
7
+ * values, and absolute paths. Home-directory paths are redacted.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.isConfigOrValidationError = exports.extractErrorMessages = exports.extractErrorProperties = exports.getErrorMessages = exports.getErrorField = exports.getErrorEntity = exports.getErrorCode = exports.getErrorClass = exports.normalizeErrorMessage = exports.truncate = exports.redactSensitiveData = exports.MAX_ERROR_MESSAGES = void 0;
11
+ const tslib_1 = require("tslib");
12
+ const os_1 = tslib_1.__importDefault(require("os"));
13
+ const apsorc_parser_1 = require("../apsorc-parser");
14
+ /**
15
+ * Sensitive patterns to redact from error messages and properties.
16
+ */
17
+ const SENSITIVE_PATTERNS = [
18
+ // API keys, tokens, secrets (common patterns)
19
+ /\b[\w-]{20,}\b/g,
20
+ /api[_-]?key[\s:=]+\S+/gi,
21
+ /token[\s:=]+\S+/gi,
22
+ /secret[\s:=]+\S+/gi,
23
+ /password[\s:=]+\S+/gi,
24
+ /bearer\s+\S+/gi,
25
+ // Environment variable values
26
+ /\b[A-Z_]+=\S+/g,
27
+ // JWT tokens
28
+ /(?:eyJ[\w-]+\.){2}[\w-]+/g,
29
+ ];
30
+ /**
31
+ * Maximum length for error messages in telemetry (truncate longer messages).
32
+ */
33
+ const MAX_MESSAGE_LENGTH = 500;
34
+ /**
35
+ * Maximum number of error messages to include in an array.
36
+ */
37
+ exports.MAX_ERROR_MESSAGES = 10;
38
+ /**
39
+ * Redact home directory paths from a string, replacing them with ~.
40
+ * Handles both Unix (/) and Windows (\) path separators.
41
+ */
42
+ function redactHomePath(str) {
43
+ const homeDir = os_1.default.homedir();
44
+ if (!homeDir)
45
+ return str;
46
+ // Use split/join for safe replacement (no regex)
47
+ let redacted = str.split(homeDir).join("~");
48
+ // Also handle Windows paths with forward slashes (normalized paths)
49
+ if (os_1.default.platform() === "win32" && homeDir.includes("\\")) {
50
+ const homeDirForward = homeDir.replace(/\\/g, "/");
51
+ redacted = redacted.split(homeDirForward).join("~");
52
+ }
53
+ return redacted;
54
+ }
55
+ /**
56
+ * Redact sensitive information from a string.
57
+ */
58
+ function redactSensitiveData(str) {
59
+ if (!str)
60
+ return str;
61
+ let redacted = str;
62
+ // Redact home directory paths
63
+ redacted = redactHomePath(redacted);
64
+ // Redact sensitive patterns
65
+ for (const pattern of SENSITIVE_PATTERNS) {
66
+ redacted = redacted.replace(pattern, "[REDACTED]");
67
+ }
68
+ return redacted;
69
+ }
70
+ exports.redactSensitiveData = redactSensitiveData;
71
+ /**
72
+ * Truncate a string to a maximum length, adding ellipsis if truncated.
73
+ */
74
+ function truncate(str, maxLength = MAX_MESSAGE_LENGTH) {
75
+ if (!str || str.length <= maxLength)
76
+ return str;
77
+ return str.slice(0, maxLength - 3) + "...";
78
+ }
79
+ exports.truncate = truncate;
80
+ /**
81
+ * Normalize an error message by redacting sensitive data and truncating.
82
+ */
83
+ function normalizeErrorMessage(message) {
84
+ return truncate(redactSensitiveData(message));
85
+ }
86
+ exports.normalizeErrorMessage = normalizeErrorMessage;
87
+ /**
88
+ * Extract the error class name from an error object.
89
+ */
90
+ function getErrorClass(err) {
91
+ if (!err || typeof err !== "object")
92
+ return undefined;
93
+ const constructor = err.constructor;
94
+ return constructor === null || constructor === void 0 ? void 0 : constructor.name;
95
+ }
96
+ exports.getErrorClass = getErrorClass;
97
+ /**
98
+ * Extract the error code from an error object (if present).
99
+ */
100
+ function getErrorCode(err) {
101
+ if (!err || typeof err !== "object")
102
+ return undefined;
103
+ const code = err.code;
104
+ return typeof code === "string" ? code : undefined;
105
+ }
106
+ exports.getErrorCode = getErrorCode;
107
+ /**
108
+ * Extract entity name from an error object (for schema/config errors).
109
+ */
110
+ function getErrorEntity(err) {
111
+ if (!err || typeof err !== "object")
112
+ return undefined;
113
+ const entity = err.entity;
114
+ return typeof entity === "string" ? entity : undefined;
115
+ }
116
+ exports.getErrorEntity = getErrorEntity;
117
+ /**
118
+ * Extract field name from an error object (for schema/config errors).
119
+ */
120
+ function getErrorField(err) {
121
+ if (!err || typeof err !== "object")
122
+ return undefined;
123
+ const field = err.field;
124
+ return typeof field === "string" ? field : undefined;
125
+ }
126
+ exports.getErrorField = getErrorField;
127
+ /**
128
+ * Extract error messages array from a validation error.
129
+ * Used for errors that carry multiple individual messages (e.g. ValidationError).
130
+ */
131
+ function getErrorMessages(err) {
132
+ if (!err || typeof err !== "object")
133
+ return undefined;
134
+ const messages = err.errorMessages;
135
+ if (!Array.isArray(messages))
136
+ return undefined;
137
+ return extractErrorMessages(messages);
138
+ }
139
+ exports.getErrorMessages = getErrorMessages;
140
+ /**
141
+ * Extract structured error properties for telemetry.
142
+ *
143
+ * @param err - The error object
144
+ * @returns Object with error properties suitable for telemetry
145
+ */
146
+ function extractErrorProperties(err) {
147
+ const errorClass = getErrorClass(err);
148
+ const message = err instanceof Error ? err.message : String(err);
149
+ const errorCode = getErrorCode(err);
150
+ const entity = getErrorEntity(err);
151
+ const field = getErrorField(err);
152
+ const errorMessages = getErrorMessages(err);
153
+ const result = {};
154
+ // eslint-disable-next-line camelcase
155
+ if (errorClass)
156
+ result.error_class = errorClass;
157
+ // eslint-disable-next-line camelcase
158
+ if (message)
159
+ result.error_message = normalizeErrorMessage(message);
160
+ // eslint-disable-next-line camelcase
161
+ if (errorCode)
162
+ result.error_code = errorCode;
163
+ if (entity)
164
+ result.entity = entity;
165
+ if (field)
166
+ result.field = field;
167
+ // eslint-disable-next-line camelcase
168
+ if (errorMessages && errorMessages.length > 0)
169
+ result.error_messages = errorMessages;
170
+ return result;
171
+ }
172
+ exports.extractErrorProperties = extractErrorProperties;
173
+ /**
174
+ * Extract an array of error messages from multiple errors, redacted and truncated.
175
+ *
176
+ * Used for validation errors where multiple issues may be present.
177
+ *
178
+ * @param errors - Array of errors (strings or Error objects)
179
+ * @param maxCount - Maximum number of error messages to include
180
+ * @returns Array of redacted, truncated error messages
181
+ */
182
+ function extractErrorMessages(errors, maxCount = exports.MAX_ERROR_MESSAGES) {
183
+ return errors
184
+ .slice(0, maxCount)
185
+ .map((err) => {
186
+ const message = err instanceof Error ? err.message : String(err);
187
+ return normalizeErrorMessage(message);
188
+ });
189
+ }
190
+ exports.extractErrorMessages = extractErrorMessages;
191
+ /**
192
+ * Check if an error is a config or validation error (a user error).
193
+ *
194
+ * Config and validation errors should be marked as user errors, not CLI bugs.
195
+ */
196
+ function isConfigOrValidationError(err) {
197
+ if (!err)
198
+ return false;
199
+ // ApsorcNamingError and anything with userError=true
200
+ if (err instanceof apsorc_parser_1.ApsorcNamingError)
201
+ return true;
202
+ if (typeof err === "object" && err.userError === true) {
203
+ return true;
204
+ }
205
+ // Check error message patterns
206
+ if (err instanceof Error) {
207
+ const message = err.message.toLowerCase();
208
+ // Common validation/config error patterns
209
+ if (message.includes("validation failed") ||
210
+ message.includes("lint error") ||
211
+ message.includes("configuration validation failed") ||
212
+ message.includes("invalid") ||
213
+ message.includes("does not reference an existing entity") ||
214
+ message.includes("entity found with empty name") ||
215
+ message.includes("failed to read or parse .apsorc")) {
216
+ return true;
217
+ }
218
+ }
219
+ return false;
220
+ }
221
+ exports.isConfigOrValidationError = isConfigOrValidationError;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Constants for detecting internal (Apso team/system) CLI runs.
3
+ *
4
+ * Internal runs are explicitly marked so external anonymous users can be
5
+ * isolated in both PostHog and Sentry. This is separate from CI: CI is not
6
+ * always internal, and internal is not always CI.
7
+ */
8
+ /**
9
+ * GitHub repository owners that are considered internal.
10
+ * Any workflow in a repo owned by these orgs/users is marked internal.
11
+ */
12
+ export declare const INTERNAL_GITHUB_OWNERS: string[];
13
+ /**
14
+ * Email domains that are considered internal.
15
+ * Users with these domains are marked as internal.
16
+ */
17
+ export declare const INTERNAL_EMAIL_DOMAINS: string[];
18
+ /**
19
+ * Workspace slugs that are considered internal.
20
+ * Users in these workspaces are marked as internal.
21
+ */
22
+ export declare const INTERNAL_WORKSPACE_SLUGS: string[];
23
+ /**
24
+ * Workspace IDs that are considered internal.
25
+ * Users in these workspaces are marked as internal.
26
+ */
27
+ export declare const INTERNAL_WORKSPACE_IDS: string[];
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ /**
3
+ * Constants for detecting internal (Apso team/system) CLI runs.
4
+ *
5
+ * Internal runs are explicitly marked so external anonymous users can be
6
+ * isolated in both PostHog and Sentry. This is separate from CI: CI is not
7
+ * always internal, and internal is not always CI.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.INTERNAL_WORKSPACE_IDS = exports.INTERNAL_WORKSPACE_SLUGS = exports.INTERNAL_EMAIL_DOMAINS = exports.INTERNAL_GITHUB_OWNERS = void 0;
11
+ /**
12
+ * GitHub repository owners that are considered internal.
13
+ * Any workflow in a repo owned by these orgs/users is marked internal.
14
+ */
15
+ exports.INTERNAL_GITHUB_OWNERS = ["apsoai"];
16
+ /**
17
+ * Email domains that are considered internal.
18
+ * Users with these domains are marked as internal.
19
+ */
20
+ exports.INTERNAL_EMAIL_DOMAINS = ["apso.ai", "mavrictech.com"];
21
+ /**
22
+ * Workspace slugs that are considered internal.
23
+ * Users in these workspaces are marked as internal.
24
+ */
25
+ exports.INTERNAL_WORKSPACE_SLUGS = ["apso", "apso-team", "mavric"];
26
+ /**
27
+ * Workspace IDs that are considered internal.
28
+ * Users in these workspaces are marked as internal.
29
+ */
30
+ exports.INTERNAL_WORKSPACE_IDS = [
31
+ // Add specific workspace IDs here when known
32
+ ];
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Detection logic for internal (Apso team/system) CLI runs.
3
+ *
4
+ * Multiple detection methods ensure all internal runs are tagged, with any
5
+ * match marking the run as internal. The override env var APSO_INTERNAL=0
6
+ * forces false for testing external behavior internally.
7
+ */
8
+ export type InternalReason = "env" | "github_owner" | "config" | "account" | "workspace";
9
+ export interface InternalDetectionResult {
10
+ internal: boolean;
11
+ reason?: InternalReason;
12
+ }
13
+ /**
14
+ * Detect if this CLI run should be marked as internal.
15
+ *
16
+ * Detection methods, in order of precedence:
17
+ * 1. Explicit env var APSO_INTERNAL (1/true = internal, 0 = force false override)
18
+ * 2. GitHub Actions auto-detection (GITHUB_ACTIONS=true + owner in INTERNAL_GITHUB_OWNERS)
19
+ * 3. Config flag: `apso config set internal true`
20
+ * 4. Account-based: authenticated user email domain or workspace
21
+ *
22
+ * @param opts - Detection context
23
+ * @returns Object with internal boolean and reason
24
+ */
25
+ export declare function detectInternal(opts: {
26
+ configInternal?: boolean;
27
+ userEmail?: string;
28
+ workspaceSlug?: string;
29
+ workspaceId?: string;
30
+ }): InternalDetectionResult;
31
+ /**
32
+ * Extract email domain from an email address (without sending the full email).
33
+ *
34
+ * @param email - Email address
35
+ * @returns Domain part of the email (e.g., "apso.ai")
36
+ */
37
+ export declare function getEmailDomain(email: string): string | undefined;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * Detection logic for internal (Apso team/system) CLI runs.
4
+ *
5
+ * Multiple detection methods ensure all internal runs are tagged, with any
6
+ * match marking the run as internal. The override env var APSO_INTERNAL=0
7
+ * forces false for testing external behavior internally.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.getEmailDomain = exports.detectInternal = void 0;
11
+ const internal_constants_1 = require("./internal-constants");
12
+ /**
13
+ * Detect if this CLI run should be marked as internal.
14
+ *
15
+ * Detection methods, in order of precedence:
16
+ * 1. Explicit env var APSO_INTERNAL (1/true = internal, 0 = force false override)
17
+ * 2. GitHub Actions auto-detection (GITHUB_ACTIONS=true + owner in INTERNAL_GITHUB_OWNERS)
18
+ * 3. Config flag: `apso config set internal true`
19
+ * 4. Account-based: authenticated user email domain or workspace
20
+ *
21
+ * @param opts - Detection context
22
+ * @returns Object with internal boolean and reason
23
+ */
24
+ function detectInternal(opts) {
25
+ var _a, _b;
26
+ // 1. Explicit env var (with override)
27
+ const envVar = process.env.APSO_INTERNAL;
28
+ if (envVar === "0" || envVar === "false") {
29
+ // Force false - for testing external behavior internally
30
+ return { internal: false };
31
+ }
32
+ if (envVar === "1" || envVar === "true") {
33
+ return { internal: true, reason: "env" };
34
+ }
35
+ // 2. GitHub Actions auto-detection
36
+ if (process.env.GITHUB_ACTIONS === "true") {
37
+ const repoOwner = process.env.GITHUB_REPOSITORY_OWNER ||
38
+ ((_a = process.env.GITHUB_REPOSITORY) === null || _a === void 0 ? void 0 : _a.split("/")[0]);
39
+ if (repoOwner &&
40
+ internal_constants_1.INTERNAL_GITHUB_OWNERS.some((owner) => owner.toLowerCase() === repoOwner.toLowerCase())) {
41
+ return { internal: true, reason: "github_owner" };
42
+ }
43
+ }
44
+ // 3. Config flag: apso config set internal true
45
+ if (opts.configInternal === true) {
46
+ return { internal: true, reason: "config" };
47
+ }
48
+ // 4. Account-based: email domain
49
+ if (opts.userEmail) {
50
+ const domain = (_b = opts.userEmail.split("@")[1]) === null || _b === void 0 ? void 0 : _b.toLowerCase();
51
+ if (domain && internal_constants_1.INTERNAL_EMAIL_DOMAINS.includes(domain)) {
52
+ return { internal: true, reason: "account" };
53
+ }
54
+ }
55
+ // 4. Account-based: workspace slug or ID
56
+ if (opts.workspaceSlug) {
57
+ const slug = opts.workspaceSlug.toLowerCase();
58
+ if (internal_constants_1.INTERNAL_WORKSPACE_SLUGS.includes(slug)) {
59
+ return { internal: true, reason: "workspace" };
60
+ }
61
+ }
62
+ if (opts.workspaceId && internal_constants_1.INTERNAL_WORKSPACE_IDS.includes(opts.workspaceId)) {
63
+ return { internal: true, reason: "workspace" };
64
+ }
65
+ return { internal: false };
66
+ }
67
+ exports.detectInternal = detectInternal;
68
+ /**
69
+ * Extract email domain from an email address (without sending the full email).
70
+ *
71
+ * @param email - Email address
72
+ * @returns Domain part of the email (e.g., "apso.ai")
73
+ */
74
+ function getEmailDomain(email) {
75
+ var _a;
76
+ return (_a = email.split("@")[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase();
77
+ }
78
+ exports.getEmailDomain = getEmailDomain;
@@ -28,6 +28,17 @@ export declare function markFirstRunNoticeShown(): void;
28
28
  export declare function track(event: string, properties?: Record<string, unknown>): void;
29
29
  /** Report an exception to Sentry. No-op when disabled. */
30
30
  export declare function captureException(err: unknown, context?: Record<string, unknown>): void;
31
+ /**
32
+ * Capture an exception event in PostHog with structured error properties.
33
+ *
34
+ * PostHog's posthog-node SDK (v5.21.2+) doesn't have a direct captureException
35
+ * method, so we send an $exception event with $exception_list in the standard
36
+ * format: https://posthog.com/docs/data/exceptions
37
+ *
38
+ * @param err - The error to capture
39
+ * @param context - Additional context properties (command, etc.)
40
+ */
41
+ export declare function capturePostHogException(err: unknown, context?: Record<string, unknown>): void;
31
42
  /** Milliseconds since the process (CLI invocation) started. */
32
43
  export declare function elapsedMs(): number;
33
44
  /** Flush + close both clients. Call before the process exits. */
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.__testing = exports.shutdownTelemetry = exports.elapsedMs = exports.captureException = exports.track = exports.markFirstRunNoticeShown = exports.shouldShowFirstRunNotice = exports.FIRST_RUN_NOTICE = exports.initTelemetry = void 0;
3
+ exports.__testing = exports.shutdownTelemetry = exports.elapsedMs = exports.capturePostHogException = exports.captureException = exports.track = exports.markFirstRunNoticeShown = exports.shouldShowFirstRunNotice = exports.FIRST_RUN_NOTICE = exports.initTelemetry = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  /**
6
6
  * CLI telemetry — usage analytics (PostHog) + error reporting (Sentry).
@@ -25,7 +25,10 @@ const posthog_node_1 = require("posthog-node");
25
25
  const Sentry = tslib_1.__importStar(require("@sentry/node"));
26
26
  const crypto_1 = require("crypto");
27
27
  const os_1 = tslib_1.__importDefault(require("os"));
28
+ const ci_info_1 = tslib_1.__importDefault(require("ci-info"));
28
29
  const config_1 = require("../config");
30
+ const error_utils_1 = require("./error-utils");
31
+ const internal_detection_1 = require("./internal-detection");
29
32
  // Public ingestion keys (same tokens the browser/build-engine ship, per env).
30
33
  const POSTHOG_KEY_PROD = "phc_Es9UUMw8pOs7Bs21b5PhfC5Qdo94GpYVv8MfdrG12LC";
31
34
  const POSTHOG_KEY_STAGING = "phc_bkc33v3wo5LRvgPF6IdjsgDEDOwgJMz95MR2YIlvELk";
@@ -51,6 +54,7 @@ let serviceId;
51
54
  let environment = "production";
52
55
  let startedAt = Date.now();
53
56
  let noticePending = false;
57
+ let internalDetection = { internal: false };
54
58
  function isDisabled(telemetryDisabled) {
55
59
  if (process.env.DO_NOT_TRACK === "1" || process.env.DO_NOT_TRACK === "true")
56
60
  return true;
@@ -88,7 +92,7 @@ function getOrCreateInstallId(currentInstallId) {
88
92
  * when disabled — it just no-ops everything downstream.
89
93
  */
90
94
  function initTelemetry() {
91
- var _a, _b;
95
+ var _a, _b, _c;
92
96
  try {
93
97
  startedAt = Date.now();
94
98
  const cfg = config_1.globalConfig.read();
@@ -97,6 +101,8 @@ function initTelemetry() {
97
101
  return;
98
102
  }
99
103
  enabled = true;
104
+ // Install uncaught exception and unhandled rejection handlers
105
+ installGlobalErrorHandlers();
100
106
  environment = (cfg.apiUrl || "").includes("staging")
101
107
  ? "staging"
102
108
  : "production";
@@ -120,6 +126,13 @@ function initTelemetry() {
120
126
  workspaceId = (link === null || link === void 0 ? void 0 : link.workspaceId) || cfg.activeWorkspaceId || undefined;
121
127
  workspaceSlug = (link === null || link === void 0 ? void 0 : link.workspaceSlug) || cfg.activeWorkspaceSlug || undefined;
122
128
  serviceId = (link === null || link === void 0 ? void 0 : link.serviceId) || undefined;
129
+ // Detect internal runs (Apso team/system)
130
+ internalDetection = (0, internal_detection_1.detectInternal)({
131
+ configInternal: cfg.internal,
132
+ userEmail: (_c = creds === null || creds === void 0 ? void 0 : creds.user) === null || _c === void 0 ? void 0 : _c.email,
133
+ workspaceSlug,
134
+ workspaceId,
135
+ });
123
136
  posthog = new posthog_node_1.PostHog(environment === "staging" ? POSTHOG_KEY_STAGING : POSTHOG_KEY_PROD, { host: POSTHOG_HOST, flushAt: 1, flushInterval: 0 });
124
137
  // First run after login: merge this install's earlier anonymous events
125
138
  // into the user, once per user.
@@ -146,6 +159,11 @@ function initTelemetry() {
146
159
  Sentry.setTag("workspace_id", workspaceId);
147
160
  if (serviceId)
148
161
  Sentry.setTag("service_id", serviceId);
162
+ // Tag internal runs in Sentry
163
+ Sentry.setTag("internal", String(internalDetection.internal));
164
+ if (internalDetection.reason) {
165
+ Sentry.setTag("internal_reason", internalDetection.reason);
166
+ }
149
167
  sentryOn = true;
150
168
  }
151
169
  }
@@ -162,6 +180,10 @@ function commonProps() {
162
180
  arch: os_1.default.arch(),
163
181
  node_version: process.version,
164
182
  authenticated: authenticatedUser,
183
+ ci: ci_info_1.default.isCI,
184
+ internal: internalDetection.internal,
185
+ // eslint-disable-next-line camelcase
186
+ ...(internalDetection.reason ? { internal_reason: internalDetection.reason } : {}),
165
187
  ...(workspaceId ? { workspace_id: workspaceId } : {}),
166
188
  ...(workspaceSlug ? { workspace_slug: workspaceSlug } : {}),
167
189
  ...(serviceId ? { service_id: serviceId } : {}),
@@ -202,7 +224,17 @@ function track(event, properties = {}) {
202
224
  posthog.capture({
203
225
  distinctId,
204
226
  event,
205
- properties: { ...commonProps(), ...properties },
227
+ properties: {
228
+ ...commonProps(),
229
+ ...properties,
230
+ // Set internal as person properties via $set (posthog-node types don't include it, but it works)
231
+ // eslint-disable-next-line camelcase
232
+ $set: {
233
+ internal: internalDetection.internal,
234
+ // eslint-disable-next-line camelcase
235
+ ...(internalDetection.reason ? { internal_reason: internalDetection.reason } : {}),
236
+ },
237
+ },
206
238
  // PostHog group analytics: roll activity up per workspace.
207
239
  ...(workspaceId ? { groups: { workspace: workspaceId } } : {}),
208
240
  });
@@ -224,6 +256,83 @@ function captureException(err, context = {}) {
224
256
  }
225
257
  }
226
258
  exports.captureException = captureException;
259
+ /**
260
+ * Capture an exception event in PostHog with structured error properties.
261
+ *
262
+ * PostHog's posthog-node SDK (v5.21.2+) doesn't have a direct captureException
263
+ * method, so we send an $exception event with $exception_list in the standard
264
+ * format: https://posthog.com/docs/data/exceptions
265
+ *
266
+ * @param err - The error to capture
267
+ * @param context - Additional context properties (command, etc.)
268
+ */
269
+ function capturePostHogException(err, context = {}) {
270
+ try {
271
+ if (!enabled || !posthog)
272
+ return;
273
+ const errorProps = (0, error_utils_1.extractErrorProperties)(err);
274
+ const stack = err instanceof Error ? err.stack : undefined;
275
+ // PostHog exception format: $exception event with $exception_list
276
+ posthog.capture({
277
+ distinctId,
278
+ event: "$exception",
279
+ properties: {
280
+ ...commonProps(),
281
+ ...context,
282
+ // eslint-disable-next-line camelcase
283
+ $exception_list: [
284
+ {
285
+ // eslint-disable-next-line camelcase
286
+ type: errorProps.error_class || "Error",
287
+ // eslint-disable-next-line camelcase
288
+ value: errorProps.error_message || String(err),
289
+ ...(stack ? { stacktrace: { frames: parseStackTrace(stack) } } : {}),
290
+ },
291
+ ],
292
+ // Additional structured error properties
293
+ ...errorProps,
294
+ // Set internal as person properties via $set (posthog-node types don't include it, but it works)
295
+ // eslint-disable-next-line camelcase
296
+ $set: {
297
+ internal: internalDetection.internal,
298
+ // eslint-disable-next-line camelcase
299
+ ...(internalDetection.reason ? { internal_reason: internalDetection.reason } : {}),
300
+ },
301
+ },
302
+ ...(workspaceId ? { groups: { workspace: workspaceId } } : {}),
303
+ });
304
+ }
305
+ catch {
306
+ // never break a command over telemetry
307
+ }
308
+ }
309
+ exports.capturePostHogException = capturePostHogException;
310
+ /**
311
+ * Parse a stack trace string into PostHog's frame format.
312
+ * Best-effort parsing; PostHog accepts frames with minimal structure.
313
+ */
314
+ function parseStackTrace(stack) {
315
+ try {
316
+ const lines = stack.split("\n").slice(1); // Skip the error message line
317
+ return lines.slice(0, 10).map((line) => {
318
+ // Basic parsing: extract function name and location if available
319
+ const match = line.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?/);
320
+ if (match) {
321
+ const [, fn, filename, lineno, colno] = match;
322
+ return {
323
+ function: fn || "<anonymous>",
324
+ filename: (filename === null || filename === void 0 ? void 0 : filename.replace(os_1.default.homedir(), "~")) || "unknown",
325
+ lineno: Number.parseInt(lineno, 10),
326
+ colno: Number.parseInt(colno, 10),
327
+ };
328
+ }
329
+ return { raw: line.trim() };
330
+ });
331
+ }
332
+ catch {
333
+ return [{ raw: "Failed to parse stack trace" }];
334
+ }
335
+ }
227
336
  /** Milliseconds since the process (CLI invocation) started. */
228
337
  function elapsedMs() {
229
338
  return Date.now() - startedAt;
@@ -247,4 +356,89 @@ async function shutdownTelemetry() {
247
356
  }
248
357
  }
249
358
  exports.shutdownTelemetry = shutdownTelemetry;
359
+ /**
360
+ * Guard against re-entry in global error handlers.
361
+ */
362
+ let handlingFatalError = false;
363
+ /**
364
+ * Install global handlers for uncaught exceptions and unhandled rejections.
365
+ * These handlers capture telemetry, flush with a timeout, then crash properly
366
+ * with non-zero exit and stderr output (preserving Node's default behavior).
367
+ */
368
+ function installGlobalErrorHandlers() {
369
+ process.on("uncaughtException", (err) => {
370
+ if (handlingFatalError) {
371
+ // Re-entry during error handling - bail immediately
372
+ process.stderr.write("Fatal error during error handling\n");
373
+ // eslint-disable-next-line no-process-exit
374
+ process.exit(1);
375
+ }
376
+ handlingFatalError = true;
377
+ // Capture telemetry (best-effort, non-blocking)
378
+ try {
379
+ // eslint-disable-next-line camelcase
380
+ captureException(err, { event_type: "uncaught_exception" });
381
+ // eslint-disable-next-line camelcase
382
+ capturePostHogException(err, { event_type: "uncaught_exception" });
383
+ }
384
+ catch {
385
+ // ignore telemetry errors
386
+ }
387
+ // Flush telemetry with a short timeout (2s), then crash properly
388
+ const flushWithTimeout = Promise.race([
389
+ shutdownTelemetry(),
390
+ new Promise((resolve) => {
391
+ setTimeout(() => resolve(), 2000);
392
+ }),
393
+ ]);
394
+ flushWithTimeout
395
+ .catch(() => {
396
+ // ignore flush errors
397
+ })
398
+ .finally(() => {
399
+ // Print error to stderr (Node's default behavior)
400
+ process.stderr.write(`\n${err.stack || err.message}\n`);
401
+ // Exit non-zero (Node's default behavior)
402
+ // eslint-disable-next-line no-process-exit
403
+ process.exit(1);
404
+ });
405
+ });
406
+ process.on("unhandledRejection", (reason) => {
407
+ if (handlingFatalError) {
408
+ process.stderr.write("Fatal error during error handling\n");
409
+ // eslint-disable-next-line no-process-exit
410
+ process.exit(1);
411
+ }
412
+ handlingFatalError = true;
413
+ const err = reason instanceof Error ? reason : new Error(String(reason));
414
+ // Capture telemetry (best-effort, non-blocking)
415
+ try {
416
+ // eslint-disable-next-line camelcase
417
+ captureException(err, { event_type: "unhandled_rejection" });
418
+ // eslint-disable-next-line camelcase
419
+ capturePostHogException(err, { event_type: "unhandled_rejection" });
420
+ }
421
+ catch {
422
+ // ignore telemetry errors
423
+ }
424
+ // Flush telemetry with a short timeout (2s), then crash properly
425
+ const flushWithTimeout = Promise.race([
426
+ shutdownTelemetry(),
427
+ new Promise((resolve) => {
428
+ setTimeout(() => resolve(), 2000);
429
+ }),
430
+ ]);
431
+ flushWithTimeout
432
+ .catch(() => {
433
+ // ignore flush errors
434
+ })
435
+ .finally(() => {
436
+ // Print error to stderr (Node's default behavior)
437
+ process.stderr.write(`\nUnhandled rejection: ${err.stack || err.message}\n`);
438
+ // Exit non-zero (Node's default behavior)
439
+ // eslint-disable-next-line no-process-exit
440
+ process.exit(1);
441
+ });
442
+ });
443
+ }
250
444
  exports.__testing = { isDisabled, anonMachineId, getOrCreateInstallId };
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * Upgrade-on-limit flow.
3
3
  *
4
- * When the platform rejects an action because the workspace hit a plan limit
5
- * (e.g. the free-tier service cap), we surface a friendly prompt that opens the
6
- * upgrade page in the browser and retries once the user is done — mirroring the
7
- * "you've hit a limit, upgrade?" flow developers expect from modern CLIs.
4
+ * When the platform rejects an action for a plan or billing reason (the free-tier
5
+ * service cap, staging on a free service, a suspended service), the CLI opens the
6
+ * web app page where the user fixes it and retries once they are done.
8
7
  */
9
8
  import { ApiClientError } from "./api/client";
10
9
  /** Where the user is when the refusal happened, so the link can go to the exact page. */
@@ -18,8 +17,8 @@ export declare function fixPage(error: ApiClientError, ctx?: PageContext): {
18
17
  label: string;
19
18
  };
20
19
  /**
21
- * Prompt the user to resolve a plan or billing refusal in the web app, open the
22
- * page, and wait for them to finish. Returns true if the caller should retry.
20
+ * Open the web app page that resolves a plan or billing refusal, then wait for
21
+ * the user to finish there. Returns true if the caller should retry.
23
22
  */
24
23
  export declare function promptUpgrade(error: ApiClientError, ctx?: PageContext): Promise<boolean>;
25
24
  /**
@@ -2,10 +2,9 @@
2
2
  /**
3
3
  * Upgrade-on-limit flow.
4
4
  *
5
- * When the platform rejects an action because the workspace hit a plan limit
6
- * (e.g. the free-tier service cap), we surface a friendly prompt that opens the
7
- * upgrade page in the browser and retries once the user is done — mirroring the
8
- * "you've hit a limit, upgrade?" flow developers expect from modern CLIs.
5
+ * When the platform rejects an action for a plan or billing reason (the free-tier
6
+ * service cap, staging on a free service, a suspended service), the CLI opens the
7
+ * web app page where the user fixes it and retries once they are done.
9
8
  */
10
9
  Object.defineProperty(exports, "__esModule", { value: true });
11
10
  exports.withUpgradeRetry = exports.promptUpgrade = exports.fixPage = void 0;
@@ -49,38 +48,28 @@ function fixPage(error, ctx = {}) {
49
48
  }
50
49
  exports.fixPage = fixPage;
51
50
  /**
52
- * Prompt the user to resolve a plan or billing refusal in the web app, open the
53
- * page, and wait for them to finish. Returns true if the caller should retry.
51
+ * Open the web app page that resolves a plan or billing refusal, then wait for
52
+ * the user to finish there. Returns true if the caller should retry.
54
53
  */
55
54
  async function promptUpgrade(error, ctx = {}) {
56
- const { url: upgradeUrl, label } = fixPage(error, ctx);
55
+ const { url, label } = fixPage(error, ctx);
57
56
  console.log("");
58
57
  console.log(` ⚠ ${error.message || "You've reached a plan limit."}`);
59
58
  console.log("");
60
- const { proceed } = await inquirer_1.default.prompt([
61
- {
62
- type: "confirm",
63
- name: "proceed",
64
- message: `Open ${label} in your browser?`,
65
- default: true,
66
- },
67
- ]);
68
- if (!proceed) {
69
- console.log(` You can do this any time at: ${upgradeUrl}`);
70
- return false;
71
- }
72
- console.log("");
73
- console.log(` Opening ${upgradeUrl}`);
59
+ console.log(` Opening ${label} in your browser: ${url}`);
74
60
  console.log(" If the browser doesn't open, visit the URL above.");
75
- await openBrowser(upgradeUrl);
61
+ console.log("");
62
+ await openBrowser(url);
76
63
  const { done } = await inquirer_1.default.prompt([
77
64
  {
78
65
  type: "confirm",
79
66
  name: "done",
80
- message: "Press enter once you are done there to retry",
67
+ message: "Done there? Retry now",
81
68
  default: true,
82
69
  },
83
70
  ]);
71
+ if (!done)
72
+ console.log(` You can finish this any time at: ${url}`);
84
73
  return done;
85
74
  }
86
75
  exports.promptUpgrade = promptUpgrade;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.53.0",
3
+ "version": "0.54.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@apso/cli",
9
- "version": "0.53.0",
9
+ "version": "0.54.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@apso/schema-tools": "^0.2.3",
@@ -19,6 +19,7 @@
19
19
  "@oclif/plugin-warn-if-update-available": "^2.1.1",
20
20
  "@sentry/node": "^10.68.0",
21
21
  "adm-zip": "^0.6.0",
22
+ "ci-info": "^3.9.0",
22
23
  "debug": "^4.3.4",
23
24
  "eta": "^2.0.0",
24
25
  "inquirer": "^8.2.7",
@@ -4602,16 +4603,16 @@
4602
4603
  }
4603
4604
  },
4604
4605
  "node_modules/ci-info": {
4605
- "version": "3.8.0",
4606
- "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.8.0.tgz",
4607
- "integrity": "sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw==",
4608
- "dev": true,
4606
+ "version": "3.9.0",
4607
+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
4608
+ "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
4609
4609
  "funding": [
4610
4610
  {
4611
4611
  "type": "github",
4612
4612
  "url": "https://github.com/sponsors/sibiraj-s"
4613
4613
  }
4614
4614
  ],
4615
+ "license": "MIT",
4615
4616
  "engines": {
4616
4617
  "node": ">=8"
4617
4618
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.53.0",
2
+ "version": "0.54.0",
3
3
  "commands": {
4
4
  "config": {
5
5
  "id": "config",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.53.0",
3
+ "version": "0.54.0",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",
@@ -34,6 +34,7 @@
34
34
  "@oclif/plugin-warn-if-update-available": "^2.1.1",
35
35
  "@sentry/node": "^10.68.0",
36
36
  "adm-zip": "^0.6.0",
37
+ "ci-info": "^3.9.0",
37
38
  "debug": "^4.3.4",
38
39
  "eta": "^2.0.0",
39
40
  "inquirer": "^8.2.7",