Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): simplify analytics identity dispatch
Kshitij Jhunjhunwala4bdbaecc10f5
diff --git a/mise.lock b/mise.lockindex 56dd092f1..4666d7776 100644--- a/mise.lock+++ b/mise.lock@@ -89,23 +89,23 @@ version = "3.12.13"backend = "core:python"[tools.python."platforms.linux-arm64"]-checksum = "sha256:e125d3e75034fe75d49ae8577b53758b0bb7d7817fadde2c020ad2cf7afe64c4"-url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"+checksum = "sha256:f226576b91491ffa5739aa85726521e9031f4d87f80627d64ed348ac77cb31e9"+url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"provenance = "github-attestations"[tools.python."platforms.linux-x64"]-checksum = "sha256:7ceaf4360f4b4ab44f31d8217cfdc70df8e12b61d9561b4900ee7af87176e50d"-url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"+checksum = "sha256:5854aa6ec71cad00334d5065633c210b2e7feb40956767a59a91791cadcf0b79"+url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"provenance = "github-attestations"[tools.python."platforms.macos-arm64"]-checksum = "sha256:2f18cdef4125ca1440dd1ba00ebcb267526efb532138c0860438f755ea4eebac"-url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-aarch64-apple-darwin-install_only_stripped.tar.gz"+checksum = "sha256:9a1e9e06175c10efd8378b904b07fa21bd791ab3345d7cdffeb4a76c9ff55903"+url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-aarch64-apple-darwin-install_only_stripped.tar.gz"provenance = "github-attestations"[tools.python."platforms.macos-x64"]-checksum = "sha256:e654c21d0ba53e2c671868d4112fac5874deca4c35226d36c5cfe53bc5c9cd71"-url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260728/cpython-3.12.13+20260728-x86_64-apple-darwin-install_only_stripped.tar.gz"+checksum = "sha256:8e6b7e6533bdf746287008edf91102e7bee0a6ca1d24f16c4514237cafd706c5"+url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260718/cpython-3.12.13+20260718-x86_64-apple-darwin-install_only_stripped.tar.gz"provenance = "github-attestations"[[tools.uv]]@@ -115,19 +115,15 @@ backend = "aqua:astral-sh/uv"[tools.uv."platforms.linux-arm64"]checksum = "sha256:87925376fa1e59de23582e1cbd81d6aabd16611e871ad085e09be2c2fa12689d"url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-aarch64-unknown-linux-musl.tar.gz"-url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160192"[tools.uv."platforms.linux-x64"]checksum = "sha256:6a37f712ae90c7b8cf364fe751144d7acc2479d6b336378111e74cc7fb14fa7b"url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-x86_64-unknown-linux-musl.tar.gz"-url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160235"[tools.uv."platforms.macos-arm64"]checksum = "sha256:bb63d43c40a301d889a985223ee8ce540be199e98b3f27ed8477823869a0a605"url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-aarch64-apple-darwin.tar.gz"-url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160180"[tools.uv."platforms.macos-x64"]checksum = "sha256:b5f91770e55761b32c9618757ef23ded6671bb9ca0ddf5737eea60dddd493fe9"url = "https://github.com/astral-sh/uv/releases/download/0.8.19/uv-x86_64-apple-darwin.tar.gz"-url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/295160227"diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.tsindex dc5923ec3..93d818ba0 100644--- a/ts/packages/cli/src/analytics/dispatch.ts+++ b/ts/packages/cli/src/analytics/dispatch.ts@@ -13,7 +13,8 @@ import {Schema,} from 'effect';import * as constants from 'src/constants';-import { spawnDetached } from 'src/services/detached-process';+import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';+import { sha256Hex } from 'src/utils/checksums';import { djb2Hash } from 'src/utils/djb2';import { NodeOs } from 'src/services/node-os';import { TerminalUI } from 'src/services/terminal-ui';@@ -26,7 +27,8 @@ const ANALYTICS_STATE_FILE_NAME = 'analytics.json';const ANALYTICS_STATE_LOCK_FILE_NAME = `${ANALYTICS_STATE_FILE_NAME}.lock`;const ANALYTICS_STATE_LOCK_STALE_MS = 30_000;const ANALYTICS_STATE_LOCK_RETRY_MS = 10;-const ANALYTICS_STATE_LOCK_TIMEOUT_MS = ANALYTICS_STATE_LOCK_STALE_MS + 5_000;+const ANALYTICS_STATE_LOCK_TIMEOUT_MS = 500;+const PENDING_ALIAS_RETRY_MS = 5 * 60 * 1000;const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';@@ -119,6 +121,14 @@ const getPostHogConfig = environmentProvider})));+const postHogEnabled = Effect.gen(function* () {+ if (yield* analyticsDisabled) {+ return false;+ }+ const { projectKey } = yield* getPostHogConfig;+ return projectKey.length > 0;+});+const jsonFromString = Schema.parseJson();const prettyJsonFromString = Schema.parseJson({ space: 2 });const decodeJson = Schema.decodeUnknown(jsonFromString);@@ -182,9 +192,10 @@ type AnalyticsState = {readonly install_id?: string;readonly apollo_user_id?: string;readonly aliased_apollo_user_id?: string;+ readonly pending_alias_apollo_user_id?: string;+ readonly pending_alias_install_id?: string;+ readonly pending_alias_attempted_at?: string;readonly api_key_fingerprint?: string;- readonly stitch_attempted_at?: string;- readonly stitch_attempted_api_key_fingerprint?: string;readonly created_at?: string;};@@ -224,6 +235,9 @@ const acquireAnalyticsStateLock = Effect.gen(function* () {yield* fs.makeDirectory(paths.analyticsDir, { recursive: true });+ // Lock contention is wall-clock coordination between OS processes. Keeping+ // the retry on the platform timer also prevents Effect's TestClock from+ // freezing concurrent lock tests.const waitBeforeRetry = Effect.promise(() =>new Promise<void>(resolve => {@@ -354,11 +368,11 @@ const getUserApiKey = Effect.gen(function* () {: null;});-const fingerprintApiKey = (apiKey: string): string =>- `${djb2Hash(apiKey).toString(36)}.${apiKey.length.toString(36)}`;+const fingerprintApiKey = (apiKey: string) =>+ Effect.promise(() => sha256Hex(new TextEncoder().encode(apiKey)));-const getApiKeyFingerprint = Effect.map(getUserApiKey, apiKey =>- apiKey ? fingerprintApiKey(apiKey) : null+const getApiKeyFingerprint = Effect.flatMap(getUserApiKey, apiKey =>+ apiKey ? fingerprintApiKey(apiKey) : Effect.succeed(null));// The keychain* security modes strip the api key from user_data.json, so no@@ -388,7 +402,11 @@ const getDistinctId = (installId: string) =>}}- if (typeof state?.aliased_apollo_user_id !== 'string') {+ const installIdMayBeAliased =+ typeof state?.aliased_apollo_user_id === 'string' ||+ (state?.pending_alias_install_id === installId &&+ typeof state.pending_alias_apollo_user_id === 'string');+ if (!installIdMayBeAliased) {return installId;}return fingerprint !== null ? `user_${fingerprint}` : `anon_${installId}`;@@ -498,28 +516,6 @@ const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null);-const getWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const maybeScriptPath = process.argv[1];- const scriptPathExists =- typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0- ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))- : false;- const scriptPathLooksReal =- scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');-- return scriptPathLooksReal- ? {- command: process.execPath,- args: [maybeScriptPath as string, workerFlag, encodedPayload],- }- : {- command: process.execPath,- args: [workerFlag, encodedPayload],- };- });-// Effect's Command processes are scoped and die with their scope; telemetry// workers intentionally outlive the CLI process, so they go through the// sanctioned detached-spawn boundary in src/services/detached-process.@@ -556,7 +552,7 @@ const captureToPostHog = (envelope: AnalyticsEnvelope) =>endpoint: ingestUrl,eventName: envelope.event,});- return;+ return false;}const httpClient = yield* HttpClient.HttpClient;@@ -579,6 +575,7 @@ const captureToPostHog = (envelope: AnalyticsEnvelope) =>responseBody: responseBody?.slice(0, 1000),});+ return responseOk;});type CliCodactFailureBody = {@@ -686,7 +683,7 @@ const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>yield* telemetryDebugLog('enqueue', { envelope });const serializedEnvelope = yield* encodeJson(envelope);const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);- const { command, args } = yield* getWorkerSpawnArgs(+ const { command, args } = yield* getDetachedWorkerSpawnArgs(INTERNAL_ANALYTICS_WORKER_FLAG,encodedPayload);@@ -699,9 +696,11 @@ export const trackCliEventEffect = (event: TrackEvent) =>return;}- const disabled = yield* analyticsDisabled;- if (disabled) {- yield* telemetryDebugLog('skip', { reason: 'disabled', eventName: event.name });+ if (!(yield* postHogEnabled)) {+ yield* telemetryDebugLog('skip', {+ reason: (yield* analyticsDisabled) ? 'disabled' : 'missing_project_key',+ eventName: event.name,+ });return;}@@ -732,9 +731,8 @@ export const trackCliEventEffect = (event: TrackEvent) =>export const emitPostHogAlias = (installId: string, apolloUserId: string) =>Effect.gen(function* () {- const disabled = yield* analyticsDisabled;- if (disabled) {- yield* telemetryDebugLog('alias_skip', { reason: 'disabled', installId });+ if (!(yield* postHogEnabled)) {+ yield* telemetryDebugLog('alias_skip', { reason: 'disabled_or_missing_key', installId });return false;}@@ -761,20 +759,22 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: streturn;}- const disabled = yield* analyticsDisabled;- if (disabled) {- yield* telemetryDebugLog('alias_skip', { reason: 'disabled' });+ if (!(yield* postHogEnabled)) {+ yield* telemetryDebugLog('alias_skip', { reason: 'disabled_or_missing_key' });return;}- yield* withAnalyticsStateLock(+ const aliasToEmit = yield* withAnalyticsStateLock(Effect.gen(function* () {let state = yield* readAnalyticsState;let installId = yield* getOrCreateInstallIdUnlocked;// A second user on this machine must not merge into the previous user's// PostHog person: rotate to a fresh install_id before linking.- const previousIdentity = state?.apollo_user_id ?? state?.aliased_apollo_user_id;+ const previousIdentity =+ state?.apollo_user_id ??+ state?.pending_alias_apollo_user_id ??+ state?.aliased_apollo_user_id;const identityChanged =typeof previousIdentity === 'string' &&previousIdentity.length > 0 &&@@ -785,6 +785,9 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: stinstall_id: installId,apollo_user_id: undefined,aliased_apollo_user_id: undefined,+ pending_alias_apollo_user_id: undefined,+ pending_alias_install_id: undefined,+ pending_alias_attempted_at: undefined,api_key_fingerprint: undefined,});state = yield* readAnalyticsState;@@ -792,7 +795,7 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: stconst fingerprint =typeof apiKey === 'string' && apiKey.length > 0- ? fingerprintApiKey(apiKey)+ ? yield* fingerprintApiKey(apiKey): yield* getApiKeyFingerprint;if (state?.apollo_user_id !== resolved || state?.api_key_fingerprint !== fingerprint) {yield* mergeAnalyticsStateUnlocked(installId, {@@ -801,77 +804,51 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st});}- if (typeof state?.aliased_apollo_user_id === 'string') {- return;+ state = yield* readAnalyticsState;+ if (state?.aliased_apollo_user_id === resolved) {+ return undefined;}- if (yield* emitPostHogAlias(installId, resolved)) {- yield* mergeAnalyticsStateUnlocked(installId, { aliased_apollo_user_id: resolved });- }- })- );- }).pipe(Effect.catchAllCause(() => Effect.void));--const STITCH_ATTEMPT_INTERVAL_MS = 24 * 60 * 60 * 1000;-const STITCH_SESSION_INFO_TIMEOUT = '1500 millis';--type AnalyticsSessionInfoFetcher = (params: {- baseURL: string;- userApiKey: string;-}) => Effect.Effect<{ readonly org_member: { readonly id: string } }, unknown>;--// Repairs a missing/stale persisted identity for already-logged-in installs-// (e.g. keyring-stored keys that predate identity stitching). The session-info-// fetcher is injected because composio-clients already imports this module.-export const ensureAnalyticsIdentity = (params: {- apiKey: string;- baseURL: string;- fetchSessionInfo: AnalyticsSessionInfoFetcher;-}) =>- Effect.gen(function* () {- if ((yield* analyticsDisabled) || params.apiKey.trim().length === 0) {- return;- }-- const fingerprint = fingerprintApiKey(params.apiKey);- const shouldAttempt = yield* withAnalyticsStateLock(- Effect.gen(function* () {- const state = yield* readAnalyticsState;- const identityLinked =- typeof state?.apollo_user_id === 'string' &&- state.apollo_user_id.length > 0 &&- state.api_key_fingerprint === fingerprint;- if (identityLinked) {- return false;- }-- const lastAttemptMs = Date.parse(state?.stitch_attempted_at ?? '');- const nowMs = yield* Clock.currentTimeMillis;- const sameCredentialAttempt = state?.stitch_attempted_api_key_fingerprint === fingerprint;if (- sameCredentialAttempt &&- Number.isFinite(lastAttemptMs) &&- nowMs - lastAttemptMs < STITCH_ATTEMPT_INTERVAL_MS+ state?.pending_alias_apollo_user_id === resolved &&+ state.pending_alias_install_id === installId) {- return false;+ const attemptedAt = Date.parse(state.pending_alias_attempted_at ?? '');+ const now = yield* Clock.currentTimeMillis;+ if (Number.isFinite(attemptedAt) && now - attemptedAt < PENDING_ALIAS_RETRY_MS) {+ return undefined;+ }}- // Persisted before the network attempt so failures cannot retry-storm.- const installId = yield* getOrCreateInstallIdUnlocked;yield* mergeAnalyticsStateUnlocked(installId, {- stitch_attempted_at: DateTime.formatIso(yield* DateTime.now),- stitch_attempted_api_key_fingerprint: fingerprint,+ pending_alias_apollo_user_id: resolved,+ pending_alias_install_id: installId,+ pending_alias_attempted_at: DateTime.formatIso(yield* DateTime.now),});- return true;+ return { installId, apolloUserId: resolved };}));- if (!shouldAttempt) {+ if (!aliasToEmit) {return;}- const info = yield* params- .fetchSessionInfo({ baseURL: params.baseURL, userApiKey: params.apiKey })- .pipe(Effect.timeout(STITCH_SESSION_INFO_TIMEOUT));- yield* linkApolloIdentityForAnalytics(info.org_member.id, params.apiKey);+ if (!(yield* emitPostHogAlias(aliasToEmit.installId, aliasToEmit.apolloUserId))) {+ yield* withAnalyticsStateLock(+ Effect.gen(function* () {+ const state = yield* readAnalyticsState;+ if (+ state?.pending_alias_install_id !== aliasToEmit.installId ||+ state.pending_alias_apollo_user_id !== aliasToEmit.apolloUserId+ ) {+ return;+ }+ yield* mergeAnalyticsStateUnlocked(aliasToEmit.installId, {+ pending_alias_apollo_user_id: undefined,+ pending_alias_install_id: undefined,+ pending_alias_attempted_at: undefined,+ });+ })+ );+ }}).pipe(Effect.catchAllCause(() => Effect.void));export const clearApolloIdentityForAnalytics = withAnalyticsStateLock(@@ -905,7 +882,7 @@ export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>const invocation = yield* getCliInvocationContext;const body = yield* encodeJson(createCliCodactFailureBody(failure, cliSessionId, invocation));const encodedPayload = Encoding.encodeBase64Url(body);- const { command, args } = yield* getWorkerSpawnArgs(+ const { command, args } = yield* getDetachedWorkerSpawnArgs(INTERNAL_CODACT_FAILURE_WORKER_FLAG,encodedPayload);@@ -925,6 +902,32 @@ const decodeWorkerPayload = <A>(encodedPayload: string) =>return (yield* decodeJson(serialized)) as A;});+const settlePostHogAlias = (envelope: AnalyticsEnvelope, delivered: boolean) => {+ if (envelope.event !== POSTHOG_ALIAS_EVENT) {+ return Effect.void;+ }++ return withAnalyticsStateLock(+ Effect.gen(function* () {+ const state = yield* readAnalyticsState;+ if (+ state?.install_id !== envelope.installId ||+ state.pending_alias_install_id !== envelope.installId ||+ state.pending_alias_apollo_user_id !== envelope.distinctId+ ) {+ return;+ }++ yield* mergeAnalyticsStateUnlocked(envelope.installId, {+ ...(delivered ? { aliased_apollo_user_id: envelope.distinctId } : {}),+ pending_alias_apollo_user_id: undefined,+ pending_alias_install_id: undefined,+ pending_alias_attempted_at: undefined,+ });+ })+ ).pipe(Effect.catchAllCause(() => Effect.void));+};+const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {const flagIndex = getWorkerFlagIndex(argv, INTERNAL_ANALYTICS_WORKER_FLAG);if (flagIndex < 0) {@@ -941,15 +944,16 @@ const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {return true;}- yield* captureToPostHog(envelope);- return true;- }).pipe(- Effect.catchAllCause(cause =>- telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(- Effect.as(true)+ const delivered = yield* captureToPostHog(envelope).pipe(+ Effect.catchAllCause(cause =>+ telemetryDebugLog('delivery_error', { error: telemetryErrorDetails(cause) }).pipe(+ Effect.as(false)+ ))- )- );+ );+ yield* settlePostHogAlias(envelope, delivered);+ return true;+ }).pipe(Effect.catchAllCause(() => Effect.succeed(true)));};const runCodactFailureWorker = (argv: ReadonlyArray<string>) => {diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.tsindex d26092b43..e06400576 100644--- a/ts/packages/cli/src/cli-main.ts+++ b/ts/packages/cli/src/cli-main.ts@@ -1,5 +1,5 @@import process from 'node:process';-import { Cause, Effect, Exit, Layer, Logger, Option } from 'effect';+import { Cause, Effect, Exit, Layer, Logger } from 'effect';import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';import { FetchHttpClient } from '@effect/platform';@@ -15,17 +15,13 @@ import {ComposioClientSingleton,ComposioSessionRepository,ComposioToolkitsRepository,- getSessionInfoByUserApiKey,} from 'src/services/composio-clients';import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';import { NodeOs } from 'src/services/node-os';import { NodeProcess } from 'src/services/node-process';import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';import { ComposioCliUserConfigLive, ComposioCliUserConfig } from 'src/services/cli-user-config';-import {- ComposioUserContext,- ComposioUserContextLive as _ComposioUserContextLive,-} from 'src/services/user-context';+import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';import { UpgradeBinary } from 'src/services/upgrade-binary';import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';import { TriggersRealtime } from 'src/services/triggers-realtime';@@ -41,7 +37,7 @@ import {getPrimaryLifecycleInvokedEvent,getPrimaryLifecycleSucceededEvent,} from 'src/analytics/events';-import { ensureAnalyticsIdentity, trackCliEventEffect } from 'src/analytics/dispatch';+import { trackCliEventEffect } from 'src/analytics/dispatch';import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';import { SetupSkillInstaller } from 'src/services/setup-skill-installer';import { SetupCommandError } from 'src/services/setup';@@ -149,18 +145,6 @@ const runWithTelemetry = Effect.gen(function* () {const ui = yield* TerminalUI;const terminal = yield* ui.capabilities;- // Stitch the analytics identity for installs whose credential (env or- // keyring) resolved without ever passing through a login-time link.- const userContext = yield* ComposioUserContext;- const resolvedApiKey = Option.getOrUndefined(userContext.data.apiKey);- if (resolvedApiKey) {- yield* ensureAnalyticsIdentity({- apiKey: resolvedApiKey,- baseURL: userContext.data.baseURL,- fetchSessionInfo: getSessionInfoByUserApiKey,- });- }-const commandTelemetryContext = createCliCommandTelemetryContext(process.argv,constants.APP_VERSION,diff --git a/ts/packages/cli/src/services/detached-process.ts b/ts/packages/cli/src/services/detached-process.tsindex 45086105d..82854e984 100644--- a/ts/packages/cli/src/services/detached-process.ts+++ b/ts/packages/cli/src/services/detached-process.ts@@ -1,5 +1,7 @@// eslint-disable-next-line no-restricted-imports -- This Effect helper is the sole detached-spawn boundary for CLI source: @effect/platform Command processes are scope-bound and are killed when their scope closes, while these children must outlive the CLI process.import { spawn } from 'node:child_process';+import process from 'node:process';+import { FileSystem } from '@effect/platform';import { Data, Effect } from 'effect';export class DetachedProcessSpawnError extends Data.TaggedError(@@ -62,3 +64,29 @@ export const spawnDetached = (})));++/**+ * Resolve the executable/argument shape for a detached worker in both compiled+ * binaries and source-driven development.+ */+export const getDetachedWorkerSpawnArgs = (workerFlag: string, encodedPayload: string) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const maybeScriptPath = process.argv[1];+ const scriptPathExists =+ typeof maybeScriptPath === 'string' && maybeScriptPath.length > 0+ ? yield* fs.exists(maybeScriptPath).pipe(Effect.catchAll(() => Effect.succeed(false)))+ : false;+ const scriptPathLooksReal =+ scriptPathExists && /\.(?:[cm]?[jt]s|mjs|mts|cts)$/u.test(maybeScriptPath ?? '');++ return scriptPathLooksReal+ ? {+ command: process.execPath,+ args: [maybeScriptPath as string, workerFlag, encodedPayload],+ }+ : {+ command: process.execPath,+ args: [workerFlag, encodedPayload],+ };+ });diff --git a/ts/packages/cli/test/src/analytics.dispatch.test.ts b/ts/packages/cli/test/src/analytics.dispatch.test.tsindex e013a1ca0..1d51661a7 100644--- a/ts/packages/cli/test/src/analytics.dispatch.test.ts+++ b/ts/packages/cli/test/src/analytics.dispatch.test.ts@@ -9,7 +9,6 @@ import * as tempy from 'tempy';import {clearApolloIdentityForAnalytics,emitPostHogAlias,- ensureAnalyticsIdentity,getCurrentCwdSessionId,linkApolloIdentityForAnalytics,readApiBaseUrl,@@ -264,6 +263,7 @@ describe('CLI analytics dispatch', () => {yield* trackCliEventEffect({ name: 'producer_event', properties: { sample: 'value' } });expect(childProcessMocks.spawn).not.toHaveBeenCalled();+ expect(yield* fs.exists(path.join(home, '.composio', 'analytics.json'))).toBe(false);}).pipe(Effect.provide(makePlatformLayer(home)));});@@ -484,6 +484,35 @@ describe('CLI analytics dispatch', () => {);});+ it.effect('bounds the delay when another process leaves a live state lock behind', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = path.join(home, 'composio.ts');+ const composioDir = path.join(home, '.composio');+ const lockPath = path.join(composioDir, 'analytics.json.lock');+ enableTelemetry('');+ process.argv[1] = scriptPath;+ mkdirSync(composioDir, { recursive: true });+ writeFileSync(scriptPath, '');+ writeFileSync(lockPath, 'other-process');++ return Effect.gen(function* () {+ const completedBeforeDeadline = yield* Effect.race(+ trackCliEventEffect({ name: CLI_ANALYTICS_EVENTS.CLI_SETUP_SUCCEEDED }).pipe(+ Effect.as(true)+ ),+ Effect.promise(+ () =>+ new Promise<boolean>(resolve => {+ setTimeout(() => resolve(false), 1_500);+ })+ )+ );++ expect(completedBeforeDeadline).toBe(true);+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });+it.effect('keys post-login events on the persisted apollo_user_id', () => {const home = tempy.temporaryDirectory();const scriptPath = `${home}/composio.ts`;@@ -544,19 +573,81 @@ describe('CLI analytics dispatch', () => {alias: 'install_login',});- // The Apollo id is persisted while keeping the original install_id/created_at.+ // The Apollo id and pending alias are persisted while keeping the+ // original install_id/created_at.const persisted = JSON.parse(yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')- ) as { install_id: string; apollo_user_id: string; created_at: string };+ ) as {+ install_id: string;+ apollo_user_id: string;+ pending_alias_apollo_user_id: string;+ created_at: string;+ };expect(persisted).toMatchObject({install_id: 'install_login',apollo_user_id: 'om_apollo_login',+ pending_alias_apollo_user_id: 'om_apollo_login',created_at: '2026-01-01T00:00:00.000Z',});- // A repeat login with the same Apollo id does not re-emit the alias.+ // A repeat login while delivery is pending does not re-emit the alias.yield* linkApolloIdentityForAnalytics('om_apollo_login');expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);++ vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 }));+ yield* runBackgroundWorkerFromArgv([+ process.execPath,+ 'composio',+ '__analytics-worker',+ args[2]!,+ ]).pipe(Effect.provide(makePlatformLayer(home)));++ const acknowledged = JSON.parse(+ yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')+ ) as {+ aliased_apollo_user_id?: string;+ pending_alias_apollo_user_id?: string;+ };+ expect(acknowledged.aliased_apollo_user_id).toBe('om_apollo_login');+ expect(acknowledged.pending_alias_apollo_user_id).toBeUndefined();+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('retries an alias after the worker reports a failed delivery', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry('');+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ yield* fs.writeFileString(scriptPath, '');++ yield* linkApolloIdentityForAnalytics('om_alias_retry');+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];++ vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 500 }));+ yield* runBackgroundWorkerFromArgv([+ process.execPath,+ 'composio',+ '__analytics-worker',+ args[2]!,+ ]).pipe(Effect.provide(makePlatformLayer(home)));++ const afterFailure = JSON.parse(+ yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')+ ) as {+ aliased_apollo_user_id?: string;+ pending_alias_apollo_user_id?: string;+ };+ expect(afterFailure.aliased_apollo_user_id).toBeUndefined();+ expect(afterFailure.pending_alias_apollo_user_id).toBeUndefined();++ yield* linkApolloIdentityForAnalytics('om_alias_retry');+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(2);}).pipe(Effect.provide(makePlatformLayer(home)));});@@ -583,11 +674,11 @@ describe('CLI analytics dispatch', () => {yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')) as {apollo_user_id: string;- aliased_apollo_user_id: string;+ pending_alias_apollo_user_id: string;api_key_fingerprint: string;};expect(persisted.apollo_user_id).toBe('om_concurrent');- expect(persisted.aliased_apollo_user_id).toBe('om_concurrent');+ expect(persisted.pending_alias_apollo_user_id).toBe('om_concurrent');expect(persisted.api_key_fingerprint.length).toBeGreaterThan(0);}).pipe(Effect.provide(makePlatformLayer(home)));});@@ -604,14 +695,10 @@ describe('CLI analytics dispatch', () => {const path = yield* Path.Path;yield* fs.writeFileString(scriptPath, '');- // No key -> nothing enqueued, so the alias must not be marked as sent.+ // No key -> no analytics state or worker is created.yield* linkApolloIdentityForAnalytics('om_apollo_retry');expect(childProcessMocks.spawn).not.toHaveBeenCalled();- const afterSkip = JSON.parse(- yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')- ) as { apollo_user_id?: string; aliased_apollo_user_id?: string };- expect(afterSkip.apollo_user_id).toBe('om_apollo_retry');- expect(afterSkip.aliased_apollo_user_id).toBeUndefined();+ expect(yield* fs.exists(path.join(home, '.composio', 'analytics.json'))).toBe(false);// Once a key is configured the alias is attempted again.vi.stubEnv('COMPOSIO_POSTHOG_PROJECT_API_KEY', 'phc_test_key');@@ -619,8 +706,8 @@ describe('CLI analytics dispatch', () => {expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);const afterRetry = JSON.parse(yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')- ) as { aliased_apollo_user_id?: string };- expect(afterRetry.aliased_apollo_user_id).toBe('om_apollo_retry');+ ) as { pending_alias_apollo_user_id?: string };+ expect(afterRetry.pending_alias_apollo_user_id).toBe('om_apollo_retry');}).pipe(Effect.provide(makePlatformLayer(home)));});@@ -930,10 +1017,14 @@ describe('CLI analytics dispatch', () => {const persisted = JSON.parse(yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')- ) as { install_id: string; apollo_user_id: string; aliased_apollo_user_id: string };+ ) as {+ install_id: string;+ apollo_user_id: string;+ pending_alias_apollo_user_id: string;+ };expect(persisted.install_id).toBe(secondPayload.installId);expect(persisted.apollo_user_id).toBe('om_second_user');- expect(persisted.aliased_apollo_user_id).toBe('om_second_user');+ expect(persisted.pending_alias_apollo_user_id).toBe('om_second_user');}).pipe(Effect.provide(makePlatformLayer(home)));});@@ -1048,112 +1139,5 @@ describe('CLI analytics dispatch', () => {expect(payload.properties.duration_ms).toBe(42);}).pipe(Effect.provide(makePlatformLayer(home)));});-- it.effect('bootstrap stitch links a missing identity through session info', () => {- const home = tempy.temporaryDirectory();- const scriptPath = `${home}/composio.ts`;- enableTelemetry('uak_stitch');- process.argv[1] = scriptPath;- const fetchSessionInfo = vi.fn(() => Effect.succeed({ org_member: { id: 'om_stitched' } }));-- return Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- yield* fs.writeFileString(scriptPath, '');-- yield* ensureAnalyticsIdentity({- apiKey: 'uak_stitch',- baseURL: 'https://backend.example.test',- fetchSessionInfo,- });-- expect(fetchSessionInfo).toHaveBeenCalledTimes(1);- expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);- const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];- const payload = decodeWorkerPayload<{ event: string; distinctId: string }>(args[2]!);- expect(payload.event).toBe('$create_alias');- expect(payload.distinctId).toBe('om_stitched');-- // Once linked under this credential, later runs make no network attempt.- yield* ensureAnalyticsIdentity({- apiKey: 'uak_stitch',- baseURL: 'https://backend.example.test',- fetchSessionInfo,- });- expect(fetchSessionInfo).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(makePlatformLayer(home)));- });-- it.effect('bootstrap stitch attempts at most once per day after a failure', () => {- const home = tempy.temporaryDirectory();- const scriptPath = `${home}/composio.ts`;- enableTelemetry('uak_stitch');- process.argv[1] = scriptPath;- const fetchSessionInfo = vi.fn(() => Effect.fail(new Error('offline')));-- return Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- yield* fs.writeFileString(scriptPath, '');-- yield* ensureAnalyticsIdentity({- apiKey: 'uak_stitch',- baseURL: 'https://backend.example.test',- fetchSessionInfo,- });- expect(fetchSessionInfo).toHaveBeenCalledTimes(1);-- const persisted = JSON.parse(- yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')- ) as {- stitch_attempted_at?: string;- stitch_attempted_api_key_fingerprint?: string;- };- expect(typeof persisted.stitch_attempted_at).toBe('string');- expect(typeof persisted.stitch_attempted_api_key_fingerprint).toBe('string');-- // Identity is still unlinked, but the attempt is throttled for 24h.- yield* ensureAnalyticsIdentity({- apiKey: 'uak_stitch',- baseURL: 'https://backend.example.test',- fetchSessionInfo,- });- expect(fetchSessionInfo).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(makePlatformLayer(home)));- });-- it.effect('bootstrap stitch retries immediately when the credential changes', () => {- const home = tempy.temporaryDirectory();- const scriptPath = `${home}/composio.ts`;- enableTelemetry('uak_first');- process.argv[1] = scriptPath;- const failedFetch = vi.fn(() => Effect.fail(new Error('offline')));- const changedCredentialFetch = vi.fn(() =>- Effect.succeed({ org_member: { id: 'om_changed' } })- );-- return Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- yield* fs.writeFileString(scriptPath, '');-- yield* ensureAnalyticsIdentity({- apiKey: 'uak_first',- baseURL: 'https://backend.example.test',- fetchSessionInfo: failedFetch,- });- yield* ensureAnalyticsIdentity({- apiKey: 'uak_second',- baseURL: 'https://backend.example.test',- fetchSessionInfo: changedCredentialFetch,- });-- expect(failedFetch).toHaveBeenCalledTimes(1);- expect(changedCredentialFetch).toHaveBeenCalledTimes(1);- expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);- const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];- const payload = decodeWorkerPayload<{ event: string; distinctId: string }>(args[2]!);- expect(payload.event).toBe('$create_alias');- expect(payload.distinctId).toBe('om_changed');- }).pipe(Effect.provide(makePlatformLayer(home)));- });});});