Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ prompts, files the agent reads, and MCP tool arguments are scanned for secrets b

Scanning happens server-side, so the scanned content leaves the machine: the prompt text, the contents of
files the agent reads, and MCP tool arguments are sent to your Cycode tenant to be checked for secrets.
For GitHub Copilot and Claude Code, PNG and JPEG images attached to a prompt are sent along with its text.
For GitHub Copilot, Claude Code, Codex and Cursor, PNG and JPEG images attached to a prompt are sent along with its text.

Each event is also reported with context about the developer and the machine, so a finding can be attributed
to the device and user it came from. Some of this is personal data:
Expand Down
68 changes: 68 additions & 0 deletions cycode/cli/apps/ai_guardrails/ides/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import os
import re
import sys
import tempfile
import time
from collections.abc import Iterator
from pathlib import Path
from typing import ClassVar
Expand All @@ -25,6 +27,12 @@
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
from cycode.cli.apps.ai_guardrails.scan.prompt_images import (
PromptImage,
mentioned_files,
modified_between,
select_prompt_images,
)
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
from cycode.cli.utils.jwt_utils import decode_jwt_unverified
from cycode.logger import get_logger
Expand All @@ -43,6 +51,16 @@
_SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide codex'
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide codex'

# The prompt names each attached image only by an [Image #N] chip. Codex's terminal UI saves an image pasted from the
# clipboard as codex-clipboard-<random>.png in the temp directory and keeps it; an image dragged in, picked from the
# @ popup or passed with --image is attached from where it is, and nothing names it.
_IMAGE_CHIP_PATTERN = re.compile(r'\[Image #(\d+)\]')
_CLIPBOARD_IMAGE_GLOB = 'codex-clipboard-*.png'
_CLIPBOARD_IMAGE_NAME_PATTERN = re.compile(r'codex-clipboard-[A-Za-z0-9]+\.png')
_CLIPBOARD_IMAGE_NAME_PREFIX = 'codex-clipboard-'
# How long after its paste a prompt may still be sent with the image
_CLIPBOARD_IMAGE_MAX_AGE_SECONDS = 60 * 60


def _codex_home() -> Path:
"""Resolve Codex's user-scope home directory.
Expand Down Expand Up @@ -229,6 +247,41 @@ def _enable_codex_hooks_feature(scope: str, repo_path: Path | None = None) -> tu
return False, f'Failed to write Codex config at {config_path}'


# --- prompt images ------------------------------------------------------------


def _sent_clipboard_image_names(transcript_path: str) -> set[str]:
"""Names of the clipboard images the session's earlier prompts sent, as its transcript records them.

Codex records a prompt only once its hook lets it through, so a blocked prompt sent again finds its images again.
"""
names: set[str] = set()
try:
with open(transcript_path, encoding='utf-8', errors='replace') as transcript:
for line in transcript:
if _CLIPBOARD_IMAGE_NAME_PREFIX in line:
names.update(_CLIPBOARD_IMAGE_NAME_PATTERN.findall(line))
except OSError as e:
logger.debug('Failed to read the Codex transcript, %s', {'path': transcript_path}, exc_info=e)
return names


def _pasted_clipboard_images(prompt: str, transcript_path: object, now: float) -> list[Path]:
"""The newest recent clipboard pastes no earlier prompt sent, one per [Image #N] chip in the prompt.

A chip doesn't say whether its image was pasted, dragged in or picked from the @ popup, so a prompt with a dragged
or picked image takes the newest unsent paste in its place. Without a transcript nothing tells a sent paste from an
unsent one, so none is taken: the prompt Codex sends to title a new thread has none and quotes the user's prompt,
chips included.
"""
chips_count = len(set(_IMAGE_CHIP_PATTERN.findall(prompt)))
if not chips_count or not isinstance(transcript_path, str) or not transcript_path:
return []
sent = _sent_clipboard_image_names(transcript_path)
pastes = [path for path in Path(tempfile.gettempdir()).glob(_CLIPBOARD_IMAGE_GLOB) if path.name not in sent]
return modified_between(pastes, now - _CLIPBOARD_IMAGE_MAX_AGE_SECONDS, now)[-chips_count:]


class Codex(IDE):
name: ClassVar[str] = 'codex'
display_name: ClassVar[str] = 'Codex'
Expand Down Expand Up @@ -302,6 +355,21 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload:
mcp_arguments=mcp_arguments,
)

def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
"""Images attached to a prompt: clipboard pastes, one per chip, and `@path` mentions.

The payload names no image, and the transcript records a prompt only after its hook.
"""
prompt = raw_payload.get('prompt') or ''
images = select_prompt_images(
[
*_pasted_clipboard_images(prompt, raw_payload.get('transcript_path'), time.time()),
*mentioned_files(prompt, raw_payload.get('cwd')),
]
)
logger.debug('Collected prompt images, %s', {'images_count': len(images)})
return images

def build_hook_response(self, decision: HookDecision) -> dict:
# Codex hook response shapes:
# - allow: empty (no objection). Older Codex runtimes reject an explicit
Expand Down
94 changes: 94 additions & 0 deletions cycode/cli/apps/ai_guardrails/ides/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@

import json
import platform
import sqlite3
import time
from contextlib import closing
from pathlib import Path
from typing import ClassVar
from urllib.parse import urlparse
from urllib.request import url2pathname

from cycode.cli.apps.ai_guardrails.consts import CYCODE_SCAN_PROMPT_COMMAND, CYCODE_SESSION_START_COMMAND
from cycode.cli.apps.ai_guardrails.ides._plugin_utils import build_global_config_files
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_skill_dirs
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage, select_prompt_images
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
from cycode.logger import get_logger

Expand All @@ -31,6 +37,16 @@
_SCAN_COMMAND = CYCODE_SCAN_PROMPT_COMMAND
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide cursor'

# The hook payload names no image attached to a prompt; Cursor's own record of the prompt does. It is the
# conversation's bubble whose requestId is the hook's generation_id, in the cursorDiskKV table of Cursor's global
# state database, and context.selectedImages lists each pasted, dropped or picked image, saved in the workspace's
# storage when it is attached. An @-mentioned file is only a link the agent may read later, not an attachment.
# Cursor starts saving the record just before it runs the hook, so the record may take a moment to appear.
_STATE_DB_PATH_PARTS = ('User', 'globalStorage', 'state.vscdb')
_PROMPT_RECORD_QUERY = 'SELECT value FROM cursorDiskKV WHERE key >= ? AND key < ? AND instr(value, ?) > 0'
_PROMPT_RECORD_WAIT_SECONDS = 1.0
_PROMPT_RECORD_POLL_SECONDS = 0.2


def _user_hooks_dir() -> Path:
"""Per-platform Cursor user-scope settings directory."""
Expand All @@ -41,6 +57,15 @@ def _user_hooks_dir() -> Path:
return Path.home() / '.config' / 'Cursor'


def _cursor_user_data_dir() -> Path:
"""Per-platform Cursor user data directory."""
if platform.system() == 'Darwin':
return Path.home() / 'Library' / 'Application Support' / 'Cursor'
if platform.system() == 'Windows':
return Path.home() / 'AppData' / 'Roaming' / 'Cursor'
return Path.home() / '.config' / 'Cursor'


def _cursor_mcp_config_path() -> Path:
"""User-scope Cursor MCP config path (``~/.cursor/mcp.json``, all platforms)."""
return Path.home() / '.cursor' / _MCP_CONFIG_FILENAME
Expand Down Expand Up @@ -102,6 +127,68 @@ def _resolve_mcp_server_name(raw_payload: dict) -> str | None:
return command


# --- prompt images ------------------------------------------------------------


def _image_file_path(value: object) -> str | None:
"""A selected image's file, given as a path or a file URI."""
if not isinstance(value, str) or not value:
return None
if value.startswith('file:'):
return url2pathname(urlparse(value).path)
return value


def _prompt_record_image_paths(db_path: Path, conversation_id: str, generation_id: str) -> list[str] | None:
"""The image files Cursor's record of the prompt lists; None while there is no record."""
key_range = (f'bubbleId:{conversation_id}:', f'bubbleId:{conversation_id};')
# Read-only: Cursor keeps writing to the file
with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection:
values = [value for (value,) in connection.execute(_PROMPT_RECORD_QUERY, (*key_range, generation_id))]

paths: list[str] | None = None
for value in values:
try:
bubble = json.loads(value)
except (TypeError, ValueError):
continue
if not isinstance(bubble, dict) or bubble.get('requestId') != generation_id:
continue
paths = paths or []
context = bubble.get('context')
selected = context.get('selectedImages') if isinstance(context, dict) else None
for image in selected if isinstance(selected, list) else []:
path = _image_file_path(image.get('path')) if isinstance(image, dict) else None
if path:
paths.append(path)
return paths


def _prompt_record_images(conversation_id: object, generation_id: object) -> list[str]:
"""The image files Cursor's record of the prompt lists, waiting a moment for the record to be saved."""
if not isinstance(conversation_id, str) or not conversation_id:
return []
if not isinstance(generation_id, str) or not generation_id:
return []
db_path = _cursor_user_data_dir().joinpath(*_STATE_DB_PATH_PARTS)
if not db_path.is_file():
return []

deadline = time.monotonic() + _PROMPT_RECORD_WAIT_SECONDS
while True:
try:
paths = _prompt_record_image_paths(db_path, conversation_id, generation_id)
except sqlite3.Error as e:
logger.debug('Failed to read Cursor state database, %s', {'path': str(db_path)}, exc_info=e)
return []
if paths is not None:
return paths
if time.monotonic() >= deadline:
logger.debug('Cursor has not saved the prompt yet, scanning its text only')
return []
time.sleep(_PROMPT_RECORD_POLL_SECONDS)


class Cursor(IDE):
name: ClassVar[str] = 'cursor'
display_name: ClassVar[str] = 'Cursor'
Expand Down Expand Up @@ -140,6 +227,13 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload:
mcp_arguments=(raw_payload.get('arguments') or raw_payload.get('tool_input') or raw_payload.get('input')),
)

def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
"""Images attached to a prompt, as Cursor's record of the prompt lists them."""
paths = _prompt_record_images(raw_payload.get('conversation_id'), raw_payload.get('generation_id'))
images = select_prompt_images(paths)
logger.debug('Collected prompt images, %s', {'images_count': len(images)})
return images

def build_hook_response(self, decision: HookDecision) -> dict:
if decision.event_type == AiHookEventType.PROMPT:
if decision.action == DecisionAction.ALLOW:
Expand Down
122 changes: 122 additions & 0 deletions tests/cli/commands/ai_guardrails/ides/test_codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import base64
import json
import os
import sys
import tempfile
import time
from pathlib import Path
from unittest.mock import patch

Expand All @@ -18,6 +21,7 @@
_load_codex_config,
_read_codex_plugin,
)
from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType

if sys.version_info >= (3, 11):
Expand Down Expand Up @@ -460,3 +464,121 @@ def test_get_skills_reads_user_scope_skills(fs: FakeFilesystem) -> None:

def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None:
assert Codex().get_skills() == []


# --- prompt images ----------------------------------------------------------------


def _png(marker: bytes) -> bytes:
return b'\x89PNG\r\n\x1a\n' + marker


def _paste(fs: FakeFilesystem, name: str, modified_at: float) -> str:
"""An image the terminal UI saved from the clipboard."""
path = Path(tempfile.gettempdir()) / f'codex-clipboard-{name}.png'
fs.create_file(path, contents=_png(name.encode()))
os.utime(path, (modified_at, modified_at))
return str(path)


def _transcript(fs: FakeFilesystem, *sent: str) -> str:
"""A session transcript whose earlier prompts sent these images, as Codex records them."""
path = '/Users/user/.codex/sessions/2026/11/17/rollout-session-1.jsonl'
lines = [json.dumps({'type': 'session_meta', 'payload': {'id': 'session-1'}})]
for index, image in enumerate(sent, start=1):
content = [
{'type': 'input_text', 'text': f'<image name=[Image #{index}] path="{image}">'},
{'type': 'input_image', 'image_url': 'data:image/png;base64,iVBORw0KGgo='},
{'type': 'input_text', 'text': '</image>'},
]
lines.append(json.dumps({'type': 'response_item', 'payload': {'role': 'user', 'content': content}}))
fs.create_file(path, contents='\n'.join(lines) + '\n')
return path


def _prompt_payload(prompt: str, transcript_path: str | None = None) -> dict:
return {
'hook_event_name': 'UserPromptSubmit',
'session_id': 'session-1',
'turn_id': 'turn-1',
'transcript_path': transcript_path,
'cwd': '/Users/user/project',
'prompt': prompt,
}


def _paths(images: list[PromptImage]) -> list[str]:
return [image.path for image in images]


def test_collect_prompt_images_takes_the_newest_paste_per_chip(fs: FakeFilesystem) -> None:
now = time.time()
_paste(fs, 'Old111', now - 300)
middle = _paste(fs, 'Mid222', now - 60)
newest = _paste(fs, 'New333', now - 5)

images = Codex().collect_prompt_images(_prompt_payload('[Image #1] [Image #2] what changed?', _transcript(fs)))

# Oldest first, the order they were pasted in
assert _paths(images) == [middle, newest]


def test_collect_prompt_images_skips_pastes_an_earlier_prompt_sent(fs: FakeFilesystem) -> None:
now = time.time()
earlier = _paste(fs, 'Earlier1', now - 120)
unsent = _paste(fs, 'Unsent22', now - 60)
_paste(fs, 'Sent3333', now - 5)
transcript = _transcript(fs, earlier, str(Path(tempfile.gettempdir()) / 'codex-clipboard-Sent3333.png'))

# A prompt blocked before isn't in the transcript, so its paste is found again when it is sent again
assert _paths(Codex().collect_prompt_images(_prompt_payload('[Image #1] again', transcript))) == [unsent]


def test_collect_prompt_images_takes_no_paste_without_a_chip(fs: FakeFilesystem) -> None:
_paste(fs, 'Recent11', time.time() - 5)

assert Codex().collect_prompt_images(_prompt_payload('no image here', _transcript(fs))) == []


def test_collect_prompt_images_counts_a_repeated_chip_once(fs: FakeFilesystem) -> None:
now = time.time()
_paste(fs, 'First111', now - 60)
newest = _paste(fs, 'Second22', now - 5)

payload = _prompt_payload('compare [Image #1] with itself: [Image #1]', _transcript(fs))

assert _paths(Codex().collect_prompt_images(payload)) == [newest]


def test_collect_prompt_images_ignores_pastes_older_than_an_hour(fs: FakeFilesystem) -> None:
_paste(fs, 'Stale111', time.time() - 2 * 60 * 60)

assert Codex().collect_prompt_images(_prompt_payload('[Image #1]', _transcript(fs))) == []


@pytest.mark.parametrize('transcript_path', [None, ''])
def test_collect_prompt_images_takes_no_paste_without_a_transcript(
fs: FakeFilesystem, transcript_path: str | None
) -> None:
_paste(fs, 'Recent11', time.time() - 5)
# The prompt Codex sends to title a new thread has no transcript and quotes the user's prompt, chips included
title_prompt = 'Generate a concise, single-line task title.\n\nUser prompt:\nwhat does it say? [Image #1]'

assert Codex().collect_prompt_images(_prompt_payload(title_prompt, transcript_path)) == []


def test_collect_prompt_images_takes_recent_pastes_before_the_transcript_is_written(fs: FakeFilesystem) -> None:
pasted = _paste(fs, 'Recent11', time.time() - 5)

payload = _prompt_payload('[Image #1]', '/Users/user/.codex/sessions/2026/11/17/rollout-new.jsonl')

assert _paths(Codex().collect_prompt_images(payload)) == [pasted]


def test_collect_prompt_images_finds_mentions_against_cwd(fs: FakeFilesystem) -> None:
shot = Path('/Users/user/project/docs/shot.png')
fs.create_file(shot, contents=_png(b'shot'))

images = Codex().collect_prompt_images(_prompt_payload('explain @docs/shot.png', _transcript(fs)))

assert _paths(images) == [str(shot)]
Loading
Loading