clikernel 0.2.5__tar.gz → 0.2.6__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.
@@ -2,6 +2,16 @@
2
2
 
3
3
  <!-- do not remove -->
4
4
 
5
+ ## 0.2.6
6
+
7
+ ### New Features
8
+
9
+ - Replace httpx2 exception handling with fastspec APIError in kernel restart error paths ([#42](https://github.com/AnswerDotAI/clikernel/issues/42))
10
+ - Stop closing kernel managers on disconnect or kernel switch ([#40](https://github.com/AnswerDotAI/clikernel/issues/40))
11
+ - Rename httpx import to httpx2 ([#39](https://github.com/AnswerDotAI/clikernel/issues/39))
12
+ - restart now recovers when the kernel is gone by creating a fresh kernel on the same gateway, with startup files reapplied ([#38](https://github.com/AnswerDotAI/clikernel/issues/38))
13
+
14
+
5
15
  ## 0.2.5
6
16
 
7
17
  ### New Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clikernel
3
- Version: 0.2.5
3
+ Version: 0.2.6
4
4
  Summary: Serve persistent Jupyter kernels to LLMs as concise text, over MCP or a plain stream protocol
5
5
  Author: clikernel contributors
6
6
  License: Apache-2.0
@@ -12,7 +12,8 @@ Requires-Python: >=3.11
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
  Requires-Dist: fastcore>=2.2.2
15
- Requires-Dist: jupyasyncclient>=0.2.2
15
+ Requires-Dist: jupyasyncclient>=0.2.8
16
+ Requires-Dist: fastspec>=0.2.2
16
17
  Requires-Dist: mcpmini>=0.0.1
17
18
  Requires-Dist: aidialog>=0.0.7
18
19
  Requires-Dist: pillow
@@ -5,7 +5,7 @@ Modules:
5
5
  - `clikernel.cli`: The stream-protocol frontend: the service on stdin/stdout for token-reading clients
6
6
  - `clikernel.core`: Connect to gateway-hosted kernels and turn execution into concise text
7
7
  - `clikernel.mcp`: The MCP frontend: `Client` as tools on stdio
8
- - `clikernel.skill`: Use the persistent `clikernel` MCP session as the default workspace for any task advanced through live Python execution -- stateful inspection, file-editing workflows, debugging, experiments, API probes, data transforms, or notebook-style work. Read this before writing, running, or debugging Python code in a session with `clikernel` connected.
8
+ - `clikernel.skill`: Use the `clikernel` MCP session as the default workspace for Python work: reading and changing files, notebook work, trying things out, checking how a library behaves, and reshaping data. One session stays open, so imports and variables carry between calls. Read this before writing, running, or debugging Python code in a session with `clikernel` connected.
9
9
  - `clikernel.stream`: Streaming JSON-lines worker protocol: nbformat-shaped output events, and a supervisor for select-based UIs."""
10
10
 
11
- __version__ = "0.2.5"
11
+ __version__ = "0.2.6"
@@ -11,6 +11,7 @@ __all__ = ['DEFAULT_URL', 'MAXLEN', 'STATE_LOST', 'STATE_LOST_SETUP', 'cfg_dir',
11
11
 
12
12
  # %% ../nbs/00_core.ipynb #2b3b7f4a
13
13
  import os, tomllib
14
+ from fastspec.errors import APIError
14
15
  from fastcore.utils import *
15
16
  from fastcore.nbio import render_text
16
17
  from fastcore.xdg import xdg_config_home
@@ -101,7 +102,6 @@ class Client:
101
102
  async def _use(self, mgr, kid):
102
103
  "Point at `kid` on `mgr`, dropping any previous ws (never the kernel)"
103
104
  if self.kc: await self.kc.aclose()
104
- if self.mgr is not None and self.mgr is not mgr: await self.mgr.aclose()
105
105
  self.mgr,self.kid,self.kc = mgr,kid,mgr.client(kid)
106
106
  self.kc.start_channels()
107
107
  await self.kc.wait_for_ready(timeout=30)
@@ -168,7 +168,6 @@ async def list_kernels(self:Client, host=''):
168
168
  url,tok,ver = resolve(host, self.cfgdir)
169
169
  mgr = JupyAsyncMultiKernelManager(url, token=tok, verify=ver)
170
170
  ks = await mgr.list_kernels()
171
- await mgr.aclose()
172
171
  else: ks = await self.mgr.list_kernels()
173
172
  if not ks: return 'no kernels'
174
173
  def _l(k): return f"{k['id']} {k.get('execution_state','?')} connections={k.get('connections','?')}" + (' <- current' if k['id']==self.kid else '')
@@ -191,7 +190,19 @@ async def stop(self:Client, kernel=''):
191
190
  async def restart(self:Client):
192
191
  "Restart the current kernel: same id, fresh interpreter; a kernel this client created gets `startup.py` and `inspectors.py` again"
193
192
  if not self.kc: return 'no kernel: call `connect` first'
194
- await self.mgr.restart_kernel(self.kid)
193
+ try: await self.mgr.restart_kernel(self.kid)
194
+ except APIError as e:
195
+ if e.status_code is None:
196
+ return f'restart did not complete ({e.error_type}): retry, or `connect` for a fresh kernel; check the gateway if this persists'
197
+ if e.status_code != 404:
198
+ return f'restart failed ({e.message}); the kernel is still listed: retry, `stop` it, or `connect` for a fresh one'
199
+ old,kw = self.kid,{}
200
+ await self.kc.aclose()
201
+ if self.mgr.base_url == resolve('', self.cfgdir)[0]: kw = dict(cwd=os.getcwd(), env=dict(os.environ))
202
+ await self._use(self.mgr, await self.mgr.start_kernel(**kw))
203
+ self.made = True
204
+ out = await self._setup()
205
+ return f'kernel {old} was gone; created fresh kernel {self.kid}.\n' + STATE_LOST_SETUP + (f'\n{out}' if out.strip() else '')
195
206
  await self.kc.wait_for_ready(timeout=30)
196
207
  if not self.made: return STATE_LOST
197
208
  out = await self._setup()
@@ -208,5 +219,4 @@ async def interrupt(self:Client):
208
219
  async def aclose(self:Client):
209
220
  "Drop connections; kernels are left exactly as they are"
210
221
  if self.kc: await self.kc.aclose()
211
- if self.mgr: await self.mgr.aclose()
212
222
  self.mgr,self.kc,self.kid = None,None,None
@@ -0,0 +1,23 @@
1
+ """Use the `clikernel` MCP session as the default workspace for Python work: reading and changing files, notebook work, trying things out, checking how a library behaves, and reshaping data. One session stays open, so imports and variables carry between calls. Read this before writing, running, or debugging Python code in a session with `clikernel` connected.
2
+
3
+ Prefer it over one-off Python scripts (`python -c`, shell heredocs). Prefer in-kernel tools over shell equivalents when they exist: file search and directory listing go through the `rgapi` pyskill (`rg()`/`fd()`/`ls()`), and GitHub and local git work through the `ghapi` pyskill, when those are installed. Shell commands remain the right tool for project test/build commands and non-Python tools.
4
+
5
+ # Starting and stopping
6
+
7
+ The first `execute` creates a kernel and reports what it imported: read that banner, it says what to do next. That kernel stops when the conversation ends. Use a bare `connect` instead when the kernel should stay running afterwards, and tell the user its id.
8
+
9
+ To continue earlier work, or to use the user's solveit kernel, `list_kernels` then `connect` with the id. Attaching runs no setup: the kernel's live state is the point.
10
+
11
+ `restart` gives a fresh interpreter under the same id, so redo any setup. `interrupt` stops a long `execute` and keeps state. If a reply says the kernel has stopped, `connect` again. If `connect` fails, the gateway server is not running: tell the user rather than working around it.
12
+
13
+ Remote gateways are the same verbs with a `host`, named in `~/.config/clikernel/gateways.toml`.
14
+
15
+ # Working in it
16
+
17
+ - Magics work as written. `%cd` expands `~` and is the way to change directory: prefer it over `os.chdir`.
18
+ - Only the last expression in a cell displays. `print(...)` any earlier value you need to see.
19
+ - Everything a cell outputs lands in the conversation. Be selective: `len(v)` first, then decide what to show.
20
+ - Don't re-run an `import` already run this session. If a name raises `NameError`, the kernel restarted or is newly attached: redo setup.
21
+ - After an `nbdev-export` (or any edit to a module already imported), `importlib.reload` that module and re-import any names you hold from it: a name bound by `from x import y` keeps the old object, while a `@patch`ed method refreshes with the reload because the patch writes onto the shared class. Restart only when a class you hold instances of was itself redefined. Check what is loaded by calling it, never with `inspect.getsource`, which reads the file on disk.
22
+ - Try the simple import or API call first, before changing the environment, monkeypatching, or adding setup.
23
+ """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clikernel
3
- Version: 0.2.5
3
+ Version: 0.2.6
4
4
  Summary: Serve persistent Jupyter kernels to LLMs as concise text, over MCP or a plain stream protocol
5
5
  Author: clikernel contributors
6
6
  License: Apache-2.0
@@ -12,7 +12,8 @@ Requires-Python: >=3.11
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
  Requires-Dist: fastcore>=2.2.2
15
- Requires-Dist: jupyasyncclient>=0.2.2
15
+ Requires-Dist: jupyasyncclient>=0.2.8
16
+ Requires-Dist: fastspec>=0.2.2
16
17
  Requires-Dist: mcpmini>=0.0.1
17
18
  Requires-Dist: aidialog>=0.0.7
18
19
  Requires-Dist: pillow
@@ -1,5 +1,6 @@
1
1
  fastcore>=2.2.2
2
- jupyasyncclient>=0.2.2
2
+ jupyasyncclient>=0.2.8
3
+ fastspec>=0.2.2
3
4
  mcpmini>=0.0.1
4
5
  aidialog>=0.0.7
5
6
  pillow
@@ -17,7 +17,8 @@ classifiers = [
17
17
 
18
18
  dependencies = [
19
19
  "fastcore>=2.2.2",
20
- "jupyasyncclient>=0.2.2",
20
+ "jupyasyncclient>=0.2.8",
21
+ "fastspec>=0.2.2",
21
22
  "mcpmini>=0.0.1",
22
23
  "aidialog>=0.0.7",
23
24
  "pillow",
@@ -1,55 +0,0 @@
1
- """Use the persistent `clikernel` MCP session as the default workspace for any task advanced through live Python execution -- stateful inspection, file-editing workflows, debugging, experiments, API probes, data transforms, or notebook-style work. Read this before writing, running, or debugging Python code in a session with `clikernel` connected.
2
-
3
- # Core idea
4
-
5
- clikernel connects this conversation to Jupyter kernels hosted by a gateway server (rustygate) that runs all the time, independently of any conversation. State lasts the whole conversation -- imports, live objects, monkeypatches, cached results -- and a kernel you `connect` explicitly persists across conversations too. Treat it as a notebook-style workbench, not a one-shot script runner.
6
-
7
- Prefer it over one-off Python scripts (`python -c`, shell heredocs) whenever you need to inspect runtime behavior, test an idea, call a Python API, examine package state, run a live probe, or iterate on an implementation detail. Prefer in-kernel tools over shell equivalents when they exist: file search and directory listing go through the `rgapi` pyskill (`rg()`/`fd()`/`ls()`), and GitHub and local git work through the `ghapi` pyskill, when those are installed. Shell commands remain the right tool for project test/build commands and non-Python tools. Run them through the harness's shell tool, never `subprocess`/`os.system` from the kernel, which would bypass the harness's permission hooks.
8
-
9
- # The lifecycle contract
10
-
11
- The lifecycle has one implicit convenience and no implicit destruction beyond it. An `execute` with no kernel connected auto-creates one (default gateway, `startup.py` and inspectors as usual), and the connect banner arrives prepended to that first reply. That auto kernel is scoped to the conversation: it stops when the conversation ends, or the moment `connect` moves anywhere else. Kernels you `connect` explicitly -- created bare or attached by id -- are never stopped except by `stop_kernel`. The tools are self-documenting -- read each tool's MCP description -- and the shape of a session is:
12
-
13
- - Start of work: just `execute` (the first call auto-connects; read the banner: it says what is imported and what to do next), or a bare `connect` when the kernel should outlive the conversation.
14
- - Returning to earlier work (the user asks to continue where a previous conversation left off, or to use their solveit kernel): `list_kernels` to see what's running, then `connect` with the kernel id (or unique prefix). Attach runs nothing -- the kernel's live state is the point.
15
- - End of work: an auto kernel stops itself with the conversation. `stop_kernel` an explicitly created kernel when it was for this task only; leave it running if the user wants to return to it, and tell the user its id so they can.
16
-
17
- `restart` gives the current kernel a genuinely fresh interpreter under the same id (a kernel this conversation created gets `startup.py` and inspectors again; redo any other setup); `interrupt` stops a too-long `execute` while keeping state. If a reply says the kernel died, `connect` again. If `connect` fails because the gateway is unreachable, the gateway server is not running -- report that to the user rather than working around it.
18
-
19
- Remote gateways (a rustygate or solveit instance elsewhere) are the same verbs with a `host`: a name from `~/.config/clikernel/gateways.toml` (`[gateways.<name>]` tables with `url`, `token` or `token_env`, and optional `verify = false` for self-signed TLS) or a URL. Tokens live in the config file, never in tool arguments.
20
-
21
- # Notebook magics
22
-
23
- `execute` runs IPython, so magics work as written. The `%nbrun` line magic (registered by aidialog, which the standard startup imports) runs cells from a `.ipynb` file by cell id prefix -- see `doc(dsk)` after startup for its options. It runs *in the kernel*, so its cells share session state and are checked by the session's inspectors.
24
-
25
- `%cd` expands `~` and is the idiomatic way to change the kernel's directory: prefer it over `os.chdir`.
26
-
27
- # Session setup
28
-
29
- `connect` (creating) first runs `~/.config/clikernel/startup.py` (with `__file__` bound, so the file can locate its neighbors), then installs inspectors from `~/.config/clikernel/inspectors.py`. Both travel as source, so remote kernels get the same setup as local ones. Inspectors see each cell before it runs (1-arg: the AST; 2-arg: AST and raw source): a returned string prints as a note ahead of the cell's output, raising `RuleBlock` (provided in the file's namespace) blocks the cell, and inspector bugs warn and fail open. Attached kernels are taken as found: no startup, no inspectors.
30
-
31
- # Output shape
32
-
33
- Outputs are rendered with `fastcore.nbio.render_text`. A single non-empty output comes back as its preferred text form, e.g. `42`; multiple outputs use readable XML-ish tags (`<stdout>`, `<execute_result>`, ...) with raw, unescaped body text. Exceptions come back as one clean traceback: ANSI-stripped, over-long lines capped at 180 characters with `File `/`Cell ` locations and the exception message always whole. `input()` fails fast in-band (`allow_stdin=False`) rather than hanging. Image outputs (plots etc.) arrive as MCP image blocks, resized to a token-friendly budget, each preceded by a `<media id=...>` text tag naming it; when the image cannot be delivered, a `<media-unavailable>` note appears in the text instead.
34
-
35
- # Interaction rules
36
-
37
- - Try the simple import or API call first, before mutating environment, monkeypatching, or adding setup.
38
- - Like Jupyter, only the *last* expression in a cell displays. `print(...)` any earlier value you need to see.
39
- - Don't re-run an `import` already run this session. If a previously-imported name raises `NameError`, the kernel restarted or is newly attached -- redo setup.
40
- - `importlib.reload` is not always enough: `from x import *` consumers and `@patch`-decorated classes hold stale references. On stale-class symptoms, use the `restart` tool.
41
- - Everything a cell outputs lands in the conversation. Be surgical: `print(len(v))` first, then decide what to show.
42
- - A kernel is shared by anything connected to it: subagents in this session, or the user's own client. Assume shared state is a feature, not a surprise.
43
-
44
- # Pyskills
45
-
46
- This environment commonly has `pyskills` installed. When present, check it first and prefer a relevant pyskill over ad hoc code:
47
-
48
- from pyskills import list_pyskills, doc
49
- import pyskills.skill
50
- doc(pyskills.skill)
51
-
52
- # The stream protocol
53
-
54
- Driven as a plain CLI process (`clikernel [--host H] [--kernel K]`), the same client speaks a delimiter-framed stdin/stdout protocol, documented in its own startup banner and the README. Run bare it creates a kernel and stops it on exit; `--kernel` attaches and leaves it running.
55
- """
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes