@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, 03:37 UTC

next
ts 165 lines 5.71 KB
Raw
1 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
2 import * as BunServices from '@effect/platform-bun/BunServices';
3 import { Cause, Console, Data, Effect, FileSystem, Layer, Option, Schema, Stream } from 'effect';
4 import { Digest } from 'effect/crypto';
5 import { FetchHttpClient } from 'effect/http';
6 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
7
8 /** An SDK release invariant that does not hold. */
9 export class ReleaseError extends Data.TaggedError('ReleaseError')<{ readonly message: string }> {}
10
11 export const fail = (message: string) => Effect.fail(new ReleaseError({ message }));
12 export const ensure = (condition: boolean, message: string) =>
13 condition ? Effect.void : fail(message);
14
15 /** A failure raised by a Promise-based library such as Changesets. */
16 export class LibraryError extends Data.TaggedError('LibraryError')<{
17 readonly message: string;
18 readonly cause: unknown;
19 }> {}
20
21 export const fromPromise = <A>(evaluate: () => PromiseLike<A>) =>
22 Effect.tryPromise({
23 try: evaluate,
24 catch: cause =>
25 new LibraryError({
26 message: cause instanceof Error ? cause.message : String(cause),
27 cause,
28 }),
29 });
30
31 export class CommandError extends Data.TaggedError('CommandError')<{
32 readonly message: string;
33 readonly exitCode: number;
34 }> {}
35
36 export interface CommandResult {
37 readonly exitCode: number;
38 readonly stdout: string;
39 readonly stderr: string;
40 }
41
42 export interface CommandOptions {
43 readonly cwd?: string;
44 readonly env?: Record<string, string | undefined>;
45 readonly output?: 'pipe' | 'inherit';
46 }
47
48 /** Commands that build or inspect untrusted release inputs never receive controller tokens. */
49 export const withoutReleaseTokens = {
50 SDK_RELEASE_TOKEN: undefined,
51 GH_TOKEN: undefined,
52 GITHUB_TOKEN: undefined,
53 } as const;
54
55 const text = <E>(stream: Stream.Stream<Uint8Array, E>) =>
56 stream.pipe(Stream.decodeText(), Stream.mkString);
57
58 /** Runs a command to completion and reports its exit code without failing on it. */
59 export const spawn = (command: string, args: ReadonlyArray<string>, options: CommandOptions = {}) =>
60 Effect.scoped(
61 Effect.gen(function* () {
62 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
63 const output = options.output ?? 'pipe';
64 const handle = yield* spawner.spawn(
65 ChildProcess.make(command, args, {
66 cwd: options.cwd,
67 env: options.env,
68 extendEnv: true,
69 stdin: 'ignore',
70 stdout: output,
71 stderr: output,
72 })
73 );
74 const [stdout, stderr, exitCode] = yield* Effect.all(
75 [text(handle.stdout), text(handle.stderr), handle.exitCode],
76 { concurrency: 'unbounded' }
77 );
78 return { exitCode: Number(exitCode), stdout, stderr } satisfies CommandResult;
79 })
80 );
81
82 /** Runs a command and returns stdout, failing with its output when it exits non-zero. */
83 export const run = (command: string, args: ReadonlyArray<string>, options: CommandOptions = {}) =>
84 spawn(command, args, options).pipe(
85 Effect.flatMap(result =>
86 result.exitCode === 0
87 ? Effect.succeed(result.stdout)
88 : Effect.fail(
89 new CommandError({
90 message: `${command} failed: ${result.stderr || result.stdout || result.exitCode}`,
91 exitCode: result.exitCode,
92 })
93 )
94 )
95 );
96
97 export const inDirectory =
98 (cwd: string, extraEnv: Record<string, string> = {}) =>
99 (command: string, args: ReadonlyArray<string>) =>
100 run(command, args, { cwd, env: { ...withoutReleaseTokens, ...extraEnv } });
101
102 /** Reads a file as text; fails when it does not exist (see `readOptionalFile`). */
103 export const readFile = (path: string) =>
104 Effect.gen(function* () {
105 const fs = yield* FileSystem.FileSystem;
106 return yield* fs.readFileString(path);
107 });
108
109 export const readOptionalFile = (path: string) =>
110 readFile(path).pipe(
111 Effect.map(Option.some),
112 Effect.catchReason('PlatformError', 'NotFound', () => Effect.succeedNone)
113 );
114
115 export const writeFile = (path: string, contents: string) =>
116 Effect.gen(function* () {
117 const fs = yield* FileSystem.FileSystem;
118 yield* fs.writeFileString(path, contents);
119 });
120
121 export const appendFile = (path: string, text: string) =>
122 Effect.gen(function* () {
123 const fs = yield* FileSystem.FileSystem;
124 yield* fs.writeFileString(path, text, { flag: 'a' });
125 });
126
127 export const parseJson = <S extends Schema.Top>(schema: S, contents: string) =>
128 Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(contents);
129
130 export const readJson = <S extends Schema.Top>(schema: S, path: string) =>
131 readFile(path).pipe(Effect.flatMap(contents => parseJson(schema, contents)));
132
133 export const sameJson = (left: unknown, right: unknown) =>
134 JSON.stringify(left) === JSON.stringify(right);
135
136 export const formatJson = (value: unknown) => `${JSON.stringify(value, null, 2)}\n`;
137
138 export const writeJson = (path: string, value: unknown) => writeFile(path, formatJson(value));
139
140 export const sha256Hex = (bytes: Uint8Array | string) =>
141 Effect.gen(function* () {
142 const digest = yield* Digest.Digest;
143 return yield* digest.digestHex(
144 Digest.sha256,
145 typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes
146 );
147 });
148
149 export const ReleaseServices = Layer.mergeAll(
150 BunServices.layer,
151 FetchHttpClient.layer,
152 Digest.layerWebCrypto
153 );
154
155 export type ReleaseServices = Layer.Success<typeof ReleaseServices>;
156
157 /** Runs a release entry point; failures go to stderr and exit non-zero, like a thrown error. */
158 export const runMain = <A, E>(program: Effect.Effect<A, E, ReleaseServices>) =>
159 BunRuntime.runMain(
160 program.pipe(
161 Effect.tapCause(cause => Console.error(Cause.pretty(cause))),
162 Effect.provide(ReleaseServices)
163 ),
164 { disableErrorReporting: true }
165 );