clikernel 0.2.21__tar.gz → 0.2.23__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 (29) hide show
  1. {clikernel-0.2.21 → clikernel-0.2.23}/CHANGELOG.md +16 -0
  2. {clikernel-0.2.21/clikernel.egg-info → clikernel-0.2.23}/PKG-INFO +12 -13
  3. {clikernel-0.2.21 → clikernel-0.2.23}/README.md +7 -9
  4. clikernel-0.2.23/clikernel/__init__.py +1 -0
  5. clikernel-0.2.23/clikernel/_modidx.py +42 -0
  6. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel/cli.py +51 -62
  7. clikernel-0.2.23/clikernel/core.py +199 -0
  8. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel/login.py +22 -13
  9. clikernel-0.2.23/clikernel/mcp.py +387 -0
  10. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel/rules.py +94 -54
  11. clikernel-0.2.23/clikernel/skill.py +20 -0
  12. clikernel-0.2.23/clikernel/startup.py +15 -0
  13. {clikernel-0.2.21 → clikernel-0.2.23/clikernel.egg-info}/PKG-INFO +12 -13
  14. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel.egg-info/SOURCES.txt +2 -1
  15. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel.egg-info/entry_points.txt +1 -1
  16. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel.egg-info/requires.txt +4 -3
  17. {clikernel-0.2.21 → clikernel-0.2.23}/pyproject.toml +5 -6
  18. clikernel-0.2.23/tests/test_clikernel.py +340 -0
  19. clikernel-0.2.21/clikernel/__init__.py +0 -10
  20. clikernel-0.2.21/clikernel/_modidx.py +0 -56
  21. clikernel-0.2.21/clikernel/core.py +0 -162
  22. clikernel-0.2.21/clikernel/mcp.py +0 -359
  23. clikernel-0.2.21/clikernel/skill.py +0 -20
  24. clikernel-0.2.21/tests/test_rules.py +0 -80
  25. {clikernel-0.2.21 → clikernel-0.2.23}/LICENSE +0 -0
  26. {clikernel-0.2.21 → clikernel-0.2.23}/MANIFEST.in +0 -0
  27. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel.egg-info/dependency_links.txt +0 -0
  28. {clikernel-0.2.21 → clikernel-0.2.23}/clikernel.egg-info/top_level.txt +0 -0
  29. {clikernel-0.2.21 → clikernel-0.2.23}/setup.cfg +0 -0
@@ -2,6 +2,22 @@
2
2
 
3
3
  <!-- do not remove -->
4
4
 
5
+ ## 0.2.23
6
+
7
+ ### New Features
8
+
9
+ - Move standard kernel startup into clikernel and add local docs() MCP tool ([#72](https://github.com/AnswerDotAI/clikernel/pull/72)), thanks to [@jph00](https://github.com/jph00)
10
+ - Default omitted host to local gateway for HOSTED tools and update current gateway on create/use_kernel ([#71](https://github.com/AnswerDotAI/clikernel/issues/71))
11
+
12
+
13
+ ## 0.2.22
14
+
15
+ ### New Features
16
+
17
+ - Replace ipython with execnb.minipy in rules and migrate docs to fastship ([#70](https://github.com/AnswerDotAI/clikernel/pull/70)), thanks to [@jph00](https://github.com/jph00)
18
+ - Cache main kernel name per gateway in MCP Router ([#69](https://github.com/AnswerDotAI/clikernel/pull/69)), thanks to [@jph00](https://github.com/jph00)
19
+
20
+
5
21
  ## 0.2.21
6
22
 
7
23
  ### New Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clikernel
3
- Version: 0.2.21
3
+ Version: 0.2.23
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-Expression: Apache-2.0
@@ -11,27 +11,25 @@ Classifier: Programming Language :: Python :: 3 :: Only
11
11
  Requires-Python: >=3.11
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
- Requires-Dist: fastcore>=2.2.2
14
+ Requires-Dist: fastcore>=2.3.15
15
15
  Requires-Dist: jupyasyncclient>=0.2.32
16
16
  Requires-Dist: mcpmini>=0.0.5
17
17
  Requires-Dist: jupygate>=0.1.0
18
- Requires-Dist: ipymini>=0.1.28
18
+ Requires-Dist: ipymini>=0.1.31
19
19
  Requires-Dist: httpx
20
- Requires-Dist: ipython
20
+ Requires-Dist: execnb>=0.3.5
21
21
  Provides-Extra: dev
22
22
  Requires-Dist: fastship; extra == "dev"
23
+ Requires-Dist: pytest; extra == "dev"
23
24
  Dynamic: license-file
24
25
 
25
26
  # clikernel
26
27
 
27
-
28
- <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
29
-
30
28
  `clikernel` gives LLM agents persistent kernel sessions over MCP or a plain stream protocol. Imports, variables, and results remain available between calls. Agents can create kernels or attach to existing ones, including a user’s live solveit kernel.
31
29
 
32
30
  [jupygate](https://github.com/AnswerDotAI/jupygate) hosts the kernels. Clikernel routes requests to local or named remote gateways and supplies startup code to Python kernels.
33
31
 
34
- New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/core.html) for configuration and lifecycle details.
32
+ New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/docs/api/core.html) for configuration and lifecycle details.
35
33
 
36
34
  ## Install
37
35
 
@@ -60,9 +58,9 @@ create(kernel="py")
60
58
  exec(code="6*7")
61
59
  ```
62
60
 
63
- `create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/mcp.html) for named gateways and other tools.
61
+ `create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/docs/api/mcp.html) for named gateways and other tools.
64
62
 
65
- In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/mcp.html#subagent-kernels) for the settings entry.
63
+ In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/docs/api/mcp.html#subagent-hooks) for the settings entry.
66
64
 
67
65
  The router checks each `exec` cell against built-in rules for mistakes agents often make with this toolkit. Most rules add a note to the reply, and `--quiet` leaves the notes out. Two rules always block the cell: shell access through `subprocess`, [`os.system`](https://docs.python.org/3/library/os.html#os.system) or [`os.popen`](https://docs.python.org/3/library/os.html#os.popen), and changes to `sys.path`.
68
66
 
@@ -70,9 +68,10 @@ The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0`
70
68
 
71
69
  ## Configuration
72
70
 
73
- Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
71
+ Optional files under `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
74
72
 
75
- - `startup.py` runs in each Python kernel clikernel creates, with `__file__` set to its path. Its output appears in the reply announcing the kernel unless `--quiet` is set.
73
+ - `extra-docs/` holds `.md`, `.txt`, or `.py` (module docstring) files returned alongside the built-in `clikernel` guide by the local `docs()` MCP tool, wrapped in `𝍁...𝍁`.
74
+ - `startup.py` runs in each Python kernel clikernel creates after the built-in standard toolkit startup, with `__file__` set to its path. Output appears in the reply announcing the kernel unless `--quiet` is set.
76
75
  - `gateways.toml` names remote gateways and configures authentication without putting tokens in tool arguments:
77
76
 
78
77
  ``` toml
@@ -81,7 +80,7 @@ url = "https://<instance-host>/rusty"
81
80
  token_file = "~/.config/solveit/session"
82
81
  ```
83
82
 
84
- Run `solveit-login` to sign in through your browser and save that session file with mode `0600`. Restart the client after signing in again. Use the instance URL from your browser with `/rusty` appended. For other gateways, choose one of `token`, `token_env` or `token_file`; `verify = false` accepts a self-signed certificate. See [Solveit login](https://AnswerDotAI.github.io/clikernel/login.html) for login options.
83
+ Run `solveit-login` to sign in through your browser and save that session file with mode `0600`. Restart the client after signing in again. Use the instance URL from your browser with `/rusty` appended. For other gateways, choose one of `token`, `token_env` or `token_file`; `verify = false` accepts a self-signed certificate. See [Solveit login](https://AnswerDotAI.github.io/clikernel/docs/api/login.html) for login options.
85
84
 
86
85
  ## The stream protocol
87
86
 
@@ -1,13 +1,10 @@
1
1
  # clikernel
2
2
 
3
-
4
- <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
-
6
3
  `clikernel` gives LLM agents persistent kernel sessions over MCP or a plain stream protocol. Imports, variables, and results remain available between calls. Agents can create kernels or attach to existing ones, including a user’s live solveit kernel.
7
4
 
8
5
  [jupygate](https://github.com/AnswerDotAI/jupygate) hosts the kernels. Clikernel routes requests to local or named remote gateways and supplies startup code to Python kernels.
9
6
 
10
- New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/core.html) for configuration and lifecycle details.
7
+ New kernels close with their creating conversation by default. Attaching to an existing kernel does not claim ownership. Use `autoclose=false` on a persistent gateway to keep a new kernel for later conversations. See [core](https://AnswerDotAI.github.io/clikernel/docs/api/core.html) for configuration and lifecycle details.
11
8
 
12
9
  ## Install
13
10
 
@@ -36,9 +33,9 @@ create(kernel="py")
36
33
  exec(code="6*7")
37
34
  ```
38
35
 
39
- `create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/mcp.html) for named gateways and other tools.
36
+ `create` accepts any kernelspec the gateway finds. In the main conversation, `exec` never creates or switches kernels. See [MCP](https://AnswerDotAI.github.io/clikernel/docs/api/mcp.html) for named gateways and other tools.
40
37
 
41
- In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/mcp.html#subagent-kernels) for the settings entry.
38
+ In Claude Code, subagents share the current kernel unless `clikernel-hook` is registered as a `PreToolUse` hook. With the hook, each subagent’s first `exec` creates a kernel of its own. See [Subagent kernels](https://AnswerDotAI.github.io/clikernel/docs/api/mcp.html#subagent-hooks) for the settings entry.
42
39
 
43
40
  The router checks each `exec` cell against built-in rules for mistakes agents often make with this toolkit. Most rules add a note to the reply, and `--quiet` leaves the notes out. Two rules always block the cell: shell access through `subprocess`, [`os.system`](https://docs.python.org/3/library/os.html#os.system) or [`os.popen`](https://docs.python.org/3/library/os.html#os.popen), and changes to `sys.path`.
44
41
 
@@ -46,9 +43,10 @@ The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0`
46
43
 
47
44
  ## Configuration
48
45
 
49
- Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
46
+ Optional files under `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
50
47
 
51
- - `startup.py` runs in each Python kernel clikernel creates, with `__file__` set to its path. Its output appears in the reply announcing the kernel unless `--quiet` is set.
48
+ - `extra-docs/` holds `.md`, `.txt`, or `.py` (module docstring) files returned alongside the built-in `clikernel` guide by the local `docs()` MCP tool, wrapped in `𝍁...𝍁`.
49
+ - `startup.py` runs in each Python kernel clikernel creates after the built-in standard toolkit startup, with `__file__` set to its path. Output appears in the reply announcing the kernel unless `--quiet` is set.
52
50
  - `gateways.toml` names remote gateways and configures authentication without putting tokens in tool arguments:
53
51
 
54
52
  ``` toml
@@ -57,7 +55,7 @@ url = "https://<instance-host>/rusty"
57
55
  token_file = "~/.config/solveit/session"
58
56
  ```
59
57
 
60
- Run `solveit-login` to sign in through your browser and save that session file with mode `0600`. Restart the client after signing in again. Use the instance URL from your browser with `/rusty` appended. For other gateways, choose one of `token`, `token_env` or `token_file`; `verify = false` accepts a self-signed certificate. See [Solveit login](https://AnswerDotAI.github.io/clikernel/login.html) for login options.
58
+ Run `solveit-login` to sign in through your browser and save that session file with mode `0600`. Restart the client after signing in again. Use the instance URL from your browser with `/rusty` appended. For other gateways, choose one of `token`, `token_env` or `token_file`; `verify = false` accepts a self-signed certificate. See [Solveit login](https://AnswerDotAI.github.io/clikernel/docs/api/login.html) for login options.
61
59
 
62
60
  ## The stream protocol
63
61
 
@@ -0,0 +1 @@
1
+ __version__ = "0.2.23"
@@ -0,0 +1,42 @@
1
+ # Autogenerated by fastship
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'lib_path': 'clikernel',
5
+ 'git_url': 'https://github.com/AnswerDotAI/clikernel',
6
+ 'doc_host': 'https://AnswerDotAI.github.io',
7
+ 'doc_baseurl': '/clikernel'},
8
+ 'syms': { 'clikernel.core': { 'clikernel.core': ('api/core.html', 'clikernel/core.py'),
9
+ 'clikernel.core.Gateway': ('api/core.html#gateway', 'clikernel/core.py'),
10
+ 'clikernel.core.Gateway.rpc': ('api/core.html#gateway.rpc', 'clikernel/core.py'),
11
+ 'clikernel.core.Gateway.initialize': ('api/core.html#gateway.initialize', 'clikernel/core.py'),
12
+ 'clikernel.core.Gateway.tools': ('api/core.html#gateway.tools', 'clikernel/core.py'),
13
+ 'clikernel.core.Gateway.call': ('api/core.html#gateway.call', 'clikernel/core.py'),
14
+ 'clikernel.core.Gateway.text': ('api/core.html#gateway.text', 'clikernel/core.py'),
15
+ 'clikernel.core.Gateway.aclose': ('api/core.html#gateway.aclose', 'clikernel/core.py'),
16
+ 'clikernel.core.default_gateway': ('api/core.html#default_gateway', 'clikernel/core.py'),
17
+ 'clikernel.core.cfg_dir': ('api/core.html#cfg_dir', 'clikernel/core.py'),
18
+ 'clikernel.core.gateways': ('api/core.html#gateways', 'clikernel/core.py'),
19
+ 'clikernel.core.resolve': ('api/core.html#resolve', 'clikernel/core.py'),
20
+ 'clikernel.core.read_docs': ('api/core.html#read_docs', 'clikernel/core.py'),
21
+ 'clikernel.core.boot_calls': ('api/core.html#boot_calls', 'clikernel/core.py'),
22
+ 'clikernel.core.startup_src': ('api/core.html#startup_src', 'clikernel/core.py'),
23
+ 'clikernel.core.session_defaults': ('api/core.html#session_defaults', 'clikernel/core.py')},
24
+ 'clikernel.mcp': { 'clikernel.mcp': ('api/mcp.html', 'clikernel/mcp.py'),
25
+ 'clikernel.mcp.Router': ('api/mcp.html#router', 'clikernel/mcp.py'),
26
+ 'clikernel.mcp.Router.session': ('api/mcp.html#router.session', 'clikernel/mcp.py'),
27
+ 'clikernel.mcp.Router.tools': ('api/mcp.html#router.tools', 'clikernel/mcp.py'),
28
+ 'clikernel.mcp.Router.dispatch': ('api/mcp.html#router.dispatch', 'clikernel/mcp.py'),
29
+ 'clikernel.mcp.Router.aclose': ('api/mcp.html#router.aclose', 'clikernel/mcp.py'),
30
+ 'clikernel.mcp.main': ('api/mcp.html#main', 'clikernel/mcp.py'),
31
+ 'clikernel.mcp.agent_input': ('api/mcp.html#agent_input', 'clikernel/mcp.py'),
32
+ 'clikernel.mcp.hook': ('api/mcp.html#hook', 'clikernel/mcp.py')},
33
+ 'clikernel.cli': { 'clikernel.cli': ('api/cli.html', 'clikernel/cli.py'),
34
+ 'clikernel.cli.main': ('api/cli.html#main', 'clikernel/cli.py'),
35
+ 'clikernel.cli.serve_stream': ('api/cli.html#serve_stream', 'clikernel/cli.py')},
36
+ 'clikernel.rules': { 'clikernel.rules': ('api/rules.html', 'clikernel/rules.py'),
37
+ 'clikernel.rules.Rule': ('api/rules.html#rule', 'clikernel/rules.py'),
38
+ 'clikernel.rules.scan': ('api/rules.html#scan', 'clikernel/rules.py')},
39
+ 'clikernel.login': { 'clikernel.login': ('api/login.html', 'clikernel/login.py'),
40
+ 'clikernel.login.main': ('api/login.html#main', 'clikernel/login.py')}}}
41
+
42
+ docs = {'API': ['clikernel.core', 'clikernel.mcp', 'clikernel.cli', 'clikernel.rules', 'clikernel.login']}
@@ -1,27 +1,31 @@
1
- """The stream-protocol frontend: the service on stdin/stdout for token-reading clients
1
+ """Delimiter-framed stream-protocol frontend on stdin/stdout for token-reading CLI clients.
2
2
 
3
- The `clikernel` command connects a text-stream client to one gateway kernel. Requests and replies use a per-process delimiter. Input is not echoed. A `.` line acknowledges each accepted request before its result arrives.
3
+ The `clikernel` command connects a text-stream client to one `jupygate` kernel using a per-process random delimiter. Input is not echoed; a `.` line acknowledges each accepted request before its result arrives, followed by the delimiter line. Multiline cells (including `%%` cell magics) start with a bare `--` line and end with the session delimiter.
4
4
 
5
- Running the command without arguments creates a Python kernel and stops it on exit. `--kernel` attaches to an existing kernel and leaves it running. Ctrl-C during execution interrupts the kernel without ending the CLI process.
5
+ Running without `--kernel` creates a Python kernel and stops it on `exit`/`quit` or EOF; passing `--kernel` attaches to an existing kernel (by ID or unique prefix) and leaves it running on exit. Ctrl-C during execution interrupts the kernel without ending the CLI process.
6
+ """
7
+ # - order: 3
8
+ # - title: Stream protocol CLI
6
9
 
7
- Docs: https://AnswerDotAI.github.io/clikernel/cli.html.md"""
8
-
9
- # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_cli.ipynb.
10
-
11
- # %% auto #0
12
- __all__ = ['fmt_error', 'serve_stream', 'main']
13
-
14
- # %% ../nbs/02_cli.ipynb #25d654c4
15
10
  import asyncio, secrets, signal, string, sys, termios, threading, traceback, tty
16
- from fastcore.utils import *
11
+
17
12
  from fastcore.script import call_parse
18
13
  from .core import Gateway, default_gateway, resolve, session_defaults
19
14
 
15
+ __all__ = ['main', 'serve_stream']
20
16
 
21
- # %% ../nbs/02_cli.ipynb #d8413fff
22
17
  _ALPHANUM = string.ascii_letters + string.digits
23
18
  _MULTILINE = "--"
24
19
  _MARKER = "loading complete. session delimiter:"
20
+ _EXITS = ('exit', 'exit()', 'quit', 'quit()')
21
+ _PROTOCOL = """<stream-protocol>
22
+ One-line request: send the line. Each response is an acknowledgement line '.' (request accepted, not complete), the rendered output, then the session delimiter line.
23
+ Multiline request (any multi-line cell, including %% cell magics), shown indented -- send it flush-left:
24
+ --
25
+ <complete cell>
26
+ {delim}
27
+ No IPython prompt, no %cpaste, no invented terminators. A blank line is an empty request, so it doubles as an idle poll. Send 'exit' to end; a fresh process is the restart.
28
+ </stream-protocol>"""
25
29
 
26
30
 
27
31
  def _new_delim(): return "--" + ''.join(secrets.choice(_ALPHANUM) for _ in range(5))
@@ -35,44 +39,39 @@ def _read_block(stdin, delim):
35
39
  return "", f"missing block terminator: {delim}"
36
40
 
37
41
 
38
- def fmt_error(tag, text):
42
+ def _fmt_error(tag, text):
39
43
  nl = '' if text.endswith('\n') else '\n'
40
44
  return f"<{tag}>\n{text}{nl}</{tag}>"
41
45
 
42
46
 
43
- # %% ../nbs/02_cli.ipynb #5649e04a
44
47
  def _response(line, stdin, delim, execute):
45
- "Return (body, accepted), acknowledging accepted requests before execution."
46
48
  line = line.rstrip("\n")
47
- if line == delim: return fmt_error("protocol-error", "no multiline request is open: start one with a bare `--` line"), False
49
+ if line == delim: return _fmt_error("protocol-error", "no multiline request is open: start one with a bare `--` line"), False
48
50
  if line == _MULTILINE:
49
51
  code, err = _read_block(stdin, delim)
50
- if err: return fmt_error("protocol-error", err), False
52
+ if err: return _fmt_error("protocol-error", err), False
51
53
  elif line.startswith('%%'):
52
- return fmt_error("protocol-error",
54
+ return _fmt_error("protocol-error",
53
55
  f"a %% cell magic needs a multiline request; send it as (flush-left):\n --\n {line}\n <rest of cell>\n {delim}"), False
54
56
  else: code = line
55
57
  print(".", flush=True)
56
58
  try: return execute(code), True
57
- except BaseException: return fmt_error("internal-error", traceback.format_exc()), True
59
+ except BaseException: return _fmt_error("internal-error", traceback.format_exc()), True
60
+
58
61
 
59
- # %% ../nbs/02_cli.ipynb #8c3decee
60
62
  def _write_response(delim, body=None):
61
63
  if body: print(body, end='' if body.endswith('\n') else '\n', flush=True)
62
64
  print(delim, flush=True)
63
65
 
64
66
 
65
67
  def _next_line(stdin):
66
- "Read one line; when not a TTY, SIGINT while idle means 'interrupt execution', not 'kill the worker', so ignore it"
67
68
  while True:
68
69
  try: return stdin.readline()
69
70
  except KeyboardInterrupt:
70
71
  if stdin.isatty(): raise
71
72
 
72
73
 
73
- # %% ../nbs/02_cli.ipynb #bd6301f5
74
74
  def _tty_clear(stream, idx, mask, cc=None):
75
- "Clear `mask` bits in termios field `idx` when `stream` is a TTY, with optional `cc` char overrides; returns state for `_restore_termios`"
76
75
  if not stream.isatty(): return None
77
76
  fd = stream.fileno()
78
77
  attrs = termios.tcgetattr(fd)
@@ -89,46 +88,12 @@ def _restore_termios(state):
89
88
  if state: termios.tcsetattr(state[0], termios.TCSADRAIN, state[1])
90
89
 
91
90
 
92
- # %% ../nbs/02_cli.ipynb #967cb6e3
93
- def serve_stream(
94
- execute, # Callable `code -> str`: run one request, returning the rendered response body
95
- info="", # Server info announced between the loading lines (forwarded to mcp `instructions`)
96
- should_exit=None # Callable checked after each request; truthy stops the worker
97
- ):
98
- "Serve delimiter-framed requests on stdin/stdout."
99
- # ONLCR off so protocol output stays bare LF; ECHO off (echoed input corrupts the protocol) and ICANON
100
- # off (canonical mode drops bytes past MAX_CANON with BEL spam; VMIN/VTIME make non-canonical reads
101
- # return per byte; ISIG stays on so ^C still interrupts)
102
- output_state = _tty_clear(sys.__stdout__, tty.OFLAG, termios.ONLCR)
103
- echo_state = _tty_clear(sys.stdin, tty.LFLAG, termios.ECHO | termios.ICANON, {termios.VMIN: 1, termios.VTIME: 0})
104
- delim = _new_delim()
105
- print(info, flush=True)
106
- print(f"<stream-protocol>\nOne-line request: send the line. Each response is an acknowledgement line '.' (request accepted, not complete), the rendered output, then the session delimiter line.\n"
107
- f"Multiline request (any multi-line cell, including %% cell magics), shown indented -- send it flush-left:\n"
108
- f" --\n <complete cell>\n {delim}\n"
109
- f"No IPython prompt, no %cpaste, no invented terminators. A blank line is an empty request, so it doubles as an idle poll. Send 'exit' to end; a fresh process is the restart.\n</stream-protocol>", flush=True)
110
- print(_MARKER, flush=True)
111
- _write_response(delim)
112
- try:
113
- while True:
114
- line = _next_line(sys.stdin)
115
- if not line: break
116
- body, accepted = _response(line, sys.stdin, delim, execute)
117
- _write_response(delim, body)
118
- if accepted and should_exit and should_exit(): break
119
- finally:
120
- _restore_termios(echo_state)
121
- _restore_termios(output_state)
122
-
123
- # %% ../nbs/02_cli.ipynb #8347cacd
124
- _EXITS = ('exit', 'exit()', 'quit', 'quit()')
125
-
126
91
  @call_parse
127
92
  def main(
128
- host:str='', # Gateway: empty for the local default, a `gateways.toml` name, or a URL
129
- kernel:str='', # Kernel id (or unique prefix) to attach to; empty creates a kernel, stopped again on exit
130
- ):
131
- "The `clikernel` console script: the stream protocol over one gateway kernel"
93
+ host:str='', # Gateway: empty for local default, a `gateways.toml` name, or a URL
94
+ kernel:str='', # Kernel ID or unique prefix to attach to (empty creates a temporary Python kernel)
95
+ ) -> None:
96
+ "Run the `clikernel` console script serving the stream protocol over one gateway kernel."
132
97
  signal.signal(signal.SIGINT, signal.default_int_handler)
133
98
  print("please wait, loading...", flush=True)
134
99
  loop = asyncio.new_event_loop()
@@ -158,3 +123,27 @@ def main(
158
123
  if child: child.stop()
159
124
  finally: loop.call_soon_threadsafe(loop.stop)
160
125
 
126
+
127
+ def serve_stream(
128
+ execute, # Callable `code -> str` returning the rendered response body
129
+ info:str="", # Server banner printed before the protocol instructions
130
+ should_exit=None, # Optional zero-arg callable checked after each accepted request; truthy stops the loop
131
+ ) -> None:
132
+ "Serve delimiter-framed requests on stdin/stdout, disabling TTY echo and canonical line buffering while active."
133
+ output_state = _tty_clear(sys.__stdout__, tty.OFLAG, termios.ONLCR)
134
+ echo_state = _tty_clear(sys.stdin, tty.LFLAG, termios.ECHO | termios.ICANON, {termios.VMIN: 1, termios.VTIME: 0})
135
+ delim = _new_delim()
136
+ print(info, flush=True)
137
+ print(_PROTOCOL.format(delim=delim), flush=True)
138
+ print(_MARKER, flush=True)
139
+ _write_response(delim)
140
+ try:
141
+ while True:
142
+ line = _next_line(sys.stdin)
143
+ if not line: break
144
+ body, accepted = _response(line, sys.stdin, delim, execute)
145
+ _write_response(delim, body)
146
+ if accepted and should_exit and should_exit(): break
147
+ finally:
148
+ _restore_termios(echo_state)
149
+ _restore_termios(output_state)
@@ -0,0 +1,199 @@
1
+ """Gateway naming, startup delivery, and MCP sessions on `jupygate` gateways.
2
+
3
+ [Jupygate](https://github.com/AnswerDotAI/jupygate) hosts kernels and serves MCP requests at `POST /mcp`. `clikernel` runs alongside it for the duration of a conversation, routing stdio MCP or stream-protocol requests to local or named remote gateways.
4
+
5
+ `gateways.toml`, `extra-docs/`, and optional `startup.py` under `$XDG_CONFIG_HOME/clikernel/` (`~/.config/clikernel/`) configure remote gateways, extra router-served docs, and additional kernel startup. `session_defaults` packages built-in Python startup defaults plus optional `startup.py` as source so startup runs remotely without sharing files; local sessions also forward `cwd` and `os.environ`.
6
+
7
+ `Gateway` owns one MCP session on one gateway. `default_gateway` connects to `CLIKERNEL_HOST` (remote-safe defaults), else tries the local `DEFAULT_URL`, else spawns a disposable child gateway (which the caller must stop). Ending a session stops its `autoclose` kernels while leaving attached or `autoclose=False` kernels running.
8
+
9
+ `resolve` raises `ValueError` for unknown gateway names or conflicting token settings, and `Gateway.rpc` / `Gateway.text` raise `RuntimeError` on protocol or tool errors.
10
+ """
11
+ # - order: 1
12
+ # - title: Gateway sessions and configuration
13
+
14
+ from contextlib import suppress
15
+ from importlib.resources import files
16
+ from pathlib import Path
17
+ import ast, httpx, os
18
+
19
+ from fastcore.xdg import xdg_config_home
20
+ from jupyasyncclient import start_gateway
21
+ from mcpmini.core import HTTPTransport, jreq
22
+ from . import __version__, skill
23
+
24
+ __all__ = ['Gateway', 'default_gateway', 'resolve', 'gateways', 'cfg_dir', 'read_docs', 'boot_calls', 'startup_src', 'session_defaults', 'DEFAULT_URL']
25
+
26
+ DEFAULT_URL = 'http://127.0.0.1:8787'
27
+
28
+
29
+ class Gateway:
30
+ "Open an MCP session on a `jupygate` gateway, invoke its tools, and terminate the session with HTTP DELETE."
31
+ def __init__(
32
+ self,
33
+ url:str, # Gateway base URL (e.g. `'http://127.0.0.1:8787'`)
34
+ token:str=None, # Optional bearer auth token
35
+ verify:bool=True, # Verify TLS certificates
36
+ ):
37
+ client = httpx.AsyncClient(verify=verify, timeout=httpx.Timeout(None, connect=10))
38
+ self.url, self._id = url, 0
39
+ self.tr = HTTPTransport(f"{url.rstrip('/')}/mcp", token=token, http_client=client)
40
+
41
+ async def rpc(
42
+ self,
43
+ method:str, # JSON-RPC method name (e.g. `'tools/list'`, `'tools/call'`)
44
+ **params, # JSON-RPC params mapping
45
+ ): # Result payload from the JSON-RPC response
46
+ "Send a JSON-RPC request and return its `result`, raising `RuntimeError` on JSON-RPC errors."
47
+ self._id += 1
48
+ r = await self.tr.send(jreq(method, self._id, **params))
49
+ if 'error' in r: raise RuntimeError(f"{r['error']['code']}: {r['error']['message']}")
50
+ return r['result']
51
+
52
+ async def initialize(
53
+ self,
54
+ defaults:dict=None, # `jupygate` session defaults dict from `session_defaults`
55
+ ) -> "Gateway": # `self`, with `.info` populated and session initialized
56
+ "Open the MCP session with `defaults` in the `jupygate` extension and send `notifications/initialized`."
57
+ await self.tr.start()
58
+ try:
59
+ self.info = await self.rpc('initialize', protocolVersion='2025-11-25', capabilities={},
60
+ clientInfo=dict(name='clikernel', version=__version__), jupygate=defaults or {})
61
+ if defaults and not self.info.get('jupygate'):
62
+ raise RuntimeError(f'gateway at {self.url} did not acknowledge jupygate session defaults; upgrade the gateway')
63
+ self.tr.proto = self.info['protocolVersion']
64
+ await self.tr.send(jreq('notifications/initialized'))
65
+ return self
66
+ except BaseException:
67
+ with suppress(Exception): await self.aclose()
68
+ raise
69
+
70
+ async def tools(self) -> list[dict]:
71
+ "Return the gateway's MCP tool definitions (`tools/list`)."
72
+ return (await self.rpc('tools/list'))['tools']
73
+
74
+ async def call(
75
+ self,
76
+ name:str, # MCP tool name (e.g. `'create'`, `'exec'`, `'list_kernels'`)
77
+ **args, # Tool arguments
78
+ ) -> dict: # Complete MCP tool result dict (`content`, optional `isError`)
79
+ "Call MCP tool `name` and return its complete result dict, including non-text blocks."
80
+ return await self.rpc('tools/call', name=name, arguments=args)
81
+
82
+ async def text(
83
+ self,
84
+ name:str, # MCP tool name
85
+ **args, # Tool arguments
86
+ ) -> str: # Concatenated text content blocks
87
+ "Call MCP tool `name` and join its text blocks, raising `RuntimeError` on `isError` replies."
88
+ r = await self.call(name, **args)
89
+ t = ''.join(c.get('text', '') for c in r['content'] if c['type'] == 'text')
90
+ if r.get('isError'): raise RuntimeError(t)
91
+ return t
92
+
93
+ async def aclose(self) -> None:
94
+ "Send HTTP DELETE to terminate the gateway session and close the HTTP transport."
95
+ try: await self.tr.delete()
96
+ finally: await self.tr.aclose()
97
+
98
+
99
+ async def default_gateway(
100
+ cfgdir:str|Path=None, # Config directory for `session_defaults` and `gateways.toml` (default `cfg_dir()`)
101
+ quiet:bool=False, # Suppress startup output in replies
102
+ url:str=DEFAULT_URL, # Local gateway URL to try before spawning a child (ignored when `CLIKERNEL_HOST` is set)
103
+ ) -> tuple[Gateway, object]: # `(gateway, child)` where `child` is `None` if an existing gateway was reused
104
+ "Return an initialized `Gateway` and any newly spawned child process (which the caller must stop)."
105
+ if host := os.environ.get('CLIKERNEL_HOST'):
106
+ u, token, verify = resolve(host, cfgdir)
107
+ return await Gateway(u, token, verify).initialize(session_defaults(cfgdir, quiet, local=False)), None
108
+ d = session_defaults(cfgdir, quiet, local=True)
109
+ try: return await Gateway(url, os.environ.get('CLIKERNEL_TOKEN'), True).initialize(d), None
110
+ except httpx.ConnectError:
111
+ child = start_gateway()
112
+ try: return await Gateway(child.url).initialize(d), child
113
+ except BaseException:
114
+ child.stop()
115
+ raise
116
+
117
+
118
+ """## Configuration and startup
119
+
120
+ Read optional `gateways.toml` and `startup.py` from `$XDG_CONFIG_HOME/clikernel/` and build `jupygate` session initialization defaults.
121
+ """
122
+
123
+
124
+ def cfg_dir() -> Path:
125
+ "Return the `clikernel` configuration directory (`$XDG_CONFIG_HOME/clikernel`)."
126
+ return xdg_config_home()/'clikernel'
127
+
128
+
129
+ def gateways(
130
+ cfgdir:str|Path=None, # Config directory containing `gateways.toml` (default `cfg_dir()`)
131
+ ) -> dict: # `{name: {url, token|token_env|token_file, verify}}` table (empty if file absent)
132
+ "Read named gateway entries from `gateways.toml`."
133
+ p = (Path(cfgdir) if cfgdir else cfg_dir())/'gateways.toml'
134
+ return p.read_toml().get('gateways', {}) if p.exists() else {}
135
+
136
+
137
+ def resolve(
138
+ host:str='', # Empty string (default local), full URL, or `gateways.toml` name (falls back to `CLIKERNEL_HOST`)
139
+ cfgdir:str|Path=None, # Config directory for `gateways.toml` lookup (default `cfg_dir()`)
140
+ ) -> tuple[str, str|None, bool]: # `(url, token, verify)`
141
+ "Resolve an empty host, URL, or configured gateway name to `(url, token, verify)`."
142
+ host = host or os.environ.get('CLIKERNEL_HOST') or ''
143
+ if not host: return DEFAULT_URL, os.environ.get('CLIKERNEL_TOKEN'), True
144
+ if '://' in host: return host, os.environ.get('CLIKERNEL_TOKEN'), True
145
+ cfgdir = Path(cfgdir) if cfgdir else cfg_dir()
146
+ g = gateways(cfgdir).get(host)
147
+ if g is None: raise ValueError(f"unknown gateway {host!r}: not a URL, and not in {cfgdir/'gateways.toml'}")
148
+ if sum(k in g for k in ('token', 'token_env', 'token_file')) > 1:
149
+ raise ValueError(f"gateway {host!r}: choose one of token, token_env or token_file")
150
+ token = g.get('token') or os.environ.get(g.get('token_env', ''))
151
+ if 'token_file' in g: token = Path(g['token_file']).expanduser().read_text().strip()
152
+ return g['url'], token or None, g.get('verify', True)
153
+
154
+
155
+ def _with_file(src, path): return f"__file__ = {str(path)!r}\ntry: exec(compile({src!r}, __file__, 'exec'))\nfinally: del __file__"
156
+
157
+
158
+ _DOC_EXTS = {'.md', '.txt', '.py'}
159
+
160
+ def read_docs(
161
+ cfgdir:str|Path=None, # Config directory for `extra-docs/` lookup (default `cfg_dir()`)
162
+ ) -> str: # Combined `clikernel` and `extra-docs/` text with `# <name>` headers
163
+ "Read the built-in `clikernel` usage doc followed by every configured file in `extra-docs/`."
164
+ sections = [f"# clikernel\n\n{(skill.__doc__ or '').strip()}"]
165
+ ed = (Path(cfgdir) if cfgdir else cfg_dir())/'extra-docs'
166
+ if ed.is_dir():
167
+ for p in sorted(ed.iterdir()):
168
+ if not (p.is_file() and p.suffix in _DOC_EXTS): continue
169
+ txt = p.read_text()
170
+ body = (ast.get_docstring(ast.parse(txt)) or '').strip() if p.suffix == '.py' else txt.strip()
171
+ if body: sections.append(f'# {p.name}\n\n{body}')
172
+ return '\n\n'.join(sections)
173
+
174
+
175
+ def boot_calls() -> tuple[str, ...]: # Parallel MCP `docs()` and kernel `doc(...)` bootstrap calls
176
+ "Return the standard `docs()` and kernel `doc(...)` bootstrap calls."
177
+ return ('docs()', 'doc(pysk)', 'doc(edsk)', 'doc(dsk)', 'doc(exh)', 'doc(rgsk)', 'list_pyskills()')
178
+
179
+
180
+ def startup_src(
181
+ cfgdir:str|Path=None, # Config directory checked for optional `startup.py` (default `cfg_dir()`)
182
+ ) -> str: # Combined Python startup source sent to `jupygate`
183
+ "Build standard Python startup defaults followed by optional user `startup.py` source."
184
+ d = Path(cfgdir) if cfgdir else cfg_dir()
185
+ parts = [files('clikernel').joinpath('startup.py').read_text()]
186
+ if (p := d/'startup.py').exists(): parts.append(_with_file(p.read_text(), p))
187
+ return '\n'.join(parts)
188
+
189
+
190
+ def session_defaults(
191
+ cfgdir:str|Path=None, # Config directory for `startup_src` (default `cfg_dir()`)
192
+ quiet:bool=False, # Suppress startup output in gateway replies
193
+ local:bool=True, # Include local `cwd` and `os.environ` (set `False` for remote gateways)
194
+ ) -> dict: # `jupygate` initialization defaults dict
195
+ "Build `jupygate` session defaults: `startup`, `quiet`, plus `cwd`/`env` when `local=True` or harness session ids when remote."
196
+ d = dict(startup=startup_src(cfgdir), quiet=quiet)
197
+ if local: d.update(cwd=os.getcwd(), env=dict(os.environ))
198
+ elif env := {k: v for k in ('CLAUDE_CODE_SESSION_ID', 'CODEX_THREAD_ID') if (v := os.environ.get(k))}: d['env'] = env
199
+ return d
@@ -1,25 +1,34 @@
1
- """Sign in through a browser and save a Solveit session for gateway clients
1
+ """Sign in through a browser and save a Solveit session cookie for gateway clients.
2
2
 
3
- Docs: https://AnswerDotAI.github.io/clikernel/login.html.md"""
3
+ Run `solveit-login` and finish signing in in the browser. The command saves the signed `_solveit` cookie value to `$XDG_CONFIG_HOME/solveit/session` (`~/.config/solveit/session`) for use as `token_file` in `~/.config/clikernel/gateways.toml`:
4
4
 
5
- # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_login.ipynb.
5
+ ```toml
6
+ [gateways.solveit]
7
+ url = "https://<your-instance>.solve.it.com/rusty"
8
+ token_file = "~/.config/solveit/session"
9
+ ```
6
10
 
7
- # %% auto #0
8
- __all__ = ['main']
11
+ Raises `TimeoutError` if sign-in does not complete within 10 minutes and `RuntimeError` if Solveit does not return a `_solveit` cookie.
12
+ """
13
+ # - order: 5
14
+ # - title: Solveit browser login
9
15
 
10
- # %% ../nbs/03_login.ipynb #357e8981
16
+ from pathlib import Path
11
17
  import httpx, secrets, time, webbrowser
12
- from fastcore.utils import *
13
- from fastcore.xdg import xdg_config_home
18
+
14
19
  from fastcore.script import call_parse
20
+ from fastcore.xdg import xdg_config_home
21
+ from fastcore.xtras import atomic_save
22
+
23
+ __all__ = ['main']
24
+
15
25
 
16
- # %% ../nbs/03_login.ipynb #984f0dfe
17
26
  @call_parse
18
27
  def main(
19
- server:str='https://solve.it.com', # Solveit login server
20
- output:Path=None, # Session file; defaults to $XDG_CONFIG_HOME/solveit/session
21
- ):
22
- "Sign in to Solveit and save a session credential for gateway clients."
28
+ server:str='https://solve.it.com', # Solveit login server URL
29
+ output:Path=None, # Session file path (defaults to `$XDG_CONFIG_HOME/solveit/session`)
30
+ ) -> None:
31
+ "Open a browser sign-in flow for Solveit and save the `_solveit` session cookie to `output`."
23
32
  output = output.expanduser() if output else xdg_config_home()/'solveit'/'session'
24
33
  paircode = secrets.token_urlsafe(32)
25
34
  with httpx.Client(base_url=server.rstrip('/'), headers={'Accept': 'application/json'}) as client: