@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 224 lines 8.35 KB
Raw
1 /**
2 * @fileoverview The `composio.experimental` namespace. Houses experimental
3 * SDK methods whose shape may change in future releases.
4 *
5 * Domain-specific mounts remain preferred when they exist (for example
6 * `composio.connectedAccounts.updateAcl(...)`). This namespace keeps
7 * compatibility aliases while those APIs are experimental. For experimental
8 * stateless factories (e.g. `experimental_createTool`), see the top-level
9 * `experimental_*` exports from `@composio/core`.
10 */
11 import ComposioClient, { BadRequestError } from '@composio/client';
12 import {
13 ConnectedAccountPatchParams,
14 ConnectedAccountPatchResponse,
15 } from '@composio/client/resources/connected-accounts';
16 import {
17 ConnectedAccountExperimental,
18 UpdateConnectedAccountAclParams,
19 UpdateConnectedAccountAclParamsSchema,
20 } from '../types/connectedAccounts.types';
21 import { ValidationError } from '../errors/ValidationErrors';
22 import { ComposioAclOnlyForSharedError } from '../errors';
23 import { telemetry } from '../telemetry/Telemetry';
24 import { Usage } from './Usage';
25 import { CustomToolkits } from './CustomToolkits';
26
27 /**
28 * Server-side 400 message the API uses to reject ACL writes against a
29 * PRIVATE connection. Substring-matched in `updateAcl` and in the sibling
30 * `connectedAccounts.link()` / `session.authorize()` call sites — kept as
31 * a single constant so a server-side message tweak only requires one edit.
32 */
33 export const ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT = 'acl_config_for_shared is only valid on SHARED';
34
35 /**
36 * Structural shape of the wire's experimental block on requests. Both
37 * the `link.create` and `tool_router.session.link` wire types are
38 * Stainless-generated as nominally distinct namespaces but accept this
39 * shape — sharing one structural type keeps the SDK helpers reusable.
40 */
41 type ExperimentalWire = {
42 account_type?: 'PRIVATE' | 'SHARED';
43 acl_config_for_shared?: {
44 allow_all_users?: boolean;
45 allowed_user_ids?: string[];
46 not_allowed_user_ids?: string[];
47 };
48 };
49
50 /**
51 * Serialise the SDK's `aclConfigForShared` (camelCase) to the wire's
52 * `acl_config_for_shared` block. Returns `undefined` when the caller
53 * didn't pass anything (PATCH-style "don't touch ACL"); returns `{}`
54 * when the caller passed an explicit empty object.
55 */
56 export function serializeAclConfigForWire(
57 acl:
58 | {
59 allowAllUsers?: boolean;
60 allowedUserIds?: string[];
61 notAllowedUserIds?: string[];
62 }
63 | undefined
64 ): NonNullable<ExperimentalWire['acl_config_for_shared']> | undefined {
65 if (acl === undefined) return undefined;
66 return {
67 ...(acl.allowAllUsers !== undefined && { allow_all_users: acl.allowAllUsers }),
68 ...(acl.allowedUserIds !== undefined && { allowed_user_ids: acl.allowedUserIds }),
69 ...(acl.notAllowedUserIds !== undefined && { not_allowed_user_ids: acl.notAllowedUserIds }),
70 };
71 }
72
73 /**
74 * Serialise the SDK's `experimental` options block (camelCase) to the
75 * wire's `experimental` block (snake_case). Used by both
76 * `connectedAccounts.link()` and `session.authorize()`. Returns
77 * `undefined` when the caller didn't pass the block at all.
78 */
79 export function serializeExperimentalForWire(
80 experimental: ConnectedAccountExperimental | undefined
81 ): ExperimentalWire | undefined {
82 if (experimental === undefined) return undefined;
83 const aclWire = serializeAclConfigForWire(experimental.aclConfigForShared);
84 const wire: ExperimentalWire = {};
85 if (experimental.accountType !== undefined) {
86 wire.account_type = experimental.accountType;
87 }
88 if (aclWire !== undefined) {
89 wire.acl_config_for_shared = aclWire;
90 }
91 return wire;
92 }
93
94 /**
95 * `composio.experimental` namespace. Keeps compatibility aliases for
96 * experimental surfaces while domain-specific mounts graduate. **Shape may
97 * change in future releases.**
98 */
99 export async function updateConnectedAccountAcl(
100 client: ComposioClient,
101 nanoid: string,
102 params: UpdateConnectedAccountAclParams
103 ): Promise<ConnectedAccountPatchResponse> {
104 const parsedParams = UpdateConnectedAccountAclParamsSchema.safeParse(params);
105 if (!parsedParams.success) {
106 throw new ValidationError('Failed to parse connected account ACL update params', {
107 cause: parsedParams.error,
108 });
109 }
110
111 const body: ConnectedAccountPatchParams = {
112 experimental: {
113 acl_config_for_shared: serializeAclConfigForWire(parsedParams.data),
114 },
115 };
116
117 try {
118 return await client.connectedAccounts.patch(nanoid, body);
119 } catch (error) {
120 if (
121 error instanceof BadRequestError &&
122 typeof error.message === 'string' &&
123 error.message.includes(ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT)
124 ) {
125 throw new ComposioAclOnlyForSharedError(error.message, { cause: error });
126 }
127 throw error;
128 }
129 }
130
131 export class Experimental {
132 private client: ComposioClient;
133
134 /**
135 * Project-scoped usage metering (`summary()` / `breakdown()`).
136 * **Experimental — shape may change in future releases.**
137 *
138 * @example
139 * ```typescript
140 * const summary = await composio.experimental.usage.summary();
141 * const byTool = await composio.experimental.usage.breakdown('tool_calls');
142 * ```
143 */
144 usage: Usage;
145
146 /**
147 * Same object as `composio.customToolkits`.
148 * @deprecated Use `composio.customToolkits` instead. Custom toolkits are no longer experimental; this alias is kept for backwards compatibility.
149 */
150 customToolkits: CustomToolkits;
151
152 constructor(client: ComposioClient) {
153 this.client = client;
154 this.usage = new Usage(client);
155 this.customToolkits = new CustomToolkits(client);
156 telemetry.instrument(this, 'Experimental');
157 }
158
159 /**
160 * Compatibility alias for `composio.connectedAccounts.updateAcl(...)`.
161 * Update the per-user ACL on a SHARED connected account.
162 * **Experimental — shape may change in future releases.**
163 *
164 * Only meaningful for SHARED connections — calling this on a PRIVATE
165 * connection raises `ComposioAclOnlyForSharedError` (400). ACL writes
166 * require the connection's creator or an API key.
167 *
168 * PATCH semantics: omit a field to leave it unchanged; pass an empty
169 * array to clear an allow/deny list. At least one field must be
170 * provided.
171 *
172 * Resolution rule (deny wins):
173 * 1. requesting `userId` in `notAllowedUserIds` → DENY
174 * 2. `allowAllUsers === true` → ALLOW
175 * 3. requesting `userId` in `allowedUserIds` → ALLOW
176 * 4. otherwise → DENY
177 *
178 * @example
179 * ```typescript
180 * import { Composio } from '@composio/core';
181 *
182 * const composio = new Composio({ apiKey: '...' });
183 *
184 * // Allow every userId to use this connection
185 * await composio.connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true });
186 *
187 * // Everyone except a specific user
188 * await composio.connectedAccounts.updateAcl('ca_abc', {
189 * allowAllUsers: true,
190 * notAllowedUserIds: ['user_bob'],
191 * });
192 *
193 * // Targeted allow
194 * await composio.connectedAccounts.updateAcl('ca_abc', {
195 * allowedUserIds: ['user_alice', 'user_bob'],
196 * });
197 *
198 * // Revoke a previously-granted allow list (back to deny-by-default)
199 * await composio.connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
200 * ```
201 *
202 * **Empty-array semantics — read carefully.** Passing `[]` for either
203 * list **replaces** the list, it does not extend it:
204 *
205 * - `allowedUserIds: []` → revoke all previously-granted user IDs (state
206 * reverts to deny-by-default unless `allowAllUsers` is true).
207 * - `notAllowedUserIds: []` → **clears the deny list**, which silently
208 * re-grants access to users you previously blocked. Always pair an
209 * empty deny list with a deliberate audit of the allow side.
210 *
211 * @returns The PATCH response (`{ id, status, success }`). To read
212 * the updated ACL block, call
213 * `composio.connectedAccounts.get(nanoid)` after the promise
214 * resolves and inspect `account.experimental?.aclConfigForShared`.
215 *
216 * @deprecated Use `composio.connectedAccounts.updateAcl(...)` instead — ACL updates graduated onto the `connectedAccounts` mount. This experimental alias is kept only for backwards compatibility and will be removed once the API graduates. Prefer the `connectedAccounts` mount; do not generate new code against this alias.
217 */
218 async updateAcl(
219 nanoid: string,
220 params: UpdateConnectedAccountAclParams
221 ): Promise<ConnectedAccountPatchResponse> {
222 return updateConnectedAccountAcl(this.client, nanoid, params);
223 }
224 }