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): address PR review — identity coverage, logout, alias retry; trim comments
Kshitij Jhunjhunwalaecbd1a33ce9f
diff --git a/.github/workflows/build-cli-binaries.yml b/.github/workflows/build-cli-binaries.ymlindex a3c18d537..eb090217f 100644--- a/.github/workflows/build-cli-binaries.yml+++ b/.github/workflows/build-cli-binaries.yml@@ -133,9 +133,6 @@ jobs:- name: Cross-compile CLI binaryworking-directory: ts/packages/clienv:- # Public, write-only PostHog project key (project 196278), baked into- # the released binary via `--define`. Not a secret — an Actions- # *variable* so only official builds carry it and forks stay no-op.COMPOSIO_POSTHOG_KEY: ${{ vars.COMPOSIO_POSTHOG_KEY }}run: pnpm build:binary:cross --target ${{ matrix.target }}diff --git a/.gitignore b/.gitignoreindex 8fb9aa178..e1572b91e 100644--- a/.gitignore+++ b/.gitignore@@ -73,4 +73,3 @@ docs/.workflow-data/*# Local agent / tooling state (regenerated per machine).pi/.playwright-mcp/-.claude/plans/diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.mdindex 5ec532e78..39a89de87 100644--- a/ts/packages/cli/CHANGELOG.md+++ b/ts/packages/cli/CHANGELOG.md@@ -2,7 +2,7 @@## Unreleased-- Telemetry now delivers directly to PostHog instead of through the Apollo analytics endpoint. This fixes the dark top-of-funnel: pre-login `install`/`setup`/`plugin-setup` events no longer require a logged-in API base URL, so they are captured under the anonymous `install_id`. At login the CLI persists the Apollo `org_member.id` and fires a single `$create_alias`, so post-login events (and all later CLI activity) resolve to the same PostHog person as web onboarding. Existing opt-outs (`COMPOSIO_CLI_TELEMETRY_DISABLED`, `TELEMETRY_DISABLED`, `COMPOSIO_DISABLE_TELEMETRY`, `CI`, `NODE_ENV=test`) are unchanged, and no secrets or tool-argument values are ever sent.+- Telemetry now delivers directly to PostHog, so pre-login `install`/`setup` events are captured. Opt-outs are unchanged.## 0.3.0diff --git a/ts/packages/cli/scripts/_shared.ts b/ts/packages/cli/scripts/_shared.tsindex 776460405..712d17c1c 100644--- a/ts/packages/cli/scripts/_shared.ts+++ b/ts/packages/cli/scripts/_shared.ts@@ -51,10 +51,7 @@ const copyBundledAcpAdapters = async (outputDir: string): Promise<void> => {export const LOCAL_TOOLS_BINARY_ASSET_DIRNAME = 'local-tools-binaries';-// Bakes the public PostHog write key from the build-time COMPOSIO_POSTHOG_KEY-// env var into the compiled binary (mirrors the dashboard's NEXT_PUBLIC baking).-// Empty when unset -> telemetry is a no-op. Kept out of --env so it doesn't-// clobber the DEBUG_OVERRIDE_* inline (Bun honors only the last --env).+// Kept out of --env: Bun honors only the last --env, which would clobber DEBUG_OVERRIDE_*.export const posthogBakeArgs = (): ReadonlyArray<string> => {const key = process.env.COMPOSIO_POSTHOG_KEY?.trim();return key ? ['--define', `COMPOSIO_POSTHOG_KEY_BAKED=${JSON.stringify(key)}`] : [];diff --git a/ts/packages/cli/scripts/build-binary.ts b/ts/packages/cli/scripts/build-binary.tsindex a62572b08..4726149ca 100644--- a/ts/packages/cli/scripts/build-binary.ts+++ b/ts/packages/cli/scripts/build-binary.ts@@ -18,8 +18,6 @@ export function buildBinary() {const cwd = process.cwd();yield* Effect.logDebug(`Building binary in ${cwd}`);- // `--env DEBUG_OVERRIDE_*` inlines matching env vars; the PostHog key is- // baked via `--define` instead (Bun honors only the last `--env`).const args: ReadonlyArray<string> = ['build','./src/bin.ts',diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.tsindex 2c2859e67..747ed1086 100644--- a/ts/packages/cli/src/analytics/dispatch.ts+++ b/ts/packages/cli/src/analytics/dispatch.ts@@ -100,8 +100,6 @@ const analyticsDisabled = environmentProvider.load());-// Direct-to-PostHog target; env overrides fall back to the embedded constants.-// No dependency on the API base URL, so pre-login events can send.const getPostHogConfig = environmentProvider.load(Config.all({@@ -171,11 +169,12 @@ const readOptionalJson = <A>(filePath: string) =>return (yield* decodeJson(raw)) as A;}).pipe(Effect.catchAll(() => Effect.succeed(undefined)));-// `install_id` = anonymous device UUID; `apollo_user_id` = Apollo `org_member.id`-// persisted at login, used as the PostHog identity post-login.type AnalyticsState = {readonly install_id?: string;readonly apollo_user_id?: string;+ // Tracked separately from apollo_user_id so an alias that was never enqueued+ // (no project key, telemetry off) is retried instead of blocked forever.+ readonly aliased_apollo_user_id?: string;readonly created_at?: string;};@@ -216,8 +215,7 @@ const readApolloUserId = Effect.map(readAnalyticsState, state =>: null);-// Persists the Apollo `org_member.id`, preserving `install_id`/`created_at`.-const persistApolloUserId = (installId: string, apolloUserId: string) =>+const mergeAnalyticsState = (installId: string, patch: Partial<AnalyticsState>) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const paths = yield* getAnalyticsPaths;@@ -227,12 +225,11 @@ const persistApolloUserId = (installId: string, apolloUserId: string) =>.pipe(Effect.catchAll(() => Effect.void));const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);- const createdAt = state?.created_at ?? DateTime.formatIso(yield* DateTime.now);const contents = yield* encodeJson({...(state ?? {}),install_id: state?.install_id ?? installId,- apollo_user_id: apolloUserId,- created_at: createdAt,+ created_at: state?.created_at ?? DateTime.formatIso(yield* DateTime.now),+ ...patch,});yield* fs.writeFileString(paths.analyticsStatePath, contents);}).pipe(Effect.catchAll(() => Effect.void));@@ -256,8 +253,6 @@ const getUserApiKey = Effect.gen(function* () {: null;});-// Post-login: the Apollo `org_member.id`. Pre-login: the raw `install_id` (the-// login-time `$create_alias` merges this exact value into the Apollo person).const getDistinctId = (installId: string) =>Effect.map(readApolloUserId, apolloUserId => apolloUserId ?? installId);@@ -351,8 +346,6 @@ const spawnWorker = (command: string, args: ReadonlyArray<string>) =>);});-// Shapes an envelope into a PostHog capture body; the public project key-// authenticates the ingest in-band (no user API key attached).const buildPostHogBody = (envelope: AnalyticsEnvelope, projectKey: string) => ({api_key: projectKey,event: envelope.event,@@ -492,9 +485,6 @@ const captureToComposioCodactFailures = (failure: CliCodactFailure) =>});});-// Hands an envelope to the detached best-effort worker for PostHog delivery.-// Short-circuits when no project key is configured (the default for OSS forks /-// local builds) so we never spawn a worker that would only no-op.const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>Effect.gen(function* () {const { projectKey } = yield* getPostHogConfig;@@ -503,7 +493,7 @@ const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>reason: 'missing_project_key',eventName: envelope.event,});- return;+ return false;}yield* telemetryDebugLog('enqueue', { envelope });@@ -514,6 +504,7 @@ const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>encodedPayload);yield* spawnWorker(command, args);+ return true;});export const trackCliEventEffect = (event: TrackEvent) =>@@ -548,13 +539,12 @@ export const trackCliEventEffect = (event: TrackEvent) =>yield* enqueuePostHogEnvelope(envelope);}).pipe(Effect.catchAllCause(() => Effect.void));-// Fires one `$create_alias` merging the `install_id` device into the Apollo person.export const emitPostHogAlias = (installId: string, apolloUserId: string) =>Effect.gen(function* () {const disabled = yield* analyticsDisabled;if (disabled) {yield* telemetryDebugLog('alias_skip', { reason: 'disabled', installId });- return;+ return false;}const sentAt = DateTime.formatIso(yield* DateTime.now);@@ -571,11 +561,14 @@ export const emitPostHogAlias = (installId: string, apolloUserId: string) =>distinctId: apolloUserId,installId,};- yield* enqueuePostHogEnvelope(envelope);- }).pipe(Effect.catchAllCause(() => Effect.void));--// Called at login: persist the Apollo identity and, on first association, alias-// the anonymous install into it. Non-fatal so login never fails on telemetry.+ return yield* enqueuePostHogEnvelope(envelope);+ }).pipe(Effect.catchAllCause(() => Effect.succeed(false)));++/**+ * Records the Apollo `org_member.id` as the analytics identity and stitches the+ * anonymous install into it. Safe to call from any command that already resolved+ * a session, which is how already-authenticated installs get backfilled.+ */export const linkApolloIdentityForAnalytics = (apolloUserId: string) =>Effect.gen(function* () {const resolved = typeof apolloUserId === 'string' ? apolloUserId.trim() : '';@@ -583,24 +576,32 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string) =>return;}- // Disabled telemetry writes nothing — not even the local identity file.const disabled = yield* analyticsDisabled;if (disabled) {yield* telemetryDebugLog('alias_skip', { reason: 'disabled' });return;}- const existing = yield* readApolloUserId;+ const state = yield* readAnalyticsState;const installId = yield* getOrCreateInstallId;- yield* persistApolloUserId(installId, resolved);- // Alias only the first time this install is tied to an Apollo user: a repeat- // login is redundant, and PostHog rejects re-aliasing one install into a- // second account, so skip once an id has already been persisted.- if (existing === null) {- yield* emitPostHogAlias(installId, resolved);+ if (state?.apollo_user_id !== resolved) {+ yield* mergeAnalyticsState(installId, { apollo_user_id: resolved });+ }++ if (state?.aliased_apollo_user_id === resolved) {+ return;+ }+ if (yield* emitPostHogAlias(installId, resolved)) {+ yield* mergeAnalyticsState(installId, { aliased_apollo_user_id: resolved });}}).pipe(Effect.catchAllCause(() => Effect.void));+/** Drops the Apollo identity on logout so later events revert to `install_id`. */+export const clearApolloIdentityForAnalytics = Effect.gen(function* () {+ const installId = yield* getOrCreateInstallId;+ yield* mergeAnalyticsState(installId, { apollo_user_id: undefined });+}).pipe(Effect.catchAllCause(() => Effect.void));+export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>Effect.gen(function* () {const endpoint = yield* getCliCodactFailuresEndpoint;diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex b0627b060..732326e4e 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -9,6 +9,7 @@ import { resolveToolRouterSession } from 'src/effects/create-tool-router-sessionimport { extractMessage, extractSlug } from 'src/utils/api-error-extraction';import { ProjectContext } from 'src/services/project-context';import { ComposioClientSingleton, getSessionInfoByUserApiKey } from 'src/services/composio-clients';+import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';import {formatResolveCommandProjectError,resolveCommandProject,@@ -240,6 +241,10 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boouserApiKey: apiKey,}).pipe(Effect.catchAll(() => Effect.succeed(null)));+ if (sessionInfo) {+ yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id);+ }+if (sessionInfo?.project.org.name) {orgName = sessionInfo.project.org.name;}diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.tsindex 75166bb82..bd51c40b7 100644--- a/ts/packages/cli/src/commands/init.cmd.ts+++ b/ts/packages/cli/src/commands/init.cmd.ts@@ -11,6 +11,7 @@ import {listOrgProjects,type OrgProject,} from 'src/services/composio-clients';+import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';import * as constants from 'src/constants';import { TerminalUI } from 'src/services/terminal-ui';import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';@@ -125,6 +126,7 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }orgId: selected.orgId,projectId: selected.projectId,});+ yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id);let projectApiKey = sessionInfo.api_key?.api_key ?? sessionInfo.api_key?.key ?? null;if (!projectApiKey && !hasProjectApiKey) {diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex fc4789634..ed1bafb86 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -891,6 +891,17 @@ export const loginCmd = Command.make(yield* ensureAgentSignupAllowed;const identity = yield* getOrSignupReadyAgent();yield* loginWithAgentIdentity(identity);+ const agentUserApiKey = identity.composio?.user_api_key;+ if (agentUserApiKey) {+ const agentSessionInfo = yield* getSessionInfoByUserApiKey({+ baseURL: ctx.data.baseURL,+ userApiKey: agentUserApiKey,+ orgId: identity.composio?.org_id ?? undefined,+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));+ if (agentSessionInfo) {+ yield* linkApolloIdentityForAnalytics(agentSessionInfo.org_member.id);+ }+ }const summary = safeAgentSummary(identity);yield* ui.log.success(`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`diff --git a/ts/packages/cli/src/commands/logout.cmd.ts b/ts/packages/cli/src/commands/logout.cmd.tsindex d7d000b0d..e7619c5a5 100644--- a/ts/packages/cli/src/commands/logout.cmd.ts+++ b/ts/packages/cli/src/commands/logout.cmd.ts@@ -7,6 +7,7 @@ import {} from 'src/services/agents';import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';+import { clearApolloIdentityForAnalytics } from 'src/analytics/dispatch';/*** CLI command to log out from the Composio CLI.@@ -54,6 +55,7 @@ export const logoutCmd = Command.make('logout', { force }, ({ force }) =>}yield* ctx.logout;+ yield* clearApolloIdentityForAnalytics;if (Option.isSome(loggedInAgent)) {yield* removeStoredAgentIdentity;diff --git a/ts/packages/cli/src/commands/whoami.cmd.ts b/ts/packages/cli/src/commands/whoami.cmd.tsindex 41a50cabb..6a7f72d97 100644--- a/ts/packages/cli/src/commands/whoami.cmd.ts+++ b/ts/packages/cli/src/commands/whoami.cmd.ts@@ -1,6 +1,7 @@import { Command } from '@effect/cli';import { Effect, Option } from 'effect';import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';+import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';import { commandHintStep } from 'src/services/command-hints';@@ -34,6 +35,10 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(// Reflect the org selected via `composio orgs switch`, not the key's home org.orgId: Option.getOrUndefined(ctx.data.orgId),}).pipe(Effect.option);+ yield* Option.match(sessionInfo, {+ onNone: () => Effect.void,+ onSome: info => linkApolloIdentityForAnalytics(info.org_member.id),+ });const email = Option.map(sessionInfo, info => info.org_member.email).pipe(Option.getOrUndefined);diff --git a/ts/packages/cli/src/constants.ts b/ts/packages/cli/src/constants.tsindex e855a88c5..8a9a02ed5 100644--- a/ts/packages/cli/src/constants.ts+++ b/ts/packages/cli/src/constants.ts@@ -78,21 +78,14 @@ export const PROJECT_ENV_FILE_NAME = '.env';export const PROJECT_COMPOSIO_DIR = '.composio';/**- * PostHog single-event capture endpoint for direct CLI telemetry. Overridable- * via `COMPOSIO_POSTHOG_INGEST_URL` (tests / staging).+ * PostHog capture endpoint for CLI telemetry.*/export const COMPOSIO_POSTHOG_INGEST_URL = 'https://us.i.posthog.com/i/v0/e/';-// Injected at build time from the COMPOSIO_POSTHOG_KEY env var via `--define`-// (see scripts/_shared.ts `posthogBakeArgs`); undefined in dev/test.declare const COMPOSIO_POSTHOG_KEY_BAKED: string | undefined;/**- * Public, write-only PostHog project write key (project 196278). Client-- * embeddable by design — it can only ingest events, never read them — same as- * the dashboard's `NEXT_PUBLIC_POSTHOG_TOKEN`. Sourced from the build-time- * bake, overridable at runtime via `COMPOSIO_POSTHOG_KEY`. Empty -> telemetry- * is a no-op.+ * Public write-only PostHog project key, baked at build from `COMPOSIO_POSTHOG_KEY`.*/export const COMPOSIO_POSTHOG_PROJECT_KEY =typeof COMPOSIO_POSTHOG_KEY_BAKED === 'string' ? COMPOSIO_POSTHOG_KEY_BAKED : '';diff --git a/ts/packages/cli/test/src/analytics.dispatch.test.ts b/ts/packages/cli/test/src/analytics.dispatch.test.tsindex 7bfaba64a..e000aaed6 100644--- a/ts/packages/cli/test/src/analytics.dispatch.test.ts+++ b/ts/packages/cli/test/src/analytics.dispatch.test.ts@@ -5,6 +5,7 @@ import { BunFileSystem, BunPath } from '@effect/platform-bun';import { Effect, Layer } from 'effect';import * as tempy from 'tempy';import {+ clearApolloIdentityForAnalytics,emitPostHogAlias,getCurrentCwdSessionId,linkApolloIdentityForAnalytics,@@ -502,6 +503,71 @@ describe('CLI analytics dispatch', () => {}).pipe(Effect.provide(makePlatformLayer(home)));});+ it.effect('retries the alias when the first attempt could not be enqueued', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry();+ vi.stubEnv('COMPOSIO_POSTHOG_KEY', '');+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.writeFileString(scriptPath, '');++ // No key -> nothing enqueued, so the alias must not be marked as sent.+ 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();++ // Once a key is configured the alias is attempted again.+ vi.stubEnv('COMPOSIO_POSTHOG_KEY', 'phc_test_key');+ yield* linkApolloIdentityForAnalytics('om_apollo_retry');+ 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');+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('clears the Apollo identity on logout so events revert to install_id', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry('');+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.writeFileString(scriptPath, '');+ const composioDir = path.join(home, '.composio');+ yield* fs.makeDirectory(composioDir, { recursive: true });+ yield* fs.writeFileString(+ path.join(composioDir, 'analytics.json'),+ JSON.stringify({ install_id: 'install_logout', apollo_user_id: 'om_apollo_gone' })+ );++ yield* clearApolloIdentityForAnalytics;++ const persisted = JSON.parse(+ yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')+ ) as { install_id: string; apollo_user_id?: string };+ expect(persisted.install_id).toBe('install_logout');+ expect(persisted.apollo_user_id).toBeUndefined();++ // Later events fall back to the anonymous install identity.+ yield* trackCliEventEffect({ name: 'producer_event' });+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ const payload = decodeWorkerPayload<{ distinctId: string }>(args[2]!);+ expect(payload.distinctId).toBe('install_logout');+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });+it.effect('delivers codact worker failures with the user key and session body', () => {const home = tempy.temporaryDirectory();const failureBody = {