codebind 0.6.16__py3-none-any.whl → 0.6.17__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.
@@ -0,0 +1,20 @@
1
+ """Bridge synchronous Codebind operations around foreign event loops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Awaitable
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from typing import TypeVar
9
+
10
+ _T = TypeVar("_T")
11
+
12
+
13
+ def run_sync(operation: Awaitable[_T]) -> _T:
14
+ """Run a coroutine without nesting asyncio.run in a loop owned by another API."""
15
+ try:
16
+ asyncio.get_running_loop()
17
+ except RuntimeError:
18
+ return asyncio.run(operation)
19
+ with ThreadPoolExecutor(max_workers=1, thread_name_prefix="codebind-async") as worker:
20
+ return worker.submit(asyncio.run, operation).result()
codebind/extension.py CHANGED
@@ -12,6 +12,7 @@ from IPython.core.page import page
12
12
  from IPython.terminal.interactiveshell import TerminalInteractiveShell
13
13
  from langchain_core.language_models import BaseChatModel
14
14
 
15
+ from .async_runtime import run_sync
15
16
  from .configuration import load_configuration, load_models
16
17
  from .context import format_context
17
18
  from .display import display_assistant
@@ -58,7 +59,7 @@ def _close_state(state: dict[str, Any]) -> None:
58
59
  try:
59
60
  asyncio.get_running_loop().create_task(discard_model())
60
61
  except RuntimeError:
61
- asyncio.run(discard_model())
62
+ run_sync(discard_model())
62
63
 
63
64
 
64
65
  def load_ipython_extension(ipython: InteractiveShell) -> None:
@@ -263,7 +264,7 @@ def load_ipython_extension(ipython: InteractiveShell) -> None:
263
264
  try:
264
265
  session.send(cell if cell is not None else line, selected, notebook=history)
265
266
  except BaseException:
266
- asyncio.run(discard_model())
267
+ run_sync(discard_model())
267
268
  raise
268
269
 
269
270
  ipython.register_magic_function(question_magic, "line_cell", "question")
codebind/session.py CHANGED
@@ -27,6 +27,7 @@ from langchain_core.messages.ai import add_ai_message_chunks
27
27
  from langchain_core.runnables import Runnable
28
28
  from models_provider import TransientProviderError
29
29
 
30
+ from .async_runtime import run_sync
30
31
  from .display import display_assistant
31
32
  from .conversation import Conversation, ConversationStore, MemoryConversationStore
32
33
  from .execution import ExecutionReport, IPythonExecutor
@@ -146,7 +147,7 @@ class Session:
146
147
  await self._ensure_loaded()
147
148
 
148
149
  def _ensure_loaded_sync(self) -> None:
149
- asyncio.run(self._ensure_loaded())
150
+ run_sync(self._ensure_loaded())
150
151
 
151
152
  @staticmethod
152
153
  async def _await_durable(operation: Awaitable[None]) -> None:
@@ -192,17 +193,17 @@ class Session:
192
193
  await self._commit(lambda conversation: conversation.append_notebook(notebook, turn_id))
193
194
 
194
195
  def _append_event_sync(self, event_type: str, **data: Any) -> None:
195
- asyncio.run(self._append_event(event_type, **data))
196
+ run_sync(self._append_event(event_type, **data))
196
197
 
197
198
  def _append_message_sync(self, message: BaseMessage, turn_id: str) -> None:
198
- asyncio.run(self._append_message(message, turn_id))
199
+ run_sync(self._append_message(message, turn_id))
199
200
 
200
201
  def _append_notebook_sync(
201
202
  self,
202
203
  notebook: list[dict[str, Any]] | None,
203
204
  turn_id: str,
204
205
  ) -> None:
205
- asyncio.run(self._append_notebook(notebook, turn_id))
206
+ run_sync(self._append_notebook(notebook, turn_id))
206
207
 
207
208
  def _model_kwargs(self, model: BaseChatModel) -> dict[str, Any]:
208
209
  if self.conversation is None:
@@ -316,7 +317,7 @@ class Session:
316
317
  except TransientProviderError as error:
317
318
  if retry == len(_MODEL_RETRY_DELAYS):
318
319
  raise
319
- asyncio.run(self._reset_model_connection(model))
320
+ run_sync(self._reset_model_connection(model))
320
321
  time.sleep(max(0.0, error.retry_after or _MODEL_RETRY_DELAYS[retry]))
321
322
  raise AssertionError("unreachable")
322
323
 
@@ -434,7 +435,7 @@ class Session:
434
435
  try:
435
436
  asyncio.get_running_loop()
436
437
  except RuntimeError:
437
- asyncio.run(self.aclear())
438
+ run_sync(self.aclear())
438
439
  return
439
440
  raise RuntimeError("clear() cannot run inside an active event loop; use await aclear().")
440
441
 
@@ -459,11 +460,14 @@ class Session:
459
460
  ) -> None:
460
461
  """Send one user message synchronously."""
461
462
  try:
462
- asyncio.get_running_loop()
463
+ loop = asyncio.get_running_loop()
463
464
  except RuntimeError:
464
465
  pass
465
466
  else:
466
- raise RuntimeError("send() cannot run inside an active event loop; use await asend().")
467
+ # Greenlet-backed sync APIs can expose their loop on this thread
468
+ # without this call actually running inside an asyncio task.
469
+ if asyncio.current_task(loop) is not None:
470
+ raise RuntimeError("send() cannot run inside an active event loop; use await asend().")
467
471
 
468
472
  text = prompt.strip()
469
473
  if not text:
codebind/terminal.py CHANGED
@@ -3,8 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import ast
6
+ import asyncio
6
7
  import sys
7
8
  from collections.abc import Callable, Iterator
9
+ from concurrent.futures import ThreadPoolExecutor
8
10
  from contextlib import contextmanager
9
11
  from copy import deepcopy
10
12
  from unittest.mock import patch
@@ -326,12 +328,36 @@ def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]
326
328
  question_mode = False
327
329
  active_prompt = False
328
330
  pending_question = False
331
+ prompt_worker: ThreadPoolExecutor | None = None
329
332
 
330
333
  def prompt_for_code() -> str:
331
- nonlocal active_prompt, pending_question
334
+ nonlocal active_prompt, pending_question, prompt_worker
332
335
  active_prompt = True
333
336
  try:
334
- text = original_prompt_for_code()
337
+ try:
338
+ asyncio.get_running_loop()
339
+ except RuntimeError:
340
+ text = original_prompt_for_code()
341
+ else:
342
+ if prompt_worker is None:
343
+ prompt_worker = ThreadPoolExecutor(max_workers=1, thread_name_prefix="codebind-prompt")
344
+ future = prompt_worker.submit(original_prompt_for_code)
345
+ try:
346
+ text = future.result()
347
+ except BaseException:
348
+ if not future.done():
349
+ app = prompt_session.app
350
+ if app.is_running and app.loop is not None:
351
+ def abort_prompt() -> None:
352
+ if app.is_running:
353
+ app.exit(exception=KeyboardInterrupt())
354
+
355
+ app.loop.call_soon_threadsafe(abort_prompt)
356
+ try:
357
+ future.result(timeout=3)
358
+ except BaseException:
359
+ pass
360
+ raise
335
361
  finally:
336
362
  active_prompt = False
337
363
  pending_question = question_mode and bool(text.strip())
@@ -391,6 +417,8 @@ def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]
391
417
  prompt_session.style = original_style
392
418
  prompt_session.mouse_support = original_prompt_mouse
393
419
  shell.mouse_support = original_shell_mouse
420
+ if prompt_worker is not None:
421
+ prompt_worker.shutdown(wait=False, cancel_futures=True)
394
422
 
395
423
  return restore
396
424
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codebind
3
- Version: 0.6.16
3
+ Version: 0.6.17
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
@@ -77,6 +77,8 @@ The `%question` and `%%question` magics remain available:
77
77
  Inspect this project and tell me what to implement first.
78
78
  ```
79
79
 
80
+ Codebind keeps its terminal prompt and internal bookkeeping usable when a tool cell leaves an asyncio loop active on the terminal thread. This also supports sync clients that manage their own loop across tool cells, without changing IPython’s normal top-level `await` behavior.
81
+
80
82
  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.
81
83
  Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown appears before the following tool cell, and tool output appears as it is written. To keep terminal scrollback usable, Codebind previews at most three gray output lines, shortening each line after 80 characters with `...`. Further lines appear as `… N more output lines.` The complete output remains available to the model and in IPython history; `%output 8` opens the full text of cell 8 in IPython's pager. User-entered Python cells keep IPython's normal display behavior. 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.
82
84
 
@@ -1,4 +1,5 @@
1
1
  codebind/__init__.py,sha256=GNO_K5EPAdgiK2CWsPVVY-3bAmH2TnFJ9ReAWgSbnqM,514
2
+ codebind/async_runtime.py,sha256=ny9QJ0wrEpBcRUsd29EgPLLKUL2YJjZjZn_UbHn9WJI,654
2
3
  codebind/cli.py,sha256=9LOR1L3P8sPsOOgsnpbOsA1PNUZdAj1Z9ROFKeo3EV8,423
3
4
  codebind/configuration.py,sha256=b9ux-MiepzAFfRhorZp4w2pdLLs44necescIGg_IKfo,1828
4
5
  codebind/context.md,sha256=Iht9nJx7drsvjXYiTm-vG-prXx1UQU4VdMgBecWubJI,64
@@ -6,21 +7,21 @@ codebind/context.py,sha256=Lo7WmsOrS1RE3Vk_Lo0Pig8IFK_-RVQOuRPVagvOziM,6051
6
7
  codebind/conversation.py,sha256=nFMe2QgFkFOA2GYInN-cO_jhA9010LpM6_Ij2g4Q2BA,17500
7
8
  codebind/display.py,sha256=IpxcElyNcr5olRIatEduN_d-sRwpsMlaq1UtrOXocQA,494
8
9
  codebind/execution.py,sha256=RBZ6RLs_iFiXBTA2VtWFuIuFN9Auf924vNeH58u1P-I,17324
9
- codebind/extension.py,sha256=eYv-W-pSJ72fg-tyZVt3K99h_WjrGTqYEmP4jIsJ3Gg,11406
10
+ codebind/extension.py,sha256=JHHSfeWsxRzpsoLeFDmaWEiiQNudZKoXo53y_AOxIjg,11436
10
11
  codebind/images.py,sha256=9bJHjXc75_YRBFTAqAWiknRTCjs8ApyGVVSxC_S5lio,4342
11
12
  codebind/instructions.md,sha256=gmj5xtqVxzHPpj32XaxdvoaDwSOchqhH3Ca4aHFLqnw,4745
12
13
  codebind/jupyter.py,sha256=Chl14OBGA_EN99bEiO0rHEQJ6vLdCw-PhaC2JWwpOQ4,9551
13
14
  codebind/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- codebind/session.py,sha256=TfS48Lhu9TgATo5oV5kg9H8_fSBNlOtm-kMIBSs4zW4,24143
15
- codebind/terminal.py,sha256=R-nWSsZBrpxJbEmCBml7UchlV3L6FhcWctaKnaDlfFw,17999
16
- codebind-0.6.16.dist-info/licenses/LICENSE,sha256=ujX46e0LFBIBTnCDY0u3Q7LV363B7CiI7QJZxIkEXlk,1073
17
- codebind-0.6.16.data/data/share/jupyter/labextensions/codebind-jupyterlab/install.json,sha256=78rEThkfrk1pXtekX5WrG9_Y0lJYi5XBEm8n9athpFE,164
18
- codebind-0.6.16.data/data/share/jupyter/labextensions/codebind-jupyterlab/package.json,sha256=kTlYeh6jdbfq3K3EOza3bcKzhNpPO_-5Uniw-wCyfIo,1193
19
- codebind-0.6.16.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.98c719a309e23852.js,sha256=3_28fXeGzVozV517cjkmxSSO9ccdVOe-4-RMBf46p8w,17613
20
- codebind-0.6.16.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.24258c9500a0850a.js,sha256=eWX4O8-R_o-6pVn1LSxUHs3LC8qfi-xX4Vg1QLwy3gg,11795
21
- codebind-0.6.16.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js,sha256=Opy15wyuR_ABqsrk-cOcOj2yZtvtq0r36aDkErnloD0,113
22
- codebind-0.6.16.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json,sha256=MNToQfru1YnHAie-2Virp23yWsc5co3qG0IzrO6SEfw,20
23
- codebind-0.6.16.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
24
- codebind-0.6.16.dist-info/entry_points.txt,sha256=GiPcU63sULDlywJSKigAS4M3vaziYIrubXOb3fAg2_c,48
25
- codebind-0.6.16.dist-info/METADATA,sha256=fnV4XxQKFwhip_rVgmL9RWKGkt3LFzcpD5-hwQDbwyc,8548
26
- codebind-0.6.16.dist-info/RECORD,,
15
+ codebind/session.py,sha256=Ty3fkVxSDVndE7rrH_uoTaK26NI-Aj0CiK8XjyxaZXY,24377
16
+ codebind/terminal.py,sha256=JGguwP1IGC_EsH02DM8Ifrz832U07Tdz8DkFtbPCVwc,19294
17
+ codebind-0.6.17.dist-info/licenses/LICENSE,sha256=ujX46e0LFBIBTnCDY0u3Q7LV363B7CiI7QJZxIkEXlk,1073
18
+ codebind-0.6.17.data/data/share/jupyter/labextensions/codebind-jupyterlab/install.json,sha256=78rEThkfrk1pXtekX5WrG9_Y0lJYi5XBEm8n9athpFE,164
19
+ codebind-0.6.17.data/data/share/jupyter/labextensions/codebind-jupyterlab/package.json,sha256=kTlYeh6jdbfq3K3EOza3bcKzhNpPO_-5Uniw-wCyfIo,1193
20
+ codebind-0.6.17.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.98c719a309e23852.js,sha256=3_28fXeGzVozV517cjkmxSSO9ccdVOe-4-RMBf46p8w,17613
21
+ codebind-0.6.17.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.24258c9500a0850a.js,sha256=eWX4O8-R_o-6pVn1LSxUHs3LC8qfi-xX4Vg1QLwy3gg,11795
22
+ codebind-0.6.17.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js,sha256=Opy15wyuR_ABqsrk-cOcOj2yZtvtq0r36aDkErnloD0,113
23
+ codebind-0.6.17.data/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json,sha256=MNToQfru1YnHAie-2Virp23yWsc5co3qG0IzrO6SEfw,20
24
+ codebind-0.6.17.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
25
+ codebind-0.6.17.dist-info/entry_points.txt,sha256=GiPcU63sULDlywJSKigAS4M3vaziYIrubXOb3fAg2_c,48
26
+ codebind-0.6.17.dist-info/METADATA,sha256=FNcN4HFs5GSpVnNziWkkKBnqAQt2w0z-HheAjGI17CM,8829
27
+ codebind-0.6.17.dist-info/RECORD,,