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

next
ts 227 lines 8.3 KB
Raw
1 /**
2 * Pins the order in which `effect/cli` composes a command's handler with the providers and guards
3 * of the groups above it. Command identity depends on it (`src/commands/registration.ts`) and the
4 * framework does not document it: if an `effect` upgrade changes it, these cases fail first.
5 */
6 import { describe, expect, layer } from '@effect/vitest';
7 import { Effect, Exit, Option, Ref } from 'effect';
8 import { CliError, Command } from 'effect/cli';
9 import { NotLoggedInError } from 'src/commands/errors';
10 import { withRegisteredSubcommands } from 'src/commands/registration';
11 import { CommandSurface } from 'src/commands/surface';
12 import { CommandInvocation, commandPathOf, withCommandMeta } from 'src/invocation/command-identity';
13 import { TestLive } from 'test/__utils__';
14
15 class GuardFailed extends CliError.UserError {}
16
17 /**
18 * A tree shaped like the CLI's: `app` (whose own handler shows help, like the root's overview)
19 * registers `outer` (whose own handler is an action), a root shortcut to `link` with its own
20 * family, a login-gated group, and a group whose own guard fails. `outer` registers `inner` (no
21 * handler, aliased `in`) and the same `link` value again. Every provider, registration, `begin`,
22 * and handler appends to the trace.
23 */
24 const traced = (args: ReadonlyArray<string>) =>
25 Effect.gen(function* () {
26 const trace = yield* Ref.make<ReadonlyArray<string>>([]);
27 const note = (entry: string) => Ref.update(trace, entries => [...entries, entry]);
28 const handler = (name: string) => () => note(`handler ${name}`);
29 const provider =
30 (name: string) =>
31 <const Name extends string, Input, ContextInput, E, R>(
32 self: Command.Command<Name, Input, ContextInput, E, R>
33 ) =>
34 Command.provideEffectDiscard(self, note(`provider ${name}`));
35
36 const show = Command.make('show', {}, handler('show'));
37 const link = Command.make('link', {}, handler('link'));
38 const inner = Command.make('inner').pipe(
39 Command.withAlias('in'),
40 withRegisteredSubcommands([show]),
41 provider('inner')
42 );
43 const outer = Command.make('outer', {}, handler('outer')).pipe(
44 withRegisteredSubcommands([inner, link], { ownAction: true }),
45 provider('outer')
46 );
47 const gated = Command.make('gated').pipe(
48 withRegisteredSubcommands([Command.make('leaf', {}, handler('gated leaf'))]),
49 withCommandMeta({ requiresLogin: true })
50 );
51 const guarded = Command.make('guarded').pipe(
52 withRegisteredSubcommands([Command.make('leaf', {}, handler('guarded leaf'))]),
53 Command.provideEffectDiscard(
54 Effect.andThen(note('guard guarded'), Effect.fail(new GuardFailed({ cause: 'guard' })))
55 )
56 );
57 const app = Command.make('app', {}, handler('app')).pipe(
58 withRegisteredSubcommands([
59 outer,
60 link.pipe(withCommandMeta({ telemetryFamily: 'link' })),
61 gated,
62 guarded,
63 ]),
64 provider('app')
65 );
66
67 const exit = yield* Command.runWith(app, { version: '1.0.0' })(args).pipe(
68 Effect.provideService(CommandInvocation, {
69 begin: (identity, input) =>
70 note(
71 `begin ${commandPathOf(identity)} ${identity.meta.telemetryFamily}${Option.isSome(input) ? '' : ' unparsed'}`
72 ),
73 enter: identity => note(`enter ${commandPathOf(identity)}`),
74 runId: Effect.succeedNone,
75 }),
76 Effect.provide(CommandSurface.root),
77 Effect.exit
78 );
79 return { exit, trace: yield* Ref.get(trace) };
80 });
81
82 const failureOf = (exit: Exit.Exit<unknown, unknown>) =>
83 Exit.isFailure(exit) ? Option.getOrUndefined(Exit.findErrorOption(exit)) : undefined;
84
85 describe('effect/cli handler composition', () => {
86 layer(TestLive())(it => {
87 it.effect.each([
88 {
89 name: 'a nested leaf runs inside every ancestor provider, outermost first',
90 args: ['outer', 'inner', 'show'],
91 trace: [
92 'provider app',
93 'enter outer',
94 'provider outer',
95 'enter outer inner',
96 'provider inner',
97 'enter outer inner show',
98 'begin outer inner show command',
99 'handler show',
100 ],
101 },
102 {
103 name: 'an alias resolves to the canonical registration',
104 args: ['outer', 'in', 'show'],
105 trace: [
106 'provider app',
107 'enter outer',
108 'provider outer',
109 'enter outer inner',
110 'provider inner',
111 'enter outer inner show',
112 'begin outer inner show command',
113 'handler show',
114 ],
115 },
116 {
117 name: 'a bare group with its own action begins it with its input, no subcommand',
118 args: ['outer'],
119 trace: [
120 'provider app',
121 'enter outer',
122 'provider outer',
123 'begin outer command',
124 'handler outer',
125 ],
126 },
127 {
128 name: 'the root with no subcommand begins as help, then runs its own handler',
129 args: [],
130 trace: ['provider app', 'begin composio command unparsed', 'handler app'],
131 },
132 {
133 name: 'a root shortcut is its own registration, with its own meta',
134 args: ['link'],
135 trace: ['provider app', 'enter link', 'begin link link', 'handler link'],
136 },
137 {
138 name: 'the same value registered in a group has the group path and no root meta',
139 args: ['outer', 'link'],
140 trace: [
141 'provider app',
142 'enter outer',
143 'provider outer',
144 'enter outer link',
145 'begin outer link command',
146 'handler link',
147 ],
148 },
149 ])('$name', ({ args, trace }) =>
150 Effect.gen(function* () {
151 const result = yield* traced(args);
152 expect(Exit.isSuccess(result.exit)).toBe(true);
153 expect(result.trace).toEqual(trace);
154 })
155 );
156
157 it.effect('a bare group without a handler begins as help, then shows its help', () =>
158 Effect.gen(function* () {
159 const { exit, trace } = yield* traced(['outer', 'inner']);
160 expect(trace).toEqual([
161 'provider app',
162 'enter outer',
163 'provider outer',
164 'enter outer inner',
165 'provider inner',
166 'begin outer inner command unparsed',
167 ]);
168 expect(failureOf(exit)).toMatchObject({
169 _tag: 'ShowHelp',
170 commandPath: ['app', 'outer', 'inner'],
171 errors: [],
172 });
173 })
174 );
175
176 it.effect('a login a group requires is checked after the selected command began', () =>
177 Effect.gen(function* () {
178 const { exit, trace } = yield* traced(['gated', 'leaf']);
179 expect(trace).toEqual([
180 'provider app',
181 'enter gated',
182 'enter gated leaf',
183 'begin gated leaf command',
184 ]);
185 expect(failureOf(exit)).toBeInstanceOf(NotLoggedInError);
186 })
187 );
188
189 // A guard a group pipes on itself wraps its whole dispatch, so it runs before the selected
190 // command is reached: only the registrations entered so far are known. A required login is
191 // `CommandMeta` for this reason, and so is a shared flag a command cannot honor.
192 it.effect('a group-level guard runs before the selected command begins', () =>
193 Effect.gen(function* () {
194 const { exit, trace } = yield* traced(['guarded', 'leaf']);
195 expect(trace).toEqual(['provider app', 'enter guarded', 'guard guarded']);
196 expect(failureOf(exit)).toBeInstanceOf(GuardFailed);
197 })
198 );
199
200 it.effect('a parse failure runs no provider, and names the canonical path reached', () =>
201 Effect.gen(function* () {
202 const { exit, trace } = yield* traced(['outer', 'in', 'shw']);
203 expect(trace).toEqual([]);
204 expect(failureOf(exit)).toMatchObject({
205 _tag: 'ShowHelp',
206 commandPath: ['app', 'outer', 'inner'],
207 errors: [{ _tag: 'UnknownSubcommand', subcommand: 'shw' }],
208 });
209 })
210 );
211
212 it.effect.each([
213 {
214 flag: '--help',
215 args: ['outer', 'in', '--help'],
216 begun: 'begin outer inner command unparsed',
217 },
218 { flag: '--version', args: ['link', '--version'], begun: 'begin link link unparsed' },
219 ])('$flag begins the command it answers for, and runs no handler', ({ args, begun }) =>
220 Effect.gen(function* () {
221 const { exit, trace } = yield* traced(args);
222 expect(Exit.isSuccess(exit)).toBe(true);
223 expect(trace).toEqual([begun]);
224 })
225 );
226 });
227 });