Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(cli): add enhanced permission cache gating (#3419)
Rahul Tarakd6bf4370d7b8
diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex f6f8bbe6b..2d7a0d004 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -215,12 +215,14 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string) =>const getConsumerCacheScope = (resolvedProject: {readonly orgId: string;+ readonly projectId: string;readonly projectType: 'CONSUMER' | 'DEVELOPER';readonly consumerUserId?: string;}) =>resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId? {orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,consumerUserId: resolvedProject.consumerUserId,}: undefined;diff --git a/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts b/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.tsindex e413f8981..84d814833 100644--- a/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts+++ b/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts@@ -1,14 +1,9 @@import { Command, Options } from '@effect/cli';import { Effect, Option } from 'effect';import { spawn } from 'node:child_process';-import fs from 'node:fs';-import path from 'node:path';-import {- detectCliPlatform,- ensureBundledBinaryExecutable,- getLocalToolsBundleRootCandidates,-} from '@composio/cli-local-tools';+import { ensureBundledBinaryExecutable } from '@composio/cli-local-tools';import { TerminalUI } from 'src/services/terminal-ui';+import { resolveNativeUiBinary } from 'src/services/native-ui-sidecar';const title = Options.text('title').pipe(Options.withDefault('Composio'),@@ -29,34 +24,6 @@ const timeout = Options.optional(Options.text('timeout')).pipe(Options.withDescription('Optional auto-close timeout in seconds.'));-const NATIVE_UI_BINARY_NAME = 'composio-native-ui';--const resolveNativeUiBinary = () => {- const platform = detectCliPlatform();- if (!platform.startsWith('darwin-')) {- return {- _tag: 'unsupported' as const,- platform,- };- }-- const candidates = getLocalToolsBundleRootCandidates().map(root =>- path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)- );- const binaryPath = candidates.find(candidate => fs.existsSync(candidate));-- return binaryPath- ? {- _tag: 'found' as const,- binaryPath,- }- : {- _tag: 'missing' as const,- platform,- candidates,- };-};-export const devNativeUiCmd = Command.make('native-ui', { title, message, detail, timeout }).pipe(Command.withDescription('Open the experimental native macOS UI sidecar.'),Command.withHandler(({ title, message, detail, timeout }) =>diff --git a/ts/packages/cli/src/commands/proxy.cmd.ts b/ts/packages/cli/src/commands/proxy.cmd.tsindex 75d121f56..9ae0d4e89 100644--- a/ts/packages/cli/src/commands/proxy.cmd.ts+++ b/ts/packages/cli/src/commands/proxy.cmd.ts@@ -316,6 +316,7 @@ export const proxyCmd = Command.make('proxy', {toolkits: [normalizedToolkit],cacheScope: {orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,consumerUserId,},});diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.tsindex fc275ab34..67f010ddb 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts@@ -1107,6 +1107,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId? {orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,consumerUserId: resolvedProject.consumerUserId,}: undefined,diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.tsindex 844f04a21..8fc3c4a9d 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts@@ -363,6 +363,7 @@ const runToolsSearch = (params: {resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId? {orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,consumerUserId: resolvedProject.consumerUserId,}: undefined,diff --git a/ts/packages/cli/src/effects/create-tool-router-session.ts b/ts/packages/cli/src/effects/create-tool-router-session.tsindex 96b5686f2..ce3f76592 100644--- a/ts/packages/cli/src/effects/create-tool-router-session.ts+++ b/ts/packages/cli/src/effects/create-tool-router-session.ts@@ -9,9 +9,17 @@ import {getFreshConsumerToolRouterConnectedAccountsFromCache,writeConsumerConnectedToolkitsCache,} from 'src/services/consumer-short-term-cache';-import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';+import {+ resolveToolRouterSessionConnections,+ type ToolRouterSessionConnectionContext,+} from 'src/services/tool-router-session-connections';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';+import {+ ENHANCED_LINK_URL_OVERWRITE,+ getConsumerPermissionSnapshot,+ type ConsumerPermissionSnapshot,+} from 'src/services/tool-permissions';export interface CreateToolRouterSessionOptions {/** Enable auto connection management. Default: false. */@@ -21,6 +29,7 @@ export interface CreateToolRouterSessionOptions {/** Consumer-only cache scope for rolling auth-config reuse. */readonly cacheScope?: {readonly orgId: string;+ readonly projectId: string;readonly consumerUserId: string;};/** Explicit connected-account pins by toolkit slug. */@@ -43,6 +52,9 @@ export interface CreatedToolRouterSession {readonly sessionId: string;/** Inline local-tool custom definitions that should be forwarded to v3.1 search/execute calls. */readonly localExperimentalPayload?: ReturnType<typeof createLocalToolRouterExperimentalPayload>;+ readonly permissionSnapshot?: ConsumerPermissionSnapshot;+ readonly connectedAccounts?: Record<string, string>;+ readonly connectedAccountWordIds?: Record<string, string>;}/**@@ -100,6 +112,21 @@ export const createToolRouterSessionContext = ();return Object.keys(filtered).length > 0 ? filtered : undefined;};+ const resolveConnectedAccountWordIds = (+ selected: Record<string, string> | undefined,+ available: ToolRouterSessionConnectionContext['availableConnectedAccounts']+ ) => {+ if (!selected || !available) return undefined;+ const wordIds = Object.fromEntries(+ Object.entries(selected).flatMap(([toolkit, connectedAccountId]) => {+ const account = available[toolkit.toLowerCase()]?.find(+ item => item.id === connectedAccountId+ );+ return account?.wordId ? [[toolkit, account.wordId]] : [];+ })+ );+ return Object.keys(wordIds).length > 0 ? wordIds : undefined;+ };const cachedAuthConfigs = options?.cacheScope? yield* getFreshConsumerToolRouterAuthConfigsFromCache({@@ -159,6 +186,24 @@ export const createToolRouterSessionContext = (}).pipe(Effect.catchAll(() => Effect.void));}+ const connectedAccountIds = Object.values(connectionContext.connectedAccounts ?? {}).filter(+ (value): value is string => typeof value === 'string'+ );+ const permissionSnapshot = options?.cacheScope+ ? yield* getConsumerPermissionSnapshot({+ orgId: options.cacheScope.orgId,+ projectId: options.cacheScope.projectId,+ consumerUserId: options.cacheScope.consumerUserId,+ connectedAccountIds,+ })+ : undefined;+ const experimentalPayload = {+ ...(localExperimentalPayload ?? {}),+ ...(permissionSnapshot?.enhancedControlsEnabled+ ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }+ : {}),+ };+return yield* Effect.tryPromise(() =>client.toolRouter.session.create({user_id: userId,@@ -173,13 +218,19 @@ export const createToolRouterSessionContext = (}: undefined,toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,- experimental: localExperimentalPayload,+ experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,})).pipe(Effect.map((session): CreatedToolRouterSession => ({sessionId: session.session_id,localExperimentalPayload,+ permissionSnapshot,+ connectedAccounts: connectionContext.connectedAccounts,+ connectedAccountWordIds: resolveConnectedAccountWordIds(+ connectionContext.connectedAccounts,+ connectionContext.availableConnectedAccounts+ ),})));diff --git a/ts/packages/cli/src/services/native-ui-sidecar.ts b/ts/packages/cli/src/services/native-ui-sidecar.tsnew file mode 100644index 000000000..93cad71ef--- /dev/null+++ b/ts/packages/cli/src/services/native-ui-sidecar.ts@@ -0,0 +1,199 @@+import { execFileSync, spawn } from 'node:child_process';+import fsSync from 'node:fs';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import {+ detectCliPlatform,+ ensureBundledBinaryExecutable,+ getLocalToolsBundleRootCandidates,+} from '@composio/cli-local-tools';++const NATIVE_UI_BINARY_NAME = 'composio-native-ui';++export type NativeUiPermissionDecision = 'allow_once' | 'allow_session' | 'deny' | 'dismissed';+export type NativeUiCallerAgent = 'claude' | 'codex' | 'openclaw' | 'composio';++export type NativeUiBinaryResolution =+ | {+ readonly _tag: 'found';+ readonly binaryPath: string;+ }+ | {+ readonly _tag: 'missing';+ readonly platform: string;+ readonly candidates: ReadonlyArray<string>;+ }+ | {+ readonly _tag: 'unsupported';+ readonly platform: string;+ };++interface NativeUiDecisionPayload {+ readonly decision?: NativeUiPermissionDecision;+}++const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>+ Object.keys(env).some(key => key.startsWith(prefix));++const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {+ const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');+ if (normalized === 'claude' || normalized === 'codex' || normalized === 'openclaw') {+ return normalized;+ }+ return undefined;+};++const detectCallerAgentFromProcessTree = (): NativeUiCallerAgent | undefined => {+ if (process.platform === 'win32') return undefined;++ let pid = process.ppid;+ for (let depth = 0; depth < 8 && pid > 1; depth += 1) {+ try {+ const output = execFileSync('ps', ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ }).trim();+ if (!output) return undefined;++ const match = output.match(/^(\d+)\s+(.+)$/);+ if (!match) return undefined;++ const command = match[2]?.toLowerCase() ?? '';+ if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';+ if (command.includes('claude')) return 'claude';+ if (command.includes('codex')) return 'codex';++ pid = Number(match[1]);+ } catch {+ return undefined;+ }+ }++ return undefined;+};++export const detectNativeUiCallerAgent = (+ env: NodeJS.ProcessEnv = process.env+): NativeUiCallerAgent => {+ const explicit = normalizeCallerAgent(env.COMPOSIO_CALLER_AGENT ?? env.COMPOSIO_AGENT);+ if (explicit) return explicit;++ if (hasEnvPrefix(env, 'OPENCLAW_')) return 'openclaw';+ if (hasEnvPrefix(env, 'CLAUDE_')) return 'claude';+ if (hasEnvPrefix(env, 'CODEX_')) return 'codex';++ return detectCallerAgentFromProcessTree() ?? 'composio';+};++export const resolveNativeUiBinary = (): NativeUiBinaryResolution => {+ const platform = detectCliPlatform();+ if (!platform.startsWith('darwin-')) {+ return {+ _tag: 'unsupported',+ platform,+ };+ }++ const candidates = getLocalToolsBundleRootCandidates().map(root =>+ path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)+ );+ const binaryPath = candidates.find(candidate => fsSync.existsSync(candidate));++ return binaryPath+ ? {+ _tag: 'found',+ binaryPath,+ }+ : {+ _tag: 'missing',+ platform,+ candidates,+ };+};++const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefined => {+ const payload = JSON.parse(raw) as NativeUiDecisionPayload;+ const decision = payload.decision;+ return decision === 'allow_once' ||+ decision === 'allow_session' ||+ decision === 'deny' ||+ decision === 'dismissed'+ ? decision+ : undefined;+};++export const requestNativeUiPermissionDecision = async (params: {+ readonly toolSlug: string;+ readonly accountLabel?: string;+ readonly timeoutSeconds?: number;+}): Promise<NativeUiPermissionDecision | undefined> => {+ const resolved = resolveNativeUiBinary();+ if (resolved._tag !== 'found') return undefined;++ await ensureBundledBinaryExecutable(resolved.binaryPath);++ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-native-ui-decision-'));+ const callbackFile = path.join(tempDir, 'decision.json');+ const timeoutSeconds = params.timeoutSeconds ?? 30;++ try {+ return await new Promise<NativeUiPermissionDecision>((resolve, reject) => {+ const args = [+ '--tool',+ params.toolSlug,+ '--account',+ params.accountLabel ?? 'default connection',+ '--caller-agent',+ detectNativeUiCallerAgent(),+ '--subtitle',+ 'Composio CLI is requesting permission to execute this tool.',+ '--callback-file',+ callbackFile,+ '--timeout',+ String(timeoutSeconds),+ ];++ const child = spawn(resolved.binaryPath, args, {+ detached: false,+ stdio: 'ignore',+ });++ const timeout = setTimeout(+ () => {+ child.kill();+ resolve('dismissed');+ },+ (timeoutSeconds + 5) * 1000+ );++ child.on('error', error => {+ clearTimeout(timeout);+ reject(error);+ });++ child.on('exit', async code => {+ clearTimeout(timeout);+ try {+ const raw = await fs.readFile(callbackFile, 'utf8');+ const decision = parseDecisionPayload(raw);+ if (decision) {+ resolve(decision);+ return;+ }+ } catch {+ // If the sidecar exits without writing a callback file, treat a non-zero+ // exit as a dismissal. A zero exit without a callback is unexpected.+ }++ if (code === 0) {+ reject(new Error('Native permission prompt exited without a decision.'));+ } else {+ resolve('dismissed');+ }+ });+ });+ } finally {+ await fs.rm(tempDir, { recursive: true, force: true });+ }+};diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.tsnew file mode 100644index 000000000..0911d1c2e--- /dev/null+++ b/ts/packages/cli/src/services/tool-permissions.ts@@ -0,0 +1,398 @@+import http from 'node:http';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import open from 'open';+import { Effect, Option } from 'effect';+import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';+import { requestNativeUiPermissionDecision } from 'src/services/native-ui-sidecar';+import { ComposioUserContext } from 'src/services/user-context';++export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhanced';++const CACHE_FILE_NAME = 'tool-permissions-cache.json';+const CACHE_TTL_MS = 5 * 60 * 1000;+const NO_CONNECTED_ACCOUNT = '__none__';++export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_per_session';+export type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';+export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';++export interface ToolRouterPermissionsConfig {+ readonly default: PermissionDefaultMode;+ readonly overrides?: Readonly<Record<string, PermissionOverrideState>>;+}++export interface ConsumerPermissionSnapshot {+ readonly orgId: string;+ readonly projectId: string;+ readonly consumerUserId: string;+ readonly enhancedControlsEnabled: boolean;+ readonly permissions?: ToolRouterPermissionsConfig;+ readonly connectedAccountIds: ReadonlyArray<string>;+ readonly fetchedAt: number;+}++interface CacheFile {+ readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;+}++interface PermissionResolveResponse {+ readonly experimental?: {+ readonly permissions?: ToolRouterPermissionsConfig;+ };+}++interface ConsumerConfigResponse {+ readonly enhanced_controls?: boolean;+ readonly enhancedControls?: boolean;+}++interface GateParams {+ readonly toolSlug: string;+ readonly connectedAccountId?: string;+ readonly connectedAccountWordId?: string;+ readonly snapshot?: ConsumerPermissionSnapshot;+}++const sessionAllowCache = new Set<string>();++const cachePath = () => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);+const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>+ [params.orgId, params.projectId, params.consumerUserId].join(':');+const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');++const uniq = (values: ReadonlyArray<string | undefined>) => [+ ...new Set(values.filter((value): value is string => Boolean(value))),+];++const readCacheFile = async (): Promise<CacheFile> => {+ try {+ const raw = await fs.readFile(cachePath(), 'utf8');+ const parsed = JSON.parse(raw) as CacheFile;+ return parsed && typeof parsed === 'object' && parsed.entries ? parsed : { entries: {} };+ } catch {+ return { entries: {} };+ }+};++const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void> => {+ await fs.mkdir(path.dirname(cachePath()), { recursive: true });+ const current = await readCacheFile();+ await fs.writeFile(+ cachePath(),+ `${JSON.stringify(+ {+ entries: {+ ...current.entries,+ [cacheKey(entry)]: entry,+ },+ } satisfies CacheFile,+ null,+ 2+ )}\n`,+ 'utf8'+ );+};++const readCachedEntry = async (params: {+ orgId: string;+ projectId: string;+ consumerUserId: string;+}): Promise<ConsumerPermissionSnapshot | undefined> => {+ const cache = await readCacheFile();+ return cache.entries[cacheKey(params)];+};++const isFreshForAccounts = (+ entry: ConsumerPermissionSnapshot | undefined,+ connectedAccountIds: ReadonlyArray<string>+): entry is ConsumerPermissionSnapshot => {+ if (!entry) return false;+ if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) return false;+ const cachedIds = new Set(entry.connectedAccountIds);+ return connectedAccountIds.every(id => cachedIds.has(id));+};++const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>+ payload.enhanced_controls === true || payload.enhancedControls === true;++const fetchJson = async <T>({+ baseURL,+ apiKey,+ orgId,+ projectId,+ path,+ method = 'GET',+ body,+}: {+ readonly baseURL: string;+ readonly apiKey: string;+ readonly orgId: string;+ readonly projectId: string;+ readonly path: string;+ readonly method?: 'GET' | 'POST';+ readonly body?: unknown;+}): Promise<T> => {+ const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {+ method,+ redirect: 'error',+ headers: {+ 'x-user-api-key': apiKey,+ 'x-org-id': orgId,+ 'x-project-id': projectId,+ 'User-Agent': '@composio/cli',+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ if (!response.ok) {+ throw new Error(`HTTP ${response.status} ${response.statusText}`);+ }+ return (await response.json()) as T;+};++export const refreshConsumerPermissionSnapshot = (params: {+ readonly orgId: string;+ readonly projectId: string;+ readonly consumerUserId: string;+ readonly connectedAccountIds?: ReadonlyArray<string>;+}) =>+ Effect.gen(function* () {+ const userContext = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);+ if (!apiKey) return undefined;++ const connectedAccountIds = uniq(params.connectedAccountIds ?? []);+ const config = yield* Effect.tryPromise(() =>+ fetchJson<ConsumerConfigResponse>({+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: params.orgId,+ projectId: params.projectId,+ path: '/api/v3.1/org/consumer/config',+ })+ );+ const enhancedControlsEnabled = readEnhancedControlsFlag(config);+ const permissions =+ enhancedControlsEnabled && connectedAccountIds.length > 0+ ? yield* Effect.tryPromise(() =>+ fetchJson<PermissionResolveResponse>({+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: params.orgId,+ projectId: params.projectId,+ path: '/api/v3.1/consumer/permissions/resolve',+ method: 'POST',+ body: {+ connected_account_ids: connectedAccountIds,+ default: 'ask_every_call',+ },+ })+ ).pipe(Effect.map(response => response.experimental?.permissions))+ : undefined;++ const snapshot: ConsumerPermissionSnapshot = {+ orgId: params.orgId,+ projectId: params.projectId,+ consumerUserId: params.consumerUserId,+ enhancedControlsEnabled,+ permissions,+ connectedAccountIds,+ fetchedAt: Date.now(),+ };+ yield* Effect.tryPromise(() => writeCacheEntry(snapshot));+ return snapshot;+ }).pipe(+ Effect.catchAll(error =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to refresh consumer permission cache', error);+ return undefined;+ })+ )+ );++export const getConsumerPermissionSnapshot = (params: {+ readonly orgId: string;+ readonly projectId: string;+ readonly consumerUserId: string;+ readonly connectedAccountIds?: ReadonlyArray<string>;+}) =>+ Effect.gen(function* () {+ const connectedAccountIds = uniq(params.connectedAccountIds ?? []);+ const cached = yield* Effect.tryPromise(() => readCachedEntry(params)).pipe(+ Effect.catchAll(() => Effect.succeed(undefined))+ );++ if (isFreshForAccounts(cached, connectedAccountIds)) {+ yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(+ Effect.forkDaemon,+ Effect.catchAll(() => Effect.void)+ );+ return cached;+ }++ const refreshed = yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds });+ return refreshed ?? cached;+ });++const permissionField = (toolSlug: string, connectedAccountId?: string) =>+ `${toolSlug}:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;+const accountPermissionField = (connectedAccountId?: string) =>+ `*:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;++const resolvePermissionState = (+ params: GateParams+): PermissionOverrideState | PermissionDefaultMode => {+ const permissions = params.snapshot?.permissions;+ const override =+ permissions?.overrides?.[permissionField(params.toolSlug, params.connectedAccountId)] ??+ permissions?.overrides?.[accountPermissionField(params.connectedAccountId)];+ return override ?? permissions?.default ?? 'allow_all';+};++const sessionCacheKey = (params: GateParams) =>+ `${params.snapshot?.orgId ?? 'unknown'}:${params.snapshot?.projectId ?? 'unknown'}:${params.snapshot?.consumerUserId ?? 'unknown'}:${permissionField(params.toolSlug, params.connectedAccountId)}`;++const escapeHtml = (value: string): string =>+ value.replace(/[&<>"']/g, char => {+ switch (char) {+ case '&':+ return '&';+ case '<':+ return '<';+ case '>':+ return '>';+ case '"':+ return '"';+ default:+ return ''';+ }+ });++const html = (params: { toolSlug: string; accountLabel?: string; port: number; token: string }) => {+ const toolSlug = escapeHtml(params.toolSlug);+ const accountLabel = params.accountLabel ? escapeHtml(params.accountLabel) : undefined;+ return `<!doctype html>+<html>+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Allow ${toolSlug}?</title>+ <style>+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: radial-gradient(circle at 20% 20%, #7c3aed33, transparent 35%), #080812; color: white; }+ main { width: min(520px, calc(100vw - 32px)); padding: 28px; border: 1px solid #ffffff22; border-radius: 24px; background: #ffffff12; box-shadow: 0 24px 80px #0008; backdrop-filter: blur(24px); }+ h1 { margin: 0 0 10px; font-size: 24px; }+ p { color: #d6d6e7; line-height: 1.5; }+ .actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 22px; }+ a { color: white; text-decoration: none; padding: 11px 14px; border-radius: 999px; background: #ffffff1c; }+ a.primary { background: #7c3aed; }+ </style>+</head>+<body>+ <main>+ <h1>Allow ${toolSlug}?</h1>+ <p>Composio CLI is requesting permission to execute this tool${accountLabel ? ` for ${accountLabel}` : ''}.</p>+ <div class="actions">+ <a class="primary" href="http://127.0.0.1:${params.port}/allow-session?token=${params.token}">Allow for this session</a>+ <a href="http://127.0.0.1:${params.port}/allow-once?token=${params.token}">Allow once</a>+ <a href="http://127.0.0.1:${params.port}/deny?token=${params.token}">Deny</a>+ </div>+ </main>+</body>+</html>`;+};++const requestPermissionInBrowser = (params: {+ readonly toolSlug: string;+ readonly accountLabel?: string;+}): Promise<PermissionDecision> =>+ new Promise((resolve, reject) => {+ const token = crypto.randomUUID();+ const server = http.createServer((req, res) => {+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');+ if (url.searchParams.get('token') !== token) {+ res.writeHead(403).end('Forbidden');+ return;+ }+ const decision =+ url.pathname === '/allow-session'+ ? 'allow_session'+ : url.pathname === '/allow-once'+ ? 'allow_once'+ : url.pathname === '/deny'+ ? 'deny'+ : undefined;+ if (!decision) {+ res.writeHead(404).end('Not found');+ return;+ }+ res.writeHead(200, { 'Content-Type': 'text/html' }).end('<p>You can close this tab.</p>');+ server.close();+ resolve(decision);+ });++ const timeout = setTimeout(() => {+ server.close();+ resolve('deny');+ }, 30_000);++ server.on('close', () => clearTimeout(timeout));+ server.on('error', reject);+ server.listen(0, '127.0.0.1', async () => {+ try {+ const address = server.address();+ const port = typeof address === 'object' && address ? address.port : undefined;+ if (!port) throw new Error('Unable to allocate permission callback port.');+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-permission-'));+ const filePath = path.join(dir, 'index.html');+ await fs.writeFile(filePath, html({ ...params, port, token }), 'utf8');+ await open(filePath);+ } catch (error) {+ server.close();+ reject(error);+ }+ });+ });++const requestPermissionDecision = async (params: {+ readonly toolSlug: string;+ readonly accountLabel?: string;+}): Promise<PermissionDecision> => {+ const nativeDecision = await requestNativeUiPermissionDecision(params);+ if (nativeDecision === 'allow_once' || nativeDecision === 'allow_session') return nativeDecision;+ if (nativeDecision === 'deny' || nativeDecision === 'dismissed') return 'deny';+ return requestPermissionInBrowser(params);+};++export const gateToolExecution = (params: GateParams) =>+ Effect.gen(function* () {+ if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return;++ const state = resolvePermissionState(params);+ if (state === 'allow_all' || state === 'always_allow') return;+ if (state === 'always_deny') {+ return yield* Effect.fail(+ new Error(`Tool execution denied by permissions: ${params.toolSlug}`)+ );+ }++ const cacheKey = sessionCacheKey(params);+ const readsSessionCache = state === 'ask_once' || state === 'ask_once_per_session';+ if (readsSessionCache && sessionAllowCache.has(cacheKey)) return;++ const decision = yield* Effect.tryPromise(() =>+ requestPermissionDecision({+ toolSlug: params.toolSlug,+ accountLabel: params.connectedAccountWordId,+ })+ );++ if (decision === 'deny') {+ return yield* Effect.fail(new Error(`Tool execution denied by user: ${params.toolSlug}`));+ }+ if (decision === 'allow_session' || (readsSessionCache && decision === 'allow_once')) {+ sessionAllowCache.add(cacheKey);+ }+ });diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.tsindex f1708be47..7719da90a 100644--- a/ts/packages/cli/src/services/tools-executor.ts+++ b/ts/packages/cli/src/services/tools-executor.ts@@ -9,6 +9,7 @@ import type {} from '@composio/client/resources/tool-router';import { ComposioClientSingleton } from 'src/services/composio-clients';import { createToolRouterSessionContext } from 'src/effects/create-tool-router-session';+import { gateToolExecution } from 'src/services/tool-permissions';import {ComposioNoActiveConnectionError,mapComposioError,@@ -32,6 +33,7 @@ export interface ToolExecuteParams {readonly connectedAccounts?: Record<string, string>;readonly cacheScope?: {readonly orgId: string;+ readonly projectId: string;readonly consumerUserId: string;};}@@ -171,15 +173,26 @@ export const ToolsExecutorLive = Layer.effect(const client = yield* clientSingleton.get();const resolvedClient = params.client ?? client;// One session per invocation — CLI runs one tool per process.- const { sessionId, localExperimentalPayload } = yield* createToolRouterSessionContext(- resolvedClient,- params.userId,- {- manageConnections: true,- connectedAccounts: params.connectedAccounts,- cacheScope: params.cacheScope,- }- );+ const {+ sessionId,+ localExperimentalPayload,+ permissionSnapshot,+ connectedAccounts,+ connectedAccountWordIds,+ } = yield* createToolRouterSessionContext(resolvedClient, params.userId, {+ manageConnections: true,+ connectedAccounts: params.connectedAccounts,+ cacheScope: params.cacheScope,+ });+ const toolkitSlug = slug.split('_')[0]?.toLowerCase();+ yield* gateToolExecution({+ toolSlug: slug,+ connectedAccountId: toolkitSlug ? connectedAccounts?.[toolkitSlug] : undefined,+ connectedAccountWordId: toolkitSlug+ ? connectedAccountWordIds?.[toolkitSlug]+ : undefined,+ snapshot: permissionSnapshot,+ });const normalizedArguments = isMetaToolSlug(slug)? params.arguments: yield* getOrFetchToolInputDefinition(slug).pipe(