codebind 0.6.6__py3-none-any.whl → 0.6.7__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.
codebind/extension.py CHANGED
@@ -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
codebind/instructions.md CHANGED
@@ -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.
codebind/terminal.py CHANGED
@@ -2,15 +2,20 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import ast
5
6
  import sys
6
7
  from collections.abc import Callable, Iterator
7
8
  from contextlib import contextmanager
9
+ from copy import deepcopy
8
10
  from unittest.mock import patch
9
11
 
10
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
11
15
  from prompt_toolkit.document import Document
12
16
  from prompt_toolkit.formatted_text import FormattedText, PygmentsTokens
13
17
  from prompt_toolkit.shortcuts import print_formatted_text
18
+ from prompt_toolkit.styles import DynamicStyle, Style, merge_styles
14
19
  from rich.console import Console
15
20
  from rich.markdown import Markdown
16
21
 
@@ -19,6 +24,206 @@ _MISSING = object()
19
24
  _IMAGE_FORMATS = ("image/png", "image/jpeg", "image/svg+xml")
20
25
 
21
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
+
22
227
  def show_input(shell: TerminalInteractiveShell, cell: str) -> None:
23
228
  """Show a model cell with the shell's own input and continuation prompts."""
24
229
  sys.stdout.write(shell.separate_in)
@@ -96,4 +301,10 @@ def record_tool_output(shell: TerminalInteractiveShell) -> Iterator[None]:
96
301
  shell.mime_renderers["image/png"] = previous_png_renderer
97
302
 
98
303
 
99
- __all__ = ["install_markdown_renderer", "record_tool_output", "show_input"]
304
+ __all__ = [
305
+ "TerminalCellHistory",
306
+ "install_markdown_renderer",
307
+ "install_question_mode",
308
+ "record_tool_output",
309
+ "show_input",
310
+ ]
@@ -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
@@ -4,21 +4,21 @@ codebind/configuration.py,sha256=b9ux-MiepzAFfRhorZp4w2pdLLs44necescIGg_IKfo,182
4
4
  codebind/conversation.py,sha256=nFMe2QgFkFOA2GYInN-cO_jhA9010LpM6_Ij2g4Q2BA,17500
5
5
  codebind/display.py,sha256=IpxcElyNcr5olRIatEduN_d-sRwpsMlaq1UtrOXocQA,494
6
6
  codebind/execution.py,sha256=gqpZP2BFlSnGkdjLXCsouU6Zim9oETz7dmAiHlIybj8,16261
7
- codebind/extension.py,sha256=kLlpPZxW5OrQSAA0Oh5tXTHqTsSat7B_HjG8qsG5F_o,6050
7
+ codebind/extension.py,sha256=y6fFRzPJIEoTNoP7NAd33tGLq-x2kzKm1Ss2eeHimA4,7233
8
8
  codebind/images.py,sha256=9bJHjXc75_YRBFTAqAWiknRTCjs8ApyGVVSxC_S5lio,4342
9
- codebind/instructions.md,sha256=WQ42UB5mmGcRqj_hQBzYLpcyUh1EuKDFU5dZ3GpB6JM,3664
9
+ codebind/instructions.md,sha256=_8CVGEuKgPRLmxfPnJMP0sNGg_Nh_o6z5iuKHKj57RM,3768
10
10
  codebind/jupyter.py,sha256=07H_S9G3iyyUtWRzlvFr5-5X6CuLBXVficu5Fz8jpVw,8652
11
11
  codebind/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
12
  codebind/session.py,sha256=b8fEFOFdZn4h1wIr9RE2K5SPWmoVyro5pRhGUr4rI6c,23722
13
- codebind/terminal.py,sha256=zSnVSHSxVqKg6wyjZm6KtxUTmuyCM46PQoXwVIVxmNw,3819
14
- codebind-0.6.6.dist-info/licenses/LICENSE,sha256=ujX46e0LFBIBTnCDY0u3Q7LV363B7CiI7QJZxIkEXlk,1073
15
- codebind-0.6.6.data/data/share/jupyter/labextensions/codebind-jupyterlab/install.json,sha256=78rEThkfrk1pXtekX5WrG9_Y0lJYi5XBEm8n9athpFE,164
16
- codebind-0.6.6.data/data/share/jupyter/labextensions/codebind-jupyterlab/package.json,sha256=hawl8ZytgxN-WbUjgbzdIVemPPczzmSFoc2HwDxtgIc,1192
17
- codebind-0.6.6.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.dae4561c5427a855.js,sha256=lMbXilytbQEc_kzyVkgzhKZxU_zgdNLTz4uLJfC7APY,16141
18
- codebind-0.6.6.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.c10098fb6e87897c.js,sha256=U0JBoOwkRkzPct8MzcUO1pc2XeVGvxgztXBMtJMg2b4,11794
19
- codebind-0.6.6.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js,sha256=Opy15wyuR_ABqsrk-cOcOj2yZtvtq0r36aDkErnloD0,113
20
- codebind-0.6.6.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json,sha256=MNToQfru1YnHAie-2Virp23yWsc5co3qG0IzrO6SEfw,20
21
- codebind-0.6.6.dist-info/WHEEL,sha256=7hzKWg-J8I3Buqyw5tBii5z_MmAVsDYXXijd_QAtNZ8,81
22
- codebind-0.6.6.dist-info/entry_points.txt,sha256=GiPcU63sULDlywJSKigAS4M3vaziYIrubXOb3fAg2_c,48
23
- codebind-0.6.6.dist-info/METADATA,sha256=2M2ZoO3gCWYhx_BSEFhhECMyXh4prs8mo2V3nF4wMlY,6959
24
- codebind-0.6.6.dist-info/RECORD,,
13
+ codebind/terminal.py,sha256=5ehefVtlrx3j6pURz9kA3nCmwE3wnnnJParOD9VqgfI,11263
14
+ codebind-0.6.7.dist-info/licenses/LICENSE,sha256=ujX46e0LFBIBTnCDY0u3Q7LV363B7CiI7QJZxIkEXlk,1073
15
+ codebind-0.6.7.data/data/share/jupyter/labextensions/codebind-jupyterlab/install.json,sha256=78rEThkfrk1pXtekX5WrG9_Y0lJYi5XBEm8n9athpFE,164
16
+ codebind-0.6.7.data/data/share/jupyter/labextensions/codebind-jupyterlab/package.json,sha256=hawl8ZytgxN-WbUjgbzdIVemPPczzmSFoc2HwDxtgIc,1192
17
+ codebind-0.6.7.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.dae4561c5427a855.js,sha256=lMbXilytbQEc_kzyVkgzhKZxU_zgdNLTz4uLJfC7APY,16141
18
+ codebind-0.6.7.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.c10098fb6e87897c.js,sha256=U0JBoOwkRkzPct8MzcUO1pc2XeVGvxgztXBMtJMg2b4,11794
19
+ codebind-0.6.7.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js,sha256=Opy15wyuR_ABqsrk-cOcOj2yZtvtq0r36aDkErnloD0,113
20
+ codebind-0.6.7.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json,sha256=MNToQfru1YnHAie-2Virp23yWsc5co3qG0IzrO6SEfw,20
21
+ codebind-0.6.7.dist-info/WHEEL,sha256=7hzKWg-J8I3Buqyw5tBii5z_MmAVsDYXXijd_QAtNZ8,81
22
+ codebind-0.6.7.dist-info/entry_points.txt,sha256=GiPcU63sULDlywJSKigAS4M3vaziYIrubXOb3fAg2_c,48
23
+ codebind-0.6.7.dist-info/METADATA,sha256=M_JwPsbx6ZC9FZb8qjs34iZ5DONwxtN0eszXB3Oy8L8,7325
24
+ codebind-0.6.7.dist-info/RECORD,,