codebind 0.6.5__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 (33) hide show
  1. codebind-0.6.7/PKG-INFO +137 -0
  2. codebind-0.6.7/README.md +109 -0
  3. {codebind-0.6.5 → codebind-0.6.7}/pyproject.toml +1 -1
  4. {codebind-0.6.5 → codebind-0.6.7}/pyproject.toml.orig +1 -1
  5. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/extension.py +28 -2
  6. {codebind-0.6.5 → 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.5/PKG-INFO +0 -118
  9. codebind-0.6.5/README.md +0 -90
  10. codebind-0.6.5/src/codebind/terminal.py +0 -99
  11. {codebind-0.6.5 → codebind-0.6.7}/LICENSE +0 -0
  12. {codebind-0.6.5 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/install.json +0 -0
  13. {codebind-0.6.5 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/package.json +0 -0
  14. {codebind-0.6.5 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.dae4561c5427a855.js +0 -0
  15. {codebind-0.6.5 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.c10098fb6e87897c.js +0 -0
  16. {codebind-0.6.5 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js +0 -0
  17. {codebind-0.6.5 → codebind-0.6.7}/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json +0 -0
  18. {codebind-0.6.5 → codebind-0.6.7}/jupyterlab/.yarnrc.yml +0 -0
  19. {codebind-0.6.5 → codebind-0.6.7}/jupyterlab/install.json +0 -0
  20. {codebind-0.6.5 → codebind-0.6.7}/jupyterlab/package.json +0 -0
  21. {codebind-0.6.5 → codebind-0.6.7}/jupyterlab/src/index.ts +0 -0
  22. {codebind-0.6.5 → codebind-0.6.7}/jupyterlab/tsconfig.json +0 -0
  23. {codebind-0.6.5 → codebind-0.6.7}/jupyterlab/yarn.lock +0 -0
  24. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/__init__.py +0 -0
  25. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/cli.py +0 -0
  26. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/configuration.py +0 -0
  27. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/conversation.py +0 -0
  28. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/display.py +0 -0
  29. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/execution.py +0 -0
  30. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/images.py +0 -0
  31. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/jupyter.py +0 -0
  32. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/py.typed +0 -0
  33. {codebind-0.6.5 → codebind-0.6.7}/src/codebind/session.py +0 -0
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.4
2
+ Name: codebind
3
+ Version: 0.6.7
4
+ Summary: A frontend-neutral model loop for persistent IPython sessions.
5
+ Keywords: ai,ipython,llm,repl,agents
6
+ Author: Giovanni Gravili
7
+ Author-email: Giovanni Gravili <ghovax@users.noreply.github.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: ipython>=9.17
19
+ Requires-Dist: langchain-core>=1.0
20
+ Requires-Dist: models-provider>=0.1.2
21
+ Requires-Dist: pillow>=11
22
+ Requires-Dist: resvg-py>=0.5
23
+ Requires-Dist: rich>=14.1
24
+ Requires-Python: >=3.13
25
+ Project-URL: Repository, https://github.com/ghovax/codebind
26
+ Project-URL: Issues, https://github.com/ghovax/codebind/issues
27
+ Description-Content-Type: text/markdown
28
+
29
+ # Codebind
30
+
31
+ Codebind turns an ordinary IPython session into a durable model harness with one tool: an IPython cell executed in the active session. IPython owns execution, namespace, history, magics, tracebacks, and rich display; Codebind owns conversation state and model orchestration.
32
+
33
+ ## Installation
34
+
35
+ ```console
36
+ uvx codebind
37
+ ```
38
+
39
+ Or install it with any Python package installer:
40
+
41
+ ```console
42
+ pip install codebind
43
+ ```
44
+
45
+ ## Configuration
46
+
47
+ Codebind reads its private model choice from `$XDG_CONFIG_HOME/codebind/configuration.json`, or `~/.config/codebind/configuration.json` when `XDG_CONFIG_HOME` is unset:
48
+
49
+ ```json
50
+ {
51
+ "model": "openai/gpt-5.6-luna",
52
+ "parameters": {
53
+ "reasoning_effort": "medium"
54
+ }
55
+ }
56
+ ```
57
+
58
+ Provider credentials use the same XDG directory in `models.json`. Keep both files readable only by their owner. Loading Codebind does not add `chat`, `model`, `models`, `Models`, or any other variable to the IPython namespace.
59
+
60
+ ## Terminal IPython
61
+
62
+ Start a new conversation:
63
+
64
+ ```console
65
+ uvx codebind
66
+ ```
67
+
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:
71
+
72
+ ```python
73
+ %%question
74
+ Inspect this project and tell me what to implement first.
75
+ ```
76
+
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.
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.
79
+
80
+ ## JupyterLab
81
+
82
+ ```console
83
+ uvx --from jupyterlab --with codebind --with 'nbconvert[webpdf]' jupyter lab
84
+ ```
85
+
86
+ When running an unpublished local checkout, expose both its editable Python source and its current prebuilt frontend:
87
+
88
+ ```console
89
+ JUPYTER_PATH=/path/to/codebind/data/share/jupyter \
90
+ uvx --refresh --from jupyterlab --with-editable /path/to/codebind \
91
+ --with 'nbconvert[webpdf]' jupyter-lab
92
+ ```
93
+
94
+ Load Codebind in a notebook:
95
+
96
+ ```python
97
+ %load_ext codebind
98
+ ```
99
+
100
+ That is the complete setup. **Question** is a native toolbar toggle:
101
+
102
+ - Turning it on converts the selected cell into a Question and makes each newly created user cell a Question until the toggle is turned off.
103
+ - Codebind-generated instruction, tool, and answer cells are never converted.
104
+ - Write ordinary Markdown and press `Shift+Enter`.
105
+
106
+ ### Instructions and notebook context
107
+
108
+ - Loading the extension adds a locked Markdown cell containing Codebind's packaged instructions. Its exact text becomes the conversation's immutable system message and remains stable when the server or kernel restarts.
109
+ - The whole notebook is model context. Before each Question, Codebind snapshots ordinary Markdown, raw, and code cells—including visible text and image outputs, but never the live Python namespace.
110
+ - Images displayed by the model's IPython tool are included in that tool's result. PNG, JPEG, WebP, GIF, and SVG renditions are prepared as model-visible images; unsupported or oversized images are reported as omissions.
111
+ - The first turn records the snapshot. Later turns append only new, changed, removed, or reordered cells. Existing Questions, tool calls, tool results, and answers in the conversation ledger are not duplicated.
112
+ - Image bytes travel in the relevant message; notebook snapshots contain only stable image descriptors. This append-only representation keeps the prior model prefix unchanged for provider caching.
113
+
114
+ ### Persistence and notebook behavior
115
+
116
+ - Codebind stores the complete LangChain message, notebook-context, and turn ledger in notebook metadata. Reopening the notebook, restarting its kernel, and loading the extension restores the accumulated context automatically.
117
+ - Each assistant Markdown segment is buffered and inserted as one complete native cell as soon as it finishes, before a following tool call completes.
118
+ - Tool executions and assistant answers are appended to the notebook end without changing the user's selection or scroll position. Tool outputs are collapsed by default and expandable through JupyterLab's native output control.
119
+
120
+ ### Reliability and editing
121
+
122
+ - The conversation ledger validates its structure and each assistant tool call against its single matching result, without a version gate.
123
+ - Interrupted saves finish before a turn is cancelled, preventing a restart from turning a partial write into an orphan tool result. An interrupted tool call is closed with an explicit interrupted result.
124
+ - Temporary model transport failures retry the same Question with a fresh connection; repeated WebSocket failures use HTTP. Invalid requests and authentication failures remain visible errors.
125
+ - If a provider stream is cancelled or fails, Codebind discards that provider session before the next Question while retaining the notebook conversation and stable prompt-cache identity.
126
+ - The instruction cell, sent Question cells, model-authored tool cells, and assistant Markdown cells are non-editable and non-deletable. Draft Questions remain editable until sent. Jupyter's standard interrupt button cancels an active Codebind question.
127
+
128
+ ### Markdown and other frontends
129
+
130
+ - Question and assistant Markdown supports `$...$`, `$$...$$`, `\(...\)`, and `\[...\]` through JupyterLab's native MathJax renderer.
131
+ - Other IPython frontends retain standard MIME display, syntax-highlighted code, Markdown, stdout, tracebacks, rich results, and native IPython history.
132
+
133
+ ## ChatGPT account access
134
+
135
+ - Models Provider owns OpenAI account authorization and token refresh.
136
+ - Save the resulting provider-values object in Codebind's XDG `models.json`; Codebind loads it privately when the extension starts.
137
+ - ChatGPT subscription access is separate from the public, pay-as-you-go OpenAI API and may require compatibility updates when the account protocol changes.
@@ -0,0 +1,109 @@
1
+ # Codebind
2
+
3
+ Codebind turns an ordinary IPython session into a durable model harness with one tool: an IPython cell executed in the active session. IPython owns execution, namespace, history, magics, tracebacks, and rich display; Codebind owns conversation state and model orchestration.
4
+
5
+ ## Installation
6
+
7
+ ```console
8
+ uvx codebind
9
+ ```
10
+
11
+ Or install it with any Python package installer:
12
+
13
+ ```console
14
+ pip install codebind
15
+ ```
16
+
17
+ ## Configuration
18
+
19
+ Codebind reads its private model choice from `$XDG_CONFIG_HOME/codebind/configuration.json`, or `~/.config/codebind/configuration.json` when `XDG_CONFIG_HOME` is unset:
20
+
21
+ ```json
22
+ {
23
+ "model": "openai/gpt-5.6-luna",
24
+ "parameters": {
25
+ "reasoning_effort": "medium"
26
+ }
27
+ }
28
+ ```
29
+
30
+ Provider credentials use the same XDG directory in `models.json`. Keep both files readable only by their owner. Loading Codebind does not add `chat`, `model`, `models`, `Models`, or any other variable to the IPython namespace.
31
+
32
+ ## Terminal IPython
33
+
34
+ Start a new conversation:
35
+
36
+ ```console
37
+ uvx codebind
38
+ ```
39
+
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:
43
+
44
+ ```python
45
+ %%question
46
+ Inspect this project and tell me what to implement first.
47
+ ```
48
+
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.
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.
51
+
52
+ ## JupyterLab
53
+
54
+ ```console
55
+ uvx --from jupyterlab --with codebind --with 'nbconvert[webpdf]' jupyter lab
56
+ ```
57
+
58
+ When running an unpublished local checkout, expose both its editable Python source and its current prebuilt frontend:
59
+
60
+ ```console
61
+ JUPYTER_PATH=/path/to/codebind/data/share/jupyter \
62
+ uvx --refresh --from jupyterlab --with-editable /path/to/codebind \
63
+ --with 'nbconvert[webpdf]' jupyter-lab
64
+ ```
65
+
66
+ Load Codebind in a notebook:
67
+
68
+ ```python
69
+ %load_ext codebind
70
+ ```
71
+
72
+ That is the complete setup. **Question** is a native toolbar toggle:
73
+
74
+ - Turning it on converts the selected cell into a Question and makes each newly created user cell a Question until the toggle is turned off.
75
+ - Codebind-generated instruction, tool, and answer cells are never converted.
76
+ - Write ordinary Markdown and press `Shift+Enter`.
77
+
78
+ ### Instructions and notebook context
79
+
80
+ - Loading the extension adds a locked Markdown cell containing Codebind's packaged instructions. Its exact text becomes the conversation's immutable system message and remains stable when the server or kernel restarts.
81
+ - The whole notebook is model context. Before each Question, Codebind snapshots ordinary Markdown, raw, and code cells—including visible text and image outputs, but never the live Python namespace.
82
+ - Images displayed by the model's IPython tool are included in that tool's result. PNG, JPEG, WebP, GIF, and SVG renditions are prepared as model-visible images; unsupported or oversized images are reported as omissions.
83
+ - The first turn records the snapshot. Later turns append only new, changed, removed, or reordered cells. Existing Questions, tool calls, tool results, and answers in the conversation ledger are not duplicated.
84
+ - Image bytes travel in the relevant message; notebook snapshots contain only stable image descriptors. This append-only representation keeps the prior model prefix unchanged for provider caching.
85
+
86
+ ### Persistence and notebook behavior
87
+
88
+ - Codebind stores the complete LangChain message, notebook-context, and turn ledger in notebook metadata. Reopening the notebook, restarting its kernel, and loading the extension restores the accumulated context automatically.
89
+ - Each assistant Markdown segment is buffered and inserted as one complete native cell as soon as it finishes, before a following tool call completes.
90
+ - Tool executions and assistant answers are appended to the notebook end without changing the user's selection or scroll position. Tool outputs are collapsed by default and expandable through JupyterLab's native output control.
91
+
92
+ ### Reliability and editing
93
+
94
+ - The conversation ledger validates its structure and each assistant tool call against its single matching result, without a version gate.
95
+ - Interrupted saves finish before a turn is cancelled, preventing a restart from turning a partial write into an orphan tool result. An interrupted tool call is closed with an explicit interrupted result.
96
+ - Temporary model transport failures retry the same Question with a fresh connection; repeated WebSocket failures use HTTP. Invalid requests and authentication failures remain visible errors.
97
+ - If a provider stream is cancelled or fails, Codebind discards that provider session before the next Question while retaining the notebook conversation and stable prompt-cache identity.
98
+ - The instruction cell, sent Question cells, model-authored tool cells, and assistant Markdown cells are non-editable and non-deletable. Draft Questions remain editable until sent. Jupyter's standard interrupt button cancels an active Codebind question.
99
+
100
+ ### Markdown and other frontends
101
+
102
+ - Question and assistant Markdown supports `$...$`, `$$...$$`, `\(...\)`, and `\[...\]` through JupyterLab's native MathJax renderer.
103
+ - Other IPython frontends retain standard MIME display, syntax-highlighted code, Markdown, stdout, tracebacks, rich results, and native IPython history.
104
+
105
+ ## ChatGPT account access
106
+
107
+ - Models Provider owns OpenAI account authorization and token refresh.
108
+ - Save the resulting provider-values object in Codebind's XDG `models.json`; Codebind loads it privately when the extension starts.
109
+ - ChatGPT subscription access is separate from the public, pay-as-you-go OpenAI API and may require compatibility updates when the account protocol changes.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codebind"
3
- version = "0.6.5"
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.5"
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
+ ]
codebind-0.6.5/PKG-INFO DELETED
@@ -1,118 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: codebind
3
- Version: 0.6.5
4
- Summary: A frontend-neutral model loop for persistent IPython sessions.
5
- Keywords: ai,ipython,llm,repl,agents
6
- Author: Giovanni Gravili
7
- Author-email: Giovanni Gravili <ghovax@users.noreply.github.com>
8
- License-Expression: MIT
9
- License-File: LICENSE
10
- Classifier: Development Status :: 3 - Alpha
11
- Classifier: Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt
12
- Classifier: Intended Audience :: Developers
13
- Classifier: Operating System :: OS Independent
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.13
16
- Classifier: Programming Language :: Python :: 3.14
17
- Classifier: Typing :: Typed
18
- Requires-Dist: ipython>=9.17
19
- Requires-Dist: langchain-core>=1.0
20
- Requires-Dist: models-provider>=0.1.2
21
- Requires-Dist: pillow>=11
22
- Requires-Dist: resvg-py>=0.5
23
- Requires-Dist: rich>=14.1
24
- Requires-Python: >=3.13
25
- Project-URL: Repository, https://github.com/ghovax/codebind
26
- Project-URL: Issues, https://github.com/ghovax/codebind/issues
27
- Description-Content-Type: text/markdown
28
-
29
- # Codebind
30
-
31
- Codebind turns an ordinary IPython session into a durable model harness with one tool: an IPython cell executed in the active session. IPython owns execution, namespace, history, magics, tracebacks, and rich display; Codebind owns conversation state and model orchestration.
32
-
33
- ## Installation
34
-
35
- ```console
36
- uvx codebind
37
- ```
38
-
39
- Or install it with any Python package installer:
40
-
41
- ```console
42
- pip install codebind
43
- ```
44
-
45
- ## Configuration
46
-
47
- Codebind reads its private model choice from `$XDG_CONFIG_HOME/codebind/configuration.json`, or `~/.config/codebind/configuration.json` when `XDG_CONFIG_HOME` is unset:
48
-
49
- ```json
50
- {
51
- "model": "openai/gpt-5.6-luna",
52
- "parameters": {
53
- "reasoning_effort": "medium"
54
- }
55
- }
56
- ```
57
-
58
- Provider credentials use the same XDG directory in `models.json`. Keep both files readable only by their owner. Loading Codebind does not add `chat`, `model`, `models`, `Models`, or any other variable to the IPython namespace.
59
-
60
- ## Terminal IPython
61
-
62
- Start a new conversation:
63
-
64
- ```console
65
- uvx codebind
66
- ```
67
-
68
- Ask through ordinary IPython magic syntax:
69
-
70
- ```python
71
- %%question
72
- Inspect this project and tell me what to implement first.
73
- ```
74
-
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.
76
- 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
-
78
- ## JupyterLab
79
-
80
- ```console
81
- uvx --from jupyterlab --with codebind --with 'nbconvert[webpdf]' jupyter lab
82
- ```
83
-
84
- When running an unpublished local checkout, expose both its editable Python source and its current prebuilt frontend:
85
-
86
- ```console
87
- JUPYTER_PATH=/path/to/codebind/data/share/jupyter \
88
- uvx --refresh --from jupyterlab --with-editable /path/to/codebind \
89
- --with 'nbconvert[webpdf]' jupyter-lab
90
- ```
91
-
92
- Load Codebind in a notebook:
93
-
94
- ```python
95
- %load_ext codebind
96
- ```
97
-
98
- That is the complete setup. **Question** is a native toolbar toggle. Turning it on converts the selected cell into a Question and automatically makes each newly created user cell a Question until the toggle is turned off. Codebind-generated instruction, tool, and answer cells are never converted. Write ordinary Markdown and press `Shift+Enter`.
99
-
100
- Loading the extension adds a locked Markdown cell containing Codebind's packaged instructions. That exact text becomes the conversation's immutable system message and remains stable when the server or kernel restarts.
101
-
102
- The whole notebook is model context. Before each Question, Codebind takes a canonical snapshot of ordinary Markdown, raw, and code cells, including visible text and image outputs but never the live Python namespace. Images displayed by the model's IPython tool are included in that tool's result as well. PNG, JPEG, WebP, GIF, and SVG renditions are prepared as model-visible images; unsupported or oversized images are reported as omissions rather than silently discarded. The first turn records the snapshot; later turns append only new, changed, removed, or reordered cells. Questions, tool calls, tool results, and answers already present in the conversation ledger are not duplicated. Image bytes are carried in the relevant message, while notebook snapshots contain only stable image descriptors. This append-only representation keeps the prior model prefix unchanged for provider caching.
103
-
104
- Codebind stores the complete LangChain message, notebook-context, and turn ledger in notebook metadata. Reopening the notebook, restarting its kernel, and loading the extension restores the exact accumulated context automatically. Each assistant Markdown segment is buffered and inserted as one complete native cell as soon as that segment finishes, before a following tool call is complete. Tool executions and assistant answers are always appended to the notebook end without changing the user's current selection or scroll position. Tool outputs are collapsed by default and remain expandable through JupyterLab's native output control.
105
-
106
- The conversation ledger validates its structure and every assistant tool call against its single matching result, without a version gate. Interrupted saves finish before a turn is cancelled, so a restart cannot turn a partial write into an orphan tool result. Temporary model transport failures retry the same Question with a fresh connection; repeated WebSocket failures use HTTP. Invalid requests and authentication failures remain visible errors.
107
-
108
- An interrupted tool call is closed with an explicit interrupted result before the turn ends. If a provider stream is cancelled or fails, Codebind discards that provider session before the next Question while retaining the notebook conversation and its stable prompt-cache identity.
109
-
110
- The instruction cell, sent Question cells, model-authored tool cells, and assistant Markdown cells are non-editable and non-deletable. Draft Question cells remain editable until they are sent. Jupyter's standard interrupt button cancels an active Codebind question.
111
-
112
- Question and assistant Markdown supports `$...$`, `$$...$$`, `\(...\)`, and `\[...\]` through JupyterLab's native MathJax renderer.
113
-
114
- Other IPython frontends retain standard MIME display, syntax-highlighted code, Markdown, stdout, tracebacks, rich results, and native IPython history.
115
-
116
- ## ChatGPT account access
117
-
118
- Models Provider owns OpenAI account authorization and token refresh. Save the resulting provider-values object in Codebind's XDG `models.json`; Codebind loads it privately when the extension starts. ChatGPT subscription access is separate from the public, pay-as-you-go OpenAI API and may require compatibility updates when the account protocol changes.
codebind-0.6.5/README.md DELETED
@@ -1,90 +0,0 @@
1
- # Codebind
2
-
3
- Codebind turns an ordinary IPython session into a durable model harness with one tool: an IPython cell executed in the active session. IPython owns execution, namespace, history, magics, tracebacks, and rich display; Codebind owns conversation state and model orchestration.
4
-
5
- ## Installation
6
-
7
- ```console
8
- uvx codebind
9
- ```
10
-
11
- Or install it with any Python package installer:
12
-
13
- ```console
14
- pip install codebind
15
- ```
16
-
17
- ## Configuration
18
-
19
- Codebind reads its private model choice from `$XDG_CONFIG_HOME/codebind/configuration.json`, or `~/.config/codebind/configuration.json` when `XDG_CONFIG_HOME` is unset:
20
-
21
- ```json
22
- {
23
- "model": "openai/gpt-5.6-luna",
24
- "parameters": {
25
- "reasoning_effort": "medium"
26
- }
27
- }
28
- ```
29
-
30
- Provider credentials use the same XDG directory in `models.json`. Keep both files readable only by their owner. Loading Codebind does not add `chat`, `model`, `models`, `Models`, or any other variable to the IPython namespace.
31
-
32
- ## Terminal IPython
33
-
34
- Start a new conversation:
35
-
36
- ```console
37
- uvx codebind
38
- ```
39
-
40
- Ask through ordinary IPython magic syntax:
41
-
42
- ```python
43
- %%question
44
- Inspect this project and tell me what to implement first.
45
- ```
46
-
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.
48
- 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
-
50
- ## JupyterLab
51
-
52
- ```console
53
- uvx --from jupyterlab --with codebind --with 'nbconvert[webpdf]' jupyter lab
54
- ```
55
-
56
- When running an unpublished local checkout, expose both its editable Python source and its current prebuilt frontend:
57
-
58
- ```console
59
- JUPYTER_PATH=/path/to/codebind/data/share/jupyter \
60
- uvx --refresh --from jupyterlab --with-editable /path/to/codebind \
61
- --with 'nbconvert[webpdf]' jupyter-lab
62
- ```
63
-
64
- Load Codebind in a notebook:
65
-
66
- ```python
67
- %load_ext codebind
68
- ```
69
-
70
- That is the complete setup. **Question** is a native toolbar toggle. Turning it on converts the selected cell into a Question and automatically makes each newly created user cell a Question until the toggle is turned off. Codebind-generated instruction, tool, and answer cells are never converted. Write ordinary Markdown and press `Shift+Enter`.
71
-
72
- Loading the extension adds a locked Markdown cell containing Codebind's packaged instructions. That exact text becomes the conversation's immutable system message and remains stable when the server or kernel restarts.
73
-
74
- The whole notebook is model context. Before each Question, Codebind takes a canonical snapshot of ordinary Markdown, raw, and code cells, including visible text and image outputs but never the live Python namespace. Images displayed by the model's IPython tool are included in that tool's result as well. PNG, JPEG, WebP, GIF, and SVG renditions are prepared as model-visible images; unsupported or oversized images are reported as omissions rather than silently discarded. The first turn records the snapshot; later turns append only new, changed, removed, or reordered cells. Questions, tool calls, tool results, and answers already present in the conversation ledger are not duplicated. Image bytes are carried in the relevant message, while notebook snapshots contain only stable image descriptors. This append-only representation keeps the prior model prefix unchanged for provider caching.
75
-
76
- Codebind stores the complete LangChain message, notebook-context, and turn ledger in notebook metadata. Reopening the notebook, restarting its kernel, and loading the extension restores the exact accumulated context automatically. Each assistant Markdown segment is buffered and inserted as one complete native cell as soon as that segment finishes, before a following tool call is complete. Tool executions and assistant answers are always appended to the notebook end without changing the user's current selection or scroll position. Tool outputs are collapsed by default and remain expandable through JupyterLab's native output control.
77
-
78
- The conversation ledger validates its structure and every assistant tool call against its single matching result, without a version gate. Interrupted saves finish before a turn is cancelled, so a restart cannot turn a partial write into an orphan tool result. Temporary model transport failures retry the same Question with a fresh connection; repeated WebSocket failures use HTTP. Invalid requests and authentication failures remain visible errors.
79
-
80
- An interrupted tool call is closed with an explicit interrupted result before the turn ends. If a provider stream is cancelled or fails, Codebind discards that provider session before the next Question while retaining the notebook conversation and its stable prompt-cache identity.
81
-
82
- The instruction cell, sent Question cells, model-authored tool cells, and assistant Markdown cells are non-editable and non-deletable. Draft Question cells remain editable until they are sent. Jupyter's standard interrupt button cancels an active Codebind question.
83
-
84
- Question and assistant Markdown supports `$...$`, `$$...$$`, `\(...\)`, and `\[...\]` through JupyterLab's native MathJax renderer.
85
-
86
- Other IPython frontends retain standard MIME display, syntax-highlighted code, Markdown, stdout, tracebacks, rich results, and native IPython history.
87
-
88
- ## ChatGPT account access
89
-
90
- Models Provider owns OpenAI account authorization and token refresh. Save the resulting provider-values object in Codebind's XDG `models.json`; Codebind loads it privately when the extension starts. ChatGPT subscription access is separate from the public, pay-as-you-go OpenAI API and may require compatibility updates when the account protocol changes.
@@ -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