Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import http from 'node:http'; |
| 2 | import * as FileSystem from 'effect/FileSystem'; |
| 3 | import * as Path from 'effect/Path'; |
| 4 | import type { ComposioClientShape } from '@composio/client/effect'; |
| 5 | import open from 'open'; |
| 6 | import { |
| 7 | Data, |
| 8 | Effect, |
| 9 | Option, |
| 10 | Record as EffectRecord, |
| 11 | Schema, |
| 12 | SchemaTransformation, |
| 13 | Semaphore, |
| 14 | } from 'effect'; |
| 15 | import { JsonRecordSchema } from 'src/effects/json'; |
| 16 | import { setupCacheDir } from 'src/effects/setup-cache-dir'; |
| 17 | import { atomicWriteFileString } from 'src/utils/atomic-write'; |
| 18 | import { collectDecodedEntries } from 'src/utils/collect-decoded-entries'; |
| 19 | import { |
| 20 | detectPermissionCallerAgent, |
| 21 | isEnhancedControlsPlatformSupported, |
| 22 | isInteractivePermissionUiDisabled, |
| 23 | type PermissionCallerAgent, |
| 24 | } from 'src/services/permission-ui'; |
| 25 | import { ComposioClientSingleton } from 'src/services/composio-clients'; |
| 26 | import { type ClientError } from 'src/services/composio-errors'; |
| 27 | import { ComposioUserContext } from 'src/services/user-context'; |
| 28 | import { idempotent } from 'src/services/composio-request'; |
| 29 | |
| 30 | export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhanced'; |
| 31 | |
| 32 | const CACHE_FILE_NAME = 'tool-permissions-cache.json'; |
| 33 | const PERMISSION_SNAPSHOT_CACHE_TTL_MS = 5 * 60 * 1000; |
| 34 | |
| 35 | // The path a `ToolPermissionsRequestError` names for each consumer request. |
| 36 | const ORG_CONSUMER_CONFIG_PATH = '/api/v3.1/org/consumer/config'; |
| 37 | const CONSUMER_PERMISSIONS_RESOLVE_PATH = '/api/v3.1/consumer/permissions/resolve'; |
| 38 | const ALLOW_FOR_DURATION_LABEL = '1 hr'; |
| 39 | const ALLOW_FOR_DURATION_MS = 60 * 60 * 1000; |
| 40 | const NO_CONNECTED_ACCOUNT = '__none__'; |
| 41 | |
| 42 | export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny'; |
| 43 | export type PermissionApprovalStatus = |
| 44 | 'always_approved' | 'cached_approved' | 'approved_once' | 'approved_for_session'; |
| 45 | export type PermissionGateResult = |
| 46 | { readonly approvalStatus: PermissionApprovalStatus } | undefined; |
| 47 | |
| 48 | const PermissionDefaultModeLiteralSchema = Schema.Literals([ |
| 49 | 'allow_all', |
| 50 | 'ask_every_call', |
| 51 | 'ask_once_per_session', |
| 52 | ]); |
| 53 | const PermissionOverrideStateLiteralSchema = Schema.Literals([ |
| 54 | 'always_allow', |
| 55 | 'always_deny', |
| 56 | 'ask_once', |
| 57 | 'ask_always', |
| 58 | ]); |
| 59 | const isPermissionDefaultMode = Schema.is(PermissionDefaultModeLiteralSchema); |
| 60 | const isPermissionOverrideState = Schema.is(PermissionOverrideStateLiteralSchema); |
| 61 | |
| 62 | // The permissions API can add modes before every installed CLI has upgraded. |
| 63 | // Preserve validation without failing open during that version-skew window: |
| 64 | // unknown defaults and overrides decode to their interactive safe equivalents. |
| 65 | const PermissionDefaultModeSchema = Schema.String.pipe( |
| 66 | Schema.decodeTo( |
| 67 | PermissionDefaultModeLiteralSchema, |
| 68 | SchemaTransformation.transform({ |
| 69 | decode: value => (isPermissionDefaultMode(value) ? value : 'ask_every_call'), |
| 70 | encode: value => value, |
| 71 | }) |
| 72 | ) |
| 73 | ); |
| 74 | const PermissionOverrideStateSchema = Schema.String.pipe( |
| 75 | Schema.decodeTo( |
| 76 | PermissionOverrideStateLiteralSchema, |
| 77 | SchemaTransformation.transform({ |
| 78 | decode: value => (isPermissionOverrideState(value) ? value : 'ask_always'), |
| 79 | encode: value => value, |
| 80 | }) |
| 81 | ) |
| 82 | ); |
| 83 | const ToolRouterPermissionsConfigSchema = Schema.Struct({ |
| 84 | default: PermissionDefaultModeSchema, |
| 85 | overrides: Schema.optional(Schema.Record(Schema.String, PermissionOverrideStateSchema)), |
| 86 | }); |
| 87 | export const decodeToolRouterPermissionsConfig = Schema.decodeUnknownOption( |
| 88 | ToolRouterPermissionsConfigSchema |
| 89 | ); |
| 90 | const ConsumerPermissionSnapshotSchema = Schema.Struct({ |
| 91 | orgId: Schema.String, |
| 92 | projectId: Schema.String, |
| 93 | consumerUserId: Schema.String, |
| 94 | enhancedControlsEnabled: Schema.Boolean, |
| 95 | permissions: Schema.optional(ToolRouterPermissionsConfigSchema), |
| 96 | connectedAccountIds: Schema.Array(Schema.String), |
| 97 | fetchedAt: Schema.Number, |
| 98 | }); |
| 99 | const CachedAllowDecisionSchema = Schema.Struct({ expiresAt: Schema.Number }); |
| 100 | const PermissionResolveResponseSchema = Schema.Struct({ |
| 101 | experimental: Schema.optional( |
| 102 | Schema.Struct({ permissions: Schema.optional(ToolRouterPermissionsConfigSchema) }) |
| 103 | ), |
| 104 | }); |
| 105 | const ConsumerConfigResponseSchema = Schema.Struct({ |
| 106 | enhanced_controls: Schema.optional(Schema.Boolean), |
| 107 | }); |
| 108 | |
| 109 | export type PermissionDefaultMode = typeof PermissionDefaultModeSchema.Type; |
| 110 | export type PermissionOverrideState = typeof PermissionOverrideStateSchema.Type; |
| 111 | export type ToolRouterPermissionsConfig = typeof ToolRouterPermissionsConfigSchema.Type; |
| 112 | export type ConsumerPermissionSnapshot = typeof ConsumerPermissionSnapshotSchema.Type; |
| 113 | type CachedAllowDecision = typeof CachedAllowDecisionSchema.Type; |
| 114 | // Decoding of the cache file is per-entry (decodeCacheShell + decodeSnapshotEntry / |
| 115 | // decodeAllowEntry below), so the file shape only needs a type, not a schema value. |
| 116 | type CacheFile = { |
| 117 | readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>; |
| 118 | readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>> | undefined; |
| 119 | }; |
| 120 | type ConsumerConfigResponse = typeof ConsumerConfigResponseSchema.Type; |
| 121 | const decodeCacheShell = Schema.decodeUnknownOption( |
| 122 | Schema.fromJsonString( |
| 123 | Schema.Struct({ |
| 124 | entries: Schema.optional(JsonRecordSchema), |
| 125 | allowEntries: Schema.optional(JsonRecordSchema), |
| 126 | }) |
| 127 | ) |
| 128 | ); |
| 129 | const decodeSnapshotEntry = Schema.decodeUnknownOption(ConsumerPermissionSnapshotSchema); |
| 130 | const decodeAllowEntry = Schema.decodeUnknownOption(CachedAllowDecisionSchema); |
| 131 | |
| 132 | // Per-entry decode: one stale or version-skewed entry drops only itself. |
| 133 | // Discarding the whole file would also wipe all cached allow decisions and |
| 134 | // be persisted back on the next write. |
| 135 | export const decodeCacheFileTolerant = (raw: string): CacheFile => |
| 136 | Option.match(decodeCacheShell(raw), { |
| 137 | onNone: (): CacheFile => ({ entries: {} }), |
| 138 | onSome: shell => ({ |
| 139 | entries: collectDecodedEntries(shell.entries, decodeSnapshotEntry), |
| 140 | allowEntries: collectDecodedEntries(shell.allowEntries, decodeAllowEntry), |
| 141 | }), |
| 142 | }); |
| 143 | |
| 144 | export class ToolPermissionDeniedError extends Data.TaggedError( |
| 145 | 'services/ToolPermissionDeniedError' |
| 146 | )<{ |
| 147 | readonly toolSlug: string; |
| 148 | readonly deniedBy: 'permissions' | 'user'; |
| 149 | readonly message: string; |
| 150 | }> {} |
| 151 | |
| 152 | export class ToolPermissionsRequestError extends Data.TaggedError( |
| 153 | 'services/ToolPermissionsRequestError' |
| 154 | )<{ |
| 155 | readonly path: string; |
| 156 | readonly message: string; |
| 157 | readonly cause: unknown; |
| 158 | }> {} |
| 159 | |
| 160 | export class ToolPermissionsCacheError extends Data.TaggedError( |
| 161 | 'services/ToolPermissionsCacheError' |
| 162 | )<{ |
| 163 | readonly operation: 'read' | 'write'; |
| 164 | readonly message: string; |
| 165 | readonly cause: unknown; |
| 166 | }> {} |
| 167 | |
| 168 | export class ToolPermissionPromptError extends Data.TaggedError( |
| 169 | 'services/ToolPermissionPromptError' |
| 170 | )<{ |
| 171 | readonly toolSlug: string; |
| 172 | readonly message: string; |
| 173 | readonly cause: unknown; |
| 174 | }> {} |
| 175 | |
| 176 | interface GateParams { |
| 177 | readonly toolSlug: string; |
| 178 | readonly connectedAccountId?: string; |
| 179 | readonly connectedAccountWordId?: string; |
| 180 | readonly snapshot?: ConsumerPermissionSnapshot; |
| 181 | } |
| 182 | |
| 183 | const allowDecisionMemoryCache = new Map<string, number>(); |
| 184 | |
| 185 | const cachePath = (path: Path.Path, cacheDirectory: string) => |
| 186 | path.join(cacheDirectory, CACHE_FILE_NAME); |
| 187 | const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) => |
| 188 | [params.orgId, params.projectId, params.consumerUserId].join(':'); |
| 189 | |
| 190 | const uniq = (values: ReadonlyArray<string | undefined>) => [ |
| 191 | ...new Set(values.filter((value): value is string => Boolean(value))), |
| 192 | ]; |
| 193 | |
| 194 | const pruneAllowEntries = ( |
| 195 | entries: Readonly<Record<string, CachedAllowDecision>> | undefined, |
| 196 | now = Date.now() |
| 197 | ): Record<string, CachedAllowDecision> => |
| 198 | EffectRecord.filter( |
| 199 | entries ?? {}, |
| 200 | entry => typeof entry.expiresAt === 'number' && entry.expiresAt > now |
| 201 | ); |
| 202 | |
| 203 | // A missing or unreadable cache file degrades to an empty cache. |
| 204 | const readCacheFile = ( |
| 205 | fs: FileSystem.FileSystem, |
| 206 | path: Path.Path, |
| 207 | cacheDirectory: string |
| 208 | ): Effect.Effect<CacheFile> => |
| 209 | fs.readFileString(cachePath(path, cacheDirectory)).pipe( |
| 210 | Effect.map((raw): CacheFile => { |
| 211 | const parsed = decodeCacheFileTolerant(raw); |
| 212 | return { |
| 213 | entries: parsed.entries, |
| 214 | allowEntries: pruneAllowEntries(parsed.allowEntries), |
| 215 | }; |
| 216 | }), |
| 217 | Effect.orElseSucceed((): CacheFile => ({ entries: {} })) |
| 218 | ); |
| 219 | |
| 220 | const writeCacheFile = ( |
| 221 | fs: FileSystem.FileSystem, |
| 222 | path: Path.Path, |
| 223 | cacheDirectory: string, |
| 224 | cache: CacheFile |
| 225 | ) => |
| 226 | Effect.gen(function* () { |
| 227 | const targetPath = cachePath(path, cacheDirectory); |
| 228 | yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true }); |
| 229 | |
| 230 | // Atomic write: on failure the temp file is dropped (best effort) and the |
| 231 | // original error is surfaced. |
| 232 | yield* atomicWriteFileString({ |
| 233 | fs, |
| 234 | target: targetPath, |
| 235 | contents: `${JSON.stringify( |
| 236 | { |
| 237 | entries: cache.entries, |
| 238 | allowEntries: pruneAllowEntries(cache.allowEntries), |
| 239 | } satisfies CacheFile, |
| 240 | null, |
| 241 | 2 |
| 242 | )}\n`, |
| 243 | }); |
| 244 | }); |
| 245 | |
| 246 | // Serializes the read-modify-write cycles on the cache file so concurrent |
| 247 | // writers cannot interleave (the same role the previous promise write queue |
| 248 | // played for the plain async helpers). |
| 249 | const cacheWriteSemaphore = Semaphore.makeUnsafe(1); |
| 250 | |
| 251 | const updateCacheFile = ( |
| 252 | fs: FileSystem.FileSystem, |
| 253 | path: Path.Path, |
| 254 | cacheDirectory: string, |
| 255 | update: (current: CacheFile) => CacheFile |
| 256 | ) => |
| 257 | cacheWriteSemaphore.withPermits(1)( |
| 258 | readCacheFile(fs, path, cacheDirectory).pipe( |
| 259 | Effect.flatMap(current => writeCacheFile(fs, path, cacheDirectory, update(current))) |
| 260 | ) |
| 261 | ); |
| 262 | |
| 263 | const writeCacheEntry = ( |
| 264 | fs: FileSystem.FileSystem, |
| 265 | path: Path.Path, |
| 266 | cacheDirectory: string, |
| 267 | entry: ConsumerPermissionSnapshot |
| 268 | ) => |
| 269 | updateCacheFile(fs, path, cacheDirectory, current => ({ |
| 270 | entries: { |
| 271 | ...current.entries, |
| 272 | [cacheKey(entry)]: entry, |
| 273 | }, |
| 274 | allowEntries: current.allowEntries, |
| 275 | })); |
| 276 | |
| 277 | const readCachedEntry = ( |
| 278 | fs: FileSystem.FileSystem, |
| 279 | path: Path.Path, |
| 280 | cacheDirectory: string, |
| 281 | params: { |
| 282 | orgId: string; |
| 283 | projectId: string; |
| 284 | consumerUserId: string; |
| 285 | } |
| 286 | ): Effect.Effect<ConsumerPermissionSnapshot | undefined> => |
| 287 | readCacheFile(fs, path, cacheDirectory).pipe( |
| 288 | Effect.map(cache => cache.entries[cacheKey(params)]) |
| 289 | ); |
| 290 | |
| 291 | const isFreshForAccounts = ( |
| 292 | entry: ConsumerPermissionSnapshot | undefined, |
| 293 | connectedAccountIds: ReadonlyArray<string> |
| 294 | ): entry is ConsumerPermissionSnapshot => { |
| 295 | if (!entry) return false; |
| 296 | if (Date.now() - entry.fetchedAt > PERMISSION_SNAPSHOT_CACHE_TTL_MS) return false; |
| 297 | const cachedIds = new Set(entry.connectedAccountIds); |
| 298 | return connectedAccountIds.every(id => cachedIds.has(id)); |
| 299 | }; |
| 300 | |
| 301 | const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean => |
| 302 | payload.enhanced_controls === true; |
| 303 | |
| 304 | // The responses are decoded with the CLI's schemas, not the client's: an |
| 305 | // unknown permission mode decodes to its safe equivalent instead of failing |
| 306 | // the whole policy. Every failure, of the request or of the decode, is a |
| 307 | // `ToolPermissionsRequestError`: the callers fail closed on that tag. |
| 308 | const decodeResponse = |
| 309 | <S extends Schema.ConstraintDecoder<unknown>>( |
| 310 | responseSchema: S, |
| 311 | { path, message }: { readonly path: string; readonly message: string } |
| 312 | ) => |
| 313 | <E>(request: Effect.Effect<unknown, E>): Effect.Effect<S['Type'], ToolPermissionsRequestError> => |
| 314 | request.pipe( |
| 315 | Effect.flatMap(Schema.decodeUnknownEffect(responseSchema)), |
| 316 | Effect.mapError(cause => new ToolPermissionsRequestError({ path, message, cause })) |
| 317 | ); |
| 318 | |
| 319 | /** |
| 320 | * The client for the caller's org and project, with a failure the permission |
| 321 | * paths already recover from. |
| 322 | */ |
| 323 | const permissionsClient = (params: { |
| 324 | readonly apiKey: string; |
| 325 | readonly orgId: string; |
| 326 | readonly projectId: string; |
| 327 | readonly path: string; |
| 328 | }): Effect.Effect<ComposioClientShape, ToolPermissionsRequestError, ComposioClientSingleton> => |
| 329 | Effect.gen(function* () { |
| 330 | const clientSingleton = yield* ComposioClientSingleton; |
| 331 | return yield* clientSingleton |
| 332 | .getFor({ |
| 333 | userApiKey: params.apiKey, |
| 334 | orgId: params.orgId, |
| 335 | projectId: params.projectId, |
| 336 | }) |
| 337 | .pipe( |
| 338 | Effect.mapError( |
| 339 | (cause: ClientError) => |
| 340 | new ToolPermissionsRequestError({ |
| 341 | path: params.path, |
| 342 | message: 'Failed to build a Composio client for the consumer permission request.', |
| 343 | cause, |
| 344 | }) |
| 345 | ) |
| 346 | ); |
| 347 | }); |
| 348 | |
| 349 | const fetchConsumerConfig = (client: ComposioClientShape) => |
| 350 | client._internal.org.consumer.retrieveConfig(idempotent).pipe( |
| 351 | decodeResponse(ConsumerConfigResponseSchema, { |
| 352 | path: ORG_CONSUMER_CONFIG_PATH, |
| 353 | message: 'Failed to fetch the org consumer config.', |
| 354 | }) |
| 355 | ); |
| 356 | |
| 357 | // A read, though it is a POST, so it is retried like one. |
| 358 | const resolveConsumerPermissions = (client: ComposioClientShape, connectedAccountIds: string[]) => |
| 359 | client._internal.consumer.permissions |
| 360 | .resolve({ connected_account_ids: connectedAccountIds, default: 'ask_every_call' }, idempotent) |
| 361 | .pipe( |
| 362 | decodeResponse(PermissionResolveResponseSchema, { |
| 363 | path: CONSUMER_PERMISSIONS_RESOLVE_PATH, |
| 364 | message: 'Failed to resolve consumer permissions.', |
| 365 | }) |
| 366 | ); |
| 367 | |
| 368 | export const refreshConsumerPermissionSnapshot = (params: { |
| 369 | readonly orgId: string; |
| 370 | readonly projectId: string; |
| 371 | readonly consumerUserId: string; |
| 372 | readonly connectedAccountIds?: ReadonlyArray<string>; |
| 373 | }) => |
| 374 | Effect.gen(function* () { |
| 375 | const fs = yield* FileSystem.FileSystem; |
| 376 | const path = yield* Path.Path; |
| 377 | const cacheDirectory = yield* setupCacheDir; |
| 378 | const userContext = yield* ComposioUserContext; |
| 379 | const apiKey = Option.getOrUndefined(userContext.data.apiKey); |
| 380 | if (!apiKey) return undefined; |
| 381 | |
| 382 | const connectedAccountIds = uniq(params.connectedAccountIds ?? []); |
| 383 | const client = yield* permissionsClient({ |
| 384 | apiKey, |
| 385 | orgId: params.orgId, |
| 386 | projectId: params.projectId, |
| 387 | path: ORG_CONSUMER_CONFIG_PATH, |
| 388 | }); |
| 389 | const config = yield* fetchConsumerConfig(client); |
| 390 | const platformSupportsEnhancedControls = isEnhancedControlsPlatformSupported(); |
| 391 | const remoteEnhancedControlsEnabled = readEnhancedControlsFlag(config); |
| 392 | if (remoteEnhancedControlsEnabled && !platformSupportsEnhancedControls) { |
| 393 | yield* Effect.logDebug( |
| 394 | 'Enhanced controls are not supported on darwin-x64; disabling locally.' |
| 395 | ); |
| 396 | } |
| 397 | const enhancedControlsEnabled = |
| 398 | remoteEnhancedControlsEnabled && platformSupportsEnhancedControls; |
| 399 | const resolved = |
| 400 | enhancedControlsEnabled && connectedAccountIds.length > 0 |
| 401 | ? yield* resolveConsumerPermissions(client, connectedAccountIds).pipe( |
| 402 | Effect.map(response => ({ |
| 403 | permissions: response.experimental?.permissions, |
| 404 | resolveFailed: false, |
| 405 | })), |
| 406 | // The org said enhanced controls are ON but the policy could not |
| 407 | // be learned: fail closed to the interactive default instead of |
| 408 | // silently allowing tools the policy may explicitly deny. |
| 409 | Effect.catchTag('services/ToolPermissionsRequestError', error => |
| 410 | Effect.logDebug( |
| 411 | 'Failed to resolve consumer permissions; failing closed to ask_every_call', |
| 412 | error |
| 413 | ).pipe( |
| 414 | Effect.as({ |
| 415 | permissions: { default: 'ask_every_call' } as ToolRouterPermissionsConfig, |
| 416 | resolveFailed: true, |
| 417 | }) |
| 418 | ) |
| 419 | ) |
| 420 | ) |
| 421 | : { permissions: undefined, resolveFailed: false }; |
| 422 | |
| 423 | const snapshot: ConsumerPermissionSnapshot = { |
| 424 | orgId: params.orgId, |
| 425 | projectId: params.projectId, |
| 426 | consumerUserId: params.consumerUserId, |
| 427 | enhancedControlsEnabled, |
| 428 | permissions: resolved.permissions, |
| 429 | connectedAccountIds, |
| 430 | fetchedAt: Date.now(), |
| 431 | }; |
| 432 | // A fail-closed snapshot is not persisted, so a healthy fetch replaces it |
| 433 | // on the next command instead of pinning ask_every_call for the TTL. |
| 434 | if (!resolved.resolveFailed) { |
| 435 | yield* writeCacheEntry(fs, path, cacheDirectory, snapshot).pipe( |
| 436 | Effect.catch(cause => |
| 437 | Effect.logDebug( |
| 438 | 'Failed to write the tool permissions cache', |
| 439 | new ToolPermissionsCacheError({ |
| 440 | operation: 'write', |
| 441 | message: 'Failed to write the tool permissions cache.', |
| 442 | cause, |
| 443 | }) |
| 444 | ) |
| 445 | ) |
| 446 | ); |
| 447 | } |
| 448 | return snapshot; |
| 449 | }).pipe( |
| 450 | Effect.catchTag('services/ToolPermissionsRequestError', error => |
| 451 | Effect.gen(function* () { |
| 452 | yield* Effect.logDebug('Failed to refresh consumer permission cache', error); |
| 453 | return undefined; |
| 454 | }) |
| 455 | ) |
| 456 | ); |
| 457 | |
| 458 | export const getConsumerPermissionSnapshot = (params: { |
| 459 | readonly orgId: string; |
| 460 | readonly projectId: string; |
| 461 | readonly consumerUserId: string; |
| 462 | readonly connectedAccountIds?: ReadonlyArray<string>; |
| 463 | }) => |
| 464 | Effect.gen(function* () { |
| 465 | const fs = yield* FileSystem.FileSystem; |
| 466 | const path = yield* Path.Path; |
| 467 | const cacheDirectory = yield* setupCacheDir; |
| 468 | const connectedAccountIds = uniq(params.connectedAccountIds ?? []); |
| 469 | // Read failures are absorbed inside readCacheFile (empty cache), so an |
| 470 | // unreadable cache file behaves exactly like a cache miss here. |
| 471 | const cached = yield* readCachedEntry(fs, path, cacheDirectory, params); |
| 472 | |
| 473 | if (isFreshForAccounts(cached, connectedAccountIds)) { |
| 474 | yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe( |
| 475 | Effect.forkDetach, |
| 476 | Effect.catch(() => Effect.void) |
| 477 | ); |
| 478 | return cached; |
| 479 | } |
| 480 | |
| 481 | const refreshed = yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }); |
| 482 | return refreshed ?? cached; |
| 483 | }); |
| 484 | |
| 485 | const permissionField = (toolSlug: string, connectedAccountId?: string) => |
| 486 | `${toolSlug}:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`; |
| 487 | const accountPermissionField = (connectedAccountId?: string) => |
| 488 | `*:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`; |
| 489 | |
| 490 | export const getOrgEnhancedControlsStatus = (params: { |
| 491 | readonly orgId: string; |
| 492 | readonly projectId: string; |
| 493 | }) => |
| 494 | Effect.gen(function* () { |
| 495 | const userContext = yield* ComposioUserContext; |
| 496 | const apiKey = Option.getOrUndefined(userContext.data.apiKey); |
| 497 | if (!apiKey) return undefined; |
| 498 | |
| 499 | const client = yield* permissionsClient({ |
| 500 | apiKey, |
| 501 | orgId: params.orgId, |
| 502 | projectId: params.projectId, |
| 503 | path: ORG_CONSUMER_CONFIG_PATH, |
| 504 | }); |
| 505 | const config = yield* fetchConsumerConfig(client); |
| 506 | const remoteEnabled = readEnhancedControlsFlag(config); |
| 507 | const platformSupported = isEnhancedControlsPlatformSupported(); |
| 508 | return { |
| 509 | enabled: remoteEnabled && platformSupported, |
| 510 | remoteEnabled, |
| 511 | platformSupported, |
| 512 | }; |
| 513 | }).pipe( |
| 514 | Effect.catchTag('services/ToolPermissionsRequestError', error => |
| 515 | Effect.gen(function* () { |
| 516 | yield* Effect.logDebug('Failed to read enhanced controls status', error); |
| 517 | return undefined; |
| 518 | }) |
| 519 | ) |
| 520 | ); |
| 521 | |
| 522 | export const getConnectedAccountPermissionGroup = (params: { |
| 523 | readonly snapshot?: ConsumerPermissionSnapshot; |
| 524 | readonly connectedAccountId?: string; |
| 525 | }): PermissionOverrideState | PermissionDefaultMode | undefined => { |
| 526 | if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return undefined; |
| 527 | return ( |
| 528 | params.snapshot.permissions.overrides?.[accountPermissionField(params.connectedAccountId)] ?? |
| 529 | params.snapshot.permissions.default ?? |
| 530 | 'allow_all' |
| 531 | ); |
| 532 | }; |
| 533 | |
| 534 | const resolvePermissionState = ( |
| 535 | params: GateParams & { readonly snapshot: ConsumerPermissionSnapshot } |
| 536 | ): PermissionOverrideState | PermissionDefaultMode => { |
| 537 | const permissions = params.snapshot.permissions; |
| 538 | const override = |
| 539 | permissions?.overrides?.[permissionField(params.toolSlug, params.connectedAccountId)] ?? |
| 540 | permissions?.overrides?.[accountPermissionField(params.connectedAccountId)]; |
| 541 | return override ?? permissions?.default ?? 'allow_all'; |
| 542 | }; |
| 543 | |
| 544 | // The gate's decision table: 'skip' means gating does not apply (developer |
| 545 | // mode, or controls known disabled). A snapshot synthesized from a failed |
| 546 | // permission resolve carries default: 'ask_every_call' and therefore prompts. |
| 547 | export const resolveGateState = ( |
| 548 | params: GateParams |
| 549 | ): PermissionOverrideState | PermissionDefaultMode | 'skip' => { |
| 550 | if (params.snapshot === undefined) return 'skip'; |
| 551 | if (!params.snapshot.enhancedControlsEnabled || !params.snapshot.permissions) return 'skip'; |
| 552 | return resolvePermissionState({ ...params, snapshot: params.snapshot }); |
| 553 | }; |
| 554 | |
| 555 | const allowCacheKey = (params: GateParams) => |
| 556 | `${params.snapshot?.orgId ?? 'unknown'}:${params.snapshot?.projectId ?? 'unknown'}:${params.snapshot?.consumerUserId ?? 'unknown'}:${permissionField(params.toolSlug, params.connectedAccountId)}`; |
| 557 | |
| 558 | const isAllowCachedInMemory = (cacheKey: string, now = Date.now()): boolean => { |
| 559 | const expiresAt = allowDecisionMemoryCache.get(cacheKey); |
| 560 | if (expiresAt === undefined) return false; |
| 561 | if (expiresAt <= now) { |
| 562 | allowDecisionMemoryCache.delete(cacheKey); |
| 563 | return false; |
| 564 | } |
| 565 | return true; |
| 566 | }; |
| 567 | |
| 568 | const isAllowCached = ( |
| 569 | fs: FileSystem.FileSystem, |
| 570 | path: Path.Path, |
| 571 | cacheDirectory: string, |
| 572 | cacheKey: string, |
| 573 | now = Date.now() |
| 574 | ): Effect.Effect<boolean> => |
| 575 | Effect.suspend(() => { |
| 576 | if (isAllowCachedInMemory(cacheKey, now)) return Effect.succeed(true); |
| 577 | |
| 578 | return readCacheFile(fs, path, cacheDirectory).pipe( |
| 579 | Effect.map(cache => { |
| 580 | const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt; |
| 581 | if (expiresAt === undefined || expiresAt <= now) return false; |
| 582 | |
| 583 | allowDecisionMemoryCache.set(cacheKey, expiresAt); |
| 584 | return true; |
| 585 | }) |
| 586 | ); |
| 587 | }); |
| 588 | |
| 589 | const cacheAllowDecision = ( |
| 590 | fs: FileSystem.FileSystem, |
| 591 | path: Path.Path, |
| 592 | cacheDirectory: string, |
| 593 | cacheKey: string, |
| 594 | now = Date.now() |
| 595 | ) => |
| 596 | Effect.suspend(() => { |
| 597 | const expiresAt = now + ALLOW_FOR_DURATION_MS; |
| 598 | allowDecisionMemoryCache.set(cacheKey, expiresAt); |
| 599 | |
| 600 | return updateCacheFile(fs, path, cacheDirectory, current => ({ |
| 601 | entries: current.entries, |
| 602 | allowEntries: { |
| 603 | ...current.allowEntries, |
| 604 | [cacheKey]: { expiresAt }, |
| 605 | }, |
| 606 | })); |
| 607 | }); |
| 608 | |
| 609 | const escapeHtml = (value: string): string => |
| 610 | value.replace(/[&<>"']/g, char => { |
| 611 | switch (char) { |
| 612 | case '&': |
| 613 | return '&'; |
| 614 | case '<': |
| 615 | return '<'; |
| 616 | case '>': |
| 617 | return '>'; |
| 618 | case '"': |
| 619 | return '"'; |
| 620 | default: |
| 621 | return '''; |
| 622 | } |
| 623 | }); |
| 624 | |
| 625 | // Agent glyphs shown next to the caller agent's name on the approval page. |
| 626 | const AGENT_SVGS: Readonly<Record<PermissionCallerAgent, string>> = { |
| 627 | composio: `<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_2367_5)"><path d="M91.7032 28.1801L35.3611 16.6572C31.6669 15.8988 28.1929 18.7367 28.1929 22.5043V49.1954V50.6144V77.3052C28.1929 81.0729 31.6669 83.9112 35.3611 83.1526L91.7032 71.6296" stroke="black" stroke-width="2.8556" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M48.1992 7.38531C48.1993 2.09223 53.6097 -1.44765 58.4546 0.57874L58.6851 0.679333L58.6902 0.68227L88.8308 14.6023C91.4759 15.7947 93.1338 18.4366 93.1346 21.3053V33.0975C93.1346 37.3994 89.4707 40.797 85.1902 40.4658L51.0547 37.918V61.8914L85.185 59.3435L85.585 59.323C89.6842 59.2231 93.1331 62.5334 93.109 66.6876V78.4797C93.109 81.3707 91.4075 83.9737 88.8105 85.1812L88.806 85.1827L58.691 99.0774L58.6917 99.0782C53.7808 101.351 48.1992 97.7714 48.1992 92.3759V81.1383C47.9779 81.2256 47.741 81.2834 47.4921 81.3015L30.8347 82.5007C29.4429 82.6007 28.2584 81.4977 28.2582 80.1023V67.7354C28.2583 67.256 28.4014 66.8063 28.6474 66.4277L14.9439 67.4513H14.9388C10.6701 67.7539 7.00001 64.3671 7 60.0823V39.7271C7.00031 35.4239 10.6671 32.0248 14.9491 32.3589H14.9483L28.3486 33.3589C28.2905 33.152 28.2583 32.9345 28.2582 32.7099V19.6826C28.2582 17.7807 29.9597 16.3299 31.8377 16.6304L47.6992 19.168C47.8735 19.1959 48.0404 19.2435 48.1992 19.3059V7.38531ZM85.4075 62.191H85.4023L51.0547 64.755V79.6601L90.2541 71.4669V66.6774L90.2496 66.435C90.1323 63.9438 87.9489 61.9928 85.4075 62.191ZM27.7075 36.1748C27.9471 36.5495 28.0863 36.9936 28.0864 37.4678V62.7813C28.0864 63.0748 28.0314 63.3559 27.9344 63.6169L48.1992 62.1044V37.7043L27.7075 36.1748ZM51.0547 35.0544L85.4023 37.6183L85.4075 37.6191L85.6511 37.6316C88.1632 37.6928 90.279 35.6595 90.279 33.0975V28.1405L51.0547 19.9411V35.0544Z" fill="black"/></g><defs><clipPath id="clip0_2367_5"><rect width="86.4662" height="100" fill="white" transform="translate(7)"/></clipPath></defs></svg>`, |
| 628 | claude: `<svg preserveAspectRatio="xMidYMid" viewBox="0 0 256 257" xmlns="http://www.w3.org/2000/svg"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"/></svg>`, |
| 629 | codex: `<svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z" fill="url(#lobe-icons-codex-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-codex-_R_0_" x1="12" x2="12" y1="3" y2="21"><stop stop-color="#B1A7FF"></stop><stop offset=".5" stop-color="#7A9DFF"></stop><stop offset="1" stop-color="#3941FF"></stop></linearGradient></defs></svg>`, |
| 630 | openclaw: `<svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="openclaw__lobster-gradient" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#ff4d4d"/><stop offset="100%" stop-color="#991b1b"/></linearGradient></defs><path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" fill="url(#openclaw__lobster-gradient)"/><path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" fill="url(#openclaw__lobster-gradient)"/><path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" fill="url(#openclaw__lobster-gradient)"/><path d="M45 15 Q35 5 30 8" stroke="#ff4d4d" stroke-width="3" stroke-linecap="round"/><path d="M75 15 Q85 5 90 8" stroke="#ff4d4d" stroke-width="3" stroke-linecap="round"/><circle cx="45" cy="35" r="6" fill="#050810"/><circle cx="75" cy="35" r="6" fill="#050810"/><circle cx="46" cy="34" r="2.5" fill="#00e5cc"/><circle cx="76" cy="34" r="2.5" fill="#00e5cc"/></svg>`, |
| 631 | }; |
| 632 | |
| 633 | const AGENT_DISPLAY_NAMES: Readonly<Record<PermissionCallerAgent, string>> = { |
| 634 | composio: 'Composio', |
| 635 | claude: 'Claude', |
| 636 | codex: 'Codex', |
| 637 | openclaw: 'OpenClaw', |
| 638 | }; |
| 639 | |
| 640 | // 8x8 Bayer matrix encoded as a tiny SVG for an ordered-dither texture. |
| 641 | // Tiled across the card as a multiply-blended background. |
| 642 | const DITHER_SVG = `<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8'><g fill='%23000' fill-opacity='0.10'>${[ |
| 643 | [0, 0], |
| 644 | [4, 0], |
| 645 | [1, 0], |
| 646 | [5, 0], |
| 647 | [6, 1], |
| 648 | [2, 1], |
| 649 | [7, 1], |
| 650 | [3, 1], |
| 651 | [1, 2], |
| 652 | [5, 2], |
| 653 | [0, 2], |
| 654 | [4, 2], |
| 655 | [7, 3], |
| 656 | [3, 3], |
| 657 | [6, 3], |
| 658 | [2, 3], |
| 659 | [0, 4], |
| 660 | [4, 4], |
| 661 | [1, 4], |
| 662 | [5, 5], |
| 663 | [6, 5], |
| 664 | [2, 5], |
| 665 | [7, 5], |
| 666 | [3, 5], |
| 667 | [1, 6], |
| 668 | [5, 6], |
| 669 | [0, 6], |
| 670 | [4, 6], |
| 671 | [7, 7], |
| 672 | [3, 7], |
| 673 | [6, 7], |
| 674 | [2, 7], |
| 675 | ] |
| 676 | .map(([x, y]) => `<rect x='${x}' y='${y}' width='1' height='1'/>`) |
| 677 | .join('')}</g></svg>`; |
| 678 | const DITHER_DATA_URI = `url("data:image/svg+xml;utf8,${DITHER_SVG}")`; |
| 679 | |
| 680 | const approvalHtml = (params: { |
| 681 | toolSlug: string; |
| 682 | accountLabel?: string; |
| 683 | token: string; |
| 684 | agent: PermissionCallerAgent; |
| 685 | }) => { |
| 686 | const toolSlug = escapeHtml(params.toolSlug); |
| 687 | const account = escapeHtml(params.accountLabel ?? 'default connection'); |
| 688 | const token = encodeURIComponent(params.token); |
| 689 | const agent = params.agent; |
| 690 | const agentName = AGENT_DISPLAY_NAMES[agent]; |
| 691 | const agentSvg = AGENT_SVGS[agent]; |
| 692 | // "AGENT wants to use TOOL" when an agent is detected; otherwise |
| 693 | // "The composio cli wants to execute TOOL". |
| 694 | const titleBody = |
| 695 | agent === 'composio' |
| 696 | ? `The composio cli wants to execute <code>${toolSlug}</code>` |
| 697 | : `<span class="agent-mark" aria-label="${agentName}">${agentSvg}</span><span class="agent-name">${agentName}</span> wants to use <code>${toolSlug}</code>`; |
| 698 | |
| 699 | return `<!doctype html> |
| 700 | <html lang="en"> |
| 701 | <head> |
| 702 | <meta charset="utf-8" /> |
| 703 | <meta name="viewport" content="width=device-width, initial-scale=1" /> |
| 704 | <title>Allow ${toolSlug}? · Composio CLI</title> |
| 705 | <style> |
| 706 | :root { |
| 707 | color-scheme: light; |
| 708 | --ink: #121212; |
| 709 | --muted: #666666; |
| 710 | --border: rgba(0, 0, 0, 0.10); |
| 711 | --card: rgba(255, 255, 255, 0.86); |
| 712 | --wash: rgba(255, 255, 255, 0.55); |
| 713 | --primary: #171717; |
| 714 | --primary-hover: #2e2e2e; |
| 715 | } |
| 716 | * { box-sizing: border-box; } |
| 717 | html, body { height: 100%; } |
| 718 | body { |
| 719 | margin: 0; |
| 720 | display: grid; |
| 721 | place-items: center; |
| 722 | padding: 24px; |
| 723 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif; |
| 724 | color: var(--ink); |
| 725 | background: #d8d8d8; |
| 726 | } |
| 727 | .card { |
| 728 | position: relative; |
| 729 | width: min(520px, calc(100vw - 32px)); |
| 730 | border: 1px solid var(--border); |
| 731 | border-radius: 16px; |
| 732 | overflow: hidden; |
| 733 | background: var(--card); |
| 734 | backdrop-filter: blur(12px); |
| 735 | box-shadow: |
| 736 | 0 1px 0 rgba(255, 255, 255, 0.6) inset, |
| 737 | 0 18px 50px rgba(0, 0, 0, 0.16), |
| 738 | 0 2px 6px rgba(0, 0, 0, 0.06); |
| 739 | } |
| 740 | /* Dithered Bayer pattern, multiplied beneath the wash. */ |
| 741 | .card::before { |
| 742 | content: ""; |
| 743 | position: absolute; |
| 744 | inset: 0; |
| 745 | background-image: ${DITHER_DATA_URI}; |
| 746 | background-size: 8px 8px; |
| 747 | mix-blend-mode: multiply; |
| 748 | opacity: 0.55; |
| 749 | pointer-events: none; |
| 750 | } |
| 751 | /* Diagonal sine-wave hint (162°), pale and soft. */ |
| 752 | .card::after { |
| 753 | content: ""; |
| 754 | position: absolute; |
| 755 | inset: -20%; |
| 756 | background: linear-gradient( |
| 757 | 108deg, |
| 758 | transparent 30%, |
| 759 | rgba(0, 0, 0, 0.07) 50%, |
| 760 | transparent 70% |
| 761 | ); |
| 762 | filter: blur(28px); |
| 763 | pointer-events: none; |
| 764 | } |
| 765 | .card > * { position: relative; z-index: 1; } |
| 766 | /* Translucent white wash that softens the dither beneath text. */ |
| 767 | .wash { |
| 768 | position: absolute; |
| 769 | inset: 0; |
| 770 | background: var(--wash); |
| 771 | pointer-events: none; |
| 772 | z-index: 0; |
| 773 | } |
| 774 | .body { |
| 775 | padding: 22px 22px 18px; |
| 776 | display: grid; |
| 777 | gap: 16px; |
| 778 | } |
| 779 | .title { |
| 780 | display: flex; |
| 781 | flex-wrap: wrap; |
| 782 | align-items: center; |
| 783 | gap: 6px 8px; |
| 784 | margin: 0; |
| 785 | font-size: 16px; |
| 786 | font-weight: 600; |
| 787 | letter-spacing: -0.2px; |
| 788 | line-height: 1.35; |
| 789 | color: var(--ink); |
| 790 | } |
| 791 | .agent-mark { |
| 792 | display: inline-flex; |
| 793 | width: 28px; |
| 794 | height: 28px; |
| 795 | align-items: center; |
| 796 | justify-content: center; |
| 797 | } |
| 798 | .agent-mark svg, .agent-mark img { width: 100%; height: 100%; display: block; } |
| 799 | .agent-name { font-weight: 600; } |
| 800 | .title code, .account code { |
| 801 | font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; |
| 802 | font-weight: 600; |
| 803 | font-size: 0.92em; |
| 804 | } |
| 805 | .account { |
| 806 | margin: 0; |
| 807 | font-size: 12.5px; |
| 808 | color: var(--muted); |
| 809 | letter-spacing: -0.1px; |
| 810 | } |
| 811 | .account code { |
| 812 | color: var(--ink); |
| 813 | font-weight: 600; |
| 814 | } |
| 815 | .row { |
| 816 | display: flex; |
| 817 | align-items: center; |
| 818 | justify-content: space-between; |
| 819 | gap: 12px; |
| 820 | margin-top: 20px; |
| 821 | } |
| 822 | .logo { |
| 823 | width: 32px; |
| 824 | height: 32px; |
| 825 | flex: none; |
| 826 | opacity: 0.85; |
| 827 | } |
| 828 | .logo svg { width: 100%; height: 100%; } |
| 829 | .actions { |
| 830 | display: flex; |
| 831 | gap: 8px; |
| 832 | flex-wrap: wrap; |
| 833 | justify-content: flex-end; |
| 834 | } |
| 835 | .btn { |
| 836 | appearance: none; |
| 837 | display: inline-flex; |
| 838 | align-items: center; |
| 839 | justify-content: center; |
| 840 | height: 30px; |
| 841 | padding: 0 14px; |
| 842 | border-radius: 8px; |
| 843 | border: 1px solid var(--border); |
| 844 | background: rgba(255, 255, 255, 0.55); |
| 845 | color: var(--ink); |
| 846 | font: 500 12.5px -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif; |
| 847 | letter-spacing: 0.1px; |
| 848 | text-decoration: none; |
| 849 | cursor: pointer; |
| 850 | transition: transform 120ms ease, background 120ms ease, box-shadow 120ms ease; |
| 851 | } |
| 852 | .btn:hover { background: rgba(255, 255, 255, 0.85); } |
| 853 | .btn:active { transform: scale(0.97); } |
| 854 | .btn.primary { |
| 855 | background: var(--primary); |
| 856 | color: #fff; |
| 857 | border-color: transparent; |
| 858 | box-shadow: 0 6px 18px rgba(0, 0, 0, 0); |
| 859 | } |
| 860 | .btn.primary:hover { |
| 861 | background: var(--primary-hover); |
| 862 | box-shadow: 0 8px 22px rgba(0, 0, 0, 0.18); |
| 863 | } |
| 864 | @media (max-width: 480px) { |
| 865 | .row { flex-direction: column; align-items: stretch; } |
| 866 | .actions { justify-content: stretch; } |
| 867 | .btn { flex: 1; } |
| 868 | } |
| 869 | </style> |
| 870 | </head> |
| 871 | <body> |
| 872 | <main class="card" aria-labelledby="approval-title"> |
| 873 | <div class="wash" aria-hidden="true"></div> |
| 874 | <div class="body"> |
| 875 | <h1 id="approval-title" class="title">${titleBody}</h1> |
| 876 | <p class="account">Account: <code>${account}</code></p> |
| 877 | <div class="row"> |
| 878 | <span class="logo" aria-hidden="true">${AGENT_SVGS.composio}</span> |
| 879 | <div class="actions"> |
| 880 | <a class="btn" href="/deny?token=${token}">Deny</a> |
| 881 | <a class="btn" href="/allow-session?token=${token}">Allow for ${ALLOW_FOR_DURATION_LABEL}</a> |
| 882 | <a class="btn primary" href="/allow-once?token=${token}">Allow once</a> |
| 883 | </div> |
| 884 | </div> |
| 885 | </div> |
| 886 | </main> |
| 887 | </body> |
| 888 | </html>`; |
| 889 | }; |
| 890 | |
| 891 | const COMPLETION_COPY: Readonly< |
| 892 | Record<PermissionDecision, { readonly title: string; readonly body: string }> |
| 893 | > = { |
| 894 | allow_once: { |
| 895 | title: 'Allowed once', |
| 896 | body: 'This tool call is going through now. We’ll ask again next time it’s used.', |
| 897 | }, |
| 898 | allow_session: { |
| 899 | title: `Allowed for ${ALLOW_FOR_DURATION_LABEL}`, |
| 900 | body: 'This tool can run again for the next hour without asking.', |
| 901 | }, |
| 902 | deny: { |
| 903 | title: 'Denied', |
| 904 | body: 'The tool call was blocked. The agent will be told it was denied and can try something else.', |
| 905 | }, |
| 906 | }; |
| 907 | |
| 908 | const DECISION_BY_APPROVAL_PATH: ReadonlyMap<string, PermissionDecision> = new Map([ |
| 909 | ['/allow-session', 'allow_session'], |
| 910 | ['/allow-once', 'allow_once'], |
| 911 | ['/deny', 'deny'], |
| 912 | ]); |
| 913 | |
| 914 | const completionHtml = (decision: PermissionDecision) => { |
| 915 | const { title, body } = COMPLETION_COPY[decision]; |
| 916 | return `<!doctype html> |
| 917 | <html lang="en"> |
| 918 | <head> |
| 919 | <meta charset="utf-8" /> |
| 920 | <meta name="viewport" content="width=device-width, initial-scale=1" /> |
| 921 | <title>${title} · Composio CLI</title> |
| 922 | <style> |
| 923 | body { |
| 924 | margin: 0; |
| 925 | min-height: 100vh; |
| 926 | display: grid; |
| 927 | place-items: center; |
| 928 | padding: 24px; |
| 929 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif; |
| 930 | background: #d8d8d8; |
| 931 | color: #121212; |
| 932 | } |
| 933 | main { |
| 934 | width: min(420px, calc(100vw - 32px)); |
| 935 | border: 1px solid rgba(0, 0, 0, 0.10); |
| 936 | border-radius: 16px; |
| 937 | background: rgba(255, 255, 255, 0.86); |
| 938 | backdrop-filter: blur(12px); |
| 939 | padding: 22px; |
| 940 | box-shadow: 0 18px 50px rgba(0, 0, 0, 0.12); |
| 941 | } |
| 942 | .logo { display: block; width: 26px; height: 26px; margin-bottom: 14px; opacity: 0.85; } |
| 943 | .logo svg { width: 100%; height: 100%; display: block; } |
| 944 | h1 { margin: 0 0 6px; font-size: 16px; font-weight: 600; letter-spacing: -0.2px; } |
| 945 | p { margin: 0; font-size: 13px; line-height: 1.5; color: #555; } |
| 946 | .hint { margin-top: 14px; font-size: 12px; color: #888; } |
| 947 | </style> |
| 948 | </head> |
| 949 | <body> |
| 950 | <main> |
| 951 | <span class="logo" aria-hidden="true">${AGENT_SVGS.composio}</span> |
| 952 | <h1>${title}</h1> |
| 953 | <p>${body}</p> |
| 954 | <p class="hint">You can close this tab.</p> |
| 955 | </main> |
| 956 | </body> |
| 957 | </html>`; |
| 958 | }; |
| 959 | |
| 960 | const requestPermissionInBrowser = (params: { |
| 961 | readonly toolSlug: string; |
| 962 | readonly accountLabel?: string; |
| 963 | readonly agent: PermissionCallerAgent; |
| 964 | }): Promise<PermissionDecision> => |
| 965 | new Promise((resolve, reject) => { |
| 966 | const token = crypto.randomUUID(); |
| 967 | let settled = false; |
| 968 | |
| 969 | const settle = (decision: PermissionDecision) => { |
| 970 | if (settled) return; |
| 971 | settled = true; |
| 972 | server.close(); |
| 973 | resolve(decision); |
| 974 | }; |
| 975 | |
| 976 | const server = http.createServer((req, res) => { |
| 977 | const url = new URL(req.url ?? '/', 'http://127.0.0.1'); |
| 978 | if (url.searchParams.get('token') !== token) { |
| 979 | res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Forbidden'); |
| 980 | return; |
| 981 | } |
| 982 | |
| 983 | if (url.pathname === '/') { |
| 984 | res |
| 985 | .writeHead(200, { |
| 986 | 'Content-Type': 'text/html; charset=utf-8', |
| 987 | 'Cache-Control': 'no-store', |
| 988 | }) |
| 989 | .end(approvalHtml({ ...params, token })); |
| 990 | return; |
| 991 | } |
| 992 | |
| 993 | const decision = DECISION_BY_APPROVAL_PATH.get(url.pathname); |
| 994 | if (!decision) { |
| 995 | res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Not found'); |
| 996 | return; |
| 997 | } |
| 998 | |
| 999 | res |
| 1000 | .writeHead(200, { |
| 1001 | 'Content-Type': 'text/html; charset=utf-8', |
| 1002 | 'Cache-Control': 'no-store', |
| 1003 | }) |
| 1004 | .end(completionHtml(decision)); |
| 1005 | settle(decision); |
| 1006 | }); |
| 1007 | |
| 1008 | const timeout = setTimeout(() => settle('deny'), 30_000); |
| 1009 | |
| 1010 | server.on('close', () => clearTimeout(timeout)); |
| 1011 | server.on('error', error => { |
| 1012 | if (settled) return; |
| 1013 | settled = true; |
| 1014 | clearTimeout(timeout); |
| 1015 | reject(error); |
| 1016 | }); |
| 1017 | server.listen(0, '127.0.0.1', () => { |
| 1018 | const address = server.address(); |
| 1019 | const port = typeof address === 'object' && address ? address.port : undefined; |
| 1020 | if (!port) { |
| 1021 | server.close(); |
| 1022 | reject(new Error('Unable to allocate permission callback port.')); |
| 1023 | return; |
| 1024 | } |
| 1025 | |
| 1026 | void open(`http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`, { |
| 1027 | wait: false, |
| 1028 | }).catch(error => { |
| 1029 | server.close(); |
| 1030 | reject(error); |
| 1031 | }); |
| 1032 | }); |
| 1033 | }); |
| 1034 | |
| 1035 | const requestPermissionDecision = async (params: { |
| 1036 | readonly toolSlug: string; |
| 1037 | readonly accountLabel?: string; |
| 1038 | }): Promise<PermissionDecision> => { |
| 1039 | if (await Effect.runPromise(isInteractivePermissionUiDisabled)) { |
| 1040 | throw new Error( |
| 1041 | `Interactive permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI); cannot collect an approval for ${params.toolSlug}.` |
| 1042 | ); |
| 1043 | } |
| 1044 | |
| 1045 | return requestPermissionInBrowser({ ...params, agent: await detectPermissionCallerAgent() }); |
| 1046 | }; |
| 1047 | |
| 1048 | export const gateToolExecution = (params: GateParams) => |
| 1049 | Effect.gen(function* () { |
| 1050 | const state = resolveGateState(params); |
| 1051 | if (state === 'skip') return; |
| 1052 | |
| 1053 | if (state === 'allow_all' || state === 'always_allow') { |
| 1054 | return { approvalStatus: 'always_approved' } satisfies PermissionGateResult; |
| 1055 | } |
| 1056 | if (state === 'always_deny') { |
| 1057 | return yield* new ToolPermissionDeniedError({ |
| 1058 | toolSlug: params.toolSlug, |
| 1059 | deniedBy: 'permissions', |
| 1060 | message: `Tool execution denied by permissions: ${params.toolSlug}`, |
| 1061 | }); |
| 1062 | } |
| 1063 | |
| 1064 | const fs = yield* FileSystem.FileSystem; |
| 1065 | const path = yield* Path.Path; |
| 1066 | const cacheDirectory = yield* setupCacheDir; |
| 1067 | const cacheKey = allowCacheKey(params); |
| 1068 | // Read failures are absorbed inside readCacheFile (empty cache), so an |
| 1069 | // unreadable allow cache behaves exactly like "no cached allow decision". |
| 1070 | const hasCachedAllow = yield* isAllowCached(fs, path, cacheDirectory, cacheKey); |
| 1071 | if (hasCachedAllow) { |
| 1072 | return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult; |
| 1073 | } |
| 1074 | |
| 1075 | // Fail closed instead of spawning approval UI where nobody can answer it |
| 1076 | // (tests, CI). Cached allow decisions above still apply. |
| 1077 | if (yield* isInteractivePermissionUiDisabled) { |
| 1078 | return yield* new ToolPermissionDeniedError({ |
| 1079 | toolSlug: params.toolSlug, |
| 1080 | deniedBy: 'permissions', |
| 1081 | message: `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`, |
| 1082 | }); |
| 1083 | } |
| 1084 | |
| 1085 | const decision = yield* Effect.tryPromise({ |
| 1086 | try: () => |
| 1087 | requestPermissionDecision({ |
| 1088 | toolSlug: params.toolSlug, |
| 1089 | accountLabel: params.connectedAccountWordId, |
| 1090 | }), |
| 1091 | catch: cause => |
| 1092 | new ToolPermissionPromptError({ |
| 1093 | toolSlug: params.toolSlug, |
| 1094 | message: `Failed to collect a permission decision for: ${params.toolSlug}`, |
| 1095 | cause, |
| 1096 | }), |
| 1097 | }); |
| 1098 | |
| 1099 | if (decision === 'deny') { |
| 1100 | return yield* new ToolPermissionDeniedError({ |
| 1101 | toolSlug: params.toolSlug, |
| 1102 | deniedBy: 'user', |
| 1103 | message: `Tool execution denied by user: ${params.toolSlug}`, |
| 1104 | }); |
| 1105 | } |
| 1106 | const cachesAllowOnce = state === 'ask_once' || state === 'ask_once_per_session'; |
| 1107 | if (decision === 'allow_session' || (cachesAllowOnce && decision === 'allow_once')) { |
| 1108 | yield* cacheAllowDecision(fs, path, cacheDirectory, cacheKey).pipe( |
| 1109 | Effect.catch(cause => |
| 1110 | Effect.logDebug( |
| 1111 | 'Failed to cache tool permission allow decision', |
| 1112 | new ToolPermissionsCacheError({ |
| 1113 | operation: 'write', |
| 1114 | message: 'Failed to cache the tool permission allow decision.', |
| 1115 | cause, |
| 1116 | }) |
| 1117 | ) |
| 1118 | ) |
| 1119 | ); |
| 1120 | } |
| 1121 | |
| 1122 | return { |
| 1123 | approvalStatus: decision === 'allow_session' ? 'approved_for_session' : 'approved_once', |
| 1124 | } satisfies PermissionGateResult; |
| 1125 | }); |