cycode 3.28.0__py3-none-any.whl → 3.28.1.dev2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cycode/__init__.py +1 -1
- cycode/cli/apps/ai_guardrails/ides/_transcript_utils.py +45 -0
- cycode/cli/apps/ai_guardrails/ides/_vscode_utils.py +21 -0
- cycode/cli/apps/ai_guardrails/ides/claude_code.py +87 -38
- cycode/cli/apps/ai_guardrails/ides/codex.py +130 -0
- cycode/cli/apps/ai_guardrails/ides/copilot.py +12 -60
- cycode/cli/apps/ai_guardrails/ides/cursor.py +85 -4
- cycode/cli/apps/ai_guardrails/scan/prompt_images.py +57 -5
- {cycode-3.28.0.dist-info → cycode-3.28.1.dev2.dist-info}/METADATA +4 -4
- {cycode-3.28.0.dist-info → cycode-3.28.1.dev2.dist-info}/RECORD +13 -11
- {cycode-3.28.0.dist-info → cycode-3.28.1.dev2.dist-info}/WHEEL +0 -0
- {cycode-3.28.0.dist-info → cycode-3.28.1.dev2.dist-info}/entry_points.txt +0 -0
- {cycode-3.28.0.dist-info → cycode-3.28.1.dev2.dist-info}/licenses/LICENCE +0 -0
cycode/__init__.py
CHANGED
|
@@ -5,4 +5,4 @@ import time as _time
|
|
|
5
5
|
# end-to-end scan duration from the moment the user actually triggered it.
|
|
6
6
|
_BOOT_WALL: float = _time.time()
|
|
7
7
|
|
|
8
|
-
__version__ = '3.28.
|
|
8
|
+
__version__ = '3.28.1.dev2' # DON'T TOUCH. Placeholder. Will be filled automatically on poetry build from Git Tag
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Shared transcript helpers for IDE integrations.
|
|
2
|
+
|
|
3
|
+
Agents keep a session's transcript as JSONL that grows with every turn, images included, so it is read from
|
|
4
|
+
the end.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def reverse_readline(path: Path, buf_size: int = 8192) -> Iterator[str]:
|
|
12
|
+
"""Yield lines of `path` from end to start without loading the file.
|
|
13
|
+
|
|
14
|
+
A transcript can be very large; reading from the tail keeps memory bounded
|
|
15
|
+
since only the most recent entries are wanted.
|
|
16
|
+
"""
|
|
17
|
+
with path.open('rb') as f:
|
|
18
|
+
f.seek(0, 2)
|
|
19
|
+
file_size = f.tell()
|
|
20
|
+
if file_size == 0:
|
|
21
|
+
return
|
|
22
|
+
|
|
23
|
+
remaining = file_size
|
|
24
|
+
buffer = b''
|
|
25
|
+
|
|
26
|
+
while remaining > 0:
|
|
27
|
+
read_size = min(buf_size, remaining)
|
|
28
|
+
remaining -= read_size
|
|
29
|
+
f.seek(remaining)
|
|
30
|
+
chunk = f.read(read_size)
|
|
31
|
+
buffer = chunk + buffer
|
|
32
|
+
|
|
33
|
+
while b'\n' in buffer:
|
|
34
|
+
newline_pos = buffer.rfind(b'\n')
|
|
35
|
+
if newline_pos == len(buffer) - 1:
|
|
36
|
+
newline_pos = buffer.rfind(b'\n', 0, newline_pos)
|
|
37
|
+
if newline_pos == -1:
|
|
38
|
+
break
|
|
39
|
+
line = buffer[newline_pos + 1 :]
|
|
40
|
+
buffer = buffer[: newline_pos + 1]
|
|
41
|
+
if line.strip():
|
|
42
|
+
yield line.decode('utf-8', errors='replace')
|
|
43
|
+
|
|
44
|
+
if buffer.strip():
|
|
45
|
+
yield buffer.decode('utf-8', errors='replace')
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Shared helpers for VS Code and its forks, such as Cursor: where they keep their data, and reading their databases."""
|
|
2
|
+
|
|
3
|
+
import platform
|
|
4
|
+
import sqlite3
|
|
5
|
+
from contextlib import closing
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def vscode_user_data_dir(product_name: str = 'Code') -> Path:
|
|
10
|
+
"""Per-platform user data directory of VS Code or a fork: 'Code', 'Code - Insiders' or 'Cursor'."""
|
|
11
|
+
if platform.system() == 'Darwin':
|
|
12
|
+
return Path.home() / 'Library' / 'Application Support' / product_name
|
|
13
|
+
if platform.system() == 'Windows':
|
|
14
|
+
return Path.home() / 'AppData' / 'Roaming' / product_name
|
|
15
|
+
return Path.home() / '.config' / product_name
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def read_only_query(db_path: Path, sql: str, params: tuple = ()) -> list[tuple]:
|
|
19
|
+
"""The rows of a query on an app's SQLite database, opened read-only: the app keeps writing to the file."""
|
|
20
|
+
with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection:
|
|
21
|
+
return connection.execute(sql, params).fetchall()
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"""Claude Code IDE integration for AI guardrails."""
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
|
+
import os
|
|
4
5
|
import re
|
|
6
|
+
import tempfile
|
|
5
7
|
from collections.abc import Iterator
|
|
6
8
|
from copy import deepcopy
|
|
7
9
|
from pathlib import Path
|
|
@@ -15,8 +17,16 @@ from cycode.cli.apps.ai_guardrails.ides._plugin_utils import (
|
|
|
15
17
|
walk_enabled_plugins,
|
|
16
18
|
)
|
|
17
19
|
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs
|
|
20
|
+
from cycode.cli.apps.ai_guardrails.ides._transcript_utils import reverse_readline
|
|
18
21
|
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
|
|
19
22
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
23
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import (
|
|
24
|
+
PromptImage,
|
|
25
|
+
collect_since_prompt_mark,
|
|
26
|
+
image_chips,
|
|
27
|
+
mentioned_files,
|
|
28
|
+
modified_between,
|
|
29
|
+
)
|
|
20
30
|
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
|
|
21
31
|
from cycode.logger import get_logger
|
|
22
32
|
|
|
@@ -39,45 +49,18 @@ _CLAUDE_SETTINGS_PATH = Path.home() / '.claude' / 'settings.json'
|
|
|
39
49
|
_SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide claude-code'
|
|
40
50
|
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide claude-code'
|
|
41
51
|
|
|
42
|
-
|
|
43
|
-
#
|
|
52
|
+
# Claude Code saves every image attached to a prompt (pasted, dragged in, or attached in VS Code or the desktop app)
|
|
53
|
+
# before the prompt's hook runs, as <number>.<ext> in the session's folder of its temp directory,
|
|
54
|
+
# <temp root>/claude-<uid>/<project>/<session_id>/images, the temp root being $CLAUDE_CODE_TMPDIR or /tmp. The number
|
|
55
|
+
# counts up across the session, and a pasted or dragged image shows in the prompt as its [Image #<number>] chip.
|
|
56
|
+
_TEMP_DIR_ENV_VAR = 'CLAUDE_CODE_TMPDIR'
|
|
57
|
+
_SESSION_IMAGES_DIR_NAME = 'images'
|
|
58
|
+
_SAVED_IMAGE_NAME_PATTERN = re.compile(r'(\d+)\.[A-Za-z]+')
|
|
59
|
+
# The session id names a folder; one that could leave it (or match others) is not looked up
|
|
60
|
+
_SESSION_ID_PATTERN = re.compile(r'[A-Za-z0-9_-]+')
|
|
44
61
|
|
|
45
62
|
|
|
46
|
-
|
|
47
|
-
"""Yield lines of `path` from end to start without loading the file.
|
|
48
|
-
|
|
49
|
-
The Claude Code transcript can be very large; reading from the tail keeps
|
|
50
|
-
memory bounded since we only care about the most recent entries.
|
|
51
|
-
"""
|
|
52
|
-
with path.open('rb') as f:
|
|
53
|
-
f.seek(0, 2)
|
|
54
|
-
file_size = f.tell()
|
|
55
|
-
if file_size == 0:
|
|
56
|
-
return
|
|
57
|
-
|
|
58
|
-
remaining = file_size
|
|
59
|
-
buffer = b''
|
|
60
|
-
|
|
61
|
-
while remaining > 0:
|
|
62
|
-
read_size = min(buf_size, remaining)
|
|
63
|
-
remaining -= read_size
|
|
64
|
-
f.seek(remaining)
|
|
65
|
-
chunk = f.read(read_size)
|
|
66
|
-
buffer = chunk + buffer
|
|
67
|
-
|
|
68
|
-
while b'\n' in buffer:
|
|
69
|
-
newline_pos = buffer.rfind(b'\n')
|
|
70
|
-
if newline_pos == len(buffer) - 1:
|
|
71
|
-
newline_pos = buffer.rfind(b'\n', 0, newline_pos)
|
|
72
|
-
if newline_pos == -1:
|
|
73
|
-
break
|
|
74
|
-
line = buffer[newline_pos + 1 :]
|
|
75
|
-
buffer = buffer[: newline_pos + 1]
|
|
76
|
-
if line.strip():
|
|
77
|
-
yield line.decode('utf-8', errors='replace')
|
|
78
|
-
|
|
79
|
-
if buffer.strip():
|
|
80
|
-
yield buffer.decode('utf-8', errors='replace')
|
|
63
|
+
# --- transcript JSONL parsing -------------------------------------------------
|
|
81
64
|
|
|
82
65
|
|
|
83
66
|
def _extract_model(entry: dict) -> str | None:
|
|
@@ -112,7 +95,7 @@ def extract_from_claude_transcript(
|
|
|
112
95
|
generation_id = None
|
|
113
96
|
|
|
114
97
|
try:
|
|
115
|
-
for line in
|
|
98
|
+
for line in reverse_readline(path):
|
|
116
99
|
line = line.strip()
|
|
117
100
|
if not line:
|
|
118
101
|
continue
|
|
@@ -289,6 +272,60 @@ def _resolve_mcp_server_name(server: str, config: dict | None, cwd: str | None)
|
|
|
289
272
|
return server
|
|
290
273
|
|
|
291
274
|
|
|
275
|
+
# --- prompt images ------------------------------------------------------------
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _user_id() -> int | None:
|
|
279
|
+
"""The process's uid; None on Windows, which has none."""
|
|
280
|
+
return None if os.name == 'nt' else os.getuid()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _session_image_dirs(session_id: str) -> list[Path]:
|
|
284
|
+
"""The folders where Claude Code saved this session's images (normally one).
|
|
285
|
+
|
|
286
|
+
Without a uid (Windows) the folder is looked for under any claude* folder of the system temp directory.
|
|
287
|
+
"""
|
|
288
|
+
if not _SESSION_ID_PATTERN.fullmatch(session_id):
|
|
289
|
+
return []
|
|
290
|
+
override = os.environ.get(_TEMP_DIR_ENV_VAR)
|
|
291
|
+
uid = _user_id()
|
|
292
|
+
if uid is not None:
|
|
293
|
+
root = Path(override or '/tmp') # noqa: S108 - Claude Code's own location, read only
|
|
294
|
+
user_dir_pattern = f'claude-{uid}'
|
|
295
|
+
else:
|
|
296
|
+
root = Path(override or tempfile.gettempdir())
|
|
297
|
+
user_dir_pattern = 'claude*'
|
|
298
|
+
pattern = f'{user_dir_pattern}/*/{session_id}/{_SESSION_IMAGES_DIR_NAME}'
|
|
299
|
+
return [path for path in root.glob(pattern) if path.is_dir()]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _saved_session_images(session_id: str | None, prompt: str, since: float, until: float) -> list[Path]:
|
|
303
|
+
"""This prompt's images among those Claude Code saved for the session.
|
|
304
|
+
|
|
305
|
+
Those its chips name, then those saved since the session's previous prompt: VS Code and the desktop app put no chip
|
|
306
|
+
in the prompt. Claude Code also saves an image again when its prompt is sent, so a prompt sent again after a block
|
|
307
|
+
finds it in that window too. The chips don't rely on that: they are the prompt's own reference to its files, so a
|
|
308
|
+
named image is found even if Claude Code didn't save it again.
|
|
309
|
+
"""
|
|
310
|
+
if not isinstance(session_id, str) or not session_id:
|
|
311
|
+
return []
|
|
312
|
+
saved: dict[int, Path] = {}
|
|
313
|
+
for directory in _session_image_dirs(session_id):
|
|
314
|
+
try:
|
|
315
|
+
paths = list(directory.iterdir())
|
|
316
|
+
except OSError as e:
|
|
317
|
+
logger.debug('Failed to list a session images folder, %s', {'path': str(directory)}, exc_info=e)
|
|
318
|
+
continue
|
|
319
|
+
for path in paths:
|
|
320
|
+
match = _SAVED_IMAGE_NAME_PATTERN.fullmatch(path.name)
|
|
321
|
+
if match:
|
|
322
|
+
saved.setdefault(int(match.group(1)), path)
|
|
323
|
+
|
|
324
|
+
chips = dict.fromkeys(int(number) for number in image_chips(prompt))
|
|
325
|
+
named = [saved[number] for number in chips if number in saved]
|
|
326
|
+
return named + modified_between(saved.values(), since, until)
|
|
327
|
+
|
|
328
|
+
|
|
292
329
|
# --- IDE integration ----------------------------------------------------------
|
|
293
330
|
|
|
294
331
|
|
|
@@ -393,6 +430,18 @@ class ClaudeCode(IDE):
|
|
|
393
430
|
mcp_arguments=mcp_arguments,
|
|
394
431
|
)
|
|
395
432
|
|
|
433
|
+
def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
|
|
434
|
+
"""Images attached to a prompt: those Claude Code saved for it, and `@path` mentions."""
|
|
435
|
+
session_id = raw_payload.get('session_id')
|
|
436
|
+
prompt = raw_payload.get('prompt') or ''
|
|
437
|
+
return collect_since_prompt_mark(
|
|
438
|
+
session_id,
|
|
439
|
+
lambda since, until: [
|
|
440
|
+
*_saved_session_images(session_id, prompt, since, until),
|
|
441
|
+
*mentioned_files(prompt, raw_payload.get('cwd')),
|
|
442
|
+
],
|
|
443
|
+
)
|
|
444
|
+
|
|
396
445
|
def build_hook_response(self, decision: HookDecision) -> dict:
|
|
397
446
|
if decision.event_type == AiHookEventType.PROMPT:
|
|
398
447
|
if decision.action == DecisionAction.ALLOW:
|
|
@@ -4,7 +4,10 @@ import json
|
|
|
4
4
|
import os
|
|
5
5
|
import re
|
|
6
6
|
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import time
|
|
7
9
|
from collections.abc import Iterator
|
|
10
|
+
from datetime import datetime
|
|
8
11
|
from pathlib import Path
|
|
9
12
|
from typing import ClassVar
|
|
10
13
|
|
|
@@ -23,8 +26,16 @@ from cycode.cli.apps.ai_guardrails.ides._plugin_utils import (
|
|
|
23
26
|
walk_enabled_plugins,
|
|
24
27
|
)
|
|
25
28
|
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs
|
|
29
|
+
from cycode.cli.apps.ai_guardrails.ides._transcript_utils import reverse_readline
|
|
26
30
|
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
|
|
27
31
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
32
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import (
|
|
33
|
+
PromptImage,
|
|
34
|
+
image_chips,
|
|
35
|
+
mentioned_files,
|
|
36
|
+
modified_between,
|
|
37
|
+
select_prompt_images,
|
|
38
|
+
)
|
|
28
39
|
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
|
|
29
40
|
from cycode.cli.utils.jwt_utils import decode_jwt_unverified
|
|
30
41
|
from cycode.logger import get_logger
|
|
@@ -43,6 +54,17 @@ _CODEX_EVENT_NAMES = frozenset(e.split(':', 1)[0] for e in _HOOK_EVENTS)
|
|
|
43
54
|
_SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide codex'
|
|
44
55
|
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide codex'
|
|
45
56
|
|
|
57
|
+
# The prompt names each attached image only by an [Image #N] chip. Codex's terminal UI saves an image pasted from the
|
|
58
|
+
# clipboard as codex-clipboard-<random>.png in the temp directory and keeps it; an image dragged in, picked from the
|
|
59
|
+
# @ popup or passed with --image is attached from where it is, and nothing names it.
|
|
60
|
+
_CLIPBOARD_IMAGE_GLOB = 'codex-clipboard-*.png'
|
|
61
|
+
# How long after its paste a prompt may still be sent with the image
|
|
62
|
+
_CLIPBOARD_IMAGE_MAX_AGE_SECONDS = 60 * 60
|
|
63
|
+
# How long before a session's first prompt its pastes may have been made: Codex starts the transcript at that prompt
|
|
64
|
+
_FIRST_PROMPT_PASTE_LOOKBACK_SECONDS = 10 * 60
|
|
65
|
+
# Transcript lines worth parsing: the session's start, a turn's start, and user messages
|
|
66
|
+
_TRANSCRIPT_LINE_MARKERS = ('session_meta', 'turn_context', '"user"')
|
|
67
|
+
|
|
46
68
|
|
|
47
69
|
def _codex_home() -> Path:
|
|
48
70
|
"""Resolve Codex's user-scope home directory.
|
|
@@ -229,6 +251,99 @@ def _enable_codex_hooks_feature(scope: str, repo_path: Path | None = None) -> tu
|
|
|
229
251
|
return False, f'Failed to write Codex config at {config_path}'
|
|
230
252
|
|
|
231
253
|
|
|
254
|
+
# --- prompt images ------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _transcript_time(item: dict) -> float | None:
|
|
258
|
+
"""When a transcript line was written, from its timestamp such as 2026-11-17T16:27:50.595Z."""
|
|
259
|
+
timestamp = item.get('timestamp')
|
|
260
|
+
if not isinstance(timestamp, str):
|
|
261
|
+
return None
|
|
262
|
+
try:
|
|
263
|
+
return datetime.fromisoformat(timestamp.replace('Z', '+00:00')).timestamp()
|
|
264
|
+
except ValueError:
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _is_user_message(item: dict) -> bool:
|
|
269
|
+
payload = item.get('payload')
|
|
270
|
+
return item.get('type') == 'response_item' and isinstance(payload, dict) and payload.get('role') == 'user'
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _transcript_items_newest_first(transcript_path: str) -> Iterator[dict]:
|
|
274
|
+
"""The transcript's lines that may be a session's start, a turn's start or a user message, newest first."""
|
|
275
|
+
for line in reverse_readline(Path(transcript_path)):
|
|
276
|
+
if not any(marker in line for marker in _TRANSCRIPT_LINE_MARKERS):
|
|
277
|
+
continue
|
|
278
|
+
try:
|
|
279
|
+
item = json.loads(line)
|
|
280
|
+
except ValueError:
|
|
281
|
+
continue
|
|
282
|
+
if isinstance(item, dict):
|
|
283
|
+
yield item
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _last_prompt_time(transcript_path: str) -> float | None:
|
|
287
|
+
"""When the session's last prompt that its hook let through was sent, or None if none was.
|
|
288
|
+
|
|
289
|
+
Codex writes a prompt into the transcript as a user message only once its hook lets it through; a blocked prompt
|
|
290
|
+
leaves only turn bookkeeping. Read from the end, which the last prompt is usually near. A user message is that
|
|
291
|
+
prompt once a turn's start shows up before it. If a session's start shows up first, the message came before the
|
|
292
|
+
session's first turn: it is the session's context, not a prompt, and the read goes on to the session before it.
|
|
293
|
+
"""
|
|
294
|
+
newest_message = None
|
|
295
|
+
for item in _transcript_items_newest_first(transcript_path):
|
|
296
|
+
kind = item.get('type')
|
|
297
|
+
if kind == 'turn_context' and newest_message is not None:
|
|
298
|
+
return newest_message
|
|
299
|
+
if kind == 'session_meta':
|
|
300
|
+
newest_message = None
|
|
301
|
+
elif newest_message is None and _is_user_message(item):
|
|
302
|
+
newest_message = _transcript_time(item)
|
|
303
|
+
return None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _session_start_time(transcript_path: str) -> float | None:
|
|
307
|
+
"""When the session (re)started: its latest session_meta, which Codex writes when its first prompt is submitted."""
|
|
308
|
+
for item in _transcript_items_newest_first(transcript_path):
|
|
309
|
+
if item.get('type') == 'session_meta':
|
|
310
|
+
return _transcript_time(item)
|
|
311
|
+
return None
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _paste_window_start(transcript_path: str, now: float) -> float:
|
|
315
|
+
"""Where the pastes this prompt may carry begin: at the session's last prompt that its hook let through.
|
|
316
|
+
|
|
317
|
+
A blocked prompt isn't one, so its pastes are found again when it is sent again. Until a prompt goes through, the
|
|
318
|
+
window reaches back from the session's start.
|
|
319
|
+
"""
|
|
320
|
+
try:
|
|
321
|
+
last_prompt = _last_prompt_time(transcript_path)
|
|
322
|
+
if last_prompt is not None:
|
|
323
|
+
return last_prompt
|
|
324
|
+
session_start = _session_start_time(transcript_path)
|
|
325
|
+
except OSError as e:
|
|
326
|
+
logger.debug('Failed to read the Codex transcript, %s', {'path': transcript_path}, exc_info=e)
|
|
327
|
+
session_start = None
|
|
328
|
+
return (session_start if session_start is not None else now) - _FIRST_PROMPT_PASTE_LOOKBACK_SECONDS
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _pasted_clipboard_images(prompt: str, transcript_path: object, now: float) -> list[Path]:
|
|
332
|
+
"""The newest clipboard pastes made since the session's last prompt that went through, one per [Image #N] chip.
|
|
333
|
+
|
|
334
|
+
A chip doesn't say whether its image was pasted, dragged in or picked from the @ popup, so a dragged or picked
|
|
335
|
+
image takes in its place a paste made since then that a blocked prompt, or another session, left behind. Without
|
|
336
|
+
a transcript there is no session to go by, so none is taken: the prompt Codex sends to title a new thread has
|
|
337
|
+
none and quotes the user's prompt, chips included.
|
|
338
|
+
"""
|
|
339
|
+
chips_count = len(set(image_chips(prompt)))
|
|
340
|
+
if not chips_count or not isinstance(transcript_path, str) or not transcript_path:
|
|
341
|
+
return []
|
|
342
|
+
since = max(_paste_window_start(transcript_path, now), now - _CLIPBOARD_IMAGE_MAX_AGE_SECONDS)
|
|
343
|
+
pastes = list(Path(tempfile.gettempdir()).glob(_CLIPBOARD_IMAGE_GLOB))
|
|
344
|
+
return modified_between(pastes, since, now)[-chips_count:]
|
|
345
|
+
|
|
346
|
+
|
|
232
347
|
class Codex(IDE):
|
|
233
348
|
name: ClassVar[str] = 'codex'
|
|
234
349
|
display_name: ClassVar[str] = 'Codex'
|
|
@@ -302,6 +417,21 @@ class Codex(IDE):
|
|
|
302
417
|
mcp_arguments=mcp_arguments,
|
|
303
418
|
)
|
|
304
419
|
|
|
420
|
+
def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
|
|
421
|
+
"""Images attached to a prompt: clipboard pastes, one per chip, and `@path` mentions.
|
|
422
|
+
|
|
423
|
+
The payload names no image, and the transcript records a prompt only after its hook.
|
|
424
|
+
"""
|
|
425
|
+
prompt = raw_payload.get('prompt') or ''
|
|
426
|
+
images = select_prompt_images(
|
|
427
|
+
[
|
|
428
|
+
*_pasted_clipboard_images(prompt, raw_payload.get('transcript_path'), time.time()),
|
|
429
|
+
*mentioned_files(prompt, raw_payload.get('cwd')),
|
|
430
|
+
]
|
|
431
|
+
)
|
|
432
|
+
logger.debug('Collected prompt images, %s', {'images_count': len(images)})
|
|
433
|
+
return images
|
|
434
|
+
|
|
305
435
|
def build_hook_response(self, decision: HookDecision) -> dict:
|
|
306
436
|
# Codex hook response shapes:
|
|
307
437
|
# - allow: empty (no objection). Older Codex runtimes reject an explicit
|
|
@@ -27,13 +27,10 @@ but by the time the hook runs Copilot has saved every attached image to disk; se
|
|
|
27
27
|
|
|
28
28
|
import json
|
|
29
29
|
import os
|
|
30
|
-
import platform
|
|
31
30
|
import re
|
|
32
31
|
import sqlite3
|
|
33
32
|
import tempfile
|
|
34
|
-
import time
|
|
35
33
|
from collections.abc import Iterable
|
|
36
|
-
from contextlib import closing
|
|
37
34
|
from pathlib import Path
|
|
38
35
|
from typing import ClassVar
|
|
39
36
|
from urllib.parse import urlparse
|
|
@@ -46,14 +43,14 @@ from cycode.cli.apps.ai_guardrails.ides._plugin_utils import (
|
|
|
46
43
|
walk_enabled_plugins,
|
|
47
44
|
)
|
|
48
45
|
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs
|
|
46
|
+
from cycode.cli.apps.ai_guardrails.ides._vscode_utils import read_only_query, vscode_user_data_dir
|
|
49
47
|
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
|
|
50
48
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
51
49
|
from cycode.cli.apps.ai_guardrails.scan.prompt_images import (
|
|
52
50
|
PromptImage,
|
|
53
|
-
|
|
51
|
+
collect_since_prompt_mark,
|
|
52
|
+
mentioned_files,
|
|
54
53
|
modified_between,
|
|
55
|
-
save_prompt_mark,
|
|
56
|
-
select_prompt_images,
|
|
57
54
|
)
|
|
58
55
|
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
|
|
59
56
|
from cycode.logger import get_logger
|
|
@@ -112,13 +109,6 @@ _PLUGIN_MANIFEST_LOCATIONS = (
|
|
|
112
109
|
_SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide copilot'
|
|
113
110
|
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide copilot'
|
|
114
111
|
|
|
115
|
-
# Copilot CLI leaves an `@path` mention in the prompt as typed: quoted, with
|
|
116
|
-
# backslash-escaped spaces (a file dragged into a terminal), or plain up to the next
|
|
117
|
-
# whitespace. Never mid-word, so an email address is not a mention. A lookahead, so
|
|
118
|
-
# every `@` is read on its own: a quote left open must not swallow the mentions after
|
|
119
|
-
# it, and a quoted path never spans lines.
|
|
120
|
-
_MENTION_PATTERN = re.compile(r'(?<!\S)@(?=("[^"\n]+"|\'[^\'\n]+\'|(?:\\ |\S)+))')
|
|
121
|
-
_MENTION_TRAILING_PUNCTUATION = '.,;:!?)]}'
|
|
122
112
|
# Copilot CLI replaces a pasted image with this placeholder, naming the file it saved
|
|
123
113
|
# in the temp directory.
|
|
124
114
|
_PASTED_IMAGE_PATTERN = re.compile(r'\[image:\s*([^\]\r\n]+?)\s*\]')
|
|
@@ -153,18 +143,9 @@ def _vscode_agent_plugins_dir() -> Path:
|
|
|
153
143
|
return Path.home() / '.vscode' / 'agent-plugins'
|
|
154
144
|
|
|
155
145
|
|
|
156
|
-
def _vscode_user_data_dir(product_name: str = 'Code') -> Path:
|
|
157
|
-
"""Per-platform VS Code user data directory; ``product_name`` is 'Code' or 'Code - Insiders'."""
|
|
158
|
-
if platform.system() == 'Darwin':
|
|
159
|
-
return Path.home() / 'Library' / 'Application Support' / product_name
|
|
160
|
-
if platform.system() == 'Windows':
|
|
161
|
-
return Path.home() / 'AppData' / 'Roaming' / product_name
|
|
162
|
-
return Path.home() / '.config' / product_name
|
|
163
|
-
|
|
164
|
-
|
|
165
146
|
def _vscode_user_dir() -> Path:
|
|
166
147
|
"""Per-platform VS Code user settings directory."""
|
|
167
|
-
return
|
|
148
|
+
return vscode_user_data_dir() / 'User'
|
|
168
149
|
|
|
169
150
|
|
|
170
151
|
def _vscode_mcp_config_path() -> Path:
|
|
@@ -423,27 +404,6 @@ def split_mcp_tool_name(tool_name: str, server_names: Iterable[str]) -> tuple[st
|
|
|
423
404
|
# --- prompt images ------------------------------------------------------------------
|
|
424
405
|
|
|
425
406
|
|
|
426
|
-
def _mentioned_files(prompt: str, cwd: str | None) -> list[Path]:
|
|
427
|
-
"""Existing files named by `@` mentions, resolved against the hook's cwd."""
|
|
428
|
-
base = Path(cwd) if cwd else Path()
|
|
429
|
-
files = []
|
|
430
|
-
for match in _MENTION_PATTERN.finditer(prompt):
|
|
431
|
-
token = match.group(1)
|
|
432
|
-
if len(token) > 1 and token[0] == token[-1] and token[0] in '"\'':
|
|
433
|
-
spellings = [token[1:-1]]
|
|
434
|
-
else:
|
|
435
|
-
if os.sep == '/':
|
|
436
|
-
token = token.replace('\\ ', ' ')
|
|
437
|
-
# The mention may end a sentence ("look at @shot.png.")
|
|
438
|
-
spellings = [token, token.rstrip(_MENTION_TRAILING_PUNCTUATION)]
|
|
439
|
-
for spelling in spellings:
|
|
440
|
-
path = base / os.path.expanduser(spelling)
|
|
441
|
-
if os.path.isfile(path):
|
|
442
|
-
files.append(path)
|
|
443
|
-
break
|
|
444
|
-
return files
|
|
445
|
-
|
|
446
|
-
|
|
447
407
|
def _pasted_cli_images(prompt: str) -> list[Path]:
|
|
448
408
|
"""Images pasted into Copilot CLI, saved in the temp directory its placeholder names."""
|
|
449
409
|
temp_dir = Path(tempfile.gettempdir())
|
|
@@ -459,9 +419,7 @@ def _vscode_chat_session_id(chat_dir: Path) -> str | None:
|
|
|
459
419
|
placeholders = ', '.join('?' * len(_VSCODE_CHAT_SESSION_KEYS))
|
|
460
420
|
query = f'SELECT value FROM session_metadata WHERE key IN ({placeholders})' # noqa: S608
|
|
461
421
|
try:
|
|
462
|
-
|
|
463
|
-
with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection:
|
|
464
|
-
values = [value for (value,) in connection.execute(query, _VSCODE_CHAT_SESSION_KEYS)]
|
|
422
|
+
values = [value for (value,) in read_only_query(db_path, query, _VSCODE_CHAT_SESSION_KEYS)]
|
|
465
423
|
except sqlite3.Error as e:
|
|
466
424
|
logger.debug('Failed to read a VS Code chat session database, %s', {'path': str(db_path)}, exc_info=e)
|
|
467
425
|
return None
|
|
@@ -485,7 +443,7 @@ def _vscode_saved_attachments(session_id: str | None, since: float, until: float
|
|
|
485
443
|
return []
|
|
486
444
|
copies: list[Path] = []
|
|
487
445
|
for product_name in _VSCODE_PRODUCT_NAMES:
|
|
488
|
-
copies.extend(
|
|
446
|
+
copies.extend(vscode_user_data_dir(product_name).glob(_VSCODE_ATTACHMENT_COPIES_GLOB))
|
|
489
447
|
recent = modified_between(copies, since, until)
|
|
490
448
|
# <chat id>/attachments/<attachment id>/<file>
|
|
491
449
|
chats_of_this_session = {
|
|
@@ -574,20 +532,14 @@ class Copilot(IDE):
|
|
|
574
532
|
"""
|
|
575
533
|
session_id = raw_payload.get('session_id')
|
|
576
534
|
prompt = raw_payload.get('prompt') or ''
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
[
|
|
582
|
-
*_mentioned_files(prompt, raw_payload.get('cwd')),
|
|
535
|
+
return collect_since_prompt_mark(
|
|
536
|
+
session_id,
|
|
537
|
+
lambda since, until: [
|
|
538
|
+
*mentioned_files(prompt, raw_payload.get('cwd')),
|
|
583
539
|
*_pasted_cli_images(prompt),
|
|
584
|
-
*_vscode_saved_attachments(session_id, since,
|
|
585
|
-
]
|
|
540
|
+
*_vscode_saved_attachments(session_id, since, until),
|
|
541
|
+
],
|
|
586
542
|
)
|
|
587
|
-
save_prompt_mark(session_id, now)
|
|
588
|
-
|
|
589
|
-
logger.debug('Collected prompt images, %s', {'images_count': len(images), 'since': since})
|
|
590
|
-
return images
|
|
591
543
|
|
|
592
544
|
def build_hook_response(self, decision: HookDecision) -> dict:
|
|
593
545
|
if decision.action == DecisionAction.ALLOW:
|
|
@@ -2,14 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
4
|
import platform
|
|
5
|
+
import sqlite3
|
|
6
|
+
import time
|
|
5
7
|
from pathlib import Path
|
|
6
8
|
from typing import ClassVar
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
from urllib.request import url2pathname
|
|
7
11
|
|
|
8
12
|
from cycode.cli.apps.ai_guardrails.consts import CYCODE_SCAN_PROMPT_COMMAND, CYCODE_SESSION_START_COMMAND
|
|
9
13
|
from cycode.cli.apps.ai_guardrails.ides._plugin_utils import build_global_config_files
|
|
10
14
|
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_skill_dirs
|
|
15
|
+
from cycode.cli.apps.ai_guardrails.ides._vscode_utils import read_only_query, vscode_user_data_dir
|
|
11
16
|
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
|
|
12
17
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
18
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage, select_prompt_images
|
|
13
19
|
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
|
|
14
20
|
from cycode.logger import get_logger
|
|
15
21
|
|
|
@@ -31,14 +37,22 @@ _MCP_CONFIG_FILENAME = 'mcp.json'
|
|
|
31
37
|
_SCAN_COMMAND = CYCODE_SCAN_PROMPT_COMMAND
|
|
32
38
|
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide cursor'
|
|
33
39
|
|
|
40
|
+
# The hook payload names no image attached to a prompt; Cursor's own record of the prompt does. It is the
|
|
41
|
+
# conversation's bubble whose requestId is the hook's generation_id, in the cursorDiskKV table of Cursor's global
|
|
42
|
+
# state database, and context.selectedImages lists each pasted, dropped or picked image, saved in the workspace's
|
|
43
|
+
# storage when it is attached. An @-mentioned file is only a link the agent may read later, not an attachment.
|
|
44
|
+
# Cursor starts saving the record just before it runs the hook, so the record may take a moment to appear.
|
|
45
|
+
_STATE_DB_PATH_PARTS = ('User', 'globalStorage', 'state.vscdb')
|
|
46
|
+
_PROMPT_RECORD_QUERY = 'SELECT value FROM cursorDiskKV WHERE key >= ? AND key < ? AND instr(value, ?) > 0'
|
|
47
|
+
_PROMPT_RECORD_WAIT_SECONDS = 1.0
|
|
48
|
+
_PROMPT_RECORD_POLL_SECONDS = 0.2
|
|
49
|
+
|
|
34
50
|
|
|
35
51
|
def _user_hooks_dir() -> Path:
|
|
36
|
-
"""Per-platform Cursor user-scope settings directory."""
|
|
52
|
+
"""Per-platform Cursor user-scope settings directory: ~/.cursor on macOS, its user data directory elsewhere."""
|
|
37
53
|
if platform.system() == 'Darwin':
|
|
38
54
|
return Path.home() / '.cursor'
|
|
39
|
-
|
|
40
|
-
return Path.home() / 'AppData' / 'Roaming' / 'Cursor'
|
|
41
|
-
return Path.home() / '.config' / 'Cursor'
|
|
55
|
+
return vscode_user_data_dir('Cursor')
|
|
42
56
|
|
|
43
57
|
|
|
44
58
|
def _cursor_mcp_config_path() -> Path:
|
|
@@ -102,6 +116,66 @@ def _resolve_mcp_server_name(raw_payload: dict) -> str | None:
|
|
|
102
116
|
return command
|
|
103
117
|
|
|
104
118
|
|
|
119
|
+
# --- prompt images ------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _image_file_path(value: object) -> str | None:
|
|
123
|
+
"""A selected image's file, given as a path or a file URI."""
|
|
124
|
+
if not isinstance(value, str) or not value:
|
|
125
|
+
return None
|
|
126
|
+
if value.startswith('file:'):
|
|
127
|
+
return url2pathname(urlparse(value).path)
|
|
128
|
+
return value
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _prompt_record_image_paths(db_path: Path, conversation_id: str, generation_id: str) -> list[str] | None:
|
|
132
|
+
"""The image files Cursor's record of the prompt lists; None while there is no record."""
|
|
133
|
+
key_range = (f'bubbleId:{conversation_id}:', f'bubbleId:{conversation_id};')
|
|
134
|
+
values = [value for (value,) in read_only_query(db_path, _PROMPT_RECORD_QUERY, (*key_range, generation_id))]
|
|
135
|
+
|
|
136
|
+
paths: list[str] | None = None
|
|
137
|
+
for value in values:
|
|
138
|
+
try:
|
|
139
|
+
bubble = json.loads(value)
|
|
140
|
+
except (TypeError, ValueError):
|
|
141
|
+
continue
|
|
142
|
+
if not isinstance(bubble, dict) or bubble.get('requestId') != generation_id:
|
|
143
|
+
continue
|
|
144
|
+
paths = paths or []
|
|
145
|
+
context = bubble.get('context')
|
|
146
|
+
selected = context.get('selectedImages') if isinstance(context, dict) else None
|
|
147
|
+
for image in selected if isinstance(selected, list) else []:
|
|
148
|
+
path = _image_file_path(image.get('path')) if isinstance(image, dict) else None
|
|
149
|
+
if path:
|
|
150
|
+
paths.append(path)
|
|
151
|
+
return paths
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _prompt_record_images(conversation_id: object, generation_id: object) -> list[str]:
|
|
155
|
+
"""The image files Cursor's record of the prompt lists, waiting a moment for the record to be saved."""
|
|
156
|
+
if not isinstance(conversation_id, str) or not conversation_id:
|
|
157
|
+
return []
|
|
158
|
+
if not isinstance(generation_id, str) or not generation_id:
|
|
159
|
+
return []
|
|
160
|
+
db_path = vscode_user_data_dir('Cursor').joinpath(*_STATE_DB_PATH_PARTS)
|
|
161
|
+
if not db_path.is_file():
|
|
162
|
+
return []
|
|
163
|
+
|
|
164
|
+
deadline = time.monotonic() + _PROMPT_RECORD_WAIT_SECONDS
|
|
165
|
+
while True:
|
|
166
|
+
try:
|
|
167
|
+
paths = _prompt_record_image_paths(db_path, conversation_id, generation_id)
|
|
168
|
+
except sqlite3.Error as e:
|
|
169
|
+
logger.debug('Failed to read Cursor state database, %s', {'path': str(db_path)}, exc_info=e)
|
|
170
|
+
return []
|
|
171
|
+
if paths is not None:
|
|
172
|
+
return paths
|
|
173
|
+
if time.monotonic() >= deadline:
|
|
174
|
+
logger.debug('Cursor has not saved the prompt yet, scanning its text only')
|
|
175
|
+
return []
|
|
176
|
+
time.sleep(_PROMPT_RECORD_POLL_SECONDS)
|
|
177
|
+
|
|
178
|
+
|
|
105
179
|
class Cursor(IDE):
|
|
106
180
|
name: ClassVar[str] = 'cursor'
|
|
107
181
|
display_name: ClassVar[str] = 'Cursor'
|
|
@@ -140,6 +214,13 @@ class Cursor(IDE):
|
|
|
140
214
|
mcp_arguments=(raw_payload.get('arguments') or raw_payload.get('tool_input') or raw_payload.get('input')),
|
|
141
215
|
)
|
|
142
216
|
|
|
217
|
+
def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
|
|
218
|
+
"""Images attached to a prompt, as Cursor's record of the prompt lists them."""
|
|
219
|
+
paths = _prompt_record_images(raw_payload.get('conversation_id'), raw_payload.get('generation_id'))
|
|
220
|
+
images = select_prompt_images(paths)
|
|
221
|
+
logger.debug('Collected prompt images, %s', {'images_count': len(images)})
|
|
222
|
+
return images
|
|
223
|
+
|
|
143
224
|
def build_hook_response(self, decision: HookDecision) -> dict:
|
|
144
225
|
if decision.event_type == AiHookEventType.PROMPT:
|
|
145
226
|
if decision.action == DecisionAction.ALLOW:
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"""Images attached to an AI prompt, scanned for secrets along with its text.
|
|
2
2
|
|
|
3
|
-
Some IDEs (GitHub Copilot) save a prompt's attachments to disk before its hook runs, yet never name them
|
|
4
|
-
hook payload. The IDE integration finds the candidates (``IDE.collect_prompt_images``); this module holds what
|
|
5
|
-
IDE-agnostic about them: the filters every candidate passes, and the per-session prompt marks that
|
|
6
|
-
for this prompt" into "files saved since the session's previous prompt".
|
|
3
|
+
Some IDEs (GitHub Copilot, Claude Code) save a prompt's attachments to disk before its hook runs, yet never name them
|
|
4
|
+
in the hook payload. The IDE integration finds the candidates (``IDE.collect_prompt_images``); this module holds what
|
|
5
|
+
is IDE-agnostic about them: `@path` mentions, the filters every candidate passes, and the per-session prompt marks that
|
|
6
|
+
turn "files saved for this prompt" into "files saved since the session's previous prompt".
|
|
7
7
|
|
|
8
8
|
A session's first prompt looks back a fixed time rather than to session start: VS Code fires SessionStart together
|
|
9
9
|
with the first prompt, after its attachments were already saved.
|
|
@@ -12,8 +12,10 @@ with the first prompt, after its attachments were already saved.
|
|
|
12
12
|
import hashlib
|
|
13
13
|
import json
|
|
14
14
|
import os
|
|
15
|
+
import re
|
|
15
16
|
import stat
|
|
16
|
-
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Callable, Iterable
|
|
17
19
|
from dataclasses import dataclass
|
|
18
20
|
from pathlib import Path
|
|
19
21
|
|
|
@@ -31,6 +33,9 @@ MAX_PROMPT_IMAGES = 5
|
|
|
31
33
|
# Covers attachments saved a while before the prompt was sent
|
|
32
34
|
FIRST_PROMPT_LOOKBACK_SECONDS = 600
|
|
33
35
|
|
|
36
|
+
# A pasted or dragged image's placeholder in the prompt text, as Claude Code and Codex write it
|
|
37
|
+
_IMAGE_CHIP_PATTERN = re.compile(r'\[Image #(\d+)\]')
|
|
38
|
+
|
|
34
39
|
# A session idle this long loses its mark; if it comes back, its next prompt falls back to the lookback
|
|
35
40
|
_MARK_RETENTION_SECONDS = 7 * 24 * 60 * 60
|
|
36
41
|
|
|
@@ -42,6 +47,12 @@ _IMAGE_FORMATS = (
|
|
|
42
47
|
)
|
|
43
48
|
_SIGNATURE_LENGTH = max(len(signature) for signature, _ in _IMAGE_FORMATS)
|
|
44
49
|
|
|
50
|
+
# An `@path` mention as typed in a prompt: quoted, with backslash-escaped spaces (a file dragged into a terminal), or
|
|
51
|
+
# plain up to the next whitespace. Never mid-word, so an email address is not a mention. A lookahead, so every `@` is
|
|
52
|
+
# read on its own: a quote left open must not swallow the mentions after it, and a quoted path never spans lines.
|
|
53
|
+
_MENTION_PATTERN = re.compile(r'(?<!\S)@(?=("[^"\n]+"|\'[^\'\n]+\'|(?:\\ |\S)+))')
|
|
54
|
+
_MENTION_TRAILING_PUNCTUATION = '.,;:!?)]}'
|
|
55
|
+
|
|
45
56
|
|
|
46
57
|
def get_prompt_marks_path() -> Path:
|
|
47
58
|
return Path.home() / CYCODE_CONFIGURATION_DIRECTORY / PROMPT_MARKS_FILE_NAME
|
|
@@ -113,6 +124,27 @@ def modified_between(paths: Iterable[Path], since: float, until: float) -> list[
|
|
|
113
124
|
return [path for _, path in sorted(dated, key=lambda item: item[0])]
|
|
114
125
|
|
|
115
126
|
|
|
127
|
+
def mentioned_files(prompt: str, cwd: str | None) -> list[Path]:
|
|
128
|
+
"""Existing files named by `@` mentions, resolved against the hook's cwd."""
|
|
129
|
+
base = Path(cwd) if cwd else Path()
|
|
130
|
+
files = []
|
|
131
|
+
for match in _MENTION_PATTERN.finditer(prompt):
|
|
132
|
+
token = match.group(1)
|
|
133
|
+
if len(token) > 1 and token[0] == token[-1] and token[0] in '"\'':
|
|
134
|
+
spellings = [token[1:-1]]
|
|
135
|
+
else:
|
|
136
|
+
if os.sep == '/':
|
|
137
|
+
token = token.replace('\\ ', ' ')
|
|
138
|
+
# The mention may end a sentence ("look at @shot.png.")
|
|
139
|
+
spellings = [token, token.rstrip(_MENTION_TRAILING_PUNCTUATION)]
|
|
140
|
+
for spelling in spellings:
|
|
141
|
+
path = base / os.path.expanduser(spelling)
|
|
142
|
+
if os.path.isfile(path):
|
|
143
|
+
files.append(path)
|
|
144
|
+
break
|
|
145
|
+
return files
|
|
146
|
+
|
|
147
|
+
|
|
116
148
|
def _image_extensions(content: bytes) -> tuple[str, ...]:
|
|
117
149
|
return next((extensions for signature, extensions in _IMAGE_FORMATS if content.startswith(signature)), ())
|
|
118
150
|
|
|
@@ -182,3 +214,23 @@ def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[Prompt
|
|
|
182
214
|
selected.append(PromptImage(path=str(candidate), content=content))
|
|
183
215
|
|
|
184
216
|
return selected
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def image_chips(prompt: str) -> list[str]:
|
|
220
|
+
"""The numbers of the prompt's ``[Image #N]`` placeholders, as written and in the prompt's order."""
|
|
221
|
+
return _IMAGE_CHIP_PATTERN.findall(prompt)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def collect_since_prompt_mark(
|
|
225
|
+
session_id: str | None, gather: Callable[[float, float], Iterable[str | os.PathLike]]
|
|
226
|
+
) -> list[PromptImage]:
|
|
227
|
+
"""The images ``gather`` finds in the session's window ``[since, now)``, then the session's mark moves to now.
|
|
228
|
+
|
|
229
|
+
The mark moves only after the images are selected; moving it first would leave this prompt's files to no one.
|
|
230
|
+
"""
|
|
231
|
+
now = time.time()
|
|
232
|
+
since = get_prompt_mark(session_id, now)
|
|
233
|
+
images = select_prompt_images(gather(since, now))
|
|
234
|
+
save_prompt_mark(session_id, now)
|
|
235
|
+
logger.debug('Collected prompt images, %s', {'images_count': len(images), 'since': since})
|
|
236
|
+
return images
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cycode
|
|
3
|
-
Version: 3.28.
|
|
3
|
+
Version: 3.28.1.dev2
|
|
4
4
|
Summary: Boost security in your dev lifecycle via SAST, SCA, Secrets & IaC scanning.
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENCE
|
|
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
21
21
|
Classifier: Programming Language :: Python :: 3.14
|
|
22
22
|
Requires-Dist: anyio (>=4.14.2,<5.0.0)
|
|
23
23
|
Requires-Dist: arrow (>=1.0.0,<1.5.0)
|
|
24
|
-
Requires-Dist: click (>=8.
|
|
24
|
+
Requires-Dist: click (>=8.3.3,<8.4.0)
|
|
25
25
|
Requires-Dist: colorama (>=0.4.3,<0.5.0)
|
|
26
26
|
Requires-Dist: gitpython (>=3.2.1,<3.3.0)
|
|
27
27
|
Requires-Dist: marshmallow (>=4.1.2,<5.0.0)
|
|
@@ -38,7 +38,7 @@ Requires-Dist: tenacity (>=9.2.1,<9.3.0)
|
|
|
38
38
|
Requires-Dist: tomli (>=2.0.0,<3.0.0) ; python_version < "3.11"
|
|
39
39
|
Requires-Dist: tomli-w (>=1.0.0,<2.0.0)
|
|
40
40
|
Requires-Dist: truststore (>=0.10.4,<0.11.0)
|
|
41
|
-
Requires-Dist: typer (>=0.
|
|
41
|
+
Requires-Dist: typer (>=0.25.1,<0.26.0)
|
|
42
42
|
Requires-Dist: urllib3 (>=2.8.0,<3.0.0)
|
|
43
43
|
Project-URL: Repository, https://github.com/cycodehq/cycode-cli
|
|
44
44
|
Description-Content-Type: text/markdown
|
|
@@ -800,7 +800,7 @@ prompts, files the agent reads, and MCP tool arguments are scanned for secrets b
|
|
|
800
800
|
|
|
801
801
|
Scanning happens server-side, so the scanned content leaves the machine: the prompt text, the contents of
|
|
802
802
|
files the agent reads, and MCP tool arguments are sent to your Cycode tenant to be checked for secrets.
|
|
803
|
-
For GitHub Copilot, PNG and JPEG images attached to a prompt are sent along with its text.
|
|
803
|
+
For GitHub Copilot, Claude Code, Codex and Cursor, PNG and JPEG images attached to a prompt are sent along with its text.
|
|
804
804
|
|
|
805
805
|
Each event is also reported with context about the developer and the machine, so a finding can be attributed
|
|
806
806
|
to the device and user it came from. Some of this is personal data:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
cycode/__init__.py,sha256=
|
|
1
|
+
cycode/__init__.py,sha256=Jg0GNJpUAwQ4WNBX84huyrU4iPApLw9y2UXUe5ulfqk,396
|
|
2
2
|
cycode/__main__.py,sha256=Z3bD5yrA7yPvAChcADQrqCaZd0ChGI1gdiwALwbWJ6U,104
|
|
3
3
|
cycode/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
4
|
cycode/cli/app.py,sha256=sI6wBHmfo7RchO9rnOXaQyUHRG9fm4r9aIduV4ZOD5c,10167
|
|
@@ -11,11 +11,13 @@ cycode/cli/apps/ai_guardrails/hooks_manager.py,sha256=HrfEHamt4x9MSTDZf6HZPqJSvC
|
|
|
11
11
|
cycode/cli/apps/ai_guardrails/ides/__init__.py,sha256=wUvkI0b0RvoLNaQcEjX3v4YgAzz8gKmUxpIkjvWlWIE,3240
|
|
12
12
|
cycode/cli/apps/ai_guardrails/ides/_plugin_utils.py,sha256=RGCtuxtsLnWvVZLxjqC09Brnrwq9CP1O9dyAIm2sQfs,4018
|
|
13
13
|
cycode/cli/apps/ai_guardrails/ides/_skill_utils.py,sha256=c4FeoJAJdRIKodTiXbWH7xymSfJ9IlzlilUvT17QH8E,3941
|
|
14
|
+
cycode/cli/apps/ai_guardrails/ides/_transcript_utils.py,sha256=NL4mAjMVKHR1c8k_VEqRvNROaQOr_sj2LnpRfsFt7bQ,1484
|
|
15
|
+
cycode/cli/apps/ai_guardrails/ides/_vscode_utils.py,sha256=XonRqLPD2SV0IbBZd8QEhTsEkWTVjfIxYvCCPO_ksyQ,1012
|
|
14
16
|
cycode/cli/apps/ai_guardrails/ides/base.py,sha256=m0IJGH4xoPhUQZCFRYlr3GYRueJfhs6_qr1wIJ7GDLg,9123
|
|
15
|
-
cycode/cli/apps/ai_guardrails/ides/claude_code.py,sha256=
|
|
16
|
-
cycode/cli/apps/ai_guardrails/ides/codex.py,sha256=
|
|
17
|
-
cycode/cli/apps/ai_guardrails/ides/copilot.py,sha256=
|
|
18
|
-
cycode/cli/apps/ai_guardrails/ides/cursor.py,sha256=
|
|
17
|
+
cycode/cli/apps/ai_guardrails/ides/claude_code.py,sha256=c1r84IN9t6ItuK8rN_QXWUy8YzEsyIN3x2vtc0pYe-I,20286
|
|
18
|
+
cycode/cli/apps/ai_guardrails/ides/codex.py,sha256=rzPJxEvNTzq6jd2Wv8XYi8TFYWtVXa0iCyry01gDLhQ,19853
|
|
19
|
+
cycode/cli/apps/ai_guardrails/ides/copilot.py,sha256=N32oNXqu2NzGcYaQC3yMBptoWPcDc_t0GuQl7__h-xQ,26168
|
|
20
|
+
cycode/cli/apps/ai_guardrails/ides/cursor.py,sha256=lAAcSt1KSl-UuKb1KrHn52A3pAn4BLbtUXS6o7EjHb8,11747
|
|
19
21
|
cycode/cli/apps/ai_guardrails/install_command.py,sha256=u0v4okEHeIMnXWhqcfqUePLVrh90Lc8NwOxeoJic1IU,4053
|
|
20
22
|
cycode/cli/apps/ai_guardrails/scan/__init__.py,sha256=qJc82XiQGiAuc1sYY8Ij_A-qXpxgLPuayQq8xWlouMA,48
|
|
21
23
|
cycode/cli/apps/ai_guardrails/scan/consts.py,sha256=8H8JXlgm65sYkgTXqsBInHhHe80UPjqY4vumZXB4GGM,1060
|
|
@@ -25,7 +27,7 @@ cycode/cli/apps/ai_guardrails/scan/handlers.py,sha256=P_stqp2abf-nyhgM7Mn3Xfh2nx
|
|
|
25
27
|
cycode/cli/apps/ai_guardrails/scan/mcp_server_status.py,sha256=44wij2VtjsB7cffxEnEBqQ5RInmzLROwOC0VwtDRl4s,4355
|
|
26
28
|
cycode/cli/apps/ai_guardrails/scan/payload.py,sha256=Ntwn6f71VsZxgztPoa4UN9pJvp9KnP4ctN1qobY7QaY,1881
|
|
27
29
|
cycode/cli/apps/ai_guardrails/scan/policy.py,sha256=nqLjWqNty-p4pk4mSCyy7EfqavUNCdP3nUSkKC7QRMY,4984
|
|
28
|
-
cycode/cli/apps/ai_guardrails/scan/prompt_images.py,sha256=
|
|
30
|
+
cycode/cli/apps/ai_guardrails/scan/prompt_images.py,sha256=BF5aq3WhadDe_HExRlmxl3yXCt-mYANK25MwQkt1-AA,9790
|
|
29
31
|
cycode/cli/apps/ai_guardrails/scan/scan_command.py,sha256=zMqurztyEJMB_-93xlBDBzAWB91MXXnF-4KKVJs0RNk,9115
|
|
30
32
|
cycode/cli/apps/ai_guardrails/scan/types.py,sha256=6nh_40KSTuWabsaVqkZEl712m6lAI8k9OuhPo8KhJdw,1553
|
|
31
33
|
cycode/cli/apps/ai_guardrails/scan/utils.py,sha256=YiiajYpaUHg9eBevY6oG7chU5u_rZTDrESR-gfLKIrc,6844
|
|
@@ -225,8 +227,8 @@ cycode/cyclient/report_client.py,sha256=PaKEo6Q0GFVdpNC18vvR4uBoUX1MnllVmKkS72eA
|
|
|
225
227
|
cycode/cyclient/scan_client.py,sha256=ft80sGTsW-BW4bECuGdfLv0CrSdIkp_RLlGfwHVf_Fs,17325
|
|
226
228
|
cycode/cyclient/scan_config_base.py,sha256=mXsPZGYCtp85rv5GIige40yQZXuRcEKUW-VQJ0vgFzk,1201
|
|
227
229
|
cycode/logger.py,sha256=OHmfkf4dnyZgfixGqkWf3js3uysrOXU_4cS8TChtAzc,2079
|
|
228
|
-
cycode-3.28.
|
|
229
|
-
cycode-3.28.
|
|
230
|
-
cycode-3.28.
|
|
231
|
-
cycode-3.28.
|
|
232
|
-
cycode-3.28.
|
|
230
|
+
cycode-3.28.1.dev2.dist-info/METADATA,sha256=iYI2UXGIECBMZs2jIiaxaFypPgo8VOhF8YHnipqpSLE,97154
|
|
231
|
+
cycode-3.28.1.dev2.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
232
|
+
cycode-3.28.1.dev2.dist-info/entry_points.txt,sha256=iDcVJM8ByLElVgvBgtYxDjw1kT7O8Mo0LcWZIT5L3Ig,45
|
|
233
|
+
cycode-3.28.1.dev2.dist-info/licenses/LICENCE,sha256=2Wx4N6mD_4xB7-E3hPkZ3MPhpJy__k_I8MaCSO-PDRo,1068
|
|
234
|
+
cycode-3.28.1.dev2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|