codebind 0.6.6__tar.gz → 0.6.7__tar.gz

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 (31) hide show
  1. {codebind-0.6.6 → codebind-0.6.7}/PKG-INFO +5 -3
  2. {codebind-0.6.6 → codebind-0.6.7}/README.md +4 -2
  3. {codebind-0.6.6 → codebind-0.6.7}/pyproject.toml +1 -1
  4. {codebind-0.6.6 → codebind-0.6.7}/pyproject.toml.orig +1 -1
  5. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/extension.py +28 -2
  6. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/instructions.md +2 -2
  7. codebind-0.6.7/src/codebind/terminal.py +310 -0
  8. codebind-0.6.6/src/codebind/terminal.py +0 -99
  9. {codebind-0.6.6 → codebind-0.6.7}/LICENSE +0 -0
  10. {codebind-0.6.6 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/install.json +0 -0
  11. {codebind-0.6.6 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/package.json +0 -0
  12. {codebind-0.6.6 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.dae4561c5427a855.js +0 -0
  13. {codebind-0.6.6 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.c10098fb6e87897c.js +0 -0
  14. {codebind-0.6.6 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js +0 -0
  15. {codebind-0.6.6 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json +0 -0
  16. {codebind-0.6.6 → codebind-0.6.7}/jupyterlab/.yarnrc.yml +0 -0
  17. {codebind-0.6.6 → codebind-0.6.7}/jupyterlab/install.json +0 -0
  18. {codebind-0.6.6 → codebind-0.6.7}/jupyterlab/package.json +0 -0
  19. {codebind-0.6.6 → codebind-0.6.7}/jupyterlab/src/index.ts +0 -0
  20. {codebind-0.6.6 → codebind-0.6.7}/jupyterlab/tsconfig.json +0 -0
  21. {codebind-0.6.6 → codebind-0.6.7}/jupyterlab/yarn.lock +0 -0
  22. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/__init__.py +0 -0
  23. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/cli.py +0 -0
  24. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/configuration.py +0 -0
  25. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/conversation.py +0 -0
  26. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/display.py +0 -0
  27. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/execution.py +0 -0
  28. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/images.py +0 -0
  29. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/jupyter.py +0 -0
  30. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/py.typed +0 -0
  31. {codebind-0.6.6 → codebind-0.6.7}/src/codebind/session.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codebind
3
- Version: 0.6.6
3
+ Version: 0.6.7
4
4
  Summary: A frontend-neutral model loop for persistent IPython sessions.
5
5
  Keywords: ai,ipython,llm,repl,agents
6
6
  Author: Giovanni Gravili
@@ -65,14 +65,16 @@ Start a new conversation:
65
65
  uvx codebind
66
66
  ```
67
67
 
68
- Ask through ordinary IPython magic syntax:
68
+ Press `Shift+Tab` to switch the prompt into Question mode; the prompt turns purple. Type a question and press `Enter` to send it. Press `Shift+Tab` again to return to Python mode. Ordinary `Tab` completion is unchanged.
69
+
70
+ The `%question` and `%%question` magics remain available:
69
71
 
70
72
  ```python
71
73
  %%question
72
74
  Inspect this project and tell me what to implement first.
73
75
  ```
74
76
 
75
- Terminal conversations remain live for the current IPython process. Durable automatic resumption belongs to notebooks, where the notebook file provides an unambiguous conversation identity.
77
+ Terminal conversations remain live for the current IPython process. Previous terminal inputs and outputs, including Python cells you ran yourself, enter the model's context when you ask a question. Durable automatic resumption belongs to notebooks, where the notebook file provides an unambiguous conversation identity.
76
78
  Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown is rendered through IPython's terminal MIME renderer. A terminal is a stream rather than a notebook document, so these displays are not editable notebook cells.
77
79
 
78
80
  ## JupyterLab
@@ -37,14 +37,16 @@ Start a new conversation:
37
37
  uvx codebind
38
38
  ```
39
39
 
40
- Ask through ordinary IPython magic syntax:
40
+ Press `Shift+Tab` to switch the prompt into Question mode; the prompt turns purple. Type a question and press `Enter` to send it. Press `Shift+Tab` again to return to Python mode. Ordinary `Tab` completion is unchanged.
41
+
42
+ The `%question` and `%%question` magics remain available:
41
43
 
42
44
  ```python
43
45
  %%question
44
46
  Inspect this project and tell me what to implement first.
45
47
  ```
46
48
 
47
- Terminal conversations remain live for the current IPython process. Durable automatic resumption belongs to notebooks, where the notebook file provides an unambiguous conversation identity.
49
+ Terminal conversations remain live for the current IPython process. Previous terminal inputs and outputs, including Python cells you ran yourself, enter the model's context when you ask a question. Durable automatic resumption belongs to notebooks, where the notebook file provides an unambiguous conversation identity.
48
50
  Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown is rendered through IPython's terminal MIME renderer. A terminal is a stream rather than a notebook document, so these displays are not editable notebook cells.
49
51
 
50
52
  ## JupyterLab
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codebind"
3
- version = "0.6.6"
3
+ version = "0.6.7"
4
4
  description = "A frontend-neutral model loop for persistent IPython sessions."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codebind"
3
- version = "0.6.6"
3
+ version = "0.6.7"
4
4
  description = "A frontend-neutral model loop for persistent IPython sessions."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -13,13 +13,19 @@ from .configuration import load_configuration, load_models
13
13
  from .conversation import MemoryConversationStore, NotebookConversationStore
14
14
  from .jupyter import JupyterLabBridge, TARGET_NAME
15
15
  from .session import Session
16
- from .terminal import install_markdown_renderer
16
+ from .terminal import TerminalCellHistory, install_markdown_renderer, install_question_mode
17
17
 
18
18
 
19
19
  _STATE_ATTRIBUTE = "_codebind_extension_state"
20
20
 
21
21
 
22
22
  def _close_state(state: dict[str, Any]) -> None:
23
+ terminal_history = state.get("terminal_history")
24
+ if isinstance(terminal_history, TerminalCellHistory):
25
+ terminal_history.close()
26
+ restore_terminal_question_mode = state.get("restore_terminal_question_mode")
27
+ if callable(restore_terminal_question_mode):
28
+ restore_terminal_question_mode()
23
29
  restore_terminal_display = state.get("restore_terminal_display")
24
30
  if callable(restore_terminal_display):
25
31
  restore_terminal_display()
@@ -44,6 +50,9 @@ def _close_state(state: dict[str, Any]) -> None:
44
50
  def load_ipython_extension(ipython: InteractiveShell) -> None:
45
51
  """Load Codebind into the active IPython session."""
46
52
  previous = getattr(ipython, _STATE_ATTRIBUTE, None)
53
+ previous_terminal_history = (
54
+ previous.get("terminal_history") if isinstance(previous, dict) else None
55
+ )
47
56
  if isinstance(previous, dict):
48
57
  _close_state(previous)
49
58
 
@@ -78,12 +87,23 @@ def load_ipython_extension(ipython: InteractiveShell) -> None:
78
87
  "comm_manager": manager,
79
88
  "comm_target": None,
80
89
  "restore_terminal_display": None,
90
+ "restore_terminal_question_mode": None,
91
+ "terminal_history": None,
81
92
  }
82
93
 
83
94
  if manager is None:
84
95
  state["session"] = Session(shell=ipython, store=MemoryConversationStore())
85
96
  if isinstance(ipython, TerminalInteractiveShell):
97
+ state["terminal_history"] = TerminalCellHistory(
98
+ ipython,
99
+ previous=(
100
+ previous_terminal_history
101
+ if isinstance(previous_terminal_history, TerminalCellHistory)
102
+ else None
103
+ ),
104
+ )
86
105
  state["restore_terminal_display"] = install_markdown_renderer(ipython)
106
+ state["restore_terminal_question_mode"] = install_question_mode(ipython)
87
107
  else:
88
108
 
89
109
  def accept_comm(comm: Any, message: dict[str, Any]) -> None:
@@ -142,8 +162,14 @@ def load_ipython_extension(ipython: InteractiveShell) -> None:
142
162
  session = Session(shell=ipython, store=MemoryConversationStore())
143
163
  state["session"] = session
144
164
  selected = get_model()
165
+ terminal_history = state.get("terminal_history")
166
+ history = (
167
+ terminal_history.snapshot()
168
+ if isinstance(terminal_history, TerminalCellHistory)
169
+ else None
170
+ )
145
171
  try:
146
- session.send(cell if cell is not None else line, selected)
172
+ session.send(cell if cell is not None else line, selected, notebook=history)
147
173
  except BaseException:
148
174
  asyncio.run(discard_model())
149
175
  raise
@@ -11,7 +11,7 @@ You are a facts-rooted coding agent, operating through the user’s live IPython
11
11
  - Ground factual claims and reported results in direct observations or valid, identifiable sources that actually support them; give the user enough detail to verify the source. Never invent or simulate factual data, sources, citations, quotes, tool output, actions, or observations, or present guesses as facts. If evidence is missing, say so rather than fabricate it. Create synthetic or fictional material only when explicitly requested, label it clearly, and never present it as real; treat fabricated evidence presented as real as fraud.
12
12
  - Keep the user oriented while working. Before meaningful tool work, emit one brief Markdown update saying what you are about to do. Between tool calls, emit another update only for a new phase, an important finding, or a change of plan. Do not perform several meaningful steps silently, but do not narrate trivial operations.
13
13
  - Keep responses brief and direct, free of jargon and human-written with a clear intent.
14
- - Treat notebook-context messages as the authoritative notebook document state; later deltas override earlier cell versions.
15
- - Notebook cells and supported images displayed in them, including images from your IPython tool, enter your context automatically. Inspect those images directly before claiming you cannot see them; mention any reported image omission.
14
+ - Treat notebook-context messages as the authoritative cell history for the active notebook or terminal; later deltas override earlier cell versions. Terminal context includes completed IPython inputs and outputs.
15
+ - Notebook and terminal cells, plus supported images displayed in them, including images from your IPython tool, enter your context automatically. Inspect those images directly before claiming you cannot see them; mention any reported image omission.
16
16
  - Before importing or using a non-standard library, check whether it is available in the active IPython interpreter. If it is missing, determine a working installer for that environment (such as `uv` or `pip`), install it into that interpreter, and verify the import before proceeding; do not assume installation succeeded.
17
17
  - Be very proactive, instead of giving up. You can ask questions to the user to clarify.
@@ -0,0 +1,310 @@
1
+ """Terminal presentation using IPython's prompts, history, and MIME renderers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import sys
7
+ from collections.abc import Callable, Iterator
8
+ from contextlib import contextmanager
9
+ from copy import deepcopy
10
+ from unittest.mock import patch
11
+
12
+ from IPython.terminal.interactiveshell import IPythonPTLexer, TerminalInteractiveShell
13
+ from prompt_toolkit.enums import DEFAULT_BUFFER
14
+ from prompt_toolkit.filters import Condition, has_focus
15
+ from prompt_toolkit.document import Document
16
+ from prompt_toolkit.formatted_text import FormattedText, PygmentsTokens
17
+ from prompt_toolkit.shortcuts import print_formatted_text
18
+ from prompt_toolkit.styles import DynamicStyle, Style, merge_styles
19
+ from rich.console import Console
20
+ from rich.markdown import Markdown
21
+
22
+
23
+ _MISSING = object()
24
+ _IMAGE_FORMATS = ("image/png", "image/jpeg", "image/svg+xml")
25
+
26
+
27
+ def _question_text(transformed: str) -> str | None:
28
+ """Recover a Codebind question from IPython's own transformed history."""
29
+ try:
30
+ statements = ast.parse(transformed).body
31
+ except SyntaxError:
32
+ return None
33
+ if len(statements) != 1 or not isinstance(statements[0], ast.Expr):
34
+ return None
35
+ call = statements[0].value
36
+ if not (
37
+ isinstance(call, ast.Call)
38
+ and isinstance(call.func, ast.Attribute)
39
+ and call.func.attr in {"run_cell_magic", "run_line_magic"}
40
+ and isinstance(call.func.value, ast.Call)
41
+ and isinstance(call.func.value.func, ast.Name)
42
+ and call.func.value.func.id == "get_ipython"
43
+ and bool(call.args)
44
+ and isinstance(call.args[0], ast.Constant)
45
+ and call.args[0].value == "question"
46
+ ):
47
+ return None
48
+ text_index = 2 if call.func.attr == "run_cell_magic" else 1
49
+ if len(call.args) <= text_index or not isinstance(call.args[text_index], ast.Constant):
50
+ return None
51
+ text = call.args[text_index].value
52
+ return text.strip() if isinstance(text, str) else None
53
+
54
+
55
+ def _history_cell(
56
+ shell: TerminalInteractiveShell,
57
+ number: int,
58
+ source: str,
59
+ transformed: str,
60
+ ) -> dict[str, object] | None:
61
+ """Capture one finished IPython cell before later displays can alter its history."""
62
+ if not source.strip():
63
+ return None
64
+ history = shell.history_manager
65
+ identifier = f"terminal-{number}"
66
+ question = _question_text(transformed)
67
+ if question is not None:
68
+ return {"id": identifier, "type": "markdown", "source": question}
69
+
70
+ outputs: list[dict[str, object]] = []
71
+ for record in history.outputs.get(number, ()):
72
+ if record.output_type in {"out_stream", "err_stream"}:
73
+ stream = record.bundle.get("stream", [])
74
+ outputs.append(
75
+ {
76
+ "output_type": "stream",
77
+ "name": "stdout" if record.output_type == "out_stream" else "stderr",
78
+ "text": "".join(stream),
79
+ }
80
+ )
81
+ elif record.output_type in {"display_data", "execute_result"}:
82
+ output: dict[str, object] = {
83
+ "output_type": record.output_type,
84
+ "data": deepcopy(record.bundle),
85
+ "metadata": {},
86
+ }
87
+ if record.output_type == "execute_result":
88
+ output["execution_count"] = number
89
+ outputs.append(output)
90
+ error = history.exceptions.get(number)
91
+ if error is not None:
92
+ outputs.append({"output_type": "error", **deepcopy(error)})
93
+ return {
94
+ "id": identifier,
95
+ "type": "code",
96
+ "source": source,
97
+ "execution_count": number,
98
+ "outputs": outputs,
99
+ }
100
+
101
+
102
+ class TerminalCellHistory:
103
+ """Track completed IPython cells, without reinterpreting mutable output history."""
104
+
105
+ def __init__(
106
+ self,
107
+ shell: TerminalInteractiveShell,
108
+ previous: TerminalCellHistory | None = None,
109
+ ) -> None:
110
+ self.shell = shell
111
+ self._cells = deepcopy(previous._cells) if previous is not None else {}
112
+ history = shell.history_manager
113
+ for number in range(1, shell.execution_count):
114
+ if number in self._cells or number >= len(history.input_hist_raw):
115
+ continue
116
+ cell = _history_cell(
117
+ shell,
118
+ number,
119
+ history.input_hist_raw[number],
120
+ history.input_hist_parsed[number],
121
+ )
122
+ if cell is not None:
123
+ self._cells[number] = cell
124
+ self._callback = self._record
125
+ shell.events.register("post_run_cell", self._callback)
126
+
127
+ def _record(self, result) -> None:
128
+ if result is None or result.execution_count is None or not result.info.store_history:
129
+ return
130
+ cell = _history_cell(
131
+ self.shell,
132
+ result.execution_count,
133
+ result.info.raw_cell,
134
+ result.info.transformed_cell,
135
+ )
136
+ if cell is not None:
137
+ self._cells[result.execution_count] = cell
138
+
139
+ def snapshot(self) -> list[dict[str, object]]:
140
+ return [deepcopy(self._cells[number]) for number in sorted(self._cells)]
141
+
142
+ def close(self) -> None:
143
+ self.shell.events.unregister("post_run_cell", self._callback)
144
+
145
+
146
+ def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]:
147
+ """Let Shift+Tab switch the terminal prompt between Python and questions."""
148
+ prompt_session = shell.pt_app
149
+ if prompt_session is None:
150
+ return lambda: None
151
+
152
+ original_style = prompt_session.style
153
+ original_prompt_for_code = shell.prompt_for_code
154
+ had_prompt_override = "prompt_for_code" in vars(shell)
155
+ bindings = prompt_session.key_bindings
156
+ transforms = shell.input_transformer_manager.cleanup_transforms
157
+ question_mode = False
158
+ active_prompt = False
159
+ pending_question = False
160
+
161
+ def prompt_for_code() -> str:
162
+ nonlocal active_prompt, pending_question
163
+ active_prompt = True
164
+ try:
165
+ text = original_prompt_for_code()
166
+ finally:
167
+ active_prompt = False
168
+ pending_question = question_mode and bool(text.strip())
169
+ return text
170
+
171
+ def transform_question(lines: list[str]) -> list[str]:
172
+ nonlocal pending_question
173
+ if not pending_question:
174
+ return lines
175
+ pending_question = False
176
+ return ["%%question\n", *lines]
177
+
178
+ def toggle_question(event) -> None:
179
+ nonlocal question_mode
180
+ question_mode = not question_mode
181
+ event.app.invalidate()
182
+
183
+ def submit_question(event) -> None:
184
+ event.current_buffer.validate_and_handle()
185
+
186
+ question_active = Condition(lambda: active_prompt and question_mode)
187
+ bindings.add("s-tab", filter=has_focus(DEFAULT_BUFFER))(toggle_question)
188
+ bindings.add("enter", filter=has_focus(DEFAULT_BUFFER) & question_active)(submit_question)
189
+ shell.prompt_for_code = prompt_for_code
190
+ question_style = merge_styles(
191
+ [
192
+ original_style,
193
+ Style.from_dict(
194
+ {
195
+ key: "#a855f7"
196
+ for key in (
197
+ "pygments.prompt",
198
+ "pygments.promptnum",
199
+ "pygments.prompt.mode",
200
+ "pygments.prompt.linenumber",
201
+ "pygments.prompt.continuation",
202
+ "pygments.prompt.padding",
203
+ "pygments.prompt.wrap",
204
+ )
205
+ }
206
+ ),
207
+ ]
208
+ )
209
+ prompt_session.style = DynamicStyle(
210
+ lambda: question_style if active_prompt and question_mode else original_style
211
+ )
212
+ transforms.insert(0, transform_question)
213
+
214
+ def restore() -> None:
215
+ bindings.remove(toggle_question)
216
+ bindings.remove(submit_question)
217
+ transforms.remove(transform_question)
218
+ if had_prompt_override:
219
+ shell.prompt_for_code = original_prompt_for_code
220
+ else:
221
+ del shell.prompt_for_code
222
+ prompt_session.style = original_style
223
+
224
+ return restore
225
+
226
+
227
+ def show_input(shell: TerminalInteractiveShell, cell: str) -> None:
228
+ """Show a model cell with the shell's own input and continuation prompts."""
229
+ sys.stdout.write(shell.separate_in)
230
+ lines = cell.splitlines()
231
+ lexer = IPythonPTLexer().lex_document(Document(cell))
232
+ first_prompt = shell.prompts.in_prompt_tokens()
233
+ prompt_width = sum(len(text) for _, text in first_prompt)
234
+ style = shell.pt_app.app.style if shell.pt_app is not None else shell._style
235
+ for index, _ in enumerate(lines):
236
+ prompt = (
237
+ first_prompt
238
+ if index == 0
239
+ else shell.prompts.continuation_prompt_tokens(prompt_width, lineno=index - 1)
240
+ )
241
+ print_formatted_text(
242
+ PygmentsTokens(prompt),
243
+ FormattedText(lexer(index)),
244
+ sep="",
245
+ style=style,
246
+ color_depth=shell.color_depth,
247
+ )
248
+
249
+
250
+ def install_markdown_renderer(shell: TerminalInteractiveShell) -> Callable[[], None]:
251
+ """Render Codebind's Markdown MIME in the terminal, preserving shell settings."""
252
+ mime = "text/markdown"
253
+ formatter = shell.display_formatter.formatters[mime]
254
+ was_enabled = formatter.enabled
255
+ was_active = mime in shell.display_formatter.active_types
256
+ previous_renderer = shell.mime_renderers.get(mime, _MISSING)
257
+
258
+ def render(text: str, _metadata: object) -> None:
259
+ Console(file=sys.stdout, soft_wrap=True, no_color=shell.colors.lower() == "nocolor").print(
260
+ Markdown(text)
261
+ )
262
+
263
+ formatter.enabled = True
264
+ if not was_active:
265
+ shell.display_formatter.active_types.append(mime)
266
+ shell.mime_renderers[mime] = render
267
+
268
+ def restore() -> None:
269
+ if previous_renderer is _MISSING:
270
+ shell.mime_renderers.pop(mime, None)
271
+ else:
272
+ shell.mime_renderers[mime] = previous_renderer
273
+ if not was_active and mime in shell.display_formatter.active_types:
274
+ shell.display_formatter.active_types.remove(mime)
275
+ formatter.enabled = was_enabled
276
+
277
+ return restore
278
+
279
+
280
+ @contextmanager
281
+ def record_tool_output(shell: TerminalInteractiveShell) -> Iterator[None]:
282
+ """Keep image and shell-command output in IPython's native history."""
283
+ active = shell.display_formatter.active_types
284
+ previous_png_renderer = shell.mime_renderers.pop("image/png", _MISSING)
285
+ settings: list[tuple[str, bool, bool]] = []
286
+ for mime in _IMAGE_FORMATS:
287
+ formatter = shell.display_formatter.formatters[mime]
288
+ settings.append((mime, formatter.enabled, mime in active))
289
+ formatter.enabled = True
290
+ if mime not in active:
291
+ active.append(mime)
292
+ try:
293
+ with patch.object(shell, "system", shell.system_piped):
294
+ yield
295
+ finally:
296
+ for mime, was_enabled, was_active in settings:
297
+ if not was_active and mime in active:
298
+ active.remove(mime)
299
+ shell.display_formatter.formatters[mime].enabled = was_enabled
300
+ if previous_png_renderer is not _MISSING:
301
+ shell.mime_renderers["image/png"] = previous_png_renderer
302
+
303
+
304
+ __all__ = [
305
+ "TerminalCellHistory",
306
+ "install_markdown_renderer",
307
+ "install_question_mode",
308
+ "record_tool_output",
309
+ "show_input",
310
+ ]
@@ -1,99 +0,0 @@
1
- """Terminal presentation using IPython's prompts, history, and MIME renderers."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- from collections.abc import Callable, Iterator
7
- from contextlib import contextmanager
8
- from unittest.mock import patch
9
-
10
- from IPython.terminal.interactiveshell import IPythonPTLexer, TerminalInteractiveShell
11
- from prompt_toolkit.document import Document
12
- from prompt_toolkit.formatted_text import FormattedText, PygmentsTokens
13
- from prompt_toolkit.shortcuts import print_formatted_text
14
- from rich.console import Console
15
- from rich.markdown import Markdown
16
-
17
-
18
- _MISSING = object()
19
- _IMAGE_FORMATS = ("image/png", "image/jpeg", "image/svg+xml")
20
-
21
-
22
- def show_input(shell: TerminalInteractiveShell, cell: str) -> None:
23
- """Show a model cell with the shell's own input and continuation prompts."""
24
- sys.stdout.write(shell.separate_in)
25
- lines = cell.splitlines()
26
- lexer = IPythonPTLexer().lex_document(Document(cell))
27
- first_prompt = shell.prompts.in_prompt_tokens()
28
- prompt_width = sum(len(text) for _, text in first_prompt)
29
- style = shell.pt_app.app.style if shell.pt_app is not None else shell._style
30
- for index, _ in enumerate(lines):
31
- prompt = (
32
- first_prompt
33
- if index == 0
34
- else shell.prompts.continuation_prompt_tokens(prompt_width, lineno=index - 1)
35
- )
36
- print_formatted_text(
37
- PygmentsTokens(prompt),
38
- FormattedText(lexer(index)),
39
- sep="",
40
- style=style,
41
- color_depth=shell.color_depth,
42
- )
43
-
44
-
45
- def install_markdown_renderer(shell: TerminalInteractiveShell) -> Callable[[], None]:
46
- """Render Codebind's Markdown MIME in the terminal, preserving shell settings."""
47
- mime = "text/markdown"
48
- formatter = shell.display_formatter.formatters[mime]
49
- was_enabled = formatter.enabled
50
- was_active = mime in shell.display_formatter.active_types
51
- previous_renderer = shell.mime_renderers.get(mime, _MISSING)
52
-
53
- def render(text: str, _metadata: object) -> None:
54
- Console(file=sys.stdout, soft_wrap=True, no_color=shell.colors.lower() == "nocolor").print(
55
- Markdown(text)
56
- )
57
-
58
- formatter.enabled = True
59
- if not was_active:
60
- shell.display_formatter.active_types.append(mime)
61
- shell.mime_renderers[mime] = render
62
-
63
- def restore() -> None:
64
- if previous_renderer is _MISSING:
65
- shell.mime_renderers.pop(mime, None)
66
- else:
67
- shell.mime_renderers[mime] = previous_renderer
68
- if not was_active and mime in shell.display_formatter.active_types:
69
- shell.display_formatter.active_types.remove(mime)
70
- formatter.enabled = was_enabled
71
-
72
- return restore
73
-
74
-
75
- @contextmanager
76
- def record_tool_output(shell: TerminalInteractiveShell) -> Iterator[None]:
77
- """Keep image and shell-command output in IPython's native history."""
78
- active = shell.display_formatter.active_types
79
- previous_png_renderer = shell.mime_renderers.pop("image/png", _MISSING)
80
- settings: list[tuple[str, bool, bool]] = []
81
- for mime in _IMAGE_FORMATS:
82
- formatter = shell.display_formatter.formatters[mime]
83
- settings.append((mime, formatter.enabled, mime in active))
84
- formatter.enabled = True
85
- if mime not in active:
86
- active.append(mime)
87
- try:
88
- with patch.object(shell, "system", shell.system_piped):
89
- yield
90
- finally:
91
- for mime, was_enabled, was_active in settings:
92
- if not was_active and mime in active:
93
- active.remove(mime)
94
- shell.display_formatter.formatters[mime].enabled = was_enabled
95
- if previous_png_renderer is not _MISSING:
96
- shell.mime_renderers["image/png"] = previous_png_renderer
97
-
98
-
99
- __all__ = ["install_markdown_renderer", "record_tool_output", "show_input"]
File without changes
File without changes
File without changes
File without changes