@devries-cameron20 / composio Mirror · read-only
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, 04:45 UTC

next
ts 416 lines 16.4 KB
Raw
1 import * as BunPath from '@effect/platform-bun/BunPath';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import { Context, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
6 import semver from 'semver';
7 import { bold, cyanBright, dim } from 'src/ui/colors';
8 import { GITHUB_CONFIG } from 'src/config';
9 import { captureServices } from 'src/effects/capture-services';
10 import { APP_VERSION } from '../constants';
11 import type { InvocationHookShape } from './invocation-hook';
12 import { NodeOs } from './node-os';
13 import { resolveBinaryAssetName, resolveRunningCliVersion } from './run-companion-modules';
14 import { TerminalUI } from './terminal-ui';
15
16 /**
17 * Background update check for @composio/cli.
18 *
19 * Two invocation hooks, both run for the selected command before its handler — they must never
20 * block or fail. A command opts out of either in its `CommandMeta` (`src/commands/index.ts`):
21 *
22 * UpdateNotice — reads a tiny cached JSON file (~1 ms)
23 * BackgroundUpdateCheck — fire-and-forget fetch, no await
24 *
25 * Strategy:
26 * Uses GitHub's releases API and only considers stable @composio/cli releases
27 * that include the binary asset for the current platform. The result is cached
28 * to ~/.composio/update-check.json and refreshed at most once every 24 hours.
29 */
30
31 const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
32
33 /** Matches `@composio/cli@<semver>` — excludes prereleases. */
34 const CLI_RELEASE_TAG_RE = /^@composio\/cli@(\d+\.\d+\.\d+)$/;
35
36 export interface UpdateCheckState {
37 lastChecked: string; // ISO-8601
38 latestVersion: string; // e.g. "0.3.0"
39 }
40
41 /** Machine-readable update status for `composio version --check`. */
42 export interface UpdateStatus {
43 /** Version reported by the running CLI executable. */
44 current: string;
45 /** Latest known stable release with a binary for this platform, if known. */
46 latestStable: string | null;
47 /** True when a strictly newer stable release than `current` is available. */
48 updateAvailable: boolean;
49 /** Whether the latest known state is current, actionable, or unavailable. */
50 checkStatus: 'up-to-date' | 'update-available' | 'unknown';
51 /** When the release list was last fetched (ISO-8601), if ever. */
52 lastChecked: string | null;
53 }
54
55 const toCheckStatus = (params: {
56 readonly updateAvailable: boolean;
57 readonly versionsKnown: boolean;
58 }): UpdateStatus['checkStatus'] => {
59 if (params.updateAvailable) return 'update-available';
60 if (!params.versionsKnown) return 'unknown';
61 return 'up-to-date';
62 };
63
64 const UpdateCheckStateSchema = Schema.fromJsonString(
65 Schema.Struct({
66 lastChecked: Schema.String,
67 latestVersion: Schema.String,
68 })
69 );
70
71 const UpdateCheckAttemptSchema = Schema.fromJsonString(
72 Schema.Struct({
73 lastAttempted: Schema.String,
74 })
75 );
76
77 /** Non-2xx GitHub response; recorded as a failed attempt and otherwise swallowed. */
78 class UpdateCheckHttpError extends Data.TaggedError('UpdateCheckHttpError')<{
79 readonly status: number;
80 }> {}
81
82 // ── Injectable configuration ────────────────────────────────────────────
83
84 /** Dependencies injected into the update checker — mirrors the Effect service pattern. */
85 export interface UpdateCheckConfig {
86 readonly stateFile: string;
87 readonly currentVersion: string;
88 readonly checkIntervalMs: number;
89 readonly releasesUrl: string;
90 readonly binaryAssetName: string | undefined;
91 readonly accessToken: string | undefined;
92 readonly fetchFn: (url: string, init?: RequestInit) => Promise<Response>;
93 }
94
95 const defaultStateFile = Effect.gen(function* () {
96 const path = yield* Path.Path;
97 const os = yield* NodeOs;
98 return path.join(os.homedir, '.composio', 'update-check.json');
99 });
100
101 const defaultConfig = (stateFile: string) =>
102 Effect.gen(function* () {
103 const os = yield* NodeOs;
104 const currentVersion = yield* resolveRunningCliVersion(process.execPath, APP_VERSION);
105 const github = yield* Effect.orDie(GITHUB_CONFIG);
106 return {
107 stateFile,
108 currentVersion,
109 checkIntervalMs: CHECK_INTERVAL_MS,
110 releasesUrl: `${github.apiBaseUrl}/repos/${github.owner}/${github.repo}/releases?per_page=100`,
111 binaryAssetName: resolveBinaryAssetName({ platform: os.platform, arch: os.arch }),
112 accessToken: github.accessToken,
113 fetchFn: fetch,
114 } satisfies UpdateCheckConfig;
115 });
116
117 const attemptFileFor = (stateFile: string) => `${stateFile}.attempt`;
118
119 const writeJsonFile = (file: string, value: unknown) =>
120 Effect.gen(function* () {
121 const fs = yield* FileSystem.FileSystem;
122 const path = yield* Path.Path;
123 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
124 yield* fs.writeFileString(file, JSON.stringify(value, null, 2));
125 });
126
127 /** Persist a successful check and clear any failed-attempt marker it supersedes. */
128 const writeState = (stateFile: string, state: UpdateCheckState) =>
129 writeJsonFile(stateFile, state).pipe(
130 Effect.andThen(
131 Effect.flatMap(FileSystem.FileSystem, fs =>
132 fs.remove(attemptFileFor(stateFile), { force: true })
133 )
134 )
135 );
136
137 // ── Pure helpers ────────────────────────────────────────────────────────
138
139 /** Extract the highest stable semver from GitHub releases that include the required binary. */
140 export function parseLatestVersionFromReleases(
141 releases: unknown,
142 binaryAssetName: string | undefined
143 ): string | undefined {
144 if (!binaryAssetName || !Array.isArray(releases)) return undefined;
145
146 let latest: string | undefined;
147 for (const release of releases) {
148 if (!Predicate.isObject(release)) continue;
149
150 const candidate = release;
151 if (typeof candidate.tag_name !== 'string') continue;
152 if (candidate.prerelease === true || candidate.draft === true) continue;
153 if (!Array.isArray(candidate.assets)) continue;
154
155 const hasRequiredBinary = candidate.assets.some(
156 asset => Predicate.hasProperty(asset, 'name') && asset.name === binaryAssetName
157 );
158 if (!hasRequiredBinary) continue;
159
160 const match = CLI_RELEASE_TAG_RE.exec(candidate.tag_name);
161 if (!match) continue;
162
163 const version = match[1];
164 if (!latest || semver.gt(version, latest)) {
165 latest = version;
166 }
167 }
168
169 return latest;
170 }
171
172 // ── Factory ─────────────────────────────────────────────────────────────
173
174 export function createUpdateChecker(config: UpdateCheckConfig) {
175 const attemptFile = attemptFileFor(config.stateFile);
176
177 const readState = Effect.gen(function* () {
178 const fs = yield* FileSystem.FileSystem;
179 const rawState = yield* fs.readFileString(config.stateFile);
180 return yield* Schema.decodeUnknownEffect(UpdateCheckStateSchema)(rawState);
181 });
182
183 const readAttempt = Effect.gen(function* () {
184 const fs = yield* FileSystem.FileSystem;
185 const rawAttempt = yield* fs.readFileString(attemptFile);
186 return yield* Schema.decodeUnknownEffect(UpdateCheckAttemptSchema)(rawAttempt);
187 });
188
189 /**
190 * If a cached newer version is known, print a one-line hint to stderr.
191 * Reads a tiny JSON file and does a semver compare.
192 */
193 function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
194 return Effect.gen(function* () {
195 // `terminal.error` writes even when stderr is redirected, so gate this
196 // advisory notice explicitly while leaving stdout out of the decision.
197 const { canDecorate } = yield* terminal.capabilities;
198 if (!canDecorate) return;
199
200 const state = yield* readState;
201 const latestVersion = semver.valid(state.latestVersion);
202 const currentVersion = semver.valid(config.currentVersion);
203 if (!latestVersion || !currentVersion || latestVersion === currentVersion) return;
204
205 // Only show when the cached version is strictly newer.
206 if (!semver.gt(latestVersion, currentVersion)) return;
207
208 const msg =
209 ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(latestVersion))}\n` +
210 ` ${dim('Run')} ${cyanBright('composio upgrade')} ${dim('to update')}\n`;
211
212 yield* terminal.error(`\n${msg}`);
213 }).pipe(Effect.ignore);
214 }
215
216 /**
217 * Fetch the latest @composio/cli release from GitHub, requiring the current
218 * platform binary asset before writing the result to the state file.
219 *
220 * Never fails: every fetch/parse/write error is swallowed so nothing can
221 * propagate back into the fire-and-forget caller.
222 */
223 const checkForUpdate = Effect.gen(function* () {
224 const checkStartedAt = new Date();
225 const checkStartedAtMs = checkStartedAt.getTime();
226 const parseTimestamp = (value: string): number | undefined => {
227 const timestamp = new Date(value).getTime();
228 return Number.isFinite(timestamp) ? timestamp : undefined;
229 };
230
231 // Throttle: skip if checked recently. A missing or corrupt state file
232 // just means "re-check".
233 const cachedState = yield* Effect.option(readState);
234 const lastCheckedAt = Option.getOrUndefined(
235 Option.map(cachedState, state => parseTimestamp(state.lastChecked))
236 );
237 if (lastCheckedAt !== undefined && checkStartedAtMs - lastCheckedAt < config.checkIntervalMs) {
238 return { state: cachedState, refreshFailed: false } as const;
239 }
240 const failedAttempt = yield* Effect.option(readAttempt);
241 const lastAttemptedAt = Option.getOrUndefined(
242 Option.map(failedAttempt, attempt => parseTimestamp(attempt.lastAttempted))
243 );
244 if (
245 lastAttemptedAt !== undefined &&
246 (lastCheckedAt === undefined || lastAttemptedAt > lastCheckedAt) &&
247 checkStartedAtMs - lastAttemptedAt < config.checkIntervalMs
248 ) {
249 return { state: cachedState, refreshFailed: true } as const;
250 }
251 const previousLatestVersion = Option.getOrUndefined(
252 Option.map(cachedState, state => state.latestVersion)
253 );
254
255 const headers: Record<string, string> = {
256 Accept: 'application/vnd.github.v3+json',
257 'User-Agent': `composio-cli/${config.currentVersion}`,
258 };
259
260 if (config.accessToken) {
261 headers.Authorization = `Bearer ${config.accessToken}`;
262 }
263
264 const fetchLatestVersion = Effect.gen(function* () {
265 const response = yield* Effect.tryPromise(() =>
266 config.fetchFn(config.releasesUrl, { headers, signal: AbortSignal.timeout(10_000) })
267 );
268 if (!response.ok) {
269 return yield* new UpdateCheckHttpError({ status: response.status });
270 }
271 const releases: unknown = yield* Effect.tryPromise(() => response.json());
272 return parseLatestVersionFromReleases(releases, config.binaryAssetName);
273 });
274
275 const latestVersion = yield* Effect.option(fetchLatestVersion);
276 if (Option.isNone(latestVersion)) {
277 yield* Effect.ignore(
278 writeJsonFile(attemptFile, {
279 lastAttempted: checkStartedAt.toISOString(),
280 })
281 );
282 return { state: cachedState, refreshFailed: true } as const;
283 }
284
285 const state: UpdateCheckState = {
286 lastChecked: new Date().toISOString(),
287 latestVersion: latestVersion.value ?? previousLatestVersion ?? config.currentVersion,
288 };
289 yield* writeState(config.stateFile, state).pipe(Effect.ignore);
290 return { state: Option.some(state), refreshFailed: false } as const;
291 });
292
293 /**
294 * Refresh the release cache (self-throttled to the check interval) and
295 * report a machine-readable status. Unlike the notice, this ignores the
296 * TTY gate — callers asked for the data explicitly.
297 */
298 const getUpdateStatus: Effect.Effect<UpdateStatus, never, FileSystem.FileSystem | Path.Path> =
299 Effect.gen(function* () {
300 const { state, refreshFailed } = yield* checkForUpdate;
301
302 const cachedLatest = Option.getOrUndefined(Option.map(state, s => s.latestVersion));
303 const validLatest = cachedLatest ? semver.valid(cachedLatest) : null;
304 const validCurrent = semver.valid(config.currentVersion);
305 const latestStable =
306 validLatest && semver.prerelease(validLatest) === null ? validLatest : null;
307 const updateAvailable =
308 validCurrent !== null && latestStable !== null && semver.gt(latestStable, validCurrent);
309 const versionsKnown = !refreshFailed && validCurrent !== null && latestStable !== null;
310 const checkStatus = toCheckStatus({ updateAvailable, versionsKnown });
311
312 return {
313 current: config.currentVersion,
314 latestStable,
315 updateAvailable,
316 checkStatus,
317 lastChecked: Option.getOrElse(
318 Option.map(state, s => s.lastChecked),
319 () => null as string | null
320 ),
321 } satisfies UpdateStatus;
322 });
323
324 return { showUpdateNotice, checkForUpdate, getUpdateStatus };
325 }
326
327 // ── Public API (production defaults, fire-and-forget) ───────────────────
328
329 const DefaultConfigLayers = Layer.mergeAll(BunPath.layer, NodeOs.Default, BunFileSystem.layer);
330
331 export type UpdateNoticeShape = InvocationHookShape;
332
333 /**
334 * Prints the upgrade hint to stderr if a newer version is cached. Reads the cache under the home
335 * directory `NodeOs` reports; never fetches. `composio upgrade` turns it off: it resolves the
336 * latest release live, so a cached hint could only repeat that answer or contradict it.
337 */
338 export class UpdateNotice extends Context.Service<UpdateNotice, UpdateNoticeShape>()(
339 'services/UpdateNotice'
340 ) {
341 static readonly Default: Layer.Layer<
342 UpdateNotice,
343 never,
344 TerminalUI | FileSystem.FileSystem | Path.Path | NodeOs
345 > = Layer.effect(
346 UpdateNotice,
347 Effect.gen(function* () {
348 const terminal = yield* TerminalUI;
349 const services = yield* captureServices(FileSystem.FileSystem, Path.Path, NodeOs);
350 return UpdateNotice.of({
351 run: () =>
352 Effect.gen(function* () {
353 const stateFile = yield* defaultStateFile;
354 const config = yield* defaultConfig(stateFile);
355 yield* createUpdateChecker(config).showUpdateNotice(terminal);
356 }).pipe(Effect.provideContext(services)),
357 });
358 })
359 );
360 }
361
362 /**
363 * Refreshes the release cache from GitHub if it is stale; `checkForUpdate` swallows its own
364 * failures. `BackgroundUpdateCheck` forks it detached, so the command that started it neither
365 * waits for it nor interrupts it when it ends. A successful run still ends when the event loop
366 * drains (`src/run-main.ts`), so the request can finish; any other exit ends the process at once.
367 */
368 const refreshReleaseCache = Effect.gen(function* () {
369 const stateFile = yield* defaultStateFile;
370 const config = yield* defaultConfig(stateFile);
371 yield* createUpdateChecker(config).checkForUpdate;
372 }).pipe(Effect.provide(DefaultConfigLayers));
373
374 export type BackgroundUpdateCheckShape = InvocationHookShape;
375
376 /**
377 * Starts refreshing the release cache in the background (at most once per check interval) and
378 * returns at once. `composio upgrade` and `composio version --check` turn it off: they resolve
379 * releases themselves.
380 */
381 export class BackgroundUpdateCheck extends Context.Service<
382 BackgroundUpdateCheck,
383 BackgroundUpdateCheckShape
384 >()('services/BackgroundUpdateCheck') {
385 static readonly Default: Layer.Layer<BackgroundUpdateCheck> = Layer.succeed(
386 BackgroundUpdateCheck,
387 BackgroundUpdateCheck.of({ run: () => Effect.asVoid(Effect.forkDetach(refreshReleaseCache)) })
388 );
389 }
390
391 /**
392 * Record a live-resolved latest stable release (e.g. `@composio/cli@0.5.0`) as the cached update
393 * check, so later hints agree with what `composio upgrade` just saw. Tags that are not a stable
394 * CLI release are ignored, and a failed write is swallowed: the cache is advisory.
395 */
396 export const recordLatestStableRelease = (releaseTag: string) =>
397 Option.fromNullishOr(CLI_RELEASE_TAG_RE.exec(releaseTag)?.[1]).pipe(
398 Option.match({
399 onNone: () => Effect.void,
400 onSome: latestVersion =>
401 Effect.gen(function* () {
402 const stateFile = yield* defaultStateFile;
403 yield* writeState(stateFile, { lastChecked: new Date().toISOString(), latestVersion });
404 }).pipe(Effect.ignore),
405 })
406 );
407
408 /**
409 * Refresh the release cache if stale and return a machine-readable status.
410 * Powers `composio version --check`.
411 */
412 export const getUpdateStatus: Effect.Effect<UpdateStatus> = Effect.gen(function* () {
413 const stateFile = yield* defaultStateFile;
414 const config = yield* defaultConfig(stateFile);
415 return yield* createUpdateChecker(config).getUpdateStatus;
416 }).pipe(Effect.provide(DefaultConfigLayers));