@devries-cameron20 / composio-1 / commits / d6bf4370d
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.

feat(cli): add enhanced permission cache gating (#3419)

## Summary - Add a CLI consumer permission cache backed by `~/.composio/tool-permissions-cache.json` with a 5 minute TTL. - Read enhanced-controls state from `/api/v3.1/org/consumer/config` and resolve stored connected-account permissions from `/api/v3.1/consumer/permissions/resolve`. - Thread consumer cache scope through Tool Router session creation so CLI link sessions use the enhanced public link URL when enhanced controls are enabled. - Add execute/run-compatible gating: CLI execute checks cached permission config before the Tool Router execute call and opens the bundled macOS native UI sidecar for ask modes. - Use the sidecar `--callback-file` JSON decision channel, pass the selected connection `word_id` to the UI account line, and treat no response within 30 seconds as denial. - Fall back to browser approval when the native sidecar is unavailable/non-macOS. ## Stack - Base PR: #3418 (`pi/swift-sidecar-ui-dfceb48e`) — native UI sidecar. - This PR: CLI permissions cache and native sidecar gating integration. ## Tests - `pnpm --filter @composio/cli typecheck` - `pnpm exec eslint ts/packages/cli/src/effects/create-tool-router-session.ts ts/packages/cli/src/services/tools-executor.ts ts/packages/cli/src/services/native-ui-sidecar.ts ts/packages/cli/src/services/tool-permissions.ts` - `pnpm --filter @composio/cli build` - `pnpm --filter @composio/cli-local-tools build:composio-native-ui -- --target darwin-arm64` - Earlier on this branch: `pnpm install --frozen-lockfile`, `pnpm build:packages` ## Notes / Risks - Native approval UI is macOS-only. Non-macOS or missing sidecar binaries fall back to the temporary browser approval page. - The CLI gates locally and does not pass `experimental.permissions` into Tool Router sessions yet, because direct CLI execute does not provide MCP elicitation transport. It does pass `experimental.link_url_overwrite` for enhanced link flows. - On a cold cache, the first consumer Tool Router session creation refreshes permission state synchronously; fresh cache entries are returned immediately while a background refresh updates disk for future calls.

Rahul Tarak committed May 13, 2026 at 01:37 UTC d6bf4370d7b8ba761da0445e561d2095a055d084
9 files changed +679 -46
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+2
@@ -215,12 +215,14 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string) =>
215
216 const getConsumerCacheScope = (resolvedProject: {
217 readonly orgId: string;
218 + readonly projectId: string;
219 readonly projectType: 'CONSUMER' | 'DEVELOPER';
220 readonly consumerUserId?: string;
221 }) =>
222 resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
223 ? {
224 orgId: resolvedProject.orgId,
225 + projectId: resolvedProject.projectId,
226 consumerUserId: resolvedProject.consumerUserId,
227 }
228 : undefined;
ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts
+2 -35
@@ -1,14 +1,9 @@
1 import { Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { spawn } from 'node:child_process';
4 -import fs from 'node:fs';
5 -import path from 'node:path';
6 -import {
7 - detectCliPlatform,
8 - ensureBundledBinaryExecutable,
9 - getLocalToolsBundleRootCandidates,
10 -} from '@composio/cli-local-tools';
4 +import { ensureBundledBinaryExecutable } from '@composio/cli-local-tools';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 +import { resolveNativeUiBinary } from 'src/services/native-ui-sidecar';
7
8 const title = Options.text('title').pipe(
9 Options.withDefault('Composio'),
@@ -29,34 +24,6 @@ const timeout = Options.optional(Options.text('timeout')).pipe(
24 Options.withDescription('Optional auto-close timeout in seconds.')
25 );
26
32 -const NATIVE_UI_BINARY_NAME = 'composio-native-ui';
33 -
34 -const resolveNativeUiBinary = () => {
35 - const platform = detectCliPlatform();
36 - if (!platform.startsWith('darwin-')) {
37 - return {
38 - _tag: 'unsupported' as const,
39 - platform,
40 - };
41 - }
42 -
43 - const candidates = getLocalToolsBundleRootCandidates().map(root =>
44 - path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)
45 - );
46 - const binaryPath = candidates.find(candidate => fs.existsSync(candidate));
47 -
48 - return binaryPath
49 - ? {
50 - _tag: 'found' as const,
51 - binaryPath,
52 - }
53 - : {
54 - _tag: 'missing' as const,
55 - platform,
56 - candidates,
57 - };
58 -};
59 -
27 export const devNativeUiCmd = Command.make('native-ui', { title, message, detail, timeout }).pipe(
28 Command.withDescription('Open the experimental native macOS UI sidecar.'),
29 Command.withHandler(({ title, message, detail, timeout }) =>
ts/packages/cli/src/commands/proxy.cmd.ts
+1
@@ -316,6 +316,7 @@ export const proxyCmd = Command.make('proxy', {
316 toolkits: [normalizedToolkit],
317 cacheScope: {
318 orgId: resolvedProject.orgId,
319 + projectId: resolvedProject.projectId,
320 consumerUserId,
321 },
322 });
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+1
@@ -1107,6 +1107,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1107 resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
1108 ? {
1109 orgId: resolvedProject.orgId,
1110 + projectId: resolvedProject.projectId,
1111 consumerUserId: resolvedProject.consumerUserId,
1112 }
1113 : undefined,
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+1
@@ -363,6 +363,7 @@ const runToolsSearch = (params: {
363 resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
364 ? {
365 orgId: resolvedProject.orgId,
366 + projectId: resolvedProject.projectId,
367 consumerUserId: resolvedProject.consumerUserId,
368 }
369 : undefined,
ts/packages/cli/src/effects/create-tool-router-session.ts
+53 -2
@@ -9,9 +9,17 @@ import {
9 getFreshConsumerToolRouterConnectedAccountsFromCache,
10 writeConsumerConnectedToolkitsCache,
11 } from 'src/services/consumer-short-term-cache';
12 -import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
12 +import {
13 + resolveToolRouterSessionConnections,
14 + type ToolRouterSessionConnectionContext,
15 +} from 'src/services/tool-router-session-connections';
16 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
17 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
18 +import {
19 + ENHANCED_LINK_URL_OVERWRITE,
20 + getConsumerPermissionSnapshot,
21 + type ConsumerPermissionSnapshot,
22 +} from 'src/services/tool-permissions';
23
24 export interface CreateToolRouterSessionOptions {
25 /** Enable auto connection management. Default: false. */
@@ -21,6 +29,7 @@ export interface CreateToolRouterSessionOptions {
29 /** Consumer-only cache scope for rolling auth-config reuse. */
30 readonly cacheScope?: {
31 readonly orgId: string;
32 + readonly projectId: string;
33 readonly consumerUserId: string;
34 };
35 /** Explicit connected-account pins by toolkit slug. */
@@ -43,6 +52,9 @@ export interface CreatedToolRouterSession {
52 readonly sessionId: string;
53 /** Inline local-tool custom definitions that should be forwarded to v3.1 search/execute calls. */
54 readonly localExperimentalPayload?: ReturnType<typeof createLocalToolRouterExperimentalPayload>;
55 + readonly permissionSnapshot?: ConsumerPermissionSnapshot;
56 + readonly connectedAccounts?: Record<string, string>;
57 + readonly connectedAccountWordIds?: Record<string, string>;
58 }
59
60 /**
@@ -100,6 +112,21 @@ export const createToolRouterSessionContext = (
112 );
113 return Object.keys(filtered).length > 0 ? filtered : undefined;
114 };
115 + const resolveConnectedAccountWordIds = (
116 + selected: Record<string, string> | undefined,
117 + available: ToolRouterSessionConnectionContext['availableConnectedAccounts']
118 + ) => {
119 + if (!selected || !available) return undefined;
120 + const wordIds = Object.fromEntries(
121 + Object.entries(selected).flatMap(([toolkit, connectedAccountId]) => {
122 + const account = available[toolkit.toLowerCase()]?.find(
123 + item => item.id === connectedAccountId
124 + );
125 + return account?.wordId ? [[toolkit, account.wordId]] : [];
126 + })
127 + );
128 + return Object.keys(wordIds).length > 0 ? wordIds : undefined;
129 + };
130
131 const cachedAuthConfigs = options?.cacheScope
132 ? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
@@ -159,6 +186,24 @@ export const createToolRouterSessionContext = (
186 }).pipe(Effect.catchAll(() => Effect.void));
187 }
188
189 + const connectedAccountIds = Object.values(connectionContext.connectedAccounts ?? {}).filter(
190 + (value): value is string => typeof value === 'string'
191 + );
192 + const permissionSnapshot = options?.cacheScope
193 + ? yield* getConsumerPermissionSnapshot({
194 + orgId: options.cacheScope.orgId,
195 + projectId: options.cacheScope.projectId,
196 + consumerUserId: options.cacheScope.consumerUserId,
197 + connectedAccountIds,
198 + })
199 + : undefined;
200 + const experimentalPayload = {
201 + ...(localExperimentalPayload ?? {}),
202 + ...(permissionSnapshot?.enhancedControlsEnabled
203 + ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
204 + : {}),
205 + };
206 +
207 return yield* Effect.tryPromise(() =>
208 client.toolRouter.session.create({
209 user_id: userId,
@@ -173,13 +218,19 @@ export const createToolRouterSessionContext = (
218 }
219 : undefined,
220 toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,
176 - experimental: localExperimentalPayload,
221 + experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,
222 })
223 ).pipe(
224 Effect.map(
225 (session): CreatedToolRouterSession => ({
226 sessionId: session.session_id,
227 localExperimentalPayload,
228 + permissionSnapshot,
229 + connectedAccounts: connectionContext.connectedAccounts,
230 + connectedAccountWordIds: resolveConnectedAccountWordIds(
231 + connectionContext.connectedAccounts,
232 + connectionContext.availableConnectedAccounts
233 + ),
234 })
235 )
236 );
ts/packages/cli/src/services/native-ui-sidecar.ts new
+199
@@ -0,0 +1,199 @@
1 +import { execFileSync, spawn } from 'node:child_process';
2 +import fsSync from 'node:fs';
3 +import fs from 'node:fs/promises';
4 +import os from 'node:os';
5 +import path from 'node:path';
6 +import {
7 + detectCliPlatform,
8 + ensureBundledBinaryExecutable,
9 + getLocalToolsBundleRootCandidates,
10 +} from '@composio/cli-local-tools';
11 +
12 +const NATIVE_UI_BINARY_NAME = 'composio-native-ui';
13 +
14 +export type NativeUiPermissionDecision = 'allow_once' | 'allow_session' | 'deny' | 'dismissed';
15 +export type NativeUiCallerAgent = 'claude' | 'codex' | 'openclaw' | 'composio';
16 +
17 +export type NativeUiBinaryResolution =
18 + | {
19 + readonly _tag: 'found';
20 + readonly binaryPath: string;
21 + }
22 + | {
23 + readonly _tag: 'missing';
24 + readonly platform: string;
25 + readonly candidates: ReadonlyArray<string>;
26 + }
27 + | {
28 + readonly _tag: 'unsupported';
29 + readonly platform: string;
30 + };
31 +
32 +interface NativeUiDecisionPayload {
33 + readonly decision?: NativeUiPermissionDecision;
34 +}
35 +
36 +const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>
37 + Object.keys(env).some(key => key.startsWith(prefix));
38 +
39 +const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {
40 + const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');
41 + if (normalized === 'claude' || normalized === 'codex' || normalized === 'openclaw') {
42 + return normalized;
43 + }
44 + return undefined;
45 +};
46 +
47 +const detectCallerAgentFromProcessTree = (): NativeUiCallerAgent | undefined => {
48 + if (process.platform === 'win32') return undefined;
49 +
50 + let pid = process.ppid;
51 + for (let depth = 0; depth < 8 && pid > 1; depth += 1) {
52 + try {
53 + const output = execFileSync('ps', ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)], {
54 + encoding: 'utf8',
55 + stdio: ['ignore', 'pipe', 'ignore'],
56 + }).trim();
57 + if (!output) return undefined;
58 +
59 + const match = output.match(/^(\d+)\s+(.+)$/);
60 + if (!match) return undefined;
61 +
62 + const command = match[2]?.toLowerCase() ?? '';
63 + if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
64 + if (command.includes('claude')) return 'claude';
65 + if (command.includes('codex')) return 'codex';
66 +
67 + pid = Number(match[1]);
68 + } catch {
69 + return undefined;
70 + }
71 + }
72 +
73 + return undefined;
74 +};
75 +
76 +export const detectNativeUiCallerAgent = (
77 + env: NodeJS.ProcessEnv = process.env
78 +): NativeUiCallerAgent => {
79 + const explicit = normalizeCallerAgent(env.COMPOSIO_CALLER_AGENT ?? env.COMPOSIO_AGENT);
80 + if (explicit) return explicit;
81 +
82 + if (hasEnvPrefix(env, 'OPENCLAW_')) return 'openclaw';
83 + if (hasEnvPrefix(env, 'CLAUDE_')) return 'claude';
84 + if (hasEnvPrefix(env, 'CODEX_')) return 'codex';
85 +
86 + return detectCallerAgentFromProcessTree() ?? 'composio';
87 +};
88 +
89 +export const resolveNativeUiBinary = (): NativeUiBinaryResolution => {
90 + const platform = detectCliPlatform();
91 + if (!platform.startsWith('darwin-')) {
92 + return {
93 + _tag: 'unsupported',
94 + platform,
95 + };
96 + }
97 +
98 + const candidates = getLocalToolsBundleRootCandidates().map(root =>
99 + path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)
100 + );
101 + const binaryPath = candidates.find(candidate => fsSync.existsSync(candidate));
102 +
103 + return binaryPath
104 + ? {
105 + _tag: 'found',
106 + binaryPath,
107 + }
108 + : {
109 + _tag: 'missing',
110 + platform,
111 + candidates,
112 + };
113 +};
114 +
115 +const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefined => {
116 + const payload = JSON.parse(raw) as NativeUiDecisionPayload;
117 + const decision = payload.decision;
118 + return decision === 'allow_once' ||
119 + decision === 'allow_session' ||
120 + decision === 'deny' ||
121 + decision === 'dismissed'
122 + ? decision
123 + : undefined;
124 +};
125 +
126 +export const requestNativeUiPermissionDecision = async (params: {
127 + readonly toolSlug: string;
128 + readonly accountLabel?: string;
129 + readonly timeoutSeconds?: number;
130 +}): Promise<NativeUiPermissionDecision | undefined> => {
131 + const resolved = resolveNativeUiBinary();
132 + if (resolved._tag !== 'found') return undefined;
133 +
134 + await ensureBundledBinaryExecutable(resolved.binaryPath);
135 +
136 + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-native-ui-decision-'));
137 + const callbackFile = path.join(tempDir, 'decision.json');
138 + const timeoutSeconds = params.timeoutSeconds ?? 30;
139 +
140 + try {
141 + return await new Promise<NativeUiPermissionDecision>((resolve, reject) => {
142 + const args = [
143 + '--tool',
144 + params.toolSlug,
145 + '--account',
146 + params.accountLabel ?? 'default connection',
147 + '--caller-agent',
148 + detectNativeUiCallerAgent(),
149 + '--subtitle',
150 + 'Composio CLI is requesting permission to execute this tool.',
151 + '--callback-file',
152 + callbackFile,
153 + '--timeout',
154 + String(timeoutSeconds),
155 + ];
156 +
157 + const child = spawn(resolved.binaryPath, args, {
158 + detached: false,
159 + stdio: 'ignore',
160 + });
161 +
162 + const timeout = setTimeout(
163 + () => {
164 + child.kill();
165 + resolve('dismissed');
166 + },
167 + (timeoutSeconds + 5) * 1000
168 + );
169 +
170 + child.on('error', error => {
171 + clearTimeout(timeout);
172 + reject(error);
173 + });
174 +
175 + child.on('exit', async code => {
176 + clearTimeout(timeout);
177 + try {
178 + const raw = await fs.readFile(callbackFile, 'utf8');
179 + const decision = parseDecisionPayload(raw);
180 + if (decision) {
181 + resolve(decision);
182 + return;
183 + }
184 + } catch {
185 + // If the sidecar exits without writing a callback file, treat a non-zero
186 + // exit as a dismissal. A zero exit without a callback is unexpected.
187 + }
188 +
189 + if (code === 0) {
190 + reject(new Error('Native permission prompt exited without a decision.'));
191 + } else {
192 + resolve('dismissed');
193 + }
194 + });
195 + });
196 + } finally {
197 + await fs.rm(tempDir, { recursive: true, force: true });
198 + }
199 +};
ts/packages/cli/src/services/tool-permissions.ts new
+398
@@ -0,0 +1,398 @@
1 +import http from 'node:http';
2 +import fs from 'node:fs/promises';
3 +import os from 'node:os';
4 +import path from 'node:path';
5 +import open from 'open';
6 +import { Effect, Option } from 'effect';
7 +import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';
8 +import { requestNativeUiPermissionDecision } from 'src/services/native-ui-sidecar';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 +
11 +export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhanced';
12 +
13 +const CACHE_FILE_NAME = 'tool-permissions-cache.json';
14 +const CACHE_TTL_MS = 5 * 60 * 1000;
15 +const NO_CONNECTED_ACCOUNT = '__none__';
16 +
17 +export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_per_session';
18 +export type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';
19 +export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';
20 +
21 +export interface ToolRouterPermissionsConfig {
22 + readonly default: PermissionDefaultMode;
23 + readonly overrides?: Readonly<Record<string, PermissionOverrideState>>;
24 +}
25 +
26 +export interface ConsumerPermissionSnapshot {
27 + readonly orgId: string;
28 + readonly projectId: string;
29 + readonly consumerUserId: string;
30 + readonly enhancedControlsEnabled: boolean;
31 + readonly permissions?: ToolRouterPermissionsConfig;
32 + readonly connectedAccountIds: ReadonlyArray<string>;
33 + readonly fetchedAt: number;
34 +}
35 +
36 +interface CacheFile {
37 + readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;
38 +}
39 +
40 +interface PermissionResolveResponse {
41 + readonly experimental?: {
42 + readonly permissions?: ToolRouterPermissionsConfig;
43 + };
44 +}
45 +
46 +interface ConsumerConfigResponse {
47 + readonly enhanced_controls?: boolean;
48 + readonly enhancedControls?: boolean;
49 +}
50 +
51 +interface GateParams {
52 + readonly toolSlug: string;
53 + readonly connectedAccountId?: string;
54 + readonly connectedAccountWordId?: string;
55 + readonly snapshot?: ConsumerPermissionSnapshot;
56 +}
57 +
58 +const sessionAllowCache = new Set<string>();
59 +
60 +const cachePath = () => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);
61 +const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>
62 + [params.orgId, params.projectId, params.consumerUserId].join(':');
63 +const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');
64 +
65 +const uniq = (values: ReadonlyArray<string | undefined>) => [
66 + ...new Set(values.filter((value): value is string => Boolean(value))),
67 +];
68 +
69 +const readCacheFile = async (): Promise<CacheFile> => {
70 + try {
71 + const raw = await fs.readFile(cachePath(), 'utf8');
72 + const parsed = JSON.parse(raw) as CacheFile;
73 + return parsed && typeof parsed === 'object' && parsed.entries ? parsed : { entries: {} };
74 + } catch {
75 + return { entries: {} };
76 + }
77 +};
78 +
79 +const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void> => {
80 + await fs.mkdir(path.dirname(cachePath()), { recursive: true });
81 + const current = await readCacheFile();
82 + await fs.writeFile(
83 + cachePath(),
84 + `${JSON.stringify(
85 + {
86 + entries: {
87 + ...current.entries,
88 + [cacheKey(entry)]: entry,
89 + },
90 + } satisfies CacheFile,
91 + null,
92 + 2
93 + )}\n`,
94 + 'utf8'
95 + );
96 +};
97 +
98 +const readCachedEntry = async (params: {
99 + orgId: string;
100 + projectId: string;
101 + consumerUserId: string;
102 +}): Promise<ConsumerPermissionSnapshot | undefined> => {
103 + const cache = await readCacheFile();
104 + return cache.entries[cacheKey(params)];
105 +};
106 +
107 +const isFreshForAccounts = (
108 + entry: ConsumerPermissionSnapshot | undefined,
109 + connectedAccountIds: ReadonlyArray<string>
110 +): entry is ConsumerPermissionSnapshot => {
111 + if (!entry) return false;
112 + if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) return false;
113 + const cachedIds = new Set(entry.connectedAccountIds);
114 + return connectedAccountIds.every(id => cachedIds.has(id));
115 +};
116 +
117 +const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>
118 + payload.enhanced_controls === true || payload.enhancedControls === true;
119 +
120 +const fetchJson = async <T>({
121 + baseURL,
122 + apiKey,
123 + orgId,
124 + projectId,
125 + path,
126 + method = 'GET',
127 + body,
128 +}: {
129 + readonly baseURL: string;
130 + readonly apiKey: string;
131 + readonly orgId: string;
132 + readonly projectId: string;
133 + readonly path: string;
134 + readonly method?: 'GET' | 'POST';
135 + readonly body?: unknown;
136 +}): Promise<T> => {
137 + const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {
138 + method,
139 + redirect: 'error',
140 + headers: {
141 + 'x-user-api-key': apiKey,
142 + 'x-org-id': orgId,
143 + 'x-project-id': projectId,
144 + 'User-Agent': '@composio/cli',
145 + Accept: 'application/json',
146 + 'Content-Type': 'application/json',
147 + },
148 + ...(body === undefined ? {} : { body: JSON.stringify(body) }),
149 + });
150 + if (!response.ok) {
151 + throw new Error(`HTTP ${response.status} ${response.statusText}`);
152 + }
153 + return (await response.json()) as T;
154 +};
155 +
156 +export const refreshConsumerPermissionSnapshot = (params: {
157 + readonly orgId: string;
158 + readonly projectId: string;
159 + readonly consumerUserId: string;
160 + readonly connectedAccountIds?: ReadonlyArray<string>;
161 +}) =>
162 + Effect.gen(function* () {
163 + const userContext = yield* ComposioUserContext;
164 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
165 + if (!apiKey) return undefined;
166 +
167 + const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
168 + const config = yield* Effect.tryPromise(() =>
169 + fetchJson<ConsumerConfigResponse>({
170 + baseURL: userContext.data.baseURL,
171 + apiKey,
172 + orgId: params.orgId,
173 + projectId: params.projectId,
174 + path: '/api/v3.1/org/consumer/config',
175 + })
176 + );
177 + const enhancedControlsEnabled = readEnhancedControlsFlag(config);
178 + const permissions =
179 + enhancedControlsEnabled && connectedAccountIds.length > 0
180 + ? yield* Effect.tryPromise(() =>
181 + fetchJson<PermissionResolveResponse>({
182 + baseURL: userContext.data.baseURL,
183 + apiKey,
184 + orgId: params.orgId,
185 + projectId: params.projectId,
186 + path: '/api/v3.1/consumer/permissions/resolve',
187 + method: 'POST',
188 + body: {
189 + connected_account_ids: connectedAccountIds,
190 + default: 'ask_every_call',
191 + },
192 + })
193 + ).pipe(Effect.map(response => response.experimental?.permissions))
194 + : undefined;
195 +
196 + const snapshot: ConsumerPermissionSnapshot = {
197 + orgId: params.orgId,
198 + projectId: params.projectId,
199 + consumerUserId: params.consumerUserId,
200 + enhancedControlsEnabled,
201 + permissions,
202 + connectedAccountIds,
203 + fetchedAt: Date.now(),
204 + };
205 + yield* Effect.tryPromise(() => writeCacheEntry(snapshot));
206 + return snapshot;
207 + }).pipe(
208 + Effect.catchAll(error =>
209 + Effect.gen(function* () {
210 + yield* Effect.logDebug('Failed to refresh consumer permission cache', error);
211 + return undefined;
212 + })
213 + )
214 + );
215 +
216 +export const getConsumerPermissionSnapshot = (params: {
217 + readonly orgId: string;
218 + readonly projectId: string;
219 + readonly consumerUserId: string;
220 + readonly connectedAccountIds?: ReadonlyArray<string>;
221 +}) =>
222 + Effect.gen(function* () {
223 + const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
224 + const cached = yield* Effect.tryPromise(() => readCachedEntry(params)).pipe(
225 + Effect.catchAll(() => Effect.succeed(undefined))
226 + );
227 +
228 + if (isFreshForAccounts(cached, connectedAccountIds)) {
229 + yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(
230 + Effect.forkDaemon,
231 + Effect.catchAll(() => Effect.void)
232 + );
233 + return cached;
234 + }
235 +
236 + const refreshed = yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds });
237 + return refreshed ?? cached;
238 + });
239 +
240 +const permissionField = (toolSlug: string, connectedAccountId?: string) =>
241 + `${toolSlug}:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;
242 +const accountPermissionField = (connectedAccountId?: string) =>
243 + `*:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;
244 +
245 +const resolvePermissionState = (
246 + params: GateParams
247 +): PermissionOverrideState | PermissionDefaultMode => {
248 + const permissions = params.snapshot?.permissions;
249 + const override =
250 + permissions?.overrides?.[permissionField(params.toolSlug, params.connectedAccountId)] ??
251 + permissions?.overrides?.[accountPermissionField(params.connectedAccountId)];
252 + return override ?? permissions?.default ?? 'allow_all';
253 +};
254 +
255 +const sessionCacheKey = (params: GateParams) =>
256 + `${params.snapshot?.orgId ?? 'unknown'}:${params.snapshot?.projectId ?? 'unknown'}:${params.snapshot?.consumerUserId ?? 'unknown'}:${permissionField(params.toolSlug, params.connectedAccountId)}`;
257 +
258 +const escapeHtml = (value: string): string =>
259 + value.replace(/[&<>"']/g, char => {
260 + switch (char) {
261 + case '&':
262 + return '&amp;';
263 + case '<':
264 + return '&lt;';
265 + case '>':
266 + return '&gt;';
267 + case '"':
268 + return '&quot;';
269 + default:
270 + return '&#39;';
271 + }
272 + });
273 +
274 +const html = (params: { toolSlug: string; accountLabel?: string; port: number; token: string }) => {
275 + const toolSlug = escapeHtml(params.toolSlug);
276 + const accountLabel = params.accountLabel ? escapeHtml(params.accountLabel) : undefined;
277 + return `<!doctype html>
278 +<html>
279 +<head>
280 + <meta charset="utf-8" />
281 + <meta name="viewport" content="width=device-width, initial-scale=1" />
282 + <title>Allow ${toolSlug}?</title>
283 + <style>
284 + 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; }
285 + 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); }
286 + h1 { margin: 0 0 10px; font-size: 24px; }
287 + p { color: #d6d6e7; line-height: 1.5; }
288 + .actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 22px; }
289 + a { color: white; text-decoration: none; padding: 11px 14px; border-radius: 999px; background: #ffffff1c; }
290 + a.primary { background: #7c3aed; }
291 + </style>
292 +</head>
293 +<body>
294 + <main>
295 + <h1>Allow ${toolSlug}?</h1>
296 + <p>Composio CLI is requesting permission to execute this tool${accountLabel ? ` for ${accountLabel}` : ''}.</p>
297 + <div class="actions">
298 + <a class="primary" href="http://127.0.0.1:${params.port}/allow-session?token=${params.token}">Allow for this session</a>
299 + <a href="http://127.0.0.1:${params.port}/allow-once?token=${params.token}">Allow once</a>
300 + <a href="http://127.0.0.1:${params.port}/deny?token=${params.token}">Deny</a>
301 + </div>
302 + </main>
303 +</body>
304 +</html>`;
305 +};
306 +
307 +const requestPermissionInBrowser = (params: {
308 + readonly toolSlug: string;
309 + readonly accountLabel?: string;
310 +}): Promise<PermissionDecision> =>
311 + new Promise((resolve, reject) => {
312 + const token = crypto.randomUUID();
313 + const server = http.createServer((req, res) => {
314 + const url = new URL(req.url ?? '/', 'http://127.0.0.1');
315 + if (url.searchParams.get('token') !== token) {
316 + res.writeHead(403).end('Forbidden');
317 + return;
318 + }
319 + const decision =
320 + url.pathname === '/allow-session'
321 + ? 'allow_session'
322 + : url.pathname === '/allow-once'
323 + ? 'allow_once'
324 + : url.pathname === '/deny'
325 + ? 'deny'
326 + : undefined;
327 + if (!decision) {
328 + res.writeHead(404).end('Not found');
329 + return;
330 + }
331 + res.writeHead(200, { 'Content-Type': 'text/html' }).end('<p>You can close this tab.</p>');
332 + server.close();
333 + resolve(decision);
334 + });
335 +
336 + const timeout = setTimeout(() => {
337 + server.close();
338 + resolve('deny');
339 + }, 30_000);
340 +
341 + server.on('close', () => clearTimeout(timeout));
342 + server.on('error', reject);
343 + server.listen(0, '127.0.0.1', async () => {
344 + try {
345 + const address = server.address();
346 + const port = typeof address === 'object' && address ? address.port : undefined;
347 + if (!port) throw new Error('Unable to allocate permission callback port.');
348 + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-permission-'));
349 + const filePath = path.join(dir, 'index.html');
350 + await fs.writeFile(filePath, html({ ...params, port, token }), 'utf8');
351 + await open(filePath);
352 + } catch (error) {
353 + server.close();
354 + reject(error);
355 + }
356 + });
357 + });
358 +
359 +const requestPermissionDecision = async (params: {
360 + readonly toolSlug: string;
361 + readonly accountLabel?: string;
362 +}): Promise<PermissionDecision> => {
363 + const nativeDecision = await requestNativeUiPermissionDecision(params);
364 + if (nativeDecision === 'allow_once' || nativeDecision === 'allow_session') return nativeDecision;
365 + if (nativeDecision === 'deny' || nativeDecision === 'dismissed') return 'deny';
366 + return requestPermissionInBrowser(params);
367 +};
368 +
369 +export const gateToolExecution = (params: GateParams) =>
370 + Effect.gen(function* () {
371 + if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return;
372 +
373 + const state = resolvePermissionState(params);
374 + if (state === 'allow_all' || state === 'always_allow') return;
375 + if (state === 'always_deny') {
376 + return yield* Effect.fail(
377 + new Error(`Tool execution denied by permissions: ${params.toolSlug}`)
378 + );
379 + }
380 +
381 + const cacheKey = sessionCacheKey(params);
382 + const readsSessionCache = state === 'ask_once' || state === 'ask_once_per_session';
383 + if (readsSessionCache && sessionAllowCache.has(cacheKey)) return;
384 +
385 + const decision = yield* Effect.tryPromise(() =>
386 + requestPermissionDecision({
387 + toolSlug: params.toolSlug,
388 + accountLabel: params.connectedAccountWordId,
389 + })
390 + );
391 +
392 + if (decision === 'deny') {
393 + return yield* Effect.fail(new Error(`Tool execution denied by user: ${params.toolSlug}`));
394 + }
395 + if (decision === 'allow_session' || (readsSessionCache && decision === 'allow_once')) {
396 + sessionAllowCache.add(cacheKey);
397 + }
398 + });
ts/packages/cli/src/services/tools-executor.ts
+22 -9
@@ -9,6 +9,7 @@ import type {
9 } from '@composio/client/resources/tool-router';
10 import { ComposioClientSingleton } from 'src/services/composio-clients';
11 import { createToolRouterSessionContext } from 'src/effects/create-tool-router-session';
12 +import { gateToolExecution } from 'src/services/tool-permissions';
13 import {
14 ComposioNoActiveConnectionError,
15 mapComposioError,
@@ -32,6 +33,7 @@ export interface ToolExecuteParams {
33 readonly connectedAccounts?: Record<string, string>;
34 readonly cacheScope?: {
35 readonly orgId: string;
36 + readonly projectId: string;
37 readonly consumerUserId: string;
38 };
39 }
@@ -171,15 +173,26 @@ export const ToolsExecutorLive = Layer.effect(
173 const client = yield* clientSingleton.get();
174 const resolvedClient = params.client ?? client;
175 // One session per invocation — CLI runs one tool per process.
174 - const { sessionId, localExperimentalPayload } = yield* createToolRouterSessionContext(
175 - resolvedClient,
176 - params.userId,
177 - {
178 - manageConnections: true,
179 - connectedAccounts: params.connectedAccounts,
180 - cacheScope: params.cacheScope,
181 - }
182 - );
176 + const {
177 + sessionId,
178 + localExperimentalPayload,
179 + permissionSnapshot,
180 + connectedAccounts,
181 + connectedAccountWordIds,
182 + } = yield* createToolRouterSessionContext(resolvedClient, params.userId, {
183 + manageConnections: true,
184 + connectedAccounts: params.connectedAccounts,
185 + cacheScope: params.cacheScope,
186 + });
187 + const toolkitSlug = slug.split('_')[0]?.toLowerCase();
188 + yield* gateToolExecution({
189 + toolSlug: slug,
190 + connectedAccountId: toolkitSlug ? connectedAccounts?.[toolkitSlug] : undefined,
191 + connectedAccountWordId: toolkitSlug
192 + ? connectedAccountWordIds?.[toolkitSlug]
193 + : undefined,
194 + snapshot: permissionSnapshot,
195 + });
196 const normalizedArguments = isMetaToolSlug(slug)
197 ? params.arguments
198 : yield* getOrFetchToolInputDefinition(slug).pipe(