klaude-code 2.5.3__py3-none-any.whl → 2.7.0__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.
Files changed (60) hide show
  1. klaude_code/app/runtime.py +1 -1
  2. klaude_code/auth/__init__.py +10 -0
  3. klaude_code/auth/env.py +81 -0
  4. klaude_code/cli/auth_cmd.py +87 -8
  5. klaude_code/cli/config_cmd.py +5 -5
  6. klaude_code/cli/cost_cmd.py +159 -60
  7. klaude_code/cli/main.py +146 -65
  8. klaude_code/cli/self_update.py +7 -7
  9. klaude_code/config/builtin_config.py +23 -9
  10. klaude_code/config/config.py +19 -9
  11. klaude_code/const.py +10 -1
  12. klaude_code/core/reminders.py +4 -5
  13. klaude_code/core/turn.py +8 -9
  14. klaude_code/llm/google/client.py +12 -0
  15. klaude_code/llm/openai_compatible/stream.py +5 -1
  16. klaude_code/llm/openrouter/client.py +1 -0
  17. klaude_code/protocol/commands.py +0 -1
  18. klaude_code/protocol/events.py +214 -0
  19. klaude_code/protocol/sub_agent/image_gen.py +0 -4
  20. klaude_code/session/session.py +51 -18
  21. klaude_code/skill/loader.py +12 -13
  22. klaude_code/skill/manager.py +3 -3
  23. klaude_code/tui/command/__init__.py +1 -4
  24. klaude_code/tui/command/copy_cmd.py +1 -1
  25. klaude_code/tui/command/fork_session_cmd.py +4 -4
  26. klaude_code/tui/commands.py +0 -5
  27. klaude_code/tui/components/command_output.py +1 -1
  28. klaude_code/tui/components/metadata.py +4 -5
  29. klaude_code/tui/components/rich/markdown.py +60 -0
  30. klaude_code/tui/components/rich/theme.py +8 -0
  31. klaude_code/tui/components/sub_agent.py +6 -0
  32. klaude_code/tui/components/user_input.py +38 -27
  33. klaude_code/tui/display.py +11 -1
  34. klaude_code/tui/input/AGENTS.md +44 -0
  35. klaude_code/tui/input/completers.py +21 -21
  36. klaude_code/tui/input/drag_drop.py +197 -0
  37. klaude_code/tui/input/images.py +227 -0
  38. klaude_code/tui/input/key_bindings.py +173 -19
  39. klaude_code/tui/input/paste.py +71 -0
  40. klaude_code/tui/input/prompt_toolkit.py +13 -3
  41. klaude_code/tui/machine.py +90 -56
  42. klaude_code/tui/renderer.py +1 -62
  43. klaude_code/tui/runner.py +1 -1
  44. klaude_code/tui/terminal/image.py +40 -9
  45. klaude_code/tui/terminal/selector.py +52 -2
  46. {klaude_code-2.5.3.dist-info → klaude_code-2.7.0.dist-info}/METADATA +32 -40
  47. {klaude_code-2.5.3.dist-info → klaude_code-2.7.0.dist-info}/RECORD +49 -54
  48. klaude_code/cli/session_cmd.py +0 -87
  49. klaude_code/protocol/events/__init__.py +0 -63
  50. klaude_code/protocol/events/base.py +0 -18
  51. klaude_code/protocol/events/chat.py +0 -30
  52. klaude_code/protocol/events/lifecycle.py +0 -23
  53. klaude_code/protocol/events/metadata.py +0 -16
  54. klaude_code/protocol/events/streaming.py +0 -43
  55. klaude_code/protocol/events/system.py +0 -56
  56. klaude_code/protocol/events/tools.py +0 -27
  57. klaude_code/tui/command/terminal_setup_cmd.py +0 -248
  58. klaude_code/tui/input/clipboard.py +0 -152
  59. {klaude_code-2.5.3.dist-info → klaude_code-2.7.0.dist-info}/WHEEL +0 -0
  60. {klaude_code-2.5.3.dist-info → klaude_code-2.7.0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,227 @@
1
+ """Image handling for REPL input.
2
+
3
+ This module provides:
4
+ - IMAGE_SUFFIXES: Supported image file extensions
5
+ - IMAGE_MARKER_RE: Regex for [image ...] markers
6
+ - is_image_file(): Check if a path is an image file
7
+ - format_image_marker(): Generate [image path] string
8
+ - parse_image_marker_path(): Parse path from marker
9
+ - capture_clipboard_tag(): Capture clipboard image and return an [image ...] marker
10
+ - extract_images_from_text(): Parse [image ...] markers and return ImageURLPart list
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import uuid
20
+ from base64 import b64encode
21
+ from pathlib import Path
22
+
23
+ from klaude_code.const import get_system_temp
24
+ from klaude_code.protocol.message import ImageURLPart
25
+
26
+ # ---------------------------------------------------------------------------
27
+ # Constants and marker syntax
28
+ # ---------------------------------------------------------------------------
29
+
30
+ IMAGE_SUFFIXES = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp"})
31
+
32
+ IMAGE_MARKER_RE = re.compile(r'\[image (?P<path>"[^"]+"|[^\]]+)\]')
33
+
34
+
35
+ def is_image_file(path: Path) -> bool:
36
+ """Check if a path points to an image file based on extension."""
37
+ return path.suffix.lower() in IMAGE_SUFFIXES
38
+
39
+
40
+ def format_image_marker(path: str) -> str:
41
+ """Format a path as an [image ...] marker.
42
+
43
+ Paths with whitespace are quoted.
44
+ """
45
+ path_str = path.strip()
46
+ if any(ch.isspace() for ch in path_str):
47
+ return f'[image "{path_str}"]'
48
+ return f"[image {path_str}]"
49
+
50
+
51
+ def parse_image_marker_path(raw: str) -> str:
52
+ """Parse the path from an [image ...] marker, removing quotes if present."""
53
+ s = raw.strip()
54
+ if len(s) >= 2 and s.startswith('"') and s.endswith('"'):
55
+ return s[1:-1]
56
+ return s
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Clipboard image capture
61
+ # ---------------------------------------------------------------------------
62
+
63
+
64
+ def _clipboard_images_dir() -> Path:
65
+ return Path(get_system_temp())
66
+
67
+
68
+ def _grab_clipboard_image_macos(dest_path: Path) -> bool:
69
+ """Grab image from clipboard on macOS using pngpaste or osascript (JXA)."""
70
+ # Try pngpaste first (faster, if installed)
71
+ if shutil.which("pngpaste"):
72
+ try:
73
+ result = subprocess.run(
74
+ ["pngpaste", str(dest_path)],
75
+ capture_output=True,
76
+ )
77
+ return result.returncode == 0 and dest_path.exists() and dest_path.stat().st_size > 0
78
+ except OSError:
79
+ pass
80
+
81
+ # Fallback to osascript with JXA (JavaScript for Automation)
82
+ script = f'''
83
+ ObjC.import("AppKit");
84
+ var pb = $.NSPasteboard.generalPasteboard;
85
+ var pngData = pb.dataForType($.NSPasteboardTypePNG);
86
+ if (pngData.isNil()) {{
87
+ var tiffData = pb.dataForType($.NSPasteboardTypeTIFF);
88
+ if (tiffData.isNil()) {{
89
+ "false";
90
+ }} else {{
91
+ var bitmapRep = $.NSBitmapImageRep.imageRepWithData(tiffData);
92
+ pngData = bitmapRep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $());
93
+ }}
94
+ }}
95
+ if (!pngData.isNil()) {{
96
+ pngData.writeToFileAtomically("{dest_path}", true);
97
+ "true";
98
+ }} else {{
99
+ "false";
100
+ }}
101
+ '''
102
+ try:
103
+ result = subprocess.run(
104
+ ["osascript", "-l", "JavaScript", "-e", script],
105
+ capture_output=True,
106
+ text=True,
107
+ )
108
+ return (
109
+ result.returncode == 0 and "true" in result.stdout and dest_path.exists() and dest_path.stat().st_size > 0
110
+ )
111
+ except OSError:
112
+ return False
113
+
114
+
115
+ def _grab_clipboard_image_linux(dest_path: Path) -> bool:
116
+ """Grab image from clipboard on Linux using xclip."""
117
+ if not shutil.which("xclip"):
118
+ return False
119
+ try:
120
+ result = subprocess.run(
121
+ ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"],
122
+ capture_output=True,
123
+ )
124
+ if result.returncode == 0 and result.stdout:
125
+ dest_path.write_bytes(result.stdout)
126
+ return True
127
+ except OSError:
128
+ pass
129
+ return False
130
+
131
+
132
+ def _grab_clipboard_image_windows(dest_path: Path) -> bool:
133
+ """Grab image from clipboard on Windows using PowerShell."""
134
+ script = f'''
135
+ Add-Type -AssemblyName System.Windows.Forms
136
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
137
+ if ($img -ne $null) {{
138
+ $img.Save("{dest_path}", [System.Drawing.Imaging.ImageFormat]::Png)
139
+ Write-Output "ok"
140
+ }}
141
+ '''
142
+ try:
143
+ result = subprocess.run(
144
+ ["powershell", "-Command", script],
145
+ capture_output=True,
146
+ text=True,
147
+ )
148
+ return result.returncode == 0 and "ok" in result.stdout and dest_path.exists()
149
+ except OSError:
150
+ return False
151
+
152
+
153
+ def _grab_clipboard_image(dest_path: Path) -> bool:
154
+ """Grab image from clipboard and save to dest_path. Returns True on success."""
155
+ if sys.platform == "darwin":
156
+ return _grab_clipboard_image_macos(dest_path)
157
+ elif sys.platform == "win32":
158
+ return _grab_clipboard_image_windows(dest_path)
159
+ else:
160
+ return _grab_clipboard_image_linux(dest_path)
161
+
162
+
163
+ def capture_clipboard_tag() -> str | None:
164
+ """Capture an image from clipboard and return an [image ...] marker."""
165
+
166
+ images_dir = _clipboard_images_dir()
167
+ try:
168
+ images_dir.mkdir(parents=True, exist_ok=True)
169
+ except OSError:
170
+ return None
171
+
172
+ filename = f"klaude-image-{uuid.uuid4().hex}.png"
173
+ path = images_dir / filename
174
+
175
+ if not _grab_clipboard_image(path):
176
+ return None
177
+
178
+ return format_image_marker(str(path))
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+ # Image extraction from text
183
+ # ---------------------------------------------------------------------------
184
+
185
+
186
+ def _encode_image_file(file_path: str) -> ImageURLPart | None:
187
+ """Encode an image file as base64 data URL and create ImageURLPart."""
188
+ try:
189
+ path = Path(file_path)
190
+ if not path.exists():
191
+ return None
192
+ with open(path, "rb") as f:
193
+ encoded = b64encode(f.read()).decode("ascii")
194
+
195
+ suffix = path.suffix.lower()
196
+ mime = {
197
+ ".png": "image/png",
198
+ ".jpg": "image/jpeg",
199
+ ".jpeg": "image/jpeg",
200
+ ".gif": "image/gif",
201
+ ".webp": "image/webp",
202
+ }.get(suffix)
203
+ if mime is None:
204
+ return None
205
+
206
+ data_url = f"data:{mime};base64,{encoded}"
207
+ return ImageURLPart(url=data_url, id=None)
208
+ except OSError:
209
+ return None
210
+
211
+
212
+ def extract_images_from_text(text: str) -> list[ImageURLPart]:
213
+ """Extract images referenced by [image ...] markers in text."""
214
+
215
+ images: list[ImageURLPart] = []
216
+ for m in IMAGE_MARKER_RE.finditer(text):
217
+ raw = m.group("path")
218
+ path_str = parse_image_marker_path(raw)
219
+ if not path_str:
220
+ continue
221
+ p = Path(path_str).expanduser()
222
+ if not p.is_absolute():
223
+ p = (Path.cwd() / p).resolve()
224
+ image_part = _encode_image_file(str(p))
225
+ if image_part:
226
+ images.append(image_part)
227
+ return images
@@ -7,8 +7,13 @@ with dependencies injected to avoid circular imports.
7
7
  from __future__ import annotations
8
8
 
9
9
  import contextlib
10
+ import os
10
11
  import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
11
15
  from collections.abc import Callable
16
+ from pathlib import Path
12
17
  from typing import cast
13
18
 
14
19
  from prompt_toolkit.application.current import get_app
@@ -17,11 +22,39 @@ from prompt_toolkit.filters import Always, Condition, Filter
17
22
  from prompt_toolkit.filters.app import has_completions
18
23
  from prompt_toolkit.key_binding import KeyBindings
19
24
  from prompt_toolkit.key_binding.key_processor import KeyPressEvent
25
+ from prompt_toolkit.keys import Keys
26
+
27
+ from klaude_code.tui.input.drag_drop import convert_dropped_text
28
+ from klaude_code.tui.input.paste import expand_paste_markers, store_paste
29
+
30
+
31
+ def copy_to_clipboard(text: str) -> None:
32
+ """Copy text to system clipboard using platform-specific commands."""
33
+ try:
34
+ if sys.platform == "darwin":
35
+ subprocess.run(["pbcopy"], input=text.encode("utf-8"), check=True)
36
+ elif sys.platform == "win32":
37
+ subprocess.run(["clip"], input=text.encode("utf-16"), check=True)
38
+ else:
39
+ # Linux: try xclip first, then xsel
40
+ if shutil.which("xclip"):
41
+ subprocess.run(
42
+ ["xclip", "-selection", "clipboard"],
43
+ input=text.encode("utf-8"),
44
+ check=True,
45
+ )
46
+ elif shutil.which("xsel"):
47
+ subprocess.run(
48
+ ["xsel", "--clipboard", "--input"],
49
+ input=text.encode("utf-8"),
50
+ check=True,
51
+ )
52
+ except (OSError, subprocess.SubprocessError):
53
+ pass
20
54
 
21
55
 
22
56
  def create_key_bindings(
23
57
  capture_clipboard_tag: Callable[[], str | None],
24
- copy_to_clipboard: Callable[[str], None],
25
58
  at_token_pattern: re.Pattern[str],
26
59
  *,
27
60
  input_enabled: Filter | None = None,
@@ -31,8 +64,7 @@ def create_key_bindings(
31
64
  """Create REPL key bindings with injected dependencies.
32
65
 
33
66
  Args:
34
- capture_clipboard_tag: Callable to capture clipboard image and return tag
35
- copy_to_clipboard: Callable to copy text to system clipboard
67
+ capture_clipboard_tag: Callable to capture clipboard image and return [image ...] marker
36
68
  at_token_pattern: Pattern to match @token for completion refresh
37
69
 
38
70
  Returns:
@@ -41,6 +73,51 @@ def create_key_bindings(
41
73
  kb = KeyBindings()
42
74
  enabled = input_enabled if input_enabled is not None else Always()
43
75
 
76
+ term_program = os.environ.get("TERM_PROGRAM", "").lower()
77
+ swallow_next_control_j = False
78
+
79
+ def _data_requests_newline(data: str) -> bool:
80
+ """Return True when incoming key data should insert a newline.
81
+
82
+ Different terminals and editor-integrated terminals can emit different
83
+ sequences for Shift+Enter/Alt+Enter. We treat these as "insert newline"
84
+ instead of "submit".
85
+ """
86
+
87
+ if not data:
88
+ return False
89
+
90
+ # Pure LF or LF-prefixed sequences (e.g. when modifiers are encoded).
91
+ if data == "\n" or (ord(data[0]) == 10 and len(data) > 1):
92
+ return True
93
+
94
+ # Known escape sequences observed in some terminals.
95
+ if data in {
96
+ "\x1b\r", # Alt+Enter (ESC + CR)
97
+ "\x1b[13;2~", # Shift+Enter (some terminals)
98
+ "\x1b[27;2;13~", # Shift+Enter (xterm "CSI 27" modified keys)
99
+ "\\\r", # Backslash+Enter sentinel (some editor terminals)
100
+ }:
101
+ return True
102
+
103
+ # Any payload that contains both ESC and CR.
104
+ return len(data) > 1 and "\x1b" in data and "\r" in data
105
+
106
+ def _insert_newline(event: KeyPressEvent, *, strip_trailing_backslash: bool = False) -> None:
107
+ buf = event.current_buffer
108
+ if strip_trailing_backslash:
109
+ try:
110
+ doc = buf.document # type: ignore[reportUnknownMemberType]
111
+ if doc.text_before_cursor.endswith("\\"): # type: ignore[reportUnknownMemberType]
112
+ buf.delete_before_cursor() # type: ignore[reportUnknownMemberType]
113
+ except Exception:
114
+ pass
115
+
116
+ with contextlib.suppress(Exception):
117
+ buf.insert_text("\n") # type: ignore[reportUnknownMemberType]
118
+ with contextlib.suppress(Exception):
119
+ event.app.invalidate() # type: ignore[reportUnknownMemberType]
120
+
44
121
  def _can_move_cursor_visually_within_wrapped_line(delta_visible_y: int) -> bool:
45
122
  """Return True when Up/Down should move within a wrapped visual line.
46
123
 
@@ -233,28 +310,85 @@ def create_key_bindings(
233
310
 
234
311
  @kb.add("c-v", filter=enabled)
235
312
  def _(event: KeyPressEvent) -> None:
236
- """Paste image from clipboard as [Image #N]."""
237
- tag = capture_clipboard_tag()
238
- if tag:
313
+ """Paste image from clipboard as an `[image ...]` marker."""
314
+ marker = capture_clipboard_tag()
315
+ if marker:
316
+ with contextlib.suppress(Exception):
317
+ event.current_buffer.insert_text(marker) # pyright: ignore[reportUnknownMemberType]
318
+
319
+ @kb.add(Keys.BracketedPaste, filter=enabled)
320
+ def _(event: KeyPressEvent) -> None:
321
+ """Handle bracketed paste.
322
+
323
+ - Large multi-line pastes are folded into a marker: `[paste #N ...]`.
324
+ - Otherwise, try to convert dropped file URLs/paths into @ tokens or `[image ...]` markers.
325
+ """
326
+
327
+ data = getattr(event, "data", "")
328
+ if not isinstance(data, str) or not data:
329
+ return
330
+
331
+ pasted_lines = data.splitlines()
332
+ line_count = max(1, len(pasted_lines))
333
+ total_chars = len(data)
334
+
335
+ should_fold = line_count > 10 or total_chars > 1000
336
+ if should_fold:
337
+ marker = store_paste(data)
338
+ if marker and not marker.endswith((" ", "\t", "\n")):
339
+ marker += " "
239
340
  with contextlib.suppress(Exception):
240
- event.current_buffer.insert_text(tag) # pyright: ignore[reportUnknownMemberType]
341
+ event.current_buffer.insert_text(marker) # pyright: ignore[reportUnknownMemberType]
342
+ return
343
+
344
+ converted = convert_dropped_text(data, cwd=Path.cwd())
345
+ if converted != data and converted and not converted.endswith((" ", "\t", "\n")):
346
+ converted += " "
347
+
348
+ buf = event.current_buffer
349
+ try:
350
+ if buf.selection_state: # type: ignore[reportUnknownMemberType]
351
+ buf.cut_selection() # type: ignore[reportUnknownMemberType]
352
+ except Exception:
353
+ pass
354
+
355
+ with contextlib.suppress(Exception):
356
+ buf.insert_text(converted) # type: ignore[reportUnknownMemberType]
357
+
358
+ @kb.add("escape", "enter", filter=enabled)
359
+ def _(event: KeyPressEvent) -> None:
360
+ """Alt+Enter inserts a newline."""
361
+
362
+ _insert_newline(event)
363
+
364
+ @kb.add("escape", "[", "1", "3", ";", "2", "~", filter=enabled)
365
+ def _(event: KeyPressEvent) -> None:
366
+ """Shift+Enter sequence used by some terminals inserts a newline."""
367
+
368
+ _insert_newline(event)
241
369
 
242
370
  @kb.add("enter", filter=enabled)
243
371
  def _(event: KeyPressEvent) -> None:
372
+ nonlocal swallow_next_control_j
373
+
244
374
  buf = event.current_buffer
245
375
  doc = buf.document # type: ignore
246
376
 
247
- # If VS Code/Windsurf/Cursor sent a "\\" sentinel before Enter (Shift+Enter mapping),
248
- # treat it as a request for a newline instead of submit.
249
- # This allows Shift+Enter to insert a newline in our multiline prompt.
250
- try:
251
- if doc.text_before_cursor.endswith("\\"): # type: ignore[reportUnknownMemberType]
252
- buf.delete_before_cursor() # remove the sentinel backslash # type: ignore[reportUnknownMemberType]
253
- buf.insert_text("\n") # type: ignore[reportUnknownMemberType]
254
- return
255
- except (AttributeError, TypeError):
256
- # Fall through to default behavior if anything goes wrong
257
- pass
377
+ data = getattr(event, "data", "")
378
+ if isinstance(data, str) and _data_requests_newline(data):
379
+ _insert_newline(event)
380
+ return
381
+
382
+ # VS Code-family terminals often implement Shift+Enter via a "\\" sentinel
383
+ # before Enter. Only enable this heuristic under TERM_PROGRAM=vscode.
384
+ if term_program == "vscode":
385
+ try:
386
+ if doc.text_before_cursor.endswith("\\"): # type: ignore[reportUnknownMemberType]
387
+ swallow_next_control_j = True
388
+ _insert_newline(event, strip_trailing_backslash=True)
389
+ return
390
+ except (AttributeError, TypeError):
391
+ pass
258
392
 
259
393
  # When completions are visible, Enter accepts the current selection.
260
394
  # This aligns with common TUI completion UX: navigation doesn't modify
@@ -262,6 +396,21 @@ def create_key_bindings(
262
396
  if not _should_submit_instead_of_accepting_completion(buf) and _accept_current_completion(buf):
263
397
  return
264
398
 
399
+ # Before submitting, expand any folded paste markers so that:
400
+ # - the actual request contains the full pasted content
401
+ # - prompt_toolkit history stores the expanded content
402
+ # Also convert any remaining file:// drops that bypassed bracketed paste.
403
+ try:
404
+ current_text = buf.text # type: ignore[reportUnknownMemberType]
405
+ except Exception:
406
+ current_text = ""
407
+ prepared = expand_paste_markers(current_text)
408
+ prepared = convert_dropped_text(prepared, cwd=Path.cwd())
409
+ if prepared != current_text:
410
+ with contextlib.suppress(Exception):
411
+ buf.text = prepared # type: ignore[reportUnknownMemberType]
412
+ buf.cursor_position = len(prepared) # type: ignore[reportUnknownMemberType]
413
+
265
414
  # If the entire buffer is whitespace-only, insert a newline rather than submitting.
266
415
  if len(buf.text.strip()) == 0: # type: ignore
267
416
  buf.insert_text("\n") # type: ignore
@@ -310,6 +459,11 @@ def create_key_bindings(
310
459
 
311
460
  @kb.add("c-j", filter=enabled)
312
461
  def _(event: KeyPressEvent) -> None:
462
+ nonlocal swallow_next_control_j
463
+ if swallow_next_control_j:
464
+ swallow_next_control_j = False
465
+ return
466
+
313
467
  event.current_buffer.insert_text("\n") # type: ignore
314
468
 
315
469
  @kb.add("c", filter=enabled)
@@ -322,7 +476,7 @@ def create_key_bindings(
322
476
  selected_text: str = doc.text[start:end] # type: ignore[reportUnknownMemberType]
323
477
 
324
478
  if selected_text:
325
- copy_to_clipboard(selected_text) # type: ignore[reportUnknownArgumentType]
479
+ copy_to_clipboard(selected_text)
326
480
  buf.exit_selection() # type: ignore[reportUnknownMemberType]
327
481
  else:
328
482
  buf.insert_text("c") # type: ignore[reportUnknownMemberType]
@@ -0,0 +1,71 @@
1
+ """Fold large multi-line pastes into a short marker.
2
+
3
+ prompt_toolkit already parses terminal bracketed paste mode and exposes the
4
+ pasted payload via a `<bracketed-paste>` key event.
5
+
6
+ We keep the editor buffer small by inserting a marker like:
7
+ - `[paste #3 +42 lines]` (when many lines)
8
+ - `[paste #3 1205 chars]` (when very long)
9
+
10
+ On submit, markers are expanded back to the original pasted content.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+
17
+ _PASTE_MARKER_RE = re.compile(r"\[paste #(?P<id>\d+)(?: (?P<meta>\+\d+ lines|\d+ chars))?\]")
18
+
19
+
20
+ class PasteBufferState:
21
+ def __init__(self) -> None:
22
+ self._next_id = 1
23
+ self._pastes: dict[int, str] = {}
24
+
25
+ def store(self, text: str) -> str:
26
+ paste_id = self._next_id
27
+ self._next_id += 1
28
+
29
+ lines = text.splitlines()
30
+ line_count = max(1, len(lines))
31
+ total_chars = len(text)
32
+
33
+ if line_count > 10:
34
+ marker = f"[paste #{paste_id} +{line_count} lines]"
35
+ else:
36
+ marker = f"[paste #{paste_id} {total_chars} chars]"
37
+
38
+ self._pastes[paste_id] = text
39
+ return marker
40
+
41
+ def expand_markers(self, text: str) -> str:
42
+ used: set[int] = set()
43
+
44
+ def _replace(m: re.Match[str]) -> str:
45
+ try:
46
+ paste_id = int(m.group("id"))
47
+ except (TypeError, ValueError):
48
+ return m.group(0)
49
+
50
+ content = self._pastes.get(paste_id)
51
+ if content is None:
52
+ return m.group(0)
53
+
54
+ used.add(paste_id)
55
+ return content
56
+
57
+ out = _PASTE_MARKER_RE.sub(_replace, text)
58
+ for pid in used:
59
+ self._pastes.pop(pid, None)
60
+ return out
61
+
62
+
63
+ paste_state = PasteBufferState()
64
+
65
+
66
+ def store_paste(text: str) -> str:
67
+ return paste_state.store(text)
68
+
69
+
70
+ def expand_paste_markers(text: str) -> str:
71
+ return paste_state.expand_markers(text)
@@ -36,9 +36,14 @@ from klaude_code.protocol import llm_param
36
36
  from klaude_code.protocol.commands import CommandInfo
37
37
  from klaude_code.protocol.message import UserInputPayload
38
38
  from klaude_code.tui.components.user_input import USER_MESSAGE_MARK
39
- from klaude_code.tui.input.clipboard import capture_clipboard_tag, copy_to_clipboard, extract_images_from_text
40
39
  from klaude_code.tui.input.completers import AT_TOKEN_PATTERN, create_repl_completer
40
+ from klaude_code.tui.input.drag_drop import convert_dropped_text
41
+ from klaude_code.tui.input.images import (
42
+ capture_clipboard_tag,
43
+ extract_images_from_text,
44
+ )
41
45
  from klaude_code.tui.input.key_bindings import create_key_bindings
46
+ from klaude_code.tui.input.paste import expand_paste_markers
42
47
  from klaude_code.tui.terminal.color import is_light_terminal_background
43
48
  from klaude_code.tui.terminal.selector import SelectItem, SelectOverlay, build_model_select_items
44
49
  from klaude_code.ui.core.input import InputProviderABC
@@ -271,7 +276,6 @@ class PromptToolkitInput(InputProviderABC):
271
276
 
272
277
  kb = create_key_bindings(
273
278
  capture_clipboard_tag=capture_clipboard_tag,
274
- copy_to_clipboard=copy_to_clipboard,
275
279
  at_token_pattern=AT_TOKEN_PATTERN,
276
280
  input_enabled=input_enabled,
277
281
  open_model_picker=self._open_model_picker,
@@ -333,7 +337,7 @@ class PromptToolkitInput(InputProviderABC):
333
337
  pointer="→",
334
338
  use_search_filter=True,
335
339
  search_placeholder="type to search",
336
- list_height=10,
340
+ list_height=20,
337
341
  on_select=self._handle_model_selected,
338
342
  )
339
343
  self._model_picker = model_picker
@@ -669,6 +673,12 @@ class PromptToolkitInput(InputProviderABC):
669
673
  with contextlib.suppress(Exception):
670
674
  self._post_prompt()
671
675
 
676
+ # Expand folded paste markers back into the original content.
677
+ line = expand_paste_markers(line)
678
+
679
+ # Convert drag-and-drop file:// URIs that may have bypassed bracketed paste.
680
+ line = convert_dropped_text(line, cwd=Path.cwd())
681
+
672
682
  # Extract images referenced in the input text
673
683
  images = extract_images_from_text(line)
674
684