ptymini 0.0.1__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.
ptymini-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include pyproject.toml
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
ptymini-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: ptymini
3
+ Version: 0.0.1
4
+ Summary: Asyncio pty sessions: spawn, write, multi-client attach with replay, and a named registry
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/ptymini
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/ptymini/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore>=2.1.18
16
+ Requires-Dist: ptyprocess>=0.7
17
+ Dynamic: license-file
18
+
19
+ # ptymini
20
+
21
+
22
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
23
+
24
+ `ptymini` fills the gap between `ptyprocess` (a raw pty fd), `pexpect` (sync expect loops), and `terminado` (a pty server welded to tornado): asyncio-native pty *sessions*. A [`PtySession`](https://AnswerDotAI.github.io/ptymini/core.html#ptysession) is one spawned pty that any number of clients can attach to as independent byte streams, each primed from a byte-bounded replay buffer — so a reconnecting client resumes with recent scrollback instead of a blank screen. A [`PtyRegistry`](https://AnswerDotAI.github.io/ptymini/core.html#ptyregistry) adds named get-or-create sessions, injected shell setup (`rc`), and inactivity culling. It carries no server, no framework, and no session persistence beyond the process: web exposure belongs to the embedding app (e.g. [jupygate](https://github.com/AnswerDotAI/jupygate)), and durable session management belongs to tmux.
25
+
26
+ ## Usage
27
+
28
+ ### Installation
29
+
30
+ Install latest from the GitHub [repository](https://github.com/AnswerDotAI/ptymini):
31
+
32
+ ``` sh
33
+ $ pip install git+https://github.com/AnswerDotAI/ptymini.git
34
+ ```
35
+
36
+ or from [conda](https://anaconda.org/AnswerDotAI/ptymini)
37
+
38
+ ``` sh
39
+ $ conda install -c AnswerDotAI ptymini
40
+ ```
41
+
42
+ or from [pypi](https://pypi.org/project/ptymini/)
43
+
44
+ ``` sh
45
+ $ pip install ptymini
46
+ ```
47
+
48
+ ### Documentation
49
+
50
+ Documentation can be found hosted on this GitHub [repository](https://github.com/AnswerDotAI/ptymini)’s [pages](https://AnswerDotAI.github.io/ptymini/). Additionally you can find package manager specific guidelines on [conda](https://anaconda.org/AnswerDotAI/ptymini) and [pypi](https://pypi.org/project/ptymini/) respectively.
@@ -0,0 +1,32 @@
1
+ # ptymini
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ `ptymini` fills the gap between `ptyprocess` (a raw pty fd), `pexpect` (sync expect loops), and `terminado` (a pty server welded to tornado): asyncio-native pty *sessions*. A [`PtySession`](https://AnswerDotAI.github.io/ptymini/core.html#ptysession) is one spawned pty that any number of clients can attach to as independent byte streams, each primed from a byte-bounded replay buffer — so a reconnecting client resumes with recent scrollback instead of a blank screen. A [`PtyRegistry`](https://AnswerDotAI.github.io/ptymini/core.html#ptyregistry) adds named get-or-create sessions, injected shell setup (`rc`), and inactivity culling. It carries no server, no framework, and no session persistence beyond the process: web exposure belongs to the embedding app (e.g. [jupygate](https://github.com/AnswerDotAI/jupygate)), and durable session management belongs to tmux.
7
+
8
+ ## Usage
9
+
10
+ ### Installation
11
+
12
+ Install latest from the GitHub [repository](https://github.com/AnswerDotAI/ptymini):
13
+
14
+ ``` sh
15
+ $ pip install git+https://github.com/AnswerDotAI/ptymini.git
16
+ ```
17
+
18
+ or from [conda](https://anaconda.org/AnswerDotAI/ptymini)
19
+
20
+ ``` sh
21
+ $ conda install -c AnswerDotAI ptymini
22
+ ```
23
+
24
+ or from [pypi](https://pypi.org/project/ptymini/)
25
+
26
+ ``` sh
27
+ $ pip install ptymini
28
+ ```
29
+
30
+ ### Documentation
31
+
32
+ Documentation can be found hosted on this GitHub [repository](https://github.com/AnswerDotAI/ptymini)’s [pages](https://AnswerDotAI.github.io/ptymini/). Additionally you can find package manager specific guidelines on [conda](https://anaconda.org/AnswerDotAI/ptymini) and [pypi](https://pypi.org/project/ptymini/) respectively.
@@ -0,0 +1,8 @@
1
+ """Asyncio pty sessions: spawn, write, multi-client attach with replay, and a named registry
2
+
3
+ Modules:
4
+
5
+ - `ptymini.bg`: The bgterm API: sync, cursor-paged background terminal sessions
6
+ - `ptymini.core`: `PtySession` and `PtyRegistry`: asyncio pty sessions over one offset-tracked output ring"""
7
+
8
+ __version__ = "0.0.1"
@@ -0,0 +1,88 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/ptymini',
5
+ 'doc_host': 'https://AnswerDotAI.github.io',
6
+ 'git_url': 'https://github.com/AnswerDotAI/ptymini',
7
+ 'lib_path': 'ptymini'},
8
+ 'syms': { 'ptymini.bg': { 'ptymini.bg.BgtermError': ('bg.html#bgtermerror', 'ptymini/bg.py'),
9
+ 'ptymini.bg.PollResult': ('bg.html#pollresult', 'ptymini/bg.py'),
10
+ 'ptymini.bg.PollResult.truncated': ('bg.html#pollresult.truncated', 'ptymini/bg.py'),
11
+ 'ptymini.bg.Session': ('bg.html#session', 'ptymini/bg.py'),
12
+ 'ptymini.bg.Session.__enter__': ('bg.html#session.__enter__', 'ptymini/bg.py'),
13
+ 'ptymini.bg.Session.__exit__': ('bg.html#session.__exit__', 'ptymini/bg.py'),
14
+ 'ptymini.bg.Session.__init__': ('bg.html#session.__init__', 'ptymini/bg.py'),
15
+ 'ptymini.bg.Session.close': ('bg.html#session.close', 'ptymini/bg.py'),
16
+ 'ptymini.bg.Session.exit_code': ('bg.html#session.exit_code', 'ptymini/bg.py'),
17
+ 'ptymini.bg.Session.kill': ('bg.html#session.kill', 'ptymini/bg.py'),
18
+ 'ptymini.bg.Session.open': ('bg.html#session.open', 'ptymini/bg.py'),
19
+ 'ptymini.bg.Session.poll': ('bg.html#session.poll', 'ptymini/bg.py'),
20
+ 'ptymini.bg.Session.read': ('bg.html#session.read', 'ptymini/bg.py'),
21
+ 'ptymini.bg.Session.running': ('bg.html#session.running', 'ptymini/bg.py'),
22
+ 'ptymini.bg.Session.send': ('bg.html#session.send', 'ptymini/bg.py'),
23
+ 'ptymini.bg.Session.start': ('bg.html#session.start', 'ptymini/bg.py'),
24
+ 'ptymini.bg.Session.terminate': ('bg.html#session.terminate', 'ptymini/bg.py'),
25
+ 'ptymini.bg.Session.wait': ('bg.html#session.wait', 'ptymini/bg.py'),
26
+ 'ptymini.bg.Session.write': ('bg.html#session.write', 'ptymini/bg.py'),
27
+ 'ptymini.bg.Session.write_stdin': ('bg.html#session.write_stdin', 'ptymini/bg.py'),
28
+ 'ptymini.bg._BgSession': ('bg.html#_bgsession', 'ptymini/bg.py'),
29
+ 'ptymini.bg._BgSession.__init__': ('bg.html#_bgsession.__init__', 'ptymini/bg.py'),
30
+ 'ptymini.bg._BgSession._read': ('bg.html#_bgsession._read', 'ptymini/bg.py'),
31
+ 'ptymini.bg._BgSession.close': ('bg.html#_bgsession.close', 'ptymini/bg.py'),
32
+ 'ptymini.bg._BgSession.exit_code': ('bg.html#_bgsession.exit_code', 'ptymini/bg.py'),
33
+ 'ptymini.bg._BgSession.kill': ('bg.html#_bgsession.kill', 'ptymini/bg.py'),
34
+ 'ptymini.bg._BgSession.poll': ('bg.html#_bgsession.poll', 'ptymini/bg.py'),
35
+ 'ptymini.bg._BgSession.read': ('bg.html#_bgsession.read', 'ptymini/bg.py'),
36
+ 'ptymini.bg._BgSession.running': ('bg.html#_bgsession.running', 'ptymini/bg.py'),
37
+ 'ptymini.bg._BgSession.start': ('bg.html#_bgsession.start', 'ptymini/bg.py'),
38
+ 'ptymini.bg._BgSession.terminate': ('bg.html#_bgsession.terminate', 'ptymini/bg.py'),
39
+ 'ptymini.bg._BgSession.wait': ('bg.html#_bgsession.wait', 'ptymini/bg.py'),
40
+ 'ptymini.bg._BgSession.write_stdin': ('bg.html#_bgsession.write_stdin', 'ptymini/bg.py'),
41
+ 'ptymini.bg._call': ('bg.html#_call', 'ptymini/bg.py'),
42
+ 'ptymini.bg._ensure_loop': ('bg.html#_ensure_loop', 'ptymini/bg.py'),
43
+ 'ptymini.bg._lookup': ('bg.html#_lookup', 'ptymini/bg.py'),
44
+ 'ptymini.bg.close_bgterm': ('bg.html#close_bgterm', 'ptymini/bg.py'),
45
+ 'ptymini.bg.kill': ('bg.html#kill', 'ptymini/bg.py'),
46
+ 'ptymini.bg.list_sessions': ('bg.html#list_sessions', 'ptymini/bg.py'),
47
+ 'ptymini.bg.poll': ('bg.html#poll', 'ptymini/bg.py'),
48
+ 'ptymini.bg.read': ('bg.html#read', 'ptymini/bg.py'),
49
+ 'ptymini.bg.start_bgterm': ('bg.html#start_bgterm', 'ptymini/bg.py'),
50
+ 'ptymini.bg.terminate': ('bg.html#terminate', 'ptymini/bg.py'),
51
+ 'ptymini.bg.wait': ('bg.html#wait', 'ptymini/bg.py'),
52
+ 'ptymini.bg.write_stdin': ('bg.html#write_stdin', 'ptymini/bg.py')},
53
+ 'ptymini.core': { 'ptymini.core.Gap': ('core.html#gap', 'ptymini/core.py'),
54
+ 'ptymini.core.PtyRegistry': ('core.html#ptyregistry', 'ptymini/core.py'),
55
+ 'ptymini.core.PtyRegistry.__aenter__': ('core.html#ptyregistry.__aenter__', 'ptymini/core.py'),
56
+ 'ptymini.core.PtyRegistry.__aexit__': ('core.html#ptyregistry.__aexit__', 'ptymini/core.py'),
57
+ 'ptymini.core.PtyRegistry.__init__': ('core.html#ptyregistry.__init__', 'ptymini/core.py'),
58
+ 'ptymini.core.PtyRegistry.__len__': ('core.html#ptyregistry.__len__', 'ptymini/core.py'),
59
+ 'ptymini.core.PtyRegistry._next_name': ('core.html#ptyregistry._next_name', 'ptymini/core.py'),
60
+ 'ptymini.core.PtyRegistry.create': ('core.html#ptyregistry.create', 'ptymini/core.py'),
61
+ 'ptymini.core.PtyRegistry.cull': ('core.html#ptyregistry.cull', 'ptymini/core.py'),
62
+ 'ptymini.core.PtyRegistry.cull_ready': ('core.html#ptyregistry.cull_ready', 'ptymini/core.py'),
63
+ 'ptymini.core.PtyRegistry.delete': ('core.html#ptyregistry.delete', 'ptymini/core.py'),
64
+ 'ptymini.core.PtyRegistry.get': ('core.html#ptyregistry.get', 'ptymini/core.py'),
65
+ 'ptymini.core.PtyRegistry.shutdown': ('core.html#ptyregistry.shutdown', 'ptymini/core.py'),
66
+ 'ptymini.core.PtyRegistry.values': ('core.html#ptyregistry.values', 'ptymini/core.py'),
67
+ 'ptymini.core.PtySession': ('core.html#ptysession', 'ptymini/core.py'),
68
+ 'ptymini.core.PtySession.__aenter__': ('core.html#ptysession.__aenter__', 'ptymini/core.py'),
69
+ 'ptymini.core.PtySession.__aexit__': ('core.html#ptysession.__aexit__', 'ptymini/core.py'),
70
+ 'ptymini.core.PtySession.__init__': ('core.html#ptysession.__init__', 'ptymini/core.py'),
71
+ 'ptymini.core.PtySession._eof': ('core.html#ptysession._eof', 'ptymini/core.py'),
72
+ 'ptymini.core.PtySession._notify': ('core.html#ptysession._notify', 'ptymini/core.py'),
73
+ 'ptymini.core.PtySession._on_read': ('core.html#ptysession._on_read', 'ptymini/core.py'),
74
+ 'ptymini.core.PtySession.attach': ('core.html#ptysession.attach', 'ptymini/core.py'),
75
+ 'ptymini.core.PtySession.kill': ('core.html#ptysession.kill', 'ptymini/core.py'),
76
+ 'ptymini.core.PtySession.model': ('core.html#ptysession.model', 'ptymini/core.py'),
77
+ 'ptymini.core.PtySession.read_from': ('core.html#ptysession.read_from', 'ptymini/core.py'),
78
+ 'ptymini.core.PtySession.resize': ('core.html#ptysession.resize', 'ptymini/core.py'),
79
+ 'ptymini.core.PtySession.terminate': ('core.html#ptysession.terminate', 'ptymini/core.py'),
80
+ 'ptymini.core.PtySession.wait': ('core.html#ptysession.wait', 'ptymini/core.py'),
81
+ 'ptymini.core.PtySession.wait_change': ('core.html#ptysession.wait_change', 'ptymini/core.py'),
82
+ 'ptymini.core.PtySession.write': ('core.html#ptysession.write', 'ptymini/core.py'),
83
+ 'ptymini.core.Ring': ('core.html#ring', 'ptymini/core.py'),
84
+ 'ptymini.core.Ring.__init__': ('core.html#ring.__init__', 'ptymini/core.py'),
85
+ 'ptymini.core.Ring.__len__': ('core.html#ring.__len__', 'ptymini/core.py'),
86
+ 'ptymini.core.Ring.append': ('core.html#ring.append', 'ptymini/core.py'),
87
+ 'ptymini.core.Ring.read_from': ('core.html#ring.read_from', 'ptymini/core.py'),
88
+ 'ptymini.core.cull_loop': ('core.html#cull_loop', 'ptymini/core.py')}}}
@@ -0,0 +1,272 @@
1
+ """The bgterm API: sync, cursor-paged background terminal sessions
2
+
3
+ The [bgterm](https://github.com/AnswerDotAI/bgterm) package, folded in: a *sync*, sid-based API for background terminal sessions — start once, send input later, wait a bounded time, read what arrived since your last look. It is the cursor view of a `PtySession`, for callers that live outside an event loop (kernel tools, plain scripts, an LLM deciding between actions): every session shares one private asyncio loop on a daemon thread, and each call marshals onto it and blocks, so `write_stdin(sid, "2+2\n", 500)` means what it always meant. The buffering, paging, and drop accounting are the `Ring`'s, which was extracted from bgterm in the first place; `PollResult` and every function signature are unchanged from the original package.
4
+
5
+ Docs: https://AnswerDotAI.github.io/ptymini/bg.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_bg.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['DEFAULT_MAX_BUFFER_BYTES', 'DEFAULT_MAX_OUTPUT_BYTES', 'Cmd', 'BgtermError', 'PollResult', 'list_sessions',
11
+ 'start_bgterm', 'write_stdin', 'poll', 'read', 'wait', 'terminate', 'kill', 'close_bgterm', 'Session']
12
+
13
+ # %% ../nbs/01_bg.ipynb #214abe5a
14
+ import asyncio, itertools, os, signal, threading
15
+ from dataclasses import dataclass
16
+ from .core import PtySession
17
+
18
+ DEFAULT_MAX_BUFFER_BYTES = 1_000_000
19
+ DEFAULT_MAX_OUTPUT_BYTES = 65_536
20
+ Cmd = str | list[str]
21
+
22
+ class BgtermError(RuntimeError):
23
+ "Raised when a bgterm session cannot be started, found, or controlled."
24
+
25
+ # %% ../nbs/01_bg.ipynb #f9dfa8f5
26
+ _loop, _loop_lock = None, threading.Lock()
27
+
28
+ def _ensure_loop():
29
+ global _loop
30
+ with _loop_lock:
31
+ if _loop is None or _loop.is_closed():
32
+ _loop = asyncio.new_event_loop()
33
+ threading.Thread(target=_loop.run_forever, daemon=True, name='ptymini-bg').start()
34
+ return _loop
35
+
36
+ def _call(coro):
37
+ "Run `coro` on the bg loop thread and block for its result."
38
+ return asyncio.run_coroutine_threadsafe(coro, _ensure_loop()).result()
39
+
40
+ # %% ../nbs/01_bg.ipynb #c8b59e13
41
+ @dataclass(slots=True)
42
+ class PollResult:
43
+ "Unread output returned by a `write_stdin()` or `poll()` call."
44
+
45
+ text: str
46
+ data: bytes
47
+ start_offset: int
48
+ end_offset: int
49
+ buffer_start_offset: int
50
+ buffer_end_offset: int
51
+ bytes_returned: int
52
+ remaining_bytes: int
53
+ dropped_bytes: int
54
+ running: bool
55
+ exit_code: int | None
56
+
57
+ @property
58
+ def truncated(self):
59
+ "Return whether output was paged or older unread bytes were dropped."
60
+ return self.remaining_bytes > 0 or self.dropped_bytes > 0
61
+
62
+ # %% ../nbs/01_bg.ipynb #ee8593c4
63
+ class _BgSession:
64
+ "Sync cursor facade over one `PtySession` living on the bg loop."
65
+ def __init__(self, s:PtySession, encoding:str, errors:str):
66
+ self.s, self.encoding, self.errors, self.cursor, self._closed = s, encoding, errors, 0, False
67
+
68
+ @classmethod
69
+ def start(cls, cmd:Cmd=None, cwd=None, env=None, shell=None, encoding='utf-8', errors='replace',
70
+ max_buffer_bytes=DEFAULT_MAX_BUFFER_BYTES):
71
+ if cmd is None: cmd = os.environ.get('SHELL', '/bin/sh')
72
+ if shell is None: shell = isinstance(cmd, str)
73
+ if shell and isinstance(cmd, str): cmd = ['/bin/sh', '-c', cmd]
74
+ elif isinstance(cmd, str): cmd = [cmd]
75
+ env = dict(os.environ if env is None else env, TERM='dumb')
76
+ async def _spawn(): return PtySession(list(cmd), cwd=cwd, env=env, buffer_bytes=max_buffer_bytes)
77
+ return cls(_call(_spawn()), encoding, errors)
78
+
79
+ @property
80
+ def running(self): return self.s.alive
81
+ @property
82
+ def exit_code(self): return self.s.exit_code
83
+
84
+ def _read(self, max_output_bytes):
85
+ if max_output_bytes is not None and max_output_bytes < 0: raise ValueError('max_output_bytes must be >= 0')
86
+ r = self.s.ring
87
+ payload, end_offset, dropped = r.read_from(self.cursor, max_output_bytes)
88
+ start_offset = end_offset - len(payload)
89
+ self.cursor = end_offset
90
+ return PollResult(payload.decode(self.encoding, errors=self.errors), payload, start_offset, end_offset,
91
+ r.start, r.end, len(payload), max(0, r.end - end_offset), dropped, self.s.alive, self.s.exit_code)
92
+
93
+ def read(self, max_output_bytes=DEFAULT_MAX_OUTPUT_BYTES):
94
+ async def _r(): return self._read(max_output_bytes)
95
+ return _call(_r())
96
+
97
+ def write_stdin(self, chars='', yield_time_ms=0, max_output_bytes=DEFAULT_MAX_OUTPUT_BYTES):
98
+ async def _w():
99
+ if chars:
100
+ data = chars if isinstance(chars, bytes) else chars.encode(self.encoding)
101
+ try: self.s.write(data)
102
+ except OSError as e: raise BgtermError('session PTY is no longer writable') from e
103
+ if yield_time_ms > 0 and self.cursor >= self.s.ring.end and self.s.alive: await self.s.wait_change(timeout=yield_time_ms / 1000)
104
+ return self._read(max_output_bytes)
105
+ return _call(_w())
106
+
107
+ def poll(self, yield_time_ms=0, max_output_bytes=DEFAULT_MAX_OUTPUT_BYTES): return self.write_stdin('', yield_time_ms, max_output_bytes)
108
+
109
+ def wait(self, timeout_ms=None):
110
+ async def _w():
111
+ t = None if timeout_ms is None else max(timeout_ms, 0) / 1000
112
+ try: return await asyncio.wait_for(self.s.wait(), t)
113
+ except asyncio.TimeoutError: return None
114
+ return _call(_w())
115
+
116
+ def terminate(self):
117
+ if self.running:
118
+ try: self.s.kill(signal.SIGTERM)
119
+ except ProcessLookupError: pass
120
+
121
+ def kill(self):
122
+ if self.running:
123
+ try: self.s.kill(signal.SIGKILL)
124
+ except ProcessLookupError: pass
125
+
126
+ def close(self, terminate=True, kill_after_ms=1000):
127
+ if self._closed: return
128
+ self._closed = True
129
+ if terminate and self.running:
130
+ self.terminate()
131
+ if self.wait(kill_after_ms) is None and self.running:
132
+ self.kill()
133
+ self.wait(kill_after_ms)
134
+
135
+ # %% ../nbs/01_bg.ipynb #0924cc6e
136
+ _REGISTRY_LOCK = threading.Lock()
137
+ _SESSIONS = {}
138
+ _NEXT_SID = itertools.count(1)
139
+
140
+
141
+ def _lookup(sid: int):
142
+ try: return _SESSIONS[int(sid)]
143
+ except KeyError as e: raise BgtermError(f"unknown bgterm session id {sid!r}") from e
144
+
145
+
146
+ def list_sessions():
147
+ "List active in-process bgterm session ids."
148
+ with _REGISTRY_LOCK: return tuple(sorted(_SESSIONS))
149
+
150
+
151
+ def start_bgterm(cmd: Cmd | None = None, cwd: str | None = None, env: dict[str, str] | None = None, shell: bool | None = None, encoding: str="utf-8",
152
+ errors: str="replace", max_buffer_bytes: int=DEFAULT_MAX_BUFFER_BYTES):
153
+ "Start a PTY-backed session and return its integer session id."
154
+ session = _BgSession.start(cmd, cwd, env, shell, encoding, errors, max_buffer_bytes)
155
+ with _REGISTRY_LOCK:
156
+ sid = next(_NEXT_SID)
157
+ _SESSIONS[sid] = session
158
+ return sid
159
+
160
+
161
+ def write_stdin(sid: int, chars: str = "", yield_time_ms: int = 0, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
162
+ "Write to a session PTY, wait briefly, and return unread output."
163
+ return _lookup(sid).write_stdin(chars, yield_time_ms, max_output_bytes)
164
+
165
+
166
+ def poll(sid: int, yield_time_ms: int = 0, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
167
+ "Wait for unread session output, then return it without writing input."
168
+ return _lookup(sid).poll(yield_time_ms, max_output_bytes)
169
+
170
+
171
+ def read(sid: int, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
172
+ "Return unread session output immediately."
173
+ return _lookup(sid).read(max_output_bytes)
174
+
175
+
176
+ def wait(sid: int, timeout_ms: int | None = None):
177
+ "Wait for a session to exit and return its exit code."
178
+ return _lookup(sid).wait(timeout_ms)
179
+
180
+
181
+ def terminate(sid: int):
182
+ "Terminate the session child process."
183
+ _lookup(sid).terminate()
184
+
185
+
186
+ def kill(sid: int):
187
+ "Kill the session child process."
188
+ _lookup(sid).kill()
189
+
190
+
191
+ def close_bgterm(sid: int, terminate: bool = True, kill_after_ms: int = 1000):
192
+ "Close a session and remove it from the in-process registry."
193
+ with _REGISTRY_LOCK: session = _SESSIONS.pop(int(sid), None)
194
+ if session is None: return
195
+ session.close(terminate, kill_after_ms)
196
+
197
+ # %% ../nbs/01_bg.ipynb #8f426dc2
198
+ class Session:
199
+ "Thin OO wrapper around the sid-based bgterm API."
200
+
201
+ def __init__(self, sid: int, close_on_exit=True):
202
+ self.sid = int(sid)
203
+ self.close_on_exit = close_on_exit
204
+ self._closed = False
205
+
206
+ @classmethod
207
+ def start(cls, cmd: Cmd | None = None, cwd: str | None = None, env: dict[str, str] | None = None, shell: bool | None = None, encoding: str="utf-8",
208
+ errors: str="replace", max_buffer_bytes: int=DEFAULT_MAX_BUFFER_BYTES, close_on_exit:bool=True):
209
+ "Start a PTY-backed session and wrap it in `Session`."
210
+ return cls(start_bgterm(cmd, cwd, env, shell, encoding, errors, max_buffer_bytes), close_on_exit)
211
+
212
+ @classmethod
213
+ def open(cls, sid: int, close_on_exit=False):
214
+ "Wrap an existing session id."
215
+ _lookup(sid)
216
+ return cls(sid, close_on_exit)
217
+
218
+ def __enter__(self): return self
219
+
220
+ def __exit__(self, exc_type, exc, tb):
221
+ if self.close_on_exit: self.close()
222
+ return False
223
+
224
+ @property
225
+ def running(self):
226
+ "Return whether the wrapped session is still running."
227
+ if self._closed: return False
228
+ return _lookup(self.sid).running
229
+
230
+ @property
231
+ def exit_code(self):
232
+ "Return the wrapped session's exit code, if available."
233
+ if self._closed: return None
234
+ return _lookup(self.sid).exit_code
235
+
236
+ def write_stdin(self, chars: str | bytes = "", yield_time_ms: int = 0, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
237
+ "Write to this session PTY, wait briefly, and return unread output."
238
+ return write_stdin(self.sid, chars, yield_time_ms, max_output_bytes)
239
+
240
+ def send(self, chars: str | bytes = "", yield_time_ms: int = 0, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
241
+ "Alias for `write_stdin()`."
242
+ return self.write_stdin(chars, yield_time_ms, max_output_bytes)
243
+
244
+ def write(self, chars: str | bytes = "", yield_time_ms: int = 0, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
245
+ "Alias for `write_stdin()`."
246
+ return self.write_stdin(chars, yield_time_ms, max_output_bytes)
247
+
248
+ def poll(self, yield_time_ms: int = 0, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
249
+ "Wait for unread output from this session, then return it."
250
+ return poll(self.sid, yield_time_ms, max_output_bytes)
251
+
252
+ def read(self, max_output_bytes: int | None = DEFAULT_MAX_OUTPUT_BYTES):
253
+ "Return unread output from this session immediately."
254
+ return read(self.sid, max_output_bytes)
255
+
256
+ def wait(self, timeout_ms: int | None = None):
257
+ "Wait for this session to exit and return its exit code."
258
+ return wait(self.sid, timeout_ms)
259
+
260
+ def terminate(self):
261
+ "Terminate this session child process."
262
+ terminate(self.sid)
263
+
264
+ def kill(self):
265
+ "Kill this session child process."
266
+ kill(self.sid)
267
+
268
+ def close(self, terminate: bool = True, kill_after_ms: int = 1000):
269
+ "Close this session and make repeated closes a no-op."
270
+ if self._closed: return
271
+ close_bgterm(self.sid, terminate, kill_after_ms)
272
+ self._closed = True
@@ -0,0 +1,236 @@
1
+ """`PtySession` and `PtyRegistry`: asyncio pty sessions over one offset-tracked output ring
2
+
3
+ Every design here serves two consumer shapes over one pty. *Streams* (a websocket handler, a renderer) want every byte in order, pushed as it arrives, with recent scrollback replayed on attach. *Cursors* (an LLM tool that reads "what's new since I last looked") want bounded-memory buffering with paging and honest drop accounting. Both are views over a single structure: the `Ring`, a byte buffer with absolute offsets. Each pty read appends to the ring; a session-wide change event wakes waiters; `read_from(offset)` serves both a stream's next chunk and a cursor's next page, and reports how many bytes fell off the back. There is no server here, no framework, and no persistence beyond the process: web exposure belongs to the embedding app (e.g. jupygate), durable sessions belong to tmux.
4
+
5
+ Docs: https://AnswerDotAI.github.io/ptymini/core.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['log', 'DEFAULT_ARGV', 'Ring', 'PtySession', 'Gap', 'PtyRegistry', 'cull_loop']
11
+
12
+ # %% ../nbs/00_core.ipynb #0fc74163
13
+ import asyncio, itertools, logging, os, signal, time
14
+ from collections import deque
15
+ from pathlib import Path
16
+ from tempfile import mkdtemp
17
+ from fastcore.basics import patch
18
+ from ptyprocess import PtyProcess
19
+
20
+ log = logging.getLogger('ptymini')
21
+
22
+ # %% ../nbs/00_core.ipynb #97624ef1
23
+ class Ring:
24
+ "Bounded byte buffer with absolute offsets: `start`..`end` of the retained window, `end` = total bytes ever appended."
25
+ def __init__(self, max_bytes:int=1_000_000):
26
+ if max_bytes <= 0: raise ValueError('max_bytes must be > 0')
27
+ self.max_bytes, self.chunks, self.start, self.end = max_bytes, deque(), 0, 0
28
+
29
+ def __len__(self): return self.end - self.start
30
+
31
+ def append(self, data:bytes):
32
+ self.chunks.append((self.end, data))
33
+ self.end += len(data)
34
+ while len(self) > self.max_bytes:
35
+ off, d = self.chunks[0]
36
+ overflow = len(self) - self.max_bytes
37
+ if overflow >= len(d):
38
+ self.chunks.popleft()
39
+ self.start = off + len(d)
40
+ else:
41
+ self.chunks[0] = (off + overflow, d[overflow:])
42
+ self.start = off + overflow
43
+
44
+ def read_from(self,
45
+ offset:int, # Absolute position to read from; behind `start` counts as dropped
46
+ max_bytes_out:int=None, # Cap on returned bytes (None: everything retained)
47
+ ): # (data, new_offset, dropped)
48
+ dropped = max(0, self.start - offset)
49
+ cur = max(offset, self.start)
50
+ out = bytearray()
51
+ for off, d in self.chunks:
52
+ if off + len(d) <= cur: continue
53
+ piece = d[max(0, cur - off):]
54
+ if max_bytes_out is not None: piece = piece[:max_bytes_out - len(out)]
55
+ if not piece: break
56
+ out.extend(piece)
57
+ if max_bytes_out is not None and len(out) >= max_bytes_out: break
58
+ return bytes(out), cur + len(out), dropped
59
+
60
+ # %% ../nbs/00_core.ipynb #0bb16e1a
61
+ class PtySession:
62
+ "One pty process: reads land in a `Ring`, a change event wakes waiters, EOF reaps the exit status."
63
+ def __init__(self,
64
+ argv:list[str], # Command to spawn on the pty
65
+ cwd:str=None, # Working directory for the child
66
+ env:dict=None, # Child environment; None inherits this process's
67
+ rows:int=24, cols:int=80,
68
+ buffer_bytes:int=1_000_000, # Ring bound: how much recent output is retained
69
+ name:str=None, # Optional handle, set by `PtyRegistry`
70
+ ):
71
+ self.name, self.alive, self.exit_code = name, True, None
72
+ self.ring = Ring(buffer_bytes)
73
+ self.last_activity = time.time()
74
+ self._evt, self._eof_evt = asyncio.Event(), asyncio.Event()
75
+ self.proc = PtyProcess.spawn(list(argv), cwd=cwd, env=env, dimensions=(rows, cols))
76
+ asyncio.get_running_loop().add_reader(self.proc.fd, self._on_read)
77
+
78
+ def _notify(self):
79
+ evt, self._evt = self._evt, asyncio.Event()
80
+ evt.set()
81
+
82
+ def _on_read(self):
83
+ try: data = self.proc.read(65536)
84
+ except (EOFError, OSError): data = b''
85
+ if not data: return self._eof()
86
+ self.last_activity = time.time()
87
+ self.ring.append(data)
88
+ self._notify()
89
+
90
+ def _eof(self):
91
+ self.alive = False
92
+ asyncio.get_running_loop().remove_reader(self.proc.fd)
93
+ self.proc.isalive() # reaps; fills exitstatus/signalstatus
94
+ self.exit_code = -self.proc.signalstatus if self.proc.signalstatus else self.proc.exitstatus
95
+ try: self.proc.close()
96
+ except OSError: pass
97
+ self._eof_evt.set()
98
+ self._notify()
99
+
100
+ async def wait_change(self,
101
+ seen_end:int=None, # Wake when `ring.end` passes this (None: the value at call time)
102
+ timeout:float=None, # Max seconds to wait; None waits indefinitely
103
+ )->bool: # True when new output or EOF arrived, False on timeout
104
+ if seen_end is None: seen_end = self.ring.end
105
+ deadline = None if timeout is None else time.monotonic() + timeout
106
+ while self.alive and self.ring.end == seen_end:
107
+ t = None if deadline is None else max(0, deadline - time.monotonic())
108
+ try: await asyncio.wait_for(self._evt.wait(), t)
109
+ except asyncio.TimeoutError: return False
110
+ return True
111
+
112
+ def read_from(self, offset:int, max_bytes_out:int=None): return self.ring.read_from(offset, max_bytes_out)
113
+
114
+ def write(self, data:bytes):
115
+ self.last_activity = time.time()
116
+ self.proc.write(data)
117
+
118
+ def resize(self, rows:int, cols:int): self.proc.setwinsize(rows, cols)
119
+ def kill(self, sig:int=signal.SIGTERM): self.proc.kill(sig)
120
+
121
+ async def wait(self)->int:
122
+ "The exit code, once the pty dies (negative: terminating signal number)."
123
+ await self._eof_evt.wait()
124
+ return self.exit_code
125
+
126
+ def model(self)->dict: return dict(name=self.name, alive=self.alive, last_activity=self.last_activity)
127
+
128
+ async def __aenter__(self): return self
129
+ async def __aexit__(self, *exc): await self.terminate(force=True)
130
+
131
+ # %% ../nbs/00_core.ipynb #35b6ab39
132
+ @patch
133
+ async def terminate(self:PtySession, force:bool=False)->bool:
134
+ "SIGHUP/SIGCONT/SIGINT/SIGTERM in turn, then SIGKILL if `force`; True if the child ended."
135
+ for sig in (signal.SIGHUP, signal.SIGCONT, signal.SIGINT, signal.SIGTERM):
136
+ if not self.proc.isalive(): return True
137
+ try: self.kill(sig)
138
+ except ProcessLookupError: return True
139
+ await asyncio.sleep(self.proc.delayafterterminate)
140
+ if not self.proc.isalive(): return True
141
+ if force:
142
+ self.proc.kill(signal.SIGKILL)
143
+ await asyncio.sleep(self.proc.delayafterterminate)
144
+ return not self.proc.isalive()
145
+
146
+ # %% ../nbs/00_core.ipynb #08b260eb
147
+ class Gap(int):
148
+ "Bytes lost to ring trimming between two yields of an `attach` stream."
149
+
150
+ @patch
151
+ async def attach(self:PtySession,
152
+ gaps:bool=False, # Also yield `Gap(n)` markers when the stream fell behind the ring?
153
+ from_start:bool=True, # Begin at the oldest retained byte (replay); False starts at the live edge
154
+ ):
155
+ "Async byte stream over the session's output: replay, then live; ends at EOF."
156
+ off = self.ring.start if from_start else self.ring.end
157
+ while True:
158
+ data, off, dropped = self.read_from(off)
159
+ if dropped and gaps: yield Gap(dropped)
160
+ if data: yield data
161
+ elif not self.alive: return
162
+ else: await self.wait_change(seen_end=off)
163
+
164
+ # %% ../nbs/00_core.ipynb #a2eefe3b
165
+ DEFAULT_ARGV = [os.environ.get('SHELL') or 'bash', '-i']
166
+
167
+ class PtyRegistry:
168
+ "Named-session registry: get-or-create, list, terminate. An embedding app or a test drives this."
169
+
170
+ def __init__(self,
171
+ argv:list[str]=None, # Default spawn command; creation requests may override it
172
+ cull_timeout:float=0, # Seconds of inactivity before a terminal is reaped (0 disables)
173
+ ):
174
+ self.argv = argv or DEFAULT_ARGV
175
+ self.cull_timeout, self.terms = cull_timeout, {}
176
+
177
+ def _next_name(self): return next(str(i) for i in itertools.count(1) if str(i) not in self.terms)
178
+
179
+ async def create(self,
180
+ name:str=None, # Existing name reattaches; None auto-numbers
181
+ argv:list[str]=None, # Spawn command; the registry default if None
182
+ cwd:str=None, # Working directory for the child
183
+ env:dict=None, # Replaces the inherited environment
184
+ appendenv:dict=None, # Overlays the base environment
185
+ rc:str=None, # Shell setup text, written to a private dir; `{rcfile}`/`{rcdir}` substitute into argv and env values
186
+ rows:int=24, cols:int=80,
187
+ )->PtySession:
188
+ "Get session `name` if it exists, else spawn one (auto-named when `name` is None)."
189
+ if name and name in self.terms: return self.terms[name]
190
+ name = name or self._next_name()
191
+ argv = list(argv or self.argv)
192
+ if rc is not None:
193
+ rcdir = mkdtemp(prefix='ptymini-rc-')
194
+ rcfile = str(Path(rcdir)/'.zshrc') # one name serves bash (--rcfile {rcfile}) and zsh (ZDOTDIR={rcdir})
195
+ Path(rcfile).write_text(rc)
196
+ subst = lambda s: s.replace('{rcfile}', rcfile).replace('{rcdir}', rcdir)
197
+ argv = [subst(a) for a in argv]
198
+ if env: env = {k: subst(v) for k, v in env.items()}
199
+ if appendenv: appendenv = {k: subst(v) for k, v in appendenv.items()}
200
+ full_env = dict(os.environ if env is None else env) | (appendenv or {}) # `env` replaces the inherited environment; `appendenv` overlays the base
201
+ t = PtySession(argv, cwd=cwd, env=full_env, rows=rows, cols=cols, name=name)
202
+ self.terms[name] = t
203
+ return t
204
+
205
+ async def delete(self, name:str):
206
+ t = self.terms.pop(name)
207
+ await t.terminate(force=True)
208
+
209
+ def cull_ready(self)->list[str]:
210
+ "Names of terminals past the inactivity timeout (empty when culling is disabled)."
211
+ if not self.cull_timeout: return []
212
+ now = time.time()
213
+ return [n for n, t in self.terms.items() if now - t.last_activity > self.cull_timeout]
214
+
215
+ async def cull(self):
216
+ for n in self.cull_ready():
217
+ log.info('culling inactive session %s', n)
218
+ await self.delete(n)
219
+
220
+ async def shutdown(self):
221
+ "Reap every terminal; nothing survives the registry."
222
+ await asyncio.gather(*[self.delete(n) for n in list(self.terms)], return_exceptions=True)
223
+
224
+ def get(self, name:str)->PtySession|None: return self.terms.get(name)
225
+ def values(self): return self.terms.values()
226
+ def __len__(self): return len(self.terms)
227
+
228
+ async def __aenter__(self): return self
229
+ async def __aexit__(self, *exc): await self.shutdown()
230
+
231
+ # %% ../nbs/00_core.ipynb #eeed4f3d
232
+ async def cull_loop(reg:PtyRegistry, interval:float=300):
233
+ "Periodic cull sweep; an embedding app runs this as a task while it serves."
234
+ while True:
235
+ await asyncio.sleep(interval)
236
+ await reg.cull()
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: ptymini
3
+ Version: 0.0.1
4
+ Summary: Asyncio pty sessions: spawn, write, multi-client attach with replay, and a named registry
5
+ Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/AnswerDotAI/ptymini
8
+ Project-URL: Documentation, https://AnswerDotAI.github.io/ptymini/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: fastcore>=2.1.18
16
+ Requires-Dist: ptyprocess>=0.7
17
+ Dynamic: license-file
18
+
19
+ # ptymini
20
+
21
+
22
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
23
+
24
+ `ptymini` fills the gap between `ptyprocess` (a raw pty fd), `pexpect` (sync expect loops), and `terminado` (a pty server welded to tornado): asyncio-native pty *sessions*. A [`PtySession`](https://AnswerDotAI.github.io/ptymini/core.html#ptysession) is one spawned pty that any number of clients can attach to as independent byte streams, each primed from a byte-bounded replay buffer — so a reconnecting client resumes with recent scrollback instead of a blank screen. A [`PtyRegistry`](https://AnswerDotAI.github.io/ptymini/core.html#ptyregistry) adds named get-or-create sessions, injected shell setup (`rc`), and inactivity culling. It carries no server, no framework, and no session persistence beyond the process: web exposure belongs to the embedding app (e.g. [jupygate](https://github.com/AnswerDotAI/jupygate)), and durable session management belongs to tmux.
25
+
26
+ ## Usage
27
+
28
+ ### Installation
29
+
30
+ Install latest from the GitHub [repository](https://github.com/AnswerDotAI/ptymini):
31
+
32
+ ``` sh
33
+ $ pip install git+https://github.com/AnswerDotAI/ptymini.git
34
+ ```
35
+
36
+ or from [conda](https://anaconda.org/AnswerDotAI/ptymini)
37
+
38
+ ``` sh
39
+ $ conda install -c AnswerDotAI ptymini
40
+ ```
41
+
42
+ or from [pypi](https://pypi.org/project/ptymini/)
43
+
44
+ ``` sh
45
+ $ pip install ptymini
46
+ ```
47
+
48
+ ### Documentation
49
+
50
+ Documentation can be found hosted on this GitHub [repository](https://github.com/AnswerDotAI/ptymini)’s [pages](https://AnswerDotAI.github.io/ptymini/). Additionally you can find package manager specific guidelines on [conda](https://anaconda.org/AnswerDotAI/ptymini) and [pypi](https://pypi.org/project/ptymini/) respectively.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ ptymini/__init__.py
6
+ ptymini/_modidx.py
7
+ ptymini/bg.py
8
+ ptymini/core.py
9
+ ptymini.egg-info/PKG-INFO
10
+ ptymini.egg-info/SOURCES.txt
11
+ ptymini.egg-info/dependency_links.txt
12
+ ptymini.egg-info/entry_points.txt
13
+ ptymini.egg-info/requires.txt
14
+ ptymini.egg-info/top_level.txt
15
+ tests/test_bg.py
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ ptymini = ptymini._modidx:d
@@ -0,0 +1,2 @@
1
+ fastcore>=2.1.18
2
+ ptyprocess>=0.7
@@ -0,0 +1 @@
1
+ ptymini
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ptymini"
7
+ dynamic = ["version"]
8
+ description = "Asyncio pty sessions: spawn, write, multi-client attach with replay, and a named registry"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "Jeremy Howard", email = "github@jhoward.fastmail.fm"}]
13
+ keywords = ['nbdev']
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ ]
18
+ dependencies = ['fastcore>=2.1.18', 'ptyprocess>=0.7']
19
+
20
+ [project.urls]
21
+ Repository = "https://github.com/AnswerDotAI/ptymini"
22
+ Documentation = "https://AnswerDotAI.github.io/ptymini/"
23
+
24
+ [project.entry-points.nbdev]
25
+ ptymini = "ptymini._modidx:d"
26
+
27
+ [tool.setuptools.dynamic]
28
+ version = {attr = "ptymini.__version__"}
29
+
30
+ [tool.setuptools.packages.find]
31
+ include = ["ptymini"]
32
+
33
+ [tool.nbdev]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,73 @@
1
+
2
+ import sys, time
3
+
4
+ from ptymini.bg import Session, close_bgterm, list_sessions, poll, read, start_bgterm, write_stdin
5
+
6
+
7
+ def test_functional_write_stdin_collects_output_between_calls():
8
+ cmd = [sys.executable, "-u", "-c", "import time; print('ready', flush=True); time.sleep(0.5); print('later', flush=True)"]
9
+ sid = start_bgterm(cmd)
10
+ try:
11
+ assert sid in list_sessions()
12
+ first = poll(sid, 100)
13
+ assert "ready" in first.text
14
+
15
+ second = poll(sid, 700)
16
+ assert "later" in second.text
17
+ assert second.dropped_bytes == 0
18
+ finally: close_bgterm(sid)
19
+
20
+
21
+ def test_empty_write_stdin_returns_buffered_backlog_in_pages():
22
+ cmd = [sys.executable, "-u", "-c", "import sys; sys.stdout.write('x' * 4096); sys.stdout.flush()"]
23
+ sid = start_bgterm(cmd)
24
+ try:
25
+ time.sleep(0.1)
26
+ first = write_stdin(sid, max_output_bytes=1024)
27
+ second = read(sid, 1024)
28
+ assert first.bytes_returned == 1024
29
+ assert second.bytes_returned == 1024
30
+ assert first.remaining_bytes > 0
31
+ finally: close_bgterm(sid)
32
+
33
+
34
+ def test_small_buffer_reports_dropped_bytes():
35
+ cmd = [sys.executable, "-u", "-c", "import sys; sys.stdout.write('a' * 4096); sys.stdout.flush()"]
36
+ sid = start_bgterm(cmd, max_buffer_bytes=512)
37
+ try:
38
+ time.sleep(0.1)
39
+ result = poll(sid, max_output_bytes=None)
40
+ assert result.bytes_returned == 512
41
+ assert result.dropped_bytes == 4096 - 512
42
+ finally: close_bgterm(sid)
43
+
44
+
45
+ def test_functional_session_accepts_input_and_returns_echoed_output():
46
+ cmd = [
47
+ sys.executable,
48
+ "-u",
49
+ "-c",
50
+ "print('ready', flush=True)\n"
51
+ "import sys\n"
52
+ "for line in sys.stdin:\n"
53
+ " sys.stdout.write(f'ACK:{line}')\n"
54
+ " sys.stdout.flush()\n"]
55
+ sid = start_bgterm(cmd)
56
+ try:
57
+ ready = poll(sid, 500)
58
+ assert "ready" in ready.text
59
+
60
+ reply = write_stdin(sid, "hello\n", 100)
61
+ if "ACK:hello" not in reply.text: reply = poll(sid, 500)
62
+ assert "ACK:hello" in reply.text
63
+ finally: close_bgterm(sid)
64
+
65
+
66
+ def test_object_wrapper_delegates_to_sid_api():
67
+ cmd = [sys.executable, "-u", "-c", "print('ready', flush=True); raise SystemExit(3)"]
68
+ with Session.start(cmd) as sess:
69
+ ready = sess.poll(500)
70
+ assert "ready" in ready.text
71
+ assert sess.sid in list_sessions()
72
+ assert sess.running
73
+ assert sess.wait(3000) == 3