clikernel 0.2.20__tar.gz → 0.2.22__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.
- {clikernel-0.2.20 → clikernel-0.2.22}/CHANGELOG.md +18 -0
- {clikernel-0.2.20/clikernel.egg-info → clikernel-0.2.22}/PKG-INFO +15 -16
- {clikernel-0.2.20 → clikernel-0.2.22}/README.md +9 -10
- clikernel-0.2.22/clikernel/__init__.py +1 -0
- clikernel-0.2.22/clikernel/_modidx.py +40 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel/cli.py +51 -62
- clikernel-0.2.22/clikernel/core.py +191 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel/login.py +22 -13
- clikernel-0.2.22/clikernel/mcp.py +379 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel/rules.py +94 -54
- clikernel-0.2.22/clikernel/skill.py +19 -0
- {clikernel-0.2.20 → clikernel-0.2.22/clikernel.egg-info}/PKG-INFO +15 -16
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel.egg-info/SOURCES.txt +1 -3
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel.egg-info/entry_points.txt +1 -1
- clikernel-0.2.22/clikernel.egg-info/requires.txt +11 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/pyproject.toml +6 -8
- clikernel-0.2.22/tests/test_clikernel.py +323 -0
- clikernel-0.2.20/clikernel/__init__.py +0 -11
- clikernel-0.2.20/clikernel/_modidx.py +0 -44
- clikernel-0.2.20/clikernel/core.py +0 -148
- clikernel-0.2.20/clikernel/mcp.py +0 -145
- clikernel-0.2.20/clikernel/skill.py +0 -24
- clikernel-0.2.20/clikernel/stream.py +0 -125
- clikernel-0.2.20/clikernel.egg-info/requires.txt +0 -11
- clikernel-0.2.20/tests/test_rules.py +0 -80
- clikernel-0.2.20/tests/test_stream.py +0 -47
- {clikernel-0.2.20 → clikernel-0.2.22}/LICENSE +0 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/MANIFEST.in +0 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel.egg-info/dependency_links.txt +0 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/clikernel.egg-info/top_level.txt +0 -0
- {clikernel-0.2.20 → clikernel-0.2.22}/setup.cfg +0 -0
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
<!-- do not remove -->
|
|
4
4
|
|
|
5
|
+
## 0.2.22
|
|
6
|
+
|
|
7
|
+
### New Features
|
|
8
|
+
|
|
9
|
+
- 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)
|
|
10
|
+
- Cache main kernel name per gateway in MCP Router ([#69](https://github.com/AnswerDotAI/clikernel/pull/69)), thanks to [@jph00](https://github.com/jph00)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
## 0.2.21
|
|
14
|
+
|
|
15
|
+
### New Features
|
|
16
|
+
|
|
17
|
+
- Route subagents to per-(host, agent) gateway sessions with lazy kernel creation and idle session reaping ([#68](https://github.com/AnswerDotAI/clikernel/issues/68))
|
|
18
|
+
- Switch from rustygate to jupygate, remove stream module, and harden `CLIKERNEL_HOST` and remote host routing ([#66](https://github.com/AnswerDotAI/clikernel/issues/66))
|
|
19
|
+
- Add --maxout UTF-8 reply capping in Router with temp-file overflow and %cont paging ([#65](https://github.com/AnswerDotAI/clikernel/issues/65))
|
|
20
|
+
- Add Antigravity support to clikernel-hook, injecting per-conversation agent and cwd, and drop cwd when forwarding to remote hosts ([#64](https://github.com/AnswerDotAI/clikernel/issues/64))
|
|
21
|
+
|
|
22
|
+
|
|
5
23
|
## 0.2.20
|
|
6
24
|
|
|
7
25
|
### New Features
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: clikernel
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.22
|
|
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,28 +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.
|
|
15
|
-
Requires-Dist: jupyasyncclient>=0.2.
|
|
16
|
-
Requires-Dist: jupywire>=0.1.9
|
|
14
|
+
Requires-Dist: fastcore>=2.3.1
|
|
15
|
+
Requires-Dist: jupyasyncclient>=0.2.32
|
|
17
16
|
Requires-Dist: mcpmini>=0.0.5
|
|
18
|
-
Requires-Dist:
|
|
17
|
+
Requires-Dist: jupygate>=0.1.0
|
|
19
18
|
Requires-Dist: ipymini>=0.1.28
|
|
20
19
|
Requires-Dist: httpx
|
|
21
|
-
Requires-Dist:
|
|
20
|
+
Requires-Dist: execnb>=0.3.5
|
|
22
21
|
Provides-Extra: dev
|
|
23
22
|
Requires-Dist: fastship; extra == "dev"
|
|
23
|
+
Requires-Dist: pytest; extra == "dev"
|
|
24
24
|
Dynamic: license-file
|
|
25
25
|
|
|
26
26
|
# clikernel
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
|
|
30
|
-
|
|
31
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.
|
|
32
29
|
|
|
33
|
-
[
|
|
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.
|
|
34
31
|
|
|
35
|
-
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.
|
|
36
33
|
|
|
37
34
|
## Install
|
|
38
35
|
|
|
@@ -40,10 +37,10 @@ New kernels close with their creating conversation by default. Attaching to an e
|
|
|
40
37
|
pip install clikernel
|
|
41
38
|
```
|
|
42
39
|
|
|
43
|
-
This installs
|
|
40
|
+
This installs jupygate and ipymini. No service setup is required for a conversation-local kernel: clikernel starts a private gateway if it cannot find one. To retain kernels across conversations, run a resident gateway, for example through launchd or systemd:
|
|
44
41
|
|
|
45
42
|
``` sh
|
|
46
|
-
|
|
43
|
+
jupygate --port 8787
|
|
47
44
|
```
|
|
48
45
|
|
|
49
46
|
## Use with an MCP host
|
|
@@ -61,12 +58,14 @@ create(kernel="py")
|
|
|
61
58
|
exec(code="6*7")
|
|
62
59
|
```
|
|
63
60
|
|
|
64
|
-
|
|
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.
|
|
65
62
|
|
|
66
|
-
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-
|
|
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.
|
|
67
64
|
|
|
68
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`.
|
|
69
66
|
|
|
67
|
+
The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0` to disable). When a reply exceeds that limit, the router saves the full output to a temporary file, returns the first chunk with the file path and remaining size, and serves subsequent chunks when you run `exec(code="%cont")` (or `exec(code="%cont <id>")` when several calls overflow in parallel).
|
|
68
|
+
|
|
70
69
|
## Configuration
|
|
71
70
|
|
|
72
71
|
Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
|
|
@@ -80,7 +79,7 @@ url = "https://<instance-host>/rusty"
|
|
|
80
79
|
token_file = "~/.config/solveit/session"
|
|
81
80
|
```
|
|
82
81
|
|
|
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/login.html) for login options.
|
|
82
|
+
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.
|
|
84
83
|
|
|
85
84
|
## The stream protocol
|
|
86
85
|
|
|
@@ -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
|
|
|
@@ -15,10 +12,10 @@ New kernels close with their creating conversation by default. Attaching to an e
|
|
|
15
12
|
pip install clikernel
|
|
16
13
|
```
|
|
17
14
|
|
|
18
|
-
This installs
|
|
15
|
+
This installs jupygate and ipymini. No service setup is required for a conversation-local kernel: clikernel starts a private gateway if it cannot find one. To retain kernels across conversations, run a resident gateway, for example through launchd or systemd:
|
|
19
16
|
|
|
20
17
|
``` sh
|
|
21
|
-
|
|
18
|
+
jupygate --port 8787
|
|
22
19
|
```
|
|
23
20
|
|
|
24
21
|
## Use with an MCP host
|
|
@@ -36,12 +33,14 @@ create(kernel="py")
|
|
|
36
33
|
exec(code="6*7")
|
|
37
34
|
```
|
|
38
35
|
|
|
39
|
-
|
|
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-
|
|
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
|
|
|
42
|
+
The router caps text replies to `--maxout` UTF-8 bytes (default 40,000; pass `0` to disable). When a reply exceeds that limit, the router saves the full output to a temporary file, returns the first chunk with the file path and remaining size, and serves subsequent chunks when you run `exec(code="%cont")` (or `exec(code="%cont <id>")` when several calls overflow in parallel).
|
|
43
|
+
|
|
45
44
|
## Configuration
|
|
46
45
|
|
|
47
46
|
Two optional files in `$XDG_CONFIG_HOME/clikernel/` configure the router, usually under `~/.config/clikernel/`, or under the directory `clikernel-mcp --cfgdir` names:
|
|
@@ -55,7 +54,7 @@ url = "https://<instance-host>/rusty"
|
|
|
55
54
|
token_file = "~/.config/solveit/session"
|
|
56
55
|
```
|
|
57
56
|
|
|
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/login.html) for login options.
|
|
57
|
+
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.
|
|
59
58
|
|
|
60
59
|
## The stream protocol
|
|
61
60
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.22"
|
|
@@ -0,0 +1,40 @@
|
|
|
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.startup_src': ('api/core.html#startup_src', 'clikernel/core.py'),
|
|
21
|
+
'clikernel.core.session_defaults': ('api/core.html#session_defaults', 'clikernel/core.py')},
|
|
22
|
+
'clikernel.mcp': { 'clikernel.mcp': ('api/mcp.html', 'clikernel/mcp.py'),
|
|
23
|
+
'clikernel.mcp.Router': ('api/mcp.html#router', 'clikernel/mcp.py'),
|
|
24
|
+
'clikernel.mcp.Router.session': ('api/mcp.html#router.session', 'clikernel/mcp.py'),
|
|
25
|
+
'clikernel.mcp.Router.tools': ('api/mcp.html#router.tools', 'clikernel/mcp.py'),
|
|
26
|
+
'clikernel.mcp.Router.dispatch': ('api/mcp.html#router.dispatch', 'clikernel/mcp.py'),
|
|
27
|
+
'clikernel.mcp.Router.aclose': ('api/mcp.html#router.aclose', 'clikernel/mcp.py'),
|
|
28
|
+
'clikernel.mcp.main': ('api/mcp.html#main', 'clikernel/mcp.py'),
|
|
29
|
+
'clikernel.mcp.agent_input': ('api/mcp.html#agent_input', 'clikernel/mcp.py'),
|
|
30
|
+
'clikernel.mcp.hook': ('api/mcp.html#hook', 'clikernel/mcp.py')},
|
|
31
|
+
'clikernel.cli': { 'clikernel.cli': ('api/cli.html', 'clikernel/cli.py'),
|
|
32
|
+
'clikernel.cli.main': ('api/cli.html#main', 'clikernel/cli.py'),
|
|
33
|
+
'clikernel.cli.serve_stream': ('api/cli.html#serve_stream', 'clikernel/cli.py')},
|
|
34
|
+
'clikernel.rules': { 'clikernel.rules': ('api/rules.html', 'clikernel/rules.py'),
|
|
35
|
+
'clikernel.rules.Rule': ('api/rules.html#rule', 'clikernel/rules.py'),
|
|
36
|
+
'clikernel.rules.scan': ('api/rules.html#scan', 'clikernel/rules.py')},
|
|
37
|
+
'clikernel.login': { 'clikernel.login': ('api/login.html', 'clikernel/login.py'),
|
|
38
|
+
'clikernel.login.main': ('api/login.html#main', 'clikernel/login.py')}}}
|
|
39
|
+
|
|
40
|
+
docs = {'API': ['clikernel.core', 'clikernel.mcp', 'clikernel.cli', 'clikernel.rules', 'clikernel.login']}
|
|
@@ -1,27 +1,31 @@
|
|
|
1
|
-
"""
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
52
|
+
if err: return _fmt_error("protocol-error", err), False
|
|
51
53
|
elif line.startswith('%%'):
|
|
52
|
-
return
|
|
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
|
|
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='',
|
|
129
|
-
kernel:str='',
|
|
130
|
-
):
|
|
131
|
-
"
|
|
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,191 @@
|
|
|
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` under `$XDG_CONFIG_HOME/clikernel/` (`~/.config/clikernel/`) maps host names to gateway URLs and auth credentials (`token`, `token_env`, or `token_file`). `session_defaults` packages Python display 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 pathlib import Path
|
|
16
|
+
import httpx, inspect, os
|
|
17
|
+
|
|
18
|
+
from fastcore.xdg import xdg_config_home
|
|
19
|
+
from jupyasyncclient import start_gateway
|
|
20
|
+
from mcpmini.core import HTTPTransport, jreq
|
|
21
|
+
from . import __version__
|
|
22
|
+
|
|
23
|
+
__all__ = ['Gateway', 'default_gateway', 'resolve', 'gateways', 'cfg_dir', 'startup_src', 'session_defaults', 'DEFAULT_URL']
|
|
24
|
+
|
|
25
|
+
DEFAULT_URL = 'http://127.0.0.1:8787'
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Gateway:
|
|
29
|
+
"Open an MCP session on a `jupygate` gateway, invoke its tools, and terminate the session with HTTP DELETE."
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
url:str, # Gateway base URL (e.g. `'http://127.0.0.1:8787'`)
|
|
33
|
+
token:str=None, # Optional bearer auth token
|
|
34
|
+
verify:bool=True, # Verify TLS certificates
|
|
35
|
+
):
|
|
36
|
+
client = httpx.AsyncClient(verify=verify, timeout=httpx.Timeout(None, connect=10))
|
|
37
|
+
self.url, self._id = url, 0
|
|
38
|
+
self.tr = HTTPTransport(f"{url.rstrip('/')}/mcp", token=token, http_client=client)
|
|
39
|
+
|
|
40
|
+
async def rpc(
|
|
41
|
+
self,
|
|
42
|
+
method:str, # JSON-RPC method name (e.g. `'tools/list'`, `'tools/call'`)
|
|
43
|
+
**params, # JSON-RPC params mapping
|
|
44
|
+
): # Result payload from the JSON-RPC response
|
|
45
|
+
"Send a JSON-RPC request and return its `result`, raising `RuntimeError` on JSON-RPC errors."
|
|
46
|
+
self._id += 1
|
|
47
|
+
r = await self.tr.send(jreq(method, self._id, **params))
|
|
48
|
+
if 'error' in r: raise RuntimeError(f"{r['error']['code']}: {r['error']['message']}")
|
|
49
|
+
return r['result']
|
|
50
|
+
|
|
51
|
+
async def initialize(
|
|
52
|
+
self,
|
|
53
|
+
defaults:dict=None, # `jupygate` session defaults dict from `session_defaults`
|
|
54
|
+
) -> "Gateway": # `self`, with `.info` populated and session initialized
|
|
55
|
+
"Open the MCP session with `defaults` in the `jupygate` extension and send `notifications/initialized`."
|
|
56
|
+
await self.tr.start()
|
|
57
|
+
try:
|
|
58
|
+
self.info = await self.rpc('initialize', protocolVersion='2025-11-25', capabilities={},
|
|
59
|
+
clientInfo=dict(name='clikernel', version=__version__), jupygate=defaults or {})
|
|
60
|
+
if defaults and not self.info.get('jupygate'):
|
|
61
|
+
raise RuntimeError(f'gateway at {self.url} did not acknowledge jupygate session defaults; upgrade the gateway')
|
|
62
|
+
self.tr.proto = self.info['protocolVersion']
|
|
63
|
+
await self.tr.send(jreq('notifications/initialized'))
|
|
64
|
+
return self
|
|
65
|
+
except BaseException:
|
|
66
|
+
with suppress(Exception): await self.aclose()
|
|
67
|
+
raise
|
|
68
|
+
|
|
69
|
+
async def tools(self) -> list[dict]:
|
|
70
|
+
"Return the gateway's MCP tool definitions (`tools/list`)."
|
|
71
|
+
return (await self.rpc('tools/list'))['tools']
|
|
72
|
+
|
|
73
|
+
async def call(
|
|
74
|
+
self,
|
|
75
|
+
name:str, # MCP tool name (e.g. `'create'`, `'exec'`, `'list_kernels'`)
|
|
76
|
+
**args, # Tool arguments
|
|
77
|
+
) -> dict: # Complete MCP tool result dict (`content`, optional `isError`)
|
|
78
|
+
"Call MCP tool `name` and return its complete result dict, including non-text blocks."
|
|
79
|
+
return await self.rpc('tools/call', name=name, arguments=args)
|
|
80
|
+
|
|
81
|
+
async def text(
|
|
82
|
+
self,
|
|
83
|
+
name:str, # MCP tool name
|
|
84
|
+
**args, # Tool arguments
|
|
85
|
+
) -> str: # Concatenated text content blocks
|
|
86
|
+
"Call MCP tool `name` and join its text blocks, raising `RuntimeError` on `isError` replies."
|
|
87
|
+
r = await self.call(name, **args)
|
|
88
|
+
t = ''.join(c.get('text', '') for c in r['content'] if c['type'] == 'text')
|
|
89
|
+
if r.get('isError'): raise RuntimeError(t)
|
|
90
|
+
return t
|
|
91
|
+
|
|
92
|
+
async def aclose(self) -> None:
|
|
93
|
+
"Send HTTP DELETE to terminate the gateway session and close the HTTP transport."
|
|
94
|
+
try: await self.tr.delete()
|
|
95
|
+
finally: await self.tr.aclose()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def default_gateway(
|
|
99
|
+
cfgdir:str|Path=None, # Config directory for `session_defaults` and `gateways.toml` (default `cfg_dir()`)
|
|
100
|
+
quiet:bool=False, # Suppress startup output in replies
|
|
101
|
+
url:str=DEFAULT_URL, # Local gateway URL to try before spawning a child (ignored when `CLIKERNEL_HOST` is set)
|
|
102
|
+
) -> tuple[Gateway, object]: # `(gateway, child)` where `child` is `None` if an existing gateway was reused
|
|
103
|
+
"Return an initialized `Gateway` and any newly spawned child process (which the caller must stop)."
|
|
104
|
+
if host := os.environ.get('CLIKERNEL_HOST'):
|
|
105
|
+
u, token, verify = resolve(host, cfgdir)
|
|
106
|
+
return await Gateway(u, token, verify).initialize(session_defaults(cfgdir, quiet, local=False)), None
|
|
107
|
+
d = session_defaults(cfgdir, quiet, local=True)
|
|
108
|
+
try: return await Gateway(url, os.environ.get('CLIKERNEL_TOKEN'), True).initialize(d), None
|
|
109
|
+
except httpx.ConnectError:
|
|
110
|
+
child = start_gateway()
|
|
111
|
+
try: return await Gateway(child.url).initialize(d), child
|
|
112
|
+
except BaseException:
|
|
113
|
+
child.stop()
|
|
114
|
+
raise
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
"""## Configuration and startup
|
|
118
|
+
|
|
119
|
+
Read optional `gateways.toml` and `startup.py` from `$XDG_CONFIG_HOME/clikernel/` and build `jupygate` session initialization defaults.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cfg_dir() -> Path:
|
|
124
|
+
"Return the `clikernel` configuration directory (`$XDG_CONFIG_HOME/clikernel`)."
|
|
125
|
+
return xdg_config_home()/'clikernel'
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def gateways(
|
|
129
|
+
cfgdir:str|Path=None, # Config directory containing `gateways.toml` (default `cfg_dir()`)
|
|
130
|
+
) -> dict: # `{name: {url, token|token_env|token_file, verify}}` table (empty if file absent)
|
|
131
|
+
"Read named gateway entries from `gateways.toml`."
|
|
132
|
+
p = (Path(cfgdir) if cfgdir else cfg_dir())/'gateways.toml'
|
|
133
|
+
return p.read_toml().get('gateways', {}) if p.exists() else {}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def resolve(
|
|
137
|
+
host:str='', # Empty string (default local), full URL, or `gateways.toml` name (falls back to `CLIKERNEL_HOST`)
|
|
138
|
+
cfgdir:str|Path=None, # Config directory for `gateways.toml` lookup (default `cfg_dir()`)
|
|
139
|
+
) -> tuple[str, str|None, bool]: # `(url, token, verify)`
|
|
140
|
+
"Resolve an empty host, URL, or configured gateway name to `(url, token, verify)`."
|
|
141
|
+
host = host or os.environ.get('CLIKERNEL_HOST') or ''
|
|
142
|
+
if not host: return DEFAULT_URL, os.environ.get('CLIKERNEL_TOKEN'), True
|
|
143
|
+
if '://' in host: return host, os.environ.get('CLIKERNEL_TOKEN'), True
|
|
144
|
+
cfgdir = Path(cfgdir) if cfgdir else cfg_dir()
|
|
145
|
+
g = gateways(cfgdir).get(host)
|
|
146
|
+
if g is None: raise ValueError(f"unknown gateway {host!r}: not a URL, and not in {cfgdir/'gateways.toml'}")
|
|
147
|
+
if sum(k in g for k in ('token', 'token_env', 'token_file')) > 1:
|
|
148
|
+
raise ValueError(f"gateway {host!r}: choose one of token, token_env or token_file")
|
|
149
|
+
token = g.get('token') or os.environ.get(g.get('token_env', ''))
|
|
150
|
+
if 'token_file' in g: token = Path(g['token_file']).expanduser().read_text().strip()
|
|
151
|
+
return g['url'], token or None, g.get('verify', True)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _with_file(src, path): return f"__file__ = {str(path)!r}\ntry: exec(compile({src!r}, __file__, 'exec'))\nfinally: del __file__"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _python_display(shell):
|
|
158
|
+
import ast
|
|
159
|
+
import ipymini.term.display # chkstyle: ignore
|
|
160
|
+
run = shell.run_ast_nodes
|
|
161
|
+
async def run_ast_nodes(nodelist, cell_name, interactivity='last_expr', **kwargs):
|
|
162
|
+
if interactivity != 'all': return await run(nodelist, cell_name, interactivity, **kwargs)
|
|
163
|
+
for n in nodelist:
|
|
164
|
+
if await run([n], cell_name, 'last' if isinstance(n, ast.Expr) else 'none', **kwargs): return True
|
|
165
|
+
return False
|
|
166
|
+
shell.run_ast_nodes = run_ast_nodes
|
|
167
|
+
shell.ast_node_interactivity = 'all'
|
|
168
|
+
|
|
169
|
+
_PYTHON_DISPLAY_SRC = inspect.getsource(_python_display)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def startup_src(
|
|
173
|
+
cfgdir:str|Path=None, # Config directory checked for optional `startup.py` (default `cfg_dir()`)
|
|
174
|
+
) -> str: # Combined Python startup source sent to `jupygate`
|
|
175
|
+
"Build Python display defaults followed by user `startup.py` source if present."
|
|
176
|
+
d = Path(cfgdir) if cfgdir else cfg_dir()
|
|
177
|
+
parts = [_PYTHON_DISPLAY_SRC + '_python_display(get_ipython())\ndel _python_display']
|
|
178
|
+
if (p := d/'startup.py').exists(): parts.append(_with_file(p.read_text(), p))
|
|
179
|
+
return '\n'.join(parts)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def session_defaults(
|
|
183
|
+
cfgdir:str|Path=None, # Config directory for `startup_src` (default `cfg_dir()`)
|
|
184
|
+
quiet:bool=False, # Suppress startup output in gateway replies
|
|
185
|
+
local:bool=True, # Include local `cwd` and `os.environ` (set `False` for remote gateways)
|
|
186
|
+
) -> dict: # `jupygate` initialization defaults dict
|
|
187
|
+
"Build `jupygate` session defaults: `startup`, `quiet`, plus `cwd`/`env` when `local=True` or `CLAUDE_CODE_SESSION_ID` when remote."
|
|
188
|
+
d = dict(startup=startup_src(cfgdir), quiet=quiet)
|
|
189
|
+
if local: d.update(cwd=os.getcwd(), env=dict(os.environ))
|
|
190
|
+
elif sid := os.environ.get('CLAUDE_CODE_SESSION_ID'): d['env'] = dict(CLAUDE_CODE_SESSION_ID=sid)
|
|
191
|
+
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
|
-
|
|
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
|
-
|
|
5
|
+
```toml
|
|
6
|
+
[gateways.solveit]
|
|
7
|
+
url = "https://<your-instance>.solve.it.com/rusty"
|
|
8
|
+
token_file = "~/.config/solveit/session"
|
|
9
|
+
```
|
|
6
10
|
|
|
7
|
-
|
|
8
|
-
|
|
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
|
-
|
|
16
|
+
from pathlib import Path
|
|
11
17
|
import httpx, secrets, time, webbrowser
|
|
12
|
-
|
|
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,
|
|
21
|
-
):
|
|
22
|
-
"
|
|
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:
|