@devries-cameron20 / composio Mirror · read-only / commits / f04306195
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 18:30 UTC

fix(cli): harden client-side analytics identity and event hygiene

- trust a persisted apollo_user_id without a fingerprint only in the keychain security modes with a parseable user config - rotate to a fresh install_id when a different Apollo user links on the same machine, instead of refusing to alias - bootstrap-stitch missing identities from the resolved api key via session/info (24h throttle, 1.5s timeout, all failures swallowed) - redact secret-shaped tokens from outgoing event properties - make analytics.json writes atomic (temp file + rename) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

Kshitij Jhunjhunwala committed Jul 27, 2026 at 15:08 UTC f043061952a9ab2db751828d6582b00b094f35f6
3 files changed +380 -18
ts/packages/cli/src/analytics/dispatch.ts
+156 -13
@@ -158,6 +158,7 @@ const getAnalyticsPaths = Effect.gen(function* () {
158 analyticsDir,
159 analyticsStatePath: path.join(analyticsDir, ANALYTICS_STATE_FILE_NAME),
160 userConfigPath: path.join(analyticsDir, constants.USER_CONFIG_FILE_NAME),
161 + cliConfigPath: path.join(analyticsDir, constants.CLI_CONFIG_FILE_NAME),
162 consumerShortTermCachePath: path.join(cacheDir, CONSUMER_SHORT_TERM_CACHE_FILE_NAME),
163 };
164 });
@@ -174,6 +175,7 @@ type AnalyticsState = {
175 readonly apollo_user_id?: string;
176 readonly aliased_apollo_user_id?: string;
177 readonly api_key_fingerprint?: string;
178 + readonly stitch_attempted_at?: string;
179 readonly created_at?: string;
180 };
181
@@ -184,6 +186,19 @@ const readAnalyticsState = Effect.gen(function* () {
186 return yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
187 });
188
189 +// Concurrent CLI processes write this file; temp-file + rename keeps each
190 +// write atomic so readers never observe partial JSON.
191 +const writeAnalyticsStateFile = (contents: string) =>
192 + Effect.gen(function* () {
193 + const fs = yield* FileSystem.FileSystem;
194 + const paths = yield* getAnalyticsPaths;
195 + const temporaryPath = `${paths.analyticsStatePath}.${crypto.randomUUID().slice(0, 8)}.tmp`;
196 + yield* fs.writeFileString(temporaryPath, contents);
197 + yield* fs
198 + .rename(temporaryPath, paths.analyticsStatePath)
199 + .pipe(Effect.tapError(() => fs.remove(temporaryPath).pipe(Effect.ignore)));
200 + });
201 +
202 const getOrCreateInstallId = Effect.gen(function* () {
203 const fs = yield* FileSystem.FileSystem;
204 const paths = yield* getAnalyticsPaths;
@@ -204,7 +219,7 @@ const getOrCreateInstallId = Effect.gen(function* () {
219 install_id: installId,
220 created_at: createdAt,
221 });
207 - yield* fs.writeFileString(paths.analyticsStatePath, contents);
222 + yield* writeAnalyticsStateFile(contents);
223 return installId;
224 }).pipe(Effect.catchAll(() => makeInstallId));
225
@@ -224,7 +239,7 @@ const mergeAnalyticsState = (installId: string, patch: Partial<AnalyticsState>)
239 created_at: state?.created_at ?? DateTime.formatIso(yield* DateTime.now),
240 ...patch,
241 });
227 - yield* fs.writeFileString(paths.analyticsStatePath, contents);
242 + yield* writeAnalyticsStateFile(contents);
243 }).pipe(Effect.catchAll(() => Effect.void));
244
245 const readUserConfig = Effect.gen(function* () {
@@ -259,19 +274,31 @@ const getApiKeyFingerprint = Effect.map(getUserApiKey, apiKey =>
274 apiKey ? fingerprintApiKey(apiKey) : null
275 );
276
277 +// The keychain* security modes strip the api key from user_data.json, so no
278 +// fingerprint is computable here; a parseable user config in one of those
279 +// modes is the signal that the persisted identity still belongs to a login.
280 +const keyringBackedLoginPresent = Effect.gen(function* () {
281 + const paths = yield* getAnalyticsPaths;
282 + const cliConfig = yield* readOptionalJson<{ security?: unknown }>(paths.cliConfigPath);
283 + if (cliConfig?.security !== 'keychain' && cliConfig?.security !== 'keychain-subprocess') {
284 + return false;
285 + }
286 + return (yield* readUserConfig) !== undefined;
287 +});
288 +
289 const getDistinctId = (installId: string) =>
290 Effect.gen(function* () {
291 const state = yield* readAnalyticsState;
292 const apolloUserId = state?.apollo_user_id;
293 const fingerprint = yield* getApiKeyFingerprint;
294
268 - if (
269 - typeof apolloUserId === 'string' &&
270 - apolloUserId.length > 0 &&
271 - fingerprint !== null &&
272 - fingerprint === state?.api_key_fingerprint
273 - ) {
274 - return apolloUserId;
295 + if (typeof apolloUserId === 'string' && apolloUserId.length > 0) {
296 + if (fingerprint !== null && fingerprint === state?.api_key_fingerprint) {
297 + return apolloUserId;
298 + }
299 + if (fingerprint === null && (yield* keyringBackedLoginPresent)) {
300 + return apolloUserId;
301 + }
302 }
303
304 if (typeof state?.aliased_apollo_user_id !== 'string') {
@@ -280,6 +307,54 @@ const getDistinctId = (installId: string) =>
307 return fingerprint !== null ? `user_${fingerprint}` : `anon_${installId}`;
308 });
309
310 +// The direct-to-PostHog path bypasses Apollo's server-side sanitizer, so
311 +// secret-shaped tokens are redacted client-side before any envelope leaves.
312 +const REDACTED_VALUE = '[redacted]';
313 +const KNOWN_SECRET_PATTERNS: ReadonlyArray<RegExp> = [
314 + /\buak_[A-Za-z0-9_-]+/gu,
315 + /\bak_[A-Za-z0-9_-]+/gu,
316 + /\bphc_[A-Za-z0-9]+/gu,
317 + /\bsk-[A-Za-z0-9_-]+/gu,
318 + /\bghp_[A-Za-z0-9]+/gu,
319 + /\bBearer\s+[A-Za-z0-9._~+/=-]+/gu,
320 +];
321 +
322 +// Mixed-case-plus-digit tokens of api-key length; single-case tokens
323 +// (uuids, hex ids, tool slugs) stay untouched.
324 +const isHighEntropyToken = (token: string): boolean =>
325 + token.length >= 24 &&
326 + /^[A-Za-z0-9+/=_-]+$/u.test(token) &&
327 + /[a-z]/u.test(token) &&
328 + /[A-Z]/u.test(token) &&
329 + /[0-9]/u.test(token);
330 +
331 +const scrubSecretsFromString = (value: string): string =>
332 + KNOWN_SECRET_PATTERNS.reduce(
333 + (scrubbed, pattern) => scrubbed.replace(pattern, REDACTED_VALUE),
334 + value
335 + )
336 + .split(/(\s+)/u)
337 + .map(part => (isHighEntropyToken(part) ? REDACTED_VALUE : part))
338 + .join('');
339 +
340 +const scrubSecrets = (value: unknown): unknown => {
341 + if (typeof value === 'string') {
342 + return scrubSecretsFromString(value);
343 + }
344 + if (Array.isArray(value)) {
345 + return value.map(scrubSecrets);
346 + }
347 + if (value !== null && typeof value === 'object') {
348 + return Object.fromEntries(
349 + Object.entries(value as Record<string, unknown>).map(([key, entry]) => [
350 + key,
351 + scrubSecrets(entry),
352 + ])
353 + );
354 + }
355 + return value;
356 +};
357 +
358 const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
359
360 export const getCurrentCwdSessionId = (cwd = process.cwd()) =>
@@ -553,10 +628,10 @@ export const trackCliEventEffect = (event: TrackEvent) =>
628 const distinctId = yield* getDistinctId(installId);
629 const orgId = yield* getOrgId;
630 const sentAt = DateTime.formatIso(yield* DateTime.now);
556 - const properties = {
631 + const properties = scrubSecrets({
632 ...(enrichedEvent.properties ?? {}),
633 ...(orgId ? { org_id: orgId } : {}),
559 - };
634 + }) as Record<string, unknown>;
635 const envelope: AnalyticsEnvelope = {
636 event: enrichedEvent.name,
637 ...(Object.keys(properties).length > 0 ? { properties } : {}),
@@ -605,8 +680,27 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
680 return;
681 }
682
608 - const state = yield* readAnalyticsState;
609 - const installId = yield* getOrCreateInstallId;
683 + let state = yield* readAnalyticsState;
684 + let installId = yield* getOrCreateInstallId;
685 +
686 + // A second user on this machine must not merge into the previous user's
687 + // PostHog person: rotate to a fresh install_id before linking.
688 + const previousIdentity = state?.apollo_user_id ?? state?.aliased_apollo_user_id;
689 + const identityChanged =
690 + typeof previousIdentity === 'string' &&
691 + previousIdentity.length > 0 &&
692 + previousIdentity !== resolved;
693 + if (identityChanged) {
694 + installId = yield* makeInstallId;
695 + yield* mergeAnalyticsState(installId, {
696 + install_id: installId,
697 + apollo_user_id: undefined,
698 + aliased_apollo_user_id: undefined,
699 + api_key_fingerprint: undefined,
700 + });
701 + state = yield* readAnalyticsState;
702 + }
703 +
704 const fingerprint =
705 typeof apiKey === 'string' && apiKey.length > 0
706 ? fingerprintApiKey(apiKey)
@@ -626,6 +720,55 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st
720 }
721 }).pipe(Effect.catchAllCause(() => Effect.void));
722
723 +const STITCH_ATTEMPT_INTERVAL_MS = 24 * 60 * 60 * 1000;
724 +const STITCH_SESSION_INFO_TIMEOUT = '1500 millis';
725 +
726 +type AnalyticsSessionInfoFetcher = (params: {
727 + baseURL: string;
728 + userApiKey: string;
729 +}) => Effect.Effect<{ readonly org_member: { readonly id: string } }, unknown>;
730 +
731 +// Repairs a missing/stale persisted identity for already-logged-in installs
732 +// (e.g. keyring-stored keys that predate identity stitching). The session-info
733 +// fetcher is injected because composio-clients already imports this module.
734 +export const ensureAnalyticsIdentity = (params: {
735 + apiKey: string;
736 + baseURL: string;
737 + fetchSessionInfo: AnalyticsSessionInfoFetcher;
738 +}) =>
739 + Effect.gen(function* () {
740 + if ((yield* analyticsDisabled) || params.apiKey.trim().length === 0) {
741 + return;
742 + }
743 +
744 + const state = yield* readAnalyticsState;
745 + const fingerprint = fingerprintApiKey(params.apiKey);
746 + const identityLinked =
747 + typeof state?.apollo_user_id === 'string' &&
748 + state.apollo_user_id.length > 0 &&
749 + state.api_key_fingerprint === fingerprint;
750 + if (identityLinked) {
751 + return;
752 + }
753 +
754 + const lastAttemptMs = Date.parse(state?.stitch_attempted_at ?? '');
755 + const nowMs = yield* Clock.currentTimeMillis;
756 + if (Number.isFinite(lastAttemptMs) && nowMs - lastAttemptMs < STITCH_ATTEMPT_INTERVAL_MS) {
757 + return;
758 + }
759 +
760 + // Persisted before the network attempt so failures cannot retry-storm.
761 + const installId = yield* getOrCreateInstallId;
762 + yield* mergeAnalyticsState(installId, {
763 + stitch_attempted_at: DateTime.formatIso(yield* DateTime.now),
764 + });
765 +
766 + const info = yield* params
767 + .fetchSessionInfo({ baseURL: params.baseURL, userApiKey: params.apiKey })
768 + .pipe(Effect.timeout(STITCH_SESSION_INFO_TIMEOUT));
769 + yield* linkApolloIdentityForAnalytics(info.org_member.id, params.apiKey);
770 + }).pipe(Effect.catchAllCause(() => Effect.void));
771 +
772 export const clearApolloIdentityForAnalytics = Effect.gen(function* () {
773 const state = yield* readAnalyticsState;
774 if (!state?.install_id || !state.apollo_user_id) {
ts/packages/cli/src/cli-main.ts
+20 -3
@@ -1,5 +1,5 @@
1 import process from 'node:process';
2 -import { Cause, Effect, Exit, Layer, Logger } from 'effect';
2 +import { Cause, Effect, Exit, Layer, Logger, Option } from 'effect';
3 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4 import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';
5 import { FetchHttpClient } from '@effect/platform';
@@ -15,13 +15,17 @@ import {
15 ComposioClientSingleton,
16 ComposioSessionRepository,
17 ComposioToolkitsRepository,
18 + getSessionInfoByUserApiKey,
19 } from 'src/services/composio-clients';
20 import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
21 import { NodeOs } from 'src/services/node-os';
22 import { NodeProcess } from 'src/services/node-process';
23 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
24 import { ComposioCliUserConfigLive, ComposioCliUserConfig } from 'src/services/cli-user-config';
24 -import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
25 +import {
26 + ComposioUserContext,
27 + ComposioUserContextLive as _ComposioUserContextLive,
28 +} from 'src/services/user-context';
29 import { UpgradeBinary } from 'src/services/upgrade-binary';
30 import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
31 import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -37,7 +41,7 @@ import {
41 getPrimaryLifecycleInvokedEvent,
42 getPrimaryLifecycleSucceededEvent,
43 } from 'src/analytics/events';
40 -import { trackCliEventEffect } from 'src/analytics/dispatch';
44 +import { ensureAnalyticsIdentity, trackCliEventEffect } from 'src/analytics/dispatch';
45 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
46 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
47 import { SetupCommandError } from 'src/services/setup';
@@ -144,6 +148,19 @@ const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) sati
148 const runWithTelemetry = Effect.gen(function* () {
149 const ui = yield* TerminalUI;
150 const terminal = yield* ui.capabilities;
151 +
152 + // Stitch the analytics identity for installs whose credential (env or
153 + // keyring) resolved without ever passing through a login-time link.
154 + const userContext = yield* ComposioUserContext;
155 + const resolvedApiKey = Option.getOrUndefined(userContext.data.apiKey);
156 + if (resolvedApiKey) {
157 + yield* ensureAnalyticsIdentity({
158 + apiKey: resolvedApiKey,
159 + baseURL: userContext.data.baseURL,
160 + fetchSessionInfo: getSessionInfoByUserApiKey,
161 + });
162 + }
163 +
164 const commandTelemetryContext = createCliCommandTelemetryContext(
165 process.argv,
166 constants.APP_VERSION,
ts/packages/cli/test/src/analytics.dispatch.test.ts
+204 -2
@@ -7,6 +7,7 @@ import * as tempy from 'tempy';
7 import {
8 clearApolloIdentityForAnalytics,
9 emitPostHogAlias,
10 + ensureAnalyticsIdentity,
11 getCurrentCwdSessionId,
12 linkApolloIdentityForAnalytics,
13 readApiBaseUrl,
@@ -774,7 +775,7 @@ describe('CLI analytics dispatch', () => {
775 }).pipe(Effect.provide(makePlatformLayer(home)));
776 });
777
777 - it.effect('never re-aliases one install onto a second Apollo user', () => {
778 + it.effect('rotates to a fresh install_id when a second Apollo user links', () => {
779 const home = tempy.temporaryDirectory();
780 const scriptPath = `${home}/composio.ts`;
781 enableTelemetry();
@@ -782,15 +783,216 @@ describe('CLI analytics dispatch', () => {
783
784 return Effect.gen(function* () {
785 const fs = yield* FileSystem.FileSystem;
786 + const path = yield* Path.Path;
787 yield* fs.writeFileString(scriptPath, '');
788
789 yield* linkApolloIdentityForAnalytics('om_first_user');
790 expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
791 + const firstArgs = childProcessMocks.spawn.mock.calls[0]![1] as string[];
792 + const firstPayload = decodeWorkerPayload<{ installId: string }>(firstArgs[2]!);
793
790 - // Logout, then log in as a different user on the same device.
794 + // Logout, then log in as a different user on the same device: the
795 + // second user is aliased to a fresh install_id, never the one already
796 + // merged into the first user's PostHog person.
797 yield* clearApolloIdentityForAnalytics;
798 yield* linkApolloIdentityForAnalytics('om_second_user');
799 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(2);
800 + const secondArgs = childProcessMocks.spawn.mock.calls[1]![1] as string[];
801 + const secondPayload = decodeWorkerPayload<{
802 + event: string;
803 + distinctId: string;
804 + installId: string;
805 + properties: { alias: string };
806 + }>(secondArgs[2]!);
807 + expect(secondPayload.event).toBe('$create_alias');
808 + expect(secondPayload.distinctId).toBe('om_second_user');
809 + expect(secondPayload.installId).not.toBe(firstPayload.installId);
810 + expect(secondPayload.properties.alias).toBe(secondPayload.installId);
811 +
812 + const persisted = JSON.parse(
813 + yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
814 + ) as { install_id: string; apollo_user_id: string; aliased_apollo_user_id: string };
815 + expect(persisted.install_id).toBe(secondPayload.installId);
816 + expect(persisted.apollo_user_id).toBe('om_second_user');
817 + expect(persisted.aliased_apollo_user_id).toBe('om_second_user');
818 + }).pipe(Effect.provide(makePlatformLayer(home)));
819 + });
820 +
821 + it.effect('trusts the persisted identity when the api key lives in the OS keyring', () => {
822 + const home = tempy.temporaryDirectory();
823 + const scriptPath = `${home}/composio.ts`;
824 + // No env key and no plaintext api_key on disk -> no fingerprint.
825 + enableTelemetry('');
826 + process.argv[1] = scriptPath;
827 +
828 + return Effect.gen(function* () {
829 + const fs = yield* FileSystem.FileSystem;
830 + const path = yield* Path.Path;
831 + yield* fs.writeFileString(scriptPath, '');
832 + const composioDir = path.join(home, '.composio');
833 + yield* fs.makeDirectory(composioDir, { recursive: true });
834 + yield* fs.writeFileString(
835 + path.join(composioDir, 'config.json'),
836 + JSON.stringify({ security: 'keychain-subprocess' })
837 + );
838 + yield* fs.writeFileString(
839 + path.join(composioDir, USER_CONFIG_FILE_NAME),
840 + JSON.stringify({ base_url: 'https://backend.example.test', org_id: 'org_keychain' })
841 + );
842 + yield* fs.writeFileString(
843 + path.join(composioDir, 'analytics.json'),
844 + JSON.stringify({
845 + install_id: 'install_keychain',
846 + apollo_user_id: 'om_keychain_user',
847 + aliased_apollo_user_id: 'om_keychain_user',
848 + api_key_fingerprint: 'abc.5',
849 + })
850 + );
851 +
852 + yield* trackCliEventEffect({ name: 'producer_event' });
853 +
854 + const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
855 + const payload = decodeWorkerPayload<{ distinctId: string }>(args[2]!);
856 + expect(payload.distinctId).toBe('om_keychain_user');
857 + }).pipe(Effect.provide(makePlatformLayer(home)));
858 + });
859 +
860 + it.effect('does not trust a fingerprint-less identity outside keychain modes', () => {
861 + const home = tempy.temporaryDirectory();
862 + const scriptPath = `${home}/composio.ts`;
863 + enableTelemetry('');
864 + process.argv[1] = scriptPath;
865 +
866 + return Effect.gen(function* () {
867 + const fs = yield* FileSystem.FileSystem;
868 + const path = yield* Path.Path;
869 + yield* fs.writeFileString(scriptPath, '');
870 + const composioDir = path.join(home, '.composio');
871 + yield* fs.makeDirectory(composioDir, { recursive: true });
872 + yield* fs.writeFileString(
873 + path.join(composioDir, 'config.json'),
874 + JSON.stringify({ security: 'json' })
875 + );
876 + yield* fs.writeFileString(
877 + path.join(composioDir, USER_CONFIG_FILE_NAME),
878 + JSON.stringify({ org_id: 'org_json' })
879 + );
880 + yield* fs.writeFileString(
881 + path.join(composioDir, 'analytics.json'),
882 + JSON.stringify({
883 + install_id: 'install_json',
884 + apollo_user_id: 'om_json_user',
885 + aliased_apollo_user_id: 'om_json_user',
886 + api_key_fingerprint: 'abc.5',
887 + })
888 + );
889 +
890 + yield* trackCliEventEffect({ name: 'producer_event' });
891 +
892 + const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
893 + const payload = decodeWorkerPayload<{ distinctId: string }>(args[2]!);
894 + expect(payload.distinctId).toBe('anon_install_json');
895 + }).pipe(Effect.provide(makePlatformLayer(home)));
896 + });
897 +
898 + it.effect('redacts secret-shaped tokens from event properties', () => {
899 + const home = tempy.temporaryDirectory();
900 + const scriptPath = `${home}/composio.ts`;
901 + enableTelemetry();
902 + process.argv[1] = scriptPath;
903 +
904 + return Effect.gen(function* () {
905 + const fs = yield* FileSystem.FileSystem;
906 + yield* fs.writeFileString(scriptPath, '');
907 +
908 + yield* trackCliEventEffect({
909 + name: CLI_ANALYTICS_EVENTS.CLI_COMMAND_FAILED,
910 + properties: {
911 + error_message: 'Auth failed for uak_AbC123xyz_secret via Bearer eyJhbGciOi.Jt0ken',
912 + nested: { tokens: ['ghp_ABCdef1234567890'] },
913 + duration_ms: 42,
914 + },
915 + });
916 +
917 + const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
918 + const payload = decodeWorkerPayload<{
919 + properties: {
920 + error_message: string;
921 + nested: { tokens: string[] };
922 + duration_ms: number;
923 + };
924 + }>(args[2]!);
925 + expect(payload.properties.error_message).toBe('Auth failed for [redacted] via [redacted]');
926 + expect(payload.properties.nested.tokens).toEqual(['[redacted]']);
927 + expect(payload.properties.duration_ms).toBe(42);
928 + }).pipe(Effect.provide(makePlatformLayer(home)));
929 + });
930 +
931 + it.effect('bootstrap stitch links a missing identity through session info', () => {
932 + const home = tempy.temporaryDirectory();
933 + const scriptPath = `${home}/composio.ts`;
934 + enableTelemetry('uak_stitch');
935 + process.argv[1] = scriptPath;
936 + const fetchSessionInfo = vi.fn(() => Effect.succeed({ org_member: { id: 'om_stitched' } }));
937 +
938 + return Effect.gen(function* () {
939 + const fs = yield* FileSystem.FileSystem;
940 + yield* fs.writeFileString(scriptPath, '');
941 +
942 + yield* ensureAnalyticsIdentity({
943 + apiKey: 'uak_stitch',
944 + baseURL: 'https://backend.example.test',
945 + fetchSessionInfo,
946 + });
947 +
948 + expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
949 expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
950 + const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
951 + const payload = decodeWorkerPayload<{ event: string; distinctId: string }>(args[2]!);
952 + expect(payload.event).toBe('$create_alias');
953 + expect(payload.distinctId).toBe('om_stitched');
954 +
955 + // Once linked under this credential, later runs make no network attempt.
956 + yield* ensureAnalyticsIdentity({
957 + apiKey: 'uak_stitch',
958 + baseURL: 'https://backend.example.test',
959 + fetchSessionInfo,
960 + });
961 + expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
962 + }).pipe(Effect.provide(makePlatformLayer(home)));
963 + });
964 +
965 + it.effect('bootstrap stitch attempts at most once per day after a failure', () => {
966 + const home = tempy.temporaryDirectory();
967 + const scriptPath = `${home}/composio.ts`;
968 + enableTelemetry('uak_stitch');
969 + process.argv[1] = scriptPath;
970 + const fetchSessionInfo = vi.fn(() => Effect.fail(new Error('offline')));
971 +
972 + return Effect.gen(function* () {
973 + const fs = yield* FileSystem.FileSystem;
974 + const path = yield* Path.Path;
975 + yield* fs.writeFileString(scriptPath, '');
976 +
977 + yield* ensureAnalyticsIdentity({
978 + apiKey: 'uak_stitch',
979 + baseURL: 'https://backend.example.test',
980 + fetchSessionInfo,
981 + });
982 + expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
983 +
984 + const persisted = JSON.parse(
985 + yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')
986 + ) as { stitch_attempted_at?: string };
987 + expect(typeof persisted.stitch_attempted_at).toBe('string');
988 +
989 + // Identity is still unlinked, but the attempt is throttled for 24h.
990 + yield* ensureAnalyticsIdentity({
991 + apiKey: 'uak_stitch',
992 + baseURL: 'https://backend.example.test',
993 + fetchSessionInfo,
994 + });
995 + expect(fetchSessionInfo).toHaveBeenCalledTimes(1);
996 }).pipe(Effect.provide(makePlatformLayer(home)));
997 });
998 });