@oxygen-agent/cli 1.936.1 → 1.948.1

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.
Files changed (33) hide show
  1. package/README.md +1 -1
  2. package/dist/command-manifest.js +24 -2
  3. package/dist/help.js +1 -0
  4. package/dist/index.js +342 -54
  5. package/dist/ugc-commands.js +353 -12
  6. package/node_modules/@oxygen/shared/dist/byok-connect.d.ts +11 -6
  7. package/node_modules/@oxygen/shared/dist/byok-connect.js +14 -6
  8. package/node_modules/@oxygen/shared/dist/capability-discovery.js +53 -5
  9. package/node_modules/@oxygen/shared/dist/email-dsn.d.ts +60 -0
  10. package/node_modules/@oxygen/shared/dist/email-dsn.js +120 -0
  11. package/node_modules/@oxygen/shared/dist/email-warmup-readiness.d.ts +64 -0
  12. package/node_modules/@oxygen/shared/dist/email-warmup-readiness.js +90 -0
  13. package/node_modules/@oxygen/shared/dist/index.d.ts +6 -0
  14. package/node_modules/@oxygen/shared/dist/index.js +6 -0
  15. package/node_modules/@oxygen/shared/dist/knowledge-bootstrap.d.ts +50 -21
  16. package/node_modules/@oxygen/shared/dist/knowledge-bootstrap.js +47 -21
  17. package/node_modules/@oxygen/shared/dist/langfuse.d.ts +8 -3
  18. package/node_modules/@oxygen/shared/dist/langfuse.js +177 -130
  19. package/node_modules/@oxygen/shared/dist/llm-payload.d.ts +10 -0
  20. package/node_modules/@oxygen/shared/dist/llm-payload.js +54 -0
  21. package/node_modules/@oxygen/shared/dist/llm-usage.d.ts +11 -0
  22. package/node_modules/@oxygen/shared/dist/llm-usage.js +30 -0
  23. package/node_modules/@oxygen/shared/dist/product-analytics-core.d.ts +98 -0
  24. package/node_modules/@oxygen/shared/dist/product-analytics-core.js +159 -0
  25. package/node_modules/@oxygen/shared/dist/product-analytics-environment.d.ts +18 -0
  26. package/node_modules/@oxygen/shared/dist/product-analytics-environment.js +46 -0
  27. package/node_modules/@oxygen/shared/dist/product-analytics-events.d.ts +92 -0
  28. package/node_modules/@oxygen/shared/dist/product-analytics-events.js +96 -0
  29. package/node_modules/@oxygen/shared/dist/ugc.d.ts +21 -1
  30. package/node_modules/@oxygen/shared/dist/version.d.ts +1 -1
  31. package/node_modules/@oxygen/shared/dist/version.js +1 -1
  32. package/node_modules/@oxygen/workflows/dist/graph/lint.js +22 -0
  33. package/package.json +1 -1
@@ -0,0 +1,54 @@
1
+ import { createHash } from "node:crypto";
2
+ import { redactSecretsInString } from "./redaction.js";
3
+ // Bound individual OTLP fields in UTF-8 bytes. Large payloads remain fully
4
+ // recoverable in child events rather than losing the end of a model response.
5
+ const INLINE_BYTES = 128 * 1024;
6
+ const CHUNK_BYTES = 64 * 1024;
7
+ const SECRET_KEY = /^(?:authorization|proxy-authorization|cookie|set-cookie|password|passwd|secret|(?:x[-_]?)?api[-_]?key|x[-_]?auth[-_]?token|access[-_]?token|refresh[-_]?token|client[-_]?secret|private[-_]?key|connection[-_]?uri|database[-_]?url)$/i;
8
+ const SECRET_QUERY = /([?&](?:token|access_token|api_key|key|signature|x-amz-signature|x-goog-signature)=)[^&#\s"]+/gi;
9
+ /** Only credentials are masked: prompts, tool arguments and token counts stay. */
10
+ export function prepareLlmPayload(value, fieldKey = "") {
11
+ if (SECRET_KEY.test(fieldKey))
12
+ value = "[REDACTED]";
13
+ if (value === undefined || value === null)
14
+ return { value, chunks: [] };
15
+ let serialized;
16
+ try {
17
+ // Tool arguments and SSE frames are often JSON encoded inside a string.
18
+ // Inspect those nested documents too; redacting only outer object keys
19
+ // would leave an API key inside tool_calls[].function.arguments intact.
20
+ const serialize = (input, nestedDepth = 0) => JSON.stringify(input, (key, item) => {
21
+ if (SECRET_KEY.test(key))
22
+ return "[REDACTED]";
23
+ if (typeof item !== "string")
24
+ return item;
25
+ let text = redactSecretsInString(item).replace(SECRET_QUERY, "$1[REDACTED]");
26
+ if (/^\s*[\[{]/.test(text)) {
27
+ try {
28
+ const parsed = JSON.parse(text);
29
+ if (nestedDepth >= 32)
30
+ return "[REDACTED_NESTED_JSON_DEPTH]";
31
+ text = serialize(parsed, nestedDepth + 1);
32
+ }
33
+ catch { /* ordinary prompt text, not a JSON document */ }
34
+ }
35
+ return text;
36
+ }) ?? "null";
37
+ serialized = serialize(value);
38
+ }
39
+ catch {
40
+ return { value: { truncated: true, reason: "unserializable" }, chunks: [] };
41
+ }
42
+ const bytes = Buffer.from(serialized, "utf8");
43
+ if (bytes.length <= INLINE_BYTES)
44
+ return { value: JSON.parse(serialized), chunks: [] };
45
+ const id = createHash("sha256").update(bytes).digest("hex");
46
+ const chunks = [];
47
+ for (let offset = 0; offset < bytes.length; offset += CHUNK_BYTES) {
48
+ chunks.push({ payload_id: id, index: chunks.length, data: bytes.subarray(offset, offset + CHUNK_BYTES).toString("base64") });
49
+ }
50
+ return {
51
+ value: { oxygen_payload: { id, encoding: "base64-json-utf8", bytes: bytes.length, chunks: chunks.length, sha256: id } },
52
+ chunks,
53
+ };
54
+ }
@@ -0,0 +1,11 @@
1
+ /** Inclusive provider counts. Keep the original provider usage on the observation's metadata. */
2
+ export type LlmProviderUsage = {
3
+ promptTokens?: number | null | undefined;
4
+ completionTokens?: number | null | undefined;
5
+ reasoningTokens?: number | null | undefined;
6
+ cachedPromptTokens?: number | null | undefined;
7
+ cacheWriteTokens?: number | null | undefined;
8
+ totalTokens?: number | null | undefined;
9
+ };
10
+ /** Langfuse usage keys are mutually exclusive buckets, not inclusive breakdowns. */
11
+ export declare function normalizeLlmUsageDetails(usage: LlmProviderUsage | null | undefined): Record<string, number> | undefined;
@@ -0,0 +1,30 @@
1
+ /** Langfuse usage keys are mutually exclusive buckets, not inclusive breakdowns. */
2
+ export function normalizeLlmUsageDetails(usage) {
3
+ if (!usage)
4
+ return undefined;
5
+ const count = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
6
+ const input = count(usage.promptTokens);
7
+ const output = count(usage.completionTokens);
8
+ const details = {};
9
+ if (input !== undefined) {
10
+ const cached = Math.min(input, count(usage.cachedPromptTokens) ?? 0);
11
+ const created = Math.min(input - cached, count(usage.cacheWriteTokens) ?? 0);
12
+ details.input = input - cached - created;
13
+ if (cached > 0)
14
+ details.input_cached_tokens = cached;
15
+ if (created > 0)
16
+ details.input_cache_creation_tokens = created;
17
+ }
18
+ if (output !== undefined) {
19
+ // Some providers return a detail count larger than its inclusive parent.
20
+ // Preserve the parent total rather than inventing extra billed tokens.
21
+ const reasoning = Math.min(output, count(usage.reasoningTokens) ?? 0);
22
+ details.output = output - reasoning;
23
+ if (reasoning > 0)
24
+ details.output_reasoning_tokens = reasoning;
25
+ }
26
+ const total = input !== undefined && output !== undefined ? input + output : count(usage.totalTokens);
27
+ if (total !== undefined)
28
+ details.total = total;
29
+ return Object.keys(details).length > 0 ? details : undefined;
30
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Product-analytics core — the TRANSPORT-FREE half of PostHog emission.
3
+ *
4
+ * Two runtimes emit product events: the web/API runtime (`apps/web/src/lib/
5
+ * product-analytics.ts`, `posthog-node` on Vercel) and the Fly worker
6
+ * (`apps/worker/src/product-analytics.ts`, `posthog-node` batching). What they
7
+ * must agree on lives here, once: property sanitization, the distinct-id
8
+ * chain, the person-profile posture, org grouping, and the runtime dimensions
9
+ * every event carries. Two copies of that logic drifted in the past — the
10
+ * worker would have minted a throwaway person per request while the web side
11
+ * did not — and PostHog cannot join what the emitters disagree about.
12
+ *
13
+ * Deliberately NO `posthog-node`, no fetch, no I/O: `packages/shared` is
14
+ * vendored into the published `@oxygen-agent/cli` tarball, so every runtime
15
+ * dependency added here lands on every customer's machine
16
+ * (`scripts/cli-package-dependencies.mjs`, the langfuse-class guard). The
17
+ * capture message is a plain object structurally compatible with
18
+ * `posthog-node`'s `EventMessage`; each runtime owns its own client.
19
+ */
20
+ export declare const PRODUCT_ANALYTICS_MAX_PROPERTY_KEY_LENGTH = 80;
21
+ export declare const PRODUCT_ANALYTICS_MAX_PROPERTY_STRING_LENGTH = 500;
22
+ /**
23
+ * Byte ceiling for a structured (object/array) property value.
24
+ *
25
+ * Structured values pass through UNTOUCHED — see `sanitizeStructuredValue` — so
26
+ * this is the only thing standing between a careless caller and an unbounded
27
+ * ingest payload. Set well above `MCP_PAYLOAD_LIMITS.maxSerializedBytes` (8 KiB,
28
+ * in apps/web `analytics/mcp-analytics.ts`) so it can never re-cut a payload
29
+ * that module already bounded and marked; it exists for the callers that bound
30
+ * nothing.
31
+ */
32
+ export declare const PRODUCT_ANALYTICS_MAX_STRUCTURED_PROPERTY_BYTES = 32768;
33
+ /**
34
+ * A JSON value PostHog can index as a structured property.
35
+ *
36
+ * PostHog's reserved MCP-Analytics properties (`$mcp_parameters`,
37
+ * `$mcp_response`, `$mcp_listed_tool_names`) are objects and arrays by vendor
38
+ * contract, so a scalar-only property type made the entire `$mcp_*` surface
39
+ * untransmittable: a `.slice(...)` on an array is a `TypeError`, and that throw
40
+ * escaped `trackProductEvent` — losing the whole event, not just the property.
41
+ */
42
+ export type ProductAnalyticsJsonValue = string | number | boolean | null | readonly ProductAnalyticsJsonValue[] | {
43
+ readonly [key: string]: ProductAnalyticsJsonValue;
44
+ };
45
+ export type ProductAnalyticsValue = ProductAnalyticsJsonValue | undefined;
46
+ /** What `sanitizeProductAnalyticsProperties` is allowed to hand the SDK. */
47
+ export type ProductAnalyticsSanitizedValue = string | number | boolean | null | ProductAnalyticsJsonValue;
48
+ export type ProductAnalyticsProperties = Record<string, ProductAnalyticsValue>;
49
+ export type ProductAnalyticsEventInput = {
50
+ event: string;
51
+ distinctId?: string | null | undefined;
52
+ organizationId?: string | null | undefined;
53
+ userId?: string | null | undefined;
54
+ properties?: ProductAnalyticsProperties;
55
+ /**
56
+ * Ingestion id. PostHog dedupes on it, so a revenue event replayed from a
57
+ * Stripe webhook redelivery — or a run outcome re-read after a worker
58
+ * restart — lands once instead of double-counting. Supply a value derived
59
+ * from the source fact (the KPI event key, the run id), never a random one,
60
+ * or replay stops being deterministic.
61
+ */
62
+ uuid?: string | null | undefined;
63
+ /** When the fact happened, if that is not "now" (webhook replay, backfill, run settle). */
64
+ timestamp?: Date | null | undefined;
65
+ };
66
+ /**
67
+ * The message shape both `posthog-node` capture paths accept. Declared here so
68
+ * the builder needs no `posthog-node` import; the web/worker clients pass it
69
+ * straight to `capture` / `captureImmediate`.
70
+ */
71
+ export type ProductAnalyticsCaptureMessage = {
72
+ distinctId: string;
73
+ event: string;
74
+ properties: Record<string, ProductAnalyticsSanitizedValue>;
75
+ groups?: Record<string, string>;
76
+ uuid?: string;
77
+ timestamp?: Date;
78
+ };
79
+ /**
80
+ * What the emitting runtime knows about itself. `environment` is the
81
+ * PROD/MAIN/DEV/LOCAL dimension every insight filters on
82
+ * (`resolveProductAnalyticsEnvironmentFromEnv`); `runtimeProperties` are the
83
+ * runtime-specific facts (Vercel env/sha/region on the web, Fly app/region on
84
+ * the worker) and are set BEFORE the caller's properties so a caller can
85
+ * override them but never lose them by accident.
86
+ */
87
+ export type ProductAnalyticsRuntimeContext = {
88
+ environment: string;
89
+ oxygenVersion: string;
90
+ runtimeProperties?: ProductAnalyticsProperties;
91
+ };
92
+ export declare function sanitizeProductAnalyticsProperties(properties: ProductAnalyticsProperties): Record<string, ProductAnalyticsSanitizedValue>;
93
+ export declare function normalizeProductAnalyticsIdentifier(value: ProductAnalyticsValue): string | null;
94
+ /**
95
+ * Build the capture message every runtime sends. Returns null when no distinct
96
+ * id can be derived — an event with no subject is dropped, never invented.
97
+ */
98
+ export declare function buildProductAnalyticsCaptureMessage(input: ProductAnalyticsEventInput, context: ProductAnalyticsRuntimeContext): ProductAnalyticsCaptureMessage | null;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Product-analytics core — the TRANSPORT-FREE half of PostHog emission.
3
+ *
4
+ * Two runtimes emit product events: the web/API runtime (`apps/web/src/lib/
5
+ * product-analytics.ts`, `posthog-node` on Vercel) and the Fly worker
6
+ * (`apps/worker/src/product-analytics.ts`, `posthog-node` batching). What they
7
+ * must agree on lives here, once: property sanitization, the distinct-id
8
+ * chain, the person-profile posture, org grouping, and the runtime dimensions
9
+ * every event carries. Two copies of that logic drifted in the past — the
10
+ * worker would have minted a throwaway person per request while the web side
11
+ * did not — and PostHog cannot join what the emitters disagree about.
12
+ *
13
+ * Deliberately NO `posthog-node`, no fetch, no I/O: `packages/shared` is
14
+ * vendored into the published `@oxygen-agent/cli` tarball, so every runtime
15
+ * dependency added here lands on every customer's machine
16
+ * (`scripts/cli-package-dependencies.mjs`, the langfuse-class guard). The
17
+ * capture message is a plain object structurally compatible with
18
+ * `posthog-node`'s `EventMessage`; each runtime owns its own client.
19
+ */
20
+ export const PRODUCT_ANALYTICS_MAX_PROPERTY_KEY_LENGTH = 80;
21
+ export const PRODUCT_ANALYTICS_MAX_PROPERTY_STRING_LENGTH = 500;
22
+ /**
23
+ * Byte ceiling for a structured (object/array) property value.
24
+ *
25
+ * Structured values pass through UNTOUCHED — see `sanitizeStructuredValue` — so
26
+ * this is the only thing standing between a careless caller and an unbounded
27
+ * ingest payload. Set well above `MCP_PAYLOAD_LIMITS.maxSerializedBytes` (8 KiB,
28
+ * in apps/web `analytics/mcp-analytics.ts`) so it can never re-cut a payload
29
+ * that module already bounded and marked; it exists for the callers that bound
30
+ * nothing.
31
+ */
32
+ export const PRODUCT_ANALYTICS_MAX_STRUCTURED_PROPERTY_BYTES = 32_768;
33
+ export function sanitizeProductAnalyticsProperties(properties) {
34
+ const sanitized = {};
35
+ for (const [rawKey, rawValue] of Object.entries(properties)) {
36
+ const key = sanitizePropertyKey(rawKey);
37
+ if (!key || rawValue === undefined)
38
+ continue;
39
+ const value = sanitizePropertyValue(rawValue);
40
+ if (value !== undefined)
41
+ sanitized[key] = value;
42
+ }
43
+ return sanitized;
44
+ }
45
+ function sanitizePropertyKey(key) {
46
+ const normalized = key
47
+ .trim()
48
+ .replace(/[^A-Za-z0-9_.$-]/g, "_")
49
+ .slice(0, PRODUCT_ANALYTICS_MAX_PROPERTY_KEY_LENGTH);
50
+ return normalized || null;
51
+ }
52
+ function sanitizePropertyValue(value) {
53
+ if (value === null || value === undefined)
54
+ return value;
55
+ if (typeof value === "boolean")
56
+ return value;
57
+ if (typeof value === "number")
58
+ return Number.isFinite(value) ? value : null;
59
+ if (typeof value === "string")
60
+ return value.slice(0, PRODUCT_ANALYTICS_MAX_PROPERTY_STRING_LENGTH);
61
+ return sanitizeStructuredValue(value);
62
+ }
63
+ /**
64
+ * Objects and arrays pass through UNTOUCHED, or not at all.
65
+ *
66
+ * Deliberately not walked, re-keyed, `String()`d, or cut at the string ceiling:
67
+ * the callers that send structured values (apps/web `analytics/mcp-analytics.ts`)
68
+ * have already redacted and bounded them, and a second pass here would either
69
+ * corrupt a payload into invalid JSON — which is exactly what an old
70
+ * `.slice(0, 500)` did to any array — or silently undo the marked truncation
71
+ * the first pass recorded.
72
+ *
73
+ * The only checks are the two that protect the pipe: it must be JSON-encodable
74
+ * (a cycle or a BigInt would otherwise throw inside the SDK, and `JSON.stringify`
75
+ * itself throws HERE, upstream of the emitter's try), and it must be under the
76
+ * byte ceiling. Failing either drops the one property, never the event.
77
+ */
78
+ function sanitizeStructuredValue(value) {
79
+ try {
80
+ const serialized = JSON.stringify(value);
81
+ if (typeof serialized !== "string")
82
+ return undefined;
83
+ if (Buffer.byteLength(serialized, "utf8") > PRODUCT_ANALYTICS_MAX_STRUCTURED_PROPERTY_BYTES) {
84
+ return undefined;
85
+ }
86
+ return value;
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ }
92
+ export function normalizeProductAnalyticsIdentifier(value) {
93
+ if (typeof value === "string" && value.trim()) {
94
+ return value.trim().slice(0, PRODUCT_ANALYTICS_MAX_PROPERTY_STRING_LENGTH);
95
+ }
96
+ if (typeof value === "number" && Number.isFinite(value))
97
+ return String(value);
98
+ return null;
99
+ }
100
+ /**
101
+ * Build the capture message every runtime sends. Returns null when no distinct
102
+ * id can be derived — an event with no subject is dropped, never invented.
103
+ */
104
+ export function buildProductAnalyticsCaptureMessage(input, context) {
105
+ const organizationId = normalizeProductAnalyticsIdentifier(input.organizationId);
106
+ const distinctIdSource = [
107
+ { value: input.distinctId, identifiesPerson: true },
108
+ { value: input.userId, identifiesPerson: true },
109
+ // Namespaced: a bare org UUID is indistinguishable from a human UUID at
110
+ // query time, so an unprefixed org fallback silently pollutes person-level
111
+ // counts (and any "users who…" cohort) with workspace rows. The `groups`
112
+ // attachment below keeps the RAW id — PostHog resolves group keys by exact
113
+ // match against the org id the rest of the product uses.
114
+ { value: organizationId ? `org:${organizationId}` : null, identifiesPerson: false },
115
+ { value: input.properties?.trace_id, identifiesPerson: false },
116
+ { value: input.properties?.request_id, identifiesPerson: false },
117
+ ].find((candidate) => candidate.value !== null && candidate.value !== undefined);
118
+ const distinctId = normalizeProductAnalyticsIdentifier(distinctIdSource?.value);
119
+ if (!distinctId)
120
+ return null;
121
+ const properties = sanitizeProductAnalyticsProperties({
122
+ product_analytics_environment: context.environment,
123
+ oxygen_version: context.oxygenVersion,
124
+ ...context.runtimeProperties,
125
+ organization_id: organizationId,
126
+ user_id: normalizeProductAnalyticsIdentifier(input.userId),
127
+ ...input.properties,
128
+ // Person profiles are a per-event decision on backend SDKs, not an init
129
+ // option. `posthog-node`'s client extends `PostHogCoreStateless`, which has
130
+ // no person-mode state at all — only the browser's stateful `PostHogCore`
131
+ // reads `personProfiles`. A `personProfiles: "identified_only"` passed to the
132
+ // constructor typechecks and is then read by nothing, so every event would
133
+ // get a person profile regardless.
134
+ //
135
+ // Without this, the `trace_id`/`request_id` tail of the distinct-id chain
136
+ // mints one throwaway person per request. Set last so a caller-supplied
137
+ // property can never flip the posture.
138
+ //
139
+ // `|| organizationId` is load-bearing, not defensive: PostHog cannot run
140
+ // group analytics on an anonymous event, and `@posthog/core`'s own
141
+ // `_hasPersonProcessing()` is `isIdentified || hasGroups || enabled` — the
142
+ // SDK forces person processing ON whenever `$groups` is attached. Emitting
143
+ // the inverse pairing would silently zero every org-grouped trend, funnel
144
+ // and retention on exactly the two highest-volume events
145
+ // (`cli_command_run`, `$mcp_tool_call`), because org-API-key traffic has no
146
+ // `userId` and falls through to the org-id candidate. The cost this whole
147
+ // switch targets is the per-REQUEST trace/request-id tail; one profile per
148
+ // ORG is cheap and is where the group data lives.
149
+ $process_person_profile: (distinctIdSource?.identifiesPerson ?? false) || Boolean(organizationId),
150
+ });
151
+ return {
152
+ distinctId,
153
+ event: input.event,
154
+ properties,
155
+ ...(organizationId ? { groups: { organization: organizationId } } : {}),
156
+ ...(input.uuid ? { uuid: input.uuid } : {}),
157
+ ...(input.timestamp ? { timestamp: input.timestamp } : {}),
158
+ };
159
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The PROD / MAIN / DEV / LOCAL dimension stamped on every product event as
3
+ * `product_analytics_environment`. One resolver for both emitting runtimes:
4
+ *
5
+ * - explicit pins win (`POSTHOG_ENVIRONMENT`, its `NEXT_PUBLIC_` twin, and the
6
+ * Sentry environment vars the web app already sets);
7
+ * - the web/API runtime has `VERCEL_ENV` (+ the branch for MAIN-preview);
8
+ * - the Fly worker has NO `VERCEL_ENV` and `NODE_ENV=production` on BOTH apps,
9
+ * so — mirroring `apps/worker/src/worker-env.ts` and the Langfuse resolver —
10
+ * the Fly-injected app name is the ground truth (`-dev` marks the dev app; a
11
+ * cross-env Doppler drift cannot fake it), then `FLY_ENVIRONMENT`;
12
+ * - everything else is LOCAL. `NODE_ENV=production` is deliberately NOT read as
13
+ * PROD: it is the default for any built Node process, a local one included.
14
+ */
15
+ export type ProductAnalyticsEnvironment = "PROD" | "MAIN" | "DEV" | "LOCAL";
16
+ type EnvSource = Record<string, string | undefined>;
17
+ export declare function resolveProductAnalyticsEnvironmentFromEnv(env?: EnvSource): ProductAnalyticsEnvironment;
18
+ export {};
@@ -0,0 +1,46 @@
1
+ function normalizeProductAnalyticsEnvironment(value) {
2
+ if (!value)
3
+ return null;
4
+ switch (value.trim().toUpperCase()) {
5
+ case "PROD":
6
+ case "PRODUCTION":
7
+ return "PROD";
8
+ case "MAIN":
9
+ return "MAIN";
10
+ case "DEV":
11
+ case "DEVELOPMENT":
12
+ case "PREVIEW":
13
+ return "DEV";
14
+ case "LOCAL":
15
+ return "LOCAL";
16
+ default:
17
+ return null;
18
+ }
19
+ }
20
+ export function resolveProductAnalyticsEnvironmentFromEnv(env = process.env) {
21
+ const explicit = normalizeProductAnalyticsEnvironment(env.POSTHOG_ENVIRONMENT
22
+ ?? env.NEXT_PUBLIC_POSTHOG_ENVIRONMENT
23
+ ?? env.SENTRY_ENVIRONMENT
24
+ ?? env.NEXT_PUBLIC_SENTRY_ENVIRONMENT);
25
+ if (explicit)
26
+ return explicit;
27
+ const vercelEnv = env.VERCEL_ENV ?? env.NEXT_PUBLIC_VERCEL_ENV;
28
+ if (vercelEnv === "production")
29
+ return "PROD";
30
+ const branch = env.VERCEL_GIT_COMMIT_REF ?? env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_REF;
31
+ if (vercelEnv === "preview" && branch === "main")
32
+ return "MAIN";
33
+ if (vercelEnv === "preview")
34
+ return "DEV";
35
+ if (vercelEnv === "development")
36
+ return "LOCAL";
37
+ const flyApp = (env.FLY_APP_NAME ?? env.FLY_APP)?.trim();
38
+ if (flyApp)
39
+ return flyApp.includes("-dev") ? "DEV" : "PROD";
40
+ const flyEnvironment = env.FLY_ENVIRONMENT?.trim().toLowerCase();
41
+ if (flyEnvironment === "production")
42
+ return "PROD";
43
+ if (flyEnvironment)
44
+ return "DEV";
45
+ return "LOCAL";
46
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Every product-analytics event name OXYGEN emits, in one place — for BOTH
3
+ * emitting runtimes. The web/API runtime re-exports this from
4
+ * `apps/web/src/lib/analytics/event-names.ts` (which also owns PostHog's
5
+ * reserved `$mcp_*` vocabulary and the KPI-ledger translation); the Fly worker
6
+ * imports it directly.
7
+ *
8
+ * An event name is a contract shared by three things that cannot see each
9
+ * other: the emitter, its test, and the PostHog insight/funnel built on top. A
10
+ * literal typed at each call site drifts silently — the rename lands in the
11
+ * code, the dashboard keeps querying the old string, and the funnel reads zero
12
+ * without erroring. Import from here instead of typing the string.
13
+ *
14
+ * Names are unprefixed `subject_verb` snake_case; the web test pins the exact
15
+ * set, so adding one is a deliberate edit there too.
16
+ */
17
+ export declare const PRODUCT_EVENTS: {
18
+ /** Acquisition. */
19
+ readonly USER_SIGNED_UP: "user_signed_up";
20
+ readonly WORKSPACE_CREATED: "workspace_created";
21
+ /** Activation. */
22
+ readonly ONBOARDING_COMPLETED: "onboarding_completed";
23
+ readonly ONBOARDING_RESET: "onboarding_reset";
24
+ readonly ACTIVATION_PATH_SELECTED: "activation_path_selected";
25
+ readonly AGENT_CONNECTED: "agent_connected";
26
+ readonly FIRST_RECORD_CREATED: "first_record_created";
27
+ /**
28
+ * The prescribed first play (inbound-led outbound), walked on ANY surface.
29
+ *
30
+ * These describe progress through a play, not a lifecycle moment — a founder
31
+ * who arms capture from the CLI and drafts the sequence in the browser
32
+ * produces one continuous series. Which is exactly why they are emitted from
33
+ * one watermark-guarded helper (apps/web `lib/activation/analytics.ts`)
34
+ * rather than from each surface: the same completed-step count read twice
35
+ * must emit once.
36
+ *
37
+ * Deliberately ABSENT from the web's KPI_TYPE_TO_EVENT. The headline
38
+ * activation KPI is CLI/MCP-sourced by design; wiring a web-observable play
39
+ * step into that ledger would silently redefine what the company reports as
40
+ * activation.
41
+ */
42
+ readonly FIRST_PLAY_STARTED: "first_play_started";
43
+ readonly FIRST_PLAY_STEP_COMPLETED: "first_play_step_completed";
44
+ readonly FIRST_PLAY_COMPLETED: "first_play_completed";
45
+ readonly FIRST_PLAY_SKIPPED: "first_play_skipped";
46
+ /**
47
+ * Usage — what was ASKED for. `mcp_tool_called` used to sit here as the
48
+ * second highest-volume event; it was REPLACED (not joined) by the reserved
49
+ * `$mcp_tool_call` in the web's MCP_ANALYTICS_EVENTS — see that block for why
50
+ * both cannot be emitted.
51
+ */
52
+ readonly CLI_COMMAND_RUN: "cli_command_run";
53
+ /**
54
+ * Outcomes — what actually HAPPENED, emitted by the Fly worker when a durable
55
+ * unit of work reaches a terminal state. `cli_command_run` and `$mcp_tool_call`
56
+ * see a run being requested; nothing on the web runtime ever sees it finish,
57
+ * because workflows, column runs, ingestions, agent runs and sequence steps
58
+ * complete on Fly minutes later. Without these, every "did it work" question
59
+ * (success rate, duration, credits per run, replies per enrollment) was
60
+ * unanswerable in PostHog and biased toward optimism — sweeps, repair passes
61
+ * and lease expiries settle runs invisibly.
62
+ *
63
+ * One event per terminal transition, `uuid` = the run/outbox id so a
64
+ * re-read after a worker restart dedupes, `timestamp` = when it settled.
65
+ * Properties are ids, enums and numbers only — never row values, prompts,
66
+ * or lead names (ADR 0021: PostHog stays sanitized).
67
+ */
68
+ readonly WORKFLOW_RUN_SETTLED: "workflow_run_settled";
69
+ readonly TABLE_ACTION_RUN_SETTLED: "table_action_run_settled";
70
+ readonly TABLE_INGESTION_RUN_SETTLED: "table_ingestion_run_settled";
71
+ readonly AGENT_RUN_SETTLED: "agent_run_settled";
72
+ readonly SEQUENCE_ENROLLMENT_SETTLED: "sequence_enrollment_settled";
73
+ /** Revenue lifecycle. */
74
+ readonly TRIAL_STARTED: "trial_started";
75
+ readonly SUBSCRIPTION_ACTIVATED: "subscription_activated";
76
+ readonly SUBSCRIPTION_CHURNED: "subscription_churned";
77
+ readonly TRIAL_CANCEL_SCHEDULED: "trial_cancel_scheduled";
78
+ readonly TRIAL_CANCEL_RESUMED: "trial_cancel_resumed";
79
+ readonly TRIAL_ENDED_UNCONVERTED: "trial_ended_unconverted";
80
+ /** Pipeline heartbeat: proves ingestion is alive when the product is quiet. */
81
+ readonly POSTHOG_CANARY: "posthog_canary";
82
+ };
83
+ export type ProductEventName = (typeof PRODUCT_EVENTS)[keyof typeof PRODUCT_EVENTS];
84
+ /** Every name, for drift checks and dashboard provisioning. */
85
+ export declare const PRODUCT_EVENT_NAMES: readonly ProductEventName[];
86
+ /**
87
+ * The outcome events the worker emits, as a typed subset — so the worker's
88
+ * emitter cannot be handed a lifecycle event that only the control plane has
89
+ * the facts for.
90
+ */
91
+ export declare const WORKER_RUN_OUTCOME_EVENTS: readonly ["workflow_run_settled", "table_action_run_settled", "table_ingestion_run_settled", "agent_run_settled", "sequence_enrollment_settled"];
92
+ export type WorkerRunOutcomeEventName = (typeof WORKER_RUN_OUTCOME_EVENTS)[number];
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Every product-analytics event name OXYGEN emits, in one place — for BOTH
3
+ * emitting runtimes. The web/API runtime re-exports this from
4
+ * `apps/web/src/lib/analytics/event-names.ts` (which also owns PostHog's
5
+ * reserved `$mcp_*` vocabulary and the KPI-ledger translation); the Fly worker
6
+ * imports it directly.
7
+ *
8
+ * An event name is a contract shared by three things that cannot see each
9
+ * other: the emitter, its test, and the PostHog insight/funnel built on top. A
10
+ * literal typed at each call site drifts silently — the rename lands in the
11
+ * code, the dashboard keeps querying the old string, and the funnel reads zero
12
+ * without erroring. Import from here instead of typing the string.
13
+ *
14
+ * Names are unprefixed `subject_verb` snake_case; the web test pins the exact
15
+ * set, so adding one is a deliberate edit there too.
16
+ */
17
+ export const PRODUCT_EVENTS = {
18
+ /** Acquisition. */
19
+ USER_SIGNED_UP: "user_signed_up",
20
+ WORKSPACE_CREATED: "workspace_created",
21
+ /** Activation. */
22
+ ONBOARDING_COMPLETED: "onboarding_completed",
23
+ ONBOARDING_RESET: "onboarding_reset",
24
+ ACTIVATION_PATH_SELECTED: "activation_path_selected",
25
+ AGENT_CONNECTED: "agent_connected",
26
+ FIRST_RECORD_CREATED: "first_record_created",
27
+ /**
28
+ * The prescribed first play (inbound-led outbound), walked on ANY surface.
29
+ *
30
+ * These describe progress through a play, not a lifecycle moment — a founder
31
+ * who arms capture from the CLI and drafts the sequence in the browser
32
+ * produces one continuous series. Which is exactly why they are emitted from
33
+ * one watermark-guarded helper (apps/web `lib/activation/analytics.ts`)
34
+ * rather than from each surface: the same completed-step count read twice
35
+ * must emit once.
36
+ *
37
+ * Deliberately ABSENT from the web's KPI_TYPE_TO_EVENT. The headline
38
+ * activation KPI is CLI/MCP-sourced by design; wiring a web-observable play
39
+ * step into that ledger would silently redefine what the company reports as
40
+ * activation.
41
+ */
42
+ FIRST_PLAY_STARTED: "first_play_started",
43
+ FIRST_PLAY_STEP_COMPLETED: "first_play_step_completed",
44
+ FIRST_PLAY_COMPLETED: "first_play_completed",
45
+ FIRST_PLAY_SKIPPED: "first_play_skipped",
46
+ /**
47
+ * Usage — what was ASKED for. `mcp_tool_called` used to sit here as the
48
+ * second highest-volume event; it was REPLACED (not joined) by the reserved
49
+ * `$mcp_tool_call` in the web's MCP_ANALYTICS_EVENTS — see that block for why
50
+ * both cannot be emitted.
51
+ */
52
+ CLI_COMMAND_RUN: "cli_command_run",
53
+ /**
54
+ * Outcomes — what actually HAPPENED, emitted by the Fly worker when a durable
55
+ * unit of work reaches a terminal state. `cli_command_run` and `$mcp_tool_call`
56
+ * see a run being requested; nothing on the web runtime ever sees it finish,
57
+ * because workflows, column runs, ingestions, agent runs and sequence steps
58
+ * complete on Fly minutes later. Without these, every "did it work" question
59
+ * (success rate, duration, credits per run, replies per enrollment) was
60
+ * unanswerable in PostHog and biased toward optimism — sweeps, repair passes
61
+ * and lease expiries settle runs invisibly.
62
+ *
63
+ * One event per terminal transition, `uuid` = the run/outbox id so a
64
+ * re-read after a worker restart dedupes, `timestamp` = when it settled.
65
+ * Properties are ids, enums and numbers only — never row values, prompts,
66
+ * or lead names (ADR 0021: PostHog stays sanitized).
67
+ */
68
+ WORKFLOW_RUN_SETTLED: "workflow_run_settled",
69
+ TABLE_ACTION_RUN_SETTLED: "table_action_run_settled",
70
+ TABLE_INGESTION_RUN_SETTLED: "table_ingestion_run_settled",
71
+ AGENT_RUN_SETTLED: "agent_run_settled",
72
+ SEQUENCE_ENROLLMENT_SETTLED: "sequence_enrollment_settled",
73
+ /** Revenue lifecycle. */
74
+ TRIAL_STARTED: "trial_started",
75
+ SUBSCRIPTION_ACTIVATED: "subscription_activated",
76
+ SUBSCRIPTION_CHURNED: "subscription_churned",
77
+ TRIAL_CANCEL_SCHEDULED: "trial_cancel_scheduled",
78
+ TRIAL_CANCEL_RESUMED: "trial_cancel_resumed",
79
+ TRIAL_ENDED_UNCONVERTED: "trial_ended_unconverted",
80
+ /** Pipeline heartbeat: proves ingestion is alive when the product is quiet. */
81
+ POSTHOG_CANARY: "posthog_canary",
82
+ };
83
+ /** Every name, for drift checks and dashboard provisioning. */
84
+ export const PRODUCT_EVENT_NAMES = Object.freeze(Object.values(PRODUCT_EVENTS));
85
+ /**
86
+ * The outcome events the worker emits, as a typed subset — so the worker's
87
+ * emitter cannot be handed a lifecycle event that only the control plane has
88
+ * the facts for.
89
+ */
90
+ export const WORKER_RUN_OUTCOME_EVENTS = Object.freeze([
91
+ PRODUCT_EVENTS.WORKFLOW_RUN_SETTLED,
92
+ PRODUCT_EVENTS.TABLE_ACTION_RUN_SETTLED,
93
+ PRODUCT_EVENTS.TABLE_INGESTION_RUN_SETTLED,
94
+ PRODUCT_EVENTS.AGENT_RUN_SETTLED,
95
+ PRODUCT_EVENTS.SEQUENCE_ENROLLMENT_SETTLED,
96
+ ]);
@@ -25,6 +25,9 @@ export type UgcPostProjection = {
25
25
  title?: string | null;
26
26
  contentText: string;
27
27
  status: string;
28
+ timezone?: string;
29
+ approvalStatus?: string | null;
30
+ approvedAt?: string | null;
28
31
  scheduledAt?: string | null;
29
32
  publishedAt?: string | null;
30
33
  publishedUrl?: string | null;
@@ -54,6 +57,19 @@ export type UgcPostProjection = {
54
57
  shares: number | null;
55
58
  impressions: number | null;
56
59
  }[];
60
+ publicationReceipts?: {
61
+ attemptNumber: number;
62
+ operation: string;
63
+ status: string;
64
+ error: {
65
+ code?: string;
66
+ message?: string;
67
+ } | null;
68
+ creditsUsed: number;
69
+ startedAt: string;
70
+ completedAt: string | null;
71
+ durationMs: number | null;
72
+ }[];
57
73
  };
58
74
  export type UgcPostLink = {
59
75
  id: string;
@@ -84,7 +100,11 @@ export type UgcVoiceImport = {
84
100
  cursor: string | null;
85
101
  importedCount: number;
86
102
  scannedCount: number;
87
- maxPosts: number;
103
+ /** Null means all retrievable history, still bounded by the approved credit cap. */
104
+ maxPosts: number | null;
105
+ oldestPostAt: Date | null;
106
+ newestPostAt: Date | null;
107
+ pageFingerprints: string[];
88
108
  creditCap: number;
89
109
  creditsUsed: number;
90
110
  receiptIds: string[];
@@ -1,4 +1,4 @@
1
- export declare const OXYGEN_VERSION = "1.936.1";
1
+ export declare const OXYGEN_VERSION = "1.948.1";
2
2
  export declare const OXYGEN_MINIMUM_CLI_VERSION = "1.181.0";
3
3
  export declare const MANAGED_INBOX_MINIMUM_CLI_VERSION = "1.326.2";
4
4
  export declare const SUPPORT_AGENT_REPLY_MINIMUM_CLI_VERSION = "1.747.0";