@theokit/sdk-pty 0.1.0
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.
- package/LICENSE +201 -0
- package/README.md +17 -0
- package/dist/index.cjs +157 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +151 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -0
package/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 describing the origin of the Work and
|
|
141
|
+
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 2026 usetheo.dev
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# @theokit/sdk-pty
|
|
2
|
+
|
|
3
|
+
Local, `node-pty`-backed implementation of `@theokit/sdk`'s `InteractiveBackend`.
|
|
4
|
+
|
|
5
|
+
Opt-in and **terminal-surface only** — this is the ONLY package in the theokit
|
|
6
|
+
ecosystem that depends on `node-pty` (optionally, so install never fails on a
|
|
7
|
+
native build). Core / `@theokit/sdk-tools` / cluster / desktop backends never
|
|
8
|
+
touch it.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { PtyInteractiveBackend } from "@theokit/sdk-pty";
|
|
12
|
+
// inject into an interactive shell tool that depends on InteractiveBackend
|
|
13
|
+
const interactive = new PtyInteractiveBackend();
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
When `node-pty` is unavailable (or a spawn fails), every method throws the SDK's
|
|
17
|
+
typed `InteractiveUnavailableError` so the caller falls back to non-interactive exec.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var module$1 = require('module');
|
|
6
|
+
var interactive = require('@theokit/sdk/interactive');
|
|
7
|
+
|
|
8
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
9
|
+
// src/pty-interactive-backend.ts
|
|
10
|
+
var nodeRequire = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
|
|
11
|
+
var YIELD_MIN_MS = 250;
|
|
12
|
+
var YIELD_MAX_MS = 3e4;
|
|
13
|
+
var DEFAULT_YIELD_MS = 500;
|
|
14
|
+
var DEFAULT_TTL_MS = 3e5;
|
|
15
|
+
var DEFAULT_MAX_BYTES = 1e5;
|
|
16
|
+
function clampYield(ms) {
|
|
17
|
+
const v = ms ?? DEFAULT_YIELD_MS;
|
|
18
|
+
return Math.max(YIELD_MIN_MS, Math.min(YIELD_MAX_MS, v));
|
|
19
|
+
}
|
|
20
|
+
function capTail(buf, max) {
|
|
21
|
+
return buf.length > max ? `\u2026(truncated)
|
|
22
|
+
${buf.slice(-max)}` : buf;
|
|
23
|
+
}
|
|
24
|
+
var PtyInteractiveBackend = class extends interactive.InteractiveBackend {
|
|
25
|
+
sessions = /* @__PURE__ */ new Map();
|
|
26
|
+
ptyModule;
|
|
27
|
+
exitReaperArmed = false;
|
|
28
|
+
/** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
|
|
29
|
+
loadPty() {
|
|
30
|
+
if (this.ptyModule !== void 0) return this.ptyModule;
|
|
31
|
+
try {
|
|
32
|
+
this.ptyModule = nodeRequire("node-pty");
|
|
33
|
+
} catch {
|
|
34
|
+
this.ptyModule = null;
|
|
35
|
+
}
|
|
36
|
+
return this.ptyModule;
|
|
37
|
+
}
|
|
38
|
+
/** Whether the interactive (PTY) path is usable in this environment. */
|
|
39
|
+
available() {
|
|
40
|
+
return this.loadPty() !== null;
|
|
41
|
+
}
|
|
42
|
+
/** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
|
|
43
|
+
* handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
|
|
44
|
+
armExitReaper() {
|
|
45
|
+
if (this.exitReaperArmed) return;
|
|
46
|
+
this.exitReaperArmed = true;
|
|
47
|
+
process.on("exit", () => this.killAll());
|
|
48
|
+
}
|
|
49
|
+
async collect(session, yieldMs, maxBytes) {
|
|
50
|
+
await new Promise((r) => setTimeout(r, clampYield(yieldMs)));
|
|
51
|
+
const out = session.pending;
|
|
52
|
+
session.pending = "";
|
|
53
|
+
return capTail(out, maxBytes);
|
|
54
|
+
}
|
|
55
|
+
armTtl(session, ttlMs) {
|
|
56
|
+
clearTimeout(session.ttlTimer);
|
|
57
|
+
session.ttlTimer = setTimeout(() => this.kill(session.id), ttlMs);
|
|
58
|
+
}
|
|
59
|
+
async startInteractive(command, opts) {
|
|
60
|
+
const pty = this.loadPty();
|
|
61
|
+
if (pty === null) {
|
|
62
|
+
throw new interactive.InteractiveUnavailableError(
|
|
63
|
+
"interactive shell unavailable: node-pty native module failed to load; use non-interactive exec"
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
this.armExitReaper();
|
|
67
|
+
const shell = process.env.SHELL ?? "/bin/bash";
|
|
68
|
+
const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;
|
|
69
|
+
const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
70
|
+
const cwd = opts?.cwd ?? process.cwd();
|
|
71
|
+
if (!fs.existsSync(cwd)) {
|
|
72
|
+
throw new interactive.InteractiveUnavailableError(`interactive shell unavailable: cwd does not exist: ${cwd}`);
|
|
73
|
+
}
|
|
74
|
+
let proc;
|
|
75
|
+
try {
|
|
76
|
+
proc = pty.spawn(shell, ["-c", command], {
|
|
77
|
+
name: "xterm-color",
|
|
78
|
+
cols: opts?.cols ?? 80,
|
|
79
|
+
rows: opts?.rows ?? 24,
|
|
80
|
+
cwd,
|
|
81
|
+
env: process.env
|
|
82
|
+
});
|
|
83
|
+
} catch (err) {
|
|
84
|
+
throw new interactive.InteractiveUnavailableError(
|
|
85
|
+
`interactive shell unavailable: failed to spawn a PTY (${err instanceof Error ? err.message : String(err)})`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const id = `pty-${crypto.randomUUID()}`;
|
|
89
|
+
const session = {
|
|
90
|
+
id,
|
|
91
|
+
pty: proc,
|
|
92
|
+
pending: "",
|
|
93
|
+
alive: true,
|
|
94
|
+
ttlTimer: setTimeout(() => this.kill(id), ttlMs),
|
|
95
|
+
writeChain: Promise.resolve()
|
|
96
|
+
};
|
|
97
|
+
proc.onData((data) => {
|
|
98
|
+
session.pending = capTail(session.pending + data, maxBytes);
|
|
99
|
+
});
|
|
100
|
+
proc.onExit(() => {
|
|
101
|
+
session.alive = false;
|
|
102
|
+
clearTimeout(session.ttlTimer);
|
|
103
|
+
this.sessions.delete(id);
|
|
104
|
+
});
|
|
105
|
+
this.sessions.set(id, session);
|
|
106
|
+
const output = await this.collect(session, opts?.yieldMs ?? DEFAULT_YIELD_MS, maxBytes);
|
|
107
|
+
return { sessionId: id, output };
|
|
108
|
+
}
|
|
109
|
+
async writeStdin(sessionId, chars, opts) {
|
|
110
|
+
const session = this.sessions.get(sessionId);
|
|
111
|
+
if (session === void 0 || !session.alive) throw new interactive.NoSuchSessionError(sessionId);
|
|
112
|
+
const run = session.writeChain.then(async () => {
|
|
113
|
+
if (!session.alive) throw new interactive.NoSuchSessionError(sessionId);
|
|
114
|
+
this.armTtl(session, opts?.ttlMs ?? DEFAULT_TTL_MS);
|
|
115
|
+
if (chars.length > 0) session.pty.write(chars);
|
|
116
|
+
const output = await this.collect(
|
|
117
|
+
session,
|
|
118
|
+
opts?.yieldMs ?? DEFAULT_YIELD_MS,
|
|
119
|
+
opts?.maxBytes ?? DEFAULT_MAX_BYTES
|
|
120
|
+
);
|
|
121
|
+
return { output, alive: session.alive };
|
|
122
|
+
});
|
|
123
|
+
session.writeChain = run.catch(() => void 0);
|
|
124
|
+
return run;
|
|
125
|
+
}
|
|
126
|
+
/** Kill a single session (idempotent). Kills the whole process GROUP so a detached grandchild dies too. */
|
|
127
|
+
kill(sessionId) {
|
|
128
|
+
const session = this.sessions.get(sessionId);
|
|
129
|
+
if (session === void 0) return;
|
|
130
|
+
clearTimeout(session.ttlTimer);
|
|
131
|
+
session.alive = false;
|
|
132
|
+
this.sessions.delete(sessionId);
|
|
133
|
+
try {
|
|
134
|
+
process.kill(-session.pty.pid, "SIGKILL");
|
|
135
|
+
} catch {
|
|
136
|
+
try {
|
|
137
|
+
session.pty.kill();
|
|
138
|
+
} catch {
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** Reap every session — used by the process-exit reaper; also callable on `/clear`. */
|
|
143
|
+
killAll() {
|
|
144
|
+
for (const id of [...this.sessions.keys()]) this.kill(id);
|
|
145
|
+
}
|
|
146
|
+
/** Live session count — for observability / tests. */
|
|
147
|
+
activeSessionCount() {
|
|
148
|
+
return this.sessions.size;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
exports.PtyInteractiveBackend = PtyInteractiveBackend;
|
|
153
|
+
exports.YIELD_MAX_MS = YIELD_MAX_MS;
|
|
154
|
+
exports.YIELD_MIN_MS = YIELD_MIN_MS;
|
|
155
|
+
exports.clampYield = clampYield;
|
|
156
|
+
//# sourceMappingURL=index.cjs.map
|
|
157
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pty-interactive-backend.ts"],"names":["createRequire","InteractiveBackend","InteractiveUnavailableError","existsSync","randomUUID","NoSuchSessionError"],"mappings":";;;;;;;;;AAgCA,IAAM,WAAA,GAAcA,sBAAA,CAAc,2PAA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AC5B,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,SAAS,CAAA;AAC3C,IAAA,IAAI,YAAY,MAAA,EAAW;AAC3B,IAAA,YAAA,CAAa,QAAQ,QAAQ,CAAA;AAC7B,IAAA,OAAA,CAAQ,KAAA,GAAQ,KAAA;AAChB,IAAA,IAAA,CAAK,QAAA,CAAS,OAAO,SAAS,CAAA;AAC9B,IAAA,IAAI;AACF,MAAA,OAAA,CAAQ,IAAA,CAAK,CAAC,OAAA,CAAQ,GAAA,CAAI,KAAK,SAAS,CAAA;AAAA,IAC1C,CAAA,CAAA,MAAQ;AACN,MAAA,IAAI;AACF,QAAA,OAAA,CAAQ,IAAI,IAAA,EAAK;AAAA,MACnB,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,OAAA,GAAgB;AACd,IAAA,KAAA,MAAW,EAAA,IAAM,CAAC,GAAG,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,EAAG,IAAA,CAAK,IAAA,CAAK,EAAE,CAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,kBAAA,GAA6B;AAC3B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AACF","file":"index.cjs","sourcesContent":["/**\n * `PtyInteractiveBackend` — the LOCAL implementation of `@theokit/sdk`'s\n * `InteractiveBackend`, backed by `node-pty`. This is the terminal-surface\n * backend: it allocates a real pseudo-terminal so REPLs, `git rebase -i`, and\n * prompting commands can be driven to completion. Ported from the AgentBuilder\n * Codex clone (M11) into the ecosystem (M14) so any terminal agent injects it.\n *\n * `node-pty` is an OPTIONAL dependency of this package — the ONLY place in the\n * theokit ecosystem that touches it. Core / sdk-tools / cluster / desktop never\n * do. When the native module is unavailable (or a spawn fails), every method\n * throws the SDK's typed {@link InteractiveUnavailableError} so the caller falls\n * back to non-interactive exec.\n *\n * Safety (mirrors M11): graceful typed degradation; per-session write\n * serialization (concurrent writes never steal each other's output); idle TTL\n * reaper; process-GROUP kill so detached grandchildren die; a process-exit\n * reaper; tail-capped output (the live prompt, not the stale banner).\n */\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport {\n InteractiveBackend,\n InteractiveUnavailableError,\n NoSuchSessionError,\n type StartInteractiveOptions,\n type StartInteractiveResult,\n type WriteStdinOptions,\n type WriteStdinResult,\n} from \"@theokit/sdk/interactive\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\nexport const YIELD_MIN_MS = 250;\nexport const YIELD_MAX_MS = 30_000;\nconst DEFAULT_YIELD_MS = 500;\nconst DEFAULT_TTL_MS = 300_000; // 5 min idle → reap\nconst DEFAULT_MAX_BYTES = 100_000;\n\n/** The minimal `node-pty` surface driven here (kept structural so the import stays lazy). */\ninterface PtyProcess {\n readonly pid: number;\n write(data: string): void;\n kill(signal?: string): void;\n onData(cb: (data: string) => void): void;\n onExit(cb: (e: { exitCode: number }) => void): void;\n}\ninterface PtyModule {\n spawn(file: string, args: string[], opts: Record<string, unknown>): PtyProcess;\n}\n\ninterface PtySession {\n id: string;\n pty: PtyProcess;\n pending: string;\n alive: boolean;\n ttlTimer: ReturnType<typeof setTimeout>;\n writeChain: Promise<unknown>;\n}\n\n/** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */\nexport function clampYield(ms: number | undefined): number {\n const v = ms ?? DEFAULT_YIELD_MS;\n return Math.max(YIELD_MIN_MS, Math.min(YIELD_MAX_MS, v));\n}\n\n/** Keep the TAIL of output — the newest bytes carry the live prompt. */\nfunction capTail(buf: string, max: number): string {\n return buf.length > max ? `…(truncated)\\n${buf.slice(-max)}` : buf;\n}\n\nexport class PtyInteractiveBackend extends InteractiveBackend {\n private readonly sessions = new Map<string, PtySession>();\n private ptyModule: PtyModule | null | undefined;\n private exitReaperArmed = false;\n\n /** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */\n private loadPty(): PtyModule | null {\n if (this.ptyModule !== undefined) return this.ptyModule;\n try {\n this.ptyModule = nodeRequire(\"node-pty\") as PtyModule;\n } catch {\n this.ptyModule = null;\n }\n return this.ptyModule;\n }\n\n /** Whether the interactive (PTY) path is usable in this environment. */\n available(): boolean {\n return this.loadPty() !== null;\n }\n\n /** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM\n * handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */\n private armExitReaper(): void {\n if (this.exitReaperArmed) return;\n this.exitReaperArmed = true;\n process.on(\"exit\", () => this.killAll());\n }\n\n private async collect(session: PtySession, yieldMs: number, maxBytes: number): Promise<string> {\n await new Promise((r) => setTimeout(r, clampYield(yieldMs)));\n const out = session.pending;\n session.pending = \"\";\n return capTail(out, maxBytes);\n }\n\n private armTtl(session: PtySession, ttlMs: number): void {\n clearTimeout(session.ttlTimer);\n session.ttlTimer = setTimeout(() => this.kill(session.id), ttlMs);\n }\n\n async startInteractive(\n command: string,\n opts?: StartInteractiveOptions,\n ): Promise<StartInteractiveResult> {\n const pty = this.loadPty();\n if (pty === null) {\n throw new InteractiveUnavailableError(\n \"interactive shell unavailable: node-pty native module failed to load; use non-interactive exec\",\n );\n }\n this.armExitReaper();\n const shell = process.env.SHELL ?? \"/bin/bash\";\n const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;\n // Validate cwd at the boundary: node-pty does NOT throw on a non-existent cwd (it spawns a broken\n // session), so fail-fast to the typed fallback the caller expects.\n const cwd = opts?.cwd ?? process.cwd();\n if (!existsSync(cwd)) {\n throw new InteractiveUnavailableError(`interactive shell unavailable: cwd does not exist: ${cwd}`);\n }\n let proc: PtyProcess;\n try {\n proc = pty.spawn(shell, [\"-c\", command], {\n name: \"xterm-color\",\n cols: opts?.cols ?? 80,\n rows: opts?.rows ?? 24,\n cwd,\n env: process.env,\n });\n } catch (err) {\n throw new InteractiveUnavailableError(\n `interactive shell unavailable: failed to spawn a PTY (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n const id = `pty-${randomUUID()}`;\n const session: PtySession = {\n id,\n pty: proc,\n pending: \"\",\n alive: true,\n ttlTimer: setTimeout(() => this.kill(id), ttlMs),\n writeChain: Promise.resolve(),\n };\n proc.onData((data) => {\n session.pending = capTail(session.pending + data, maxBytes);\n });\n proc.onExit(() => {\n session.alive = false;\n clearTimeout(session.ttlTimer);\n this.sessions.delete(id);\n });\n this.sessions.set(id, session);\n const output = await this.collect(session, opts?.yieldMs ?? DEFAULT_YIELD_MS, maxBytes);\n return { sessionId: id, output };\n }\n\n async writeStdin(\n sessionId: string,\n chars: string,\n opts?: WriteStdinOptions,\n ): Promise<WriteStdinResult> {\n const session = this.sessions.get(sessionId);\n if (session === undefined || !session.alive) throw new NoSuchSessionError(sessionId);\n // Serialize per session: chain onto the previous write so two concurrent calls run strictly in\n // order and each reads only its own output window (no stolen output).\n const run = session.writeChain.then(async () => {\n if (!session.alive) throw new NoSuchSessionError(sessionId);\n this.armTtl(session, opts?.ttlMs ?? DEFAULT_TTL_MS);\n if (chars.length > 0) session.pty.write(chars);\n const output = await this.collect(\n session,\n opts?.yieldMs ?? DEFAULT_YIELD_MS,\n opts?.maxBytes ?? DEFAULT_MAX_BYTES,\n );\n return { output, alive: session.alive };\n });\n session.writeChain = run.catch(() => undefined);\n return run;\n }\n\n /** Kill a single session (idempotent). Kills the whole process GROUP so a detached grandchild dies too. */\n kill(sessionId: string): void {\n const session = this.sessions.get(sessionId);\n if (session === undefined) return;\n clearTimeout(session.ttlTimer);\n session.alive = false;\n this.sessions.delete(sessionId);\n try {\n process.kill(-session.pty.pid, \"SIGKILL\");\n } catch {\n try {\n session.pty.kill();\n } catch {\n // already dead — nothing to do\n }\n }\n }\n\n /** Reap every session — used by the process-exit reaper; also callable on `/clear`. */\n killAll(): void {\n for (const id of [...this.sessions.keys()]) this.kill(id);\n }\n\n /** Live session count — for observability / tests. */\n activeSessionCount(): number {\n return this.sessions.size;\n }\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { InteractiveBackend, StartInteractiveOptions, StartInteractiveResult, WriteStdinOptions, WriteStdinResult } from '@theokit/sdk/interactive';
|
|
2
|
+
|
|
3
|
+
declare const YIELD_MIN_MS = 250;
|
|
4
|
+
declare const YIELD_MAX_MS = 30000;
|
|
5
|
+
/** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */
|
|
6
|
+
declare function clampYield(ms: number | undefined): number;
|
|
7
|
+
declare class PtyInteractiveBackend extends InteractiveBackend {
|
|
8
|
+
private readonly sessions;
|
|
9
|
+
private ptyModule;
|
|
10
|
+
private exitReaperArmed;
|
|
11
|
+
/** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
|
|
12
|
+
private loadPty;
|
|
13
|
+
/** Whether the interactive (PTY) path is usable in this environment. */
|
|
14
|
+
available(): boolean;
|
|
15
|
+
/** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
|
|
16
|
+
* handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
|
|
17
|
+
private armExitReaper;
|
|
18
|
+
private collect;
|
|
19
|
+
private armTtl;
|
|
20
|
+
startInteractive(command: string, opts?: StartInteractiveOptions): Promise<StartInteractiveResult>;
|
|
21
|
+
writeStdin(sessionId: string, chars: string, opts?: WriteStdinOptions): Promise<WriteStdinResult>;
|
|
22
|
+
/** Kill a single session (idempotent). Kills the whole process GROUP so a detached grandchild dies too. */
|
|
23
|
+
kill(sessionId: string): void;
|
|
24
|
+
/** Reap every session — used by the process-exit reaper; also callable on `/clear`. */
|
|
25
|
+
killAll(): void;
|
|
26
|
+
/** Live session count — for observability / tests. */
|
|
27
|
+
activeSessionCount(): number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export { PtyInteractiveBackend, YIELD_MAX_MS, YIELD_MIN_MS, clampYield };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { InteractiveBackend, StartInteractiveOptions, StartInteractiveResult, WriteStdinOptions, WriteStdinResult } from '@theokit/sdk/interactive';
|
|
2
|
+
|
|
3
|
+
declare const YIELD_MIN_MS = 250;
|
|
4
|
+
declare const YIELD_MAX_MS = 30000;
|
|
5
|
+
/** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */
|
|
6
|
+
declare function clampYield(ms: number | undefined): number;
|
|
7
|
+
declare class PtyInteractiveBackend extends InteractiveBackend {
|
|
8
|
+
private readonly sessions;
|
|
9
|
+
private ptyModule;
|
|
10
|
+
private exitReaperArmed;
|
|
11
|
+
/** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
|
|
12
|
+
private loadPty;
|
|
13
|
+
/** Whether the interactive (PTY) path is usable in this environment. */
|
|
14
|
+
available(): boolean;
|
|
15
|
+
/** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
|
|
16
|
+
* handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
|
|
17
|
+
private armExitReaper;
|
|
18
|
+
private collect;
|
|
19
|
+
private armTtl;
|
|
20
|
+
startInteractive(command: string, opts?: StartInteractiveOptions): Promise<StartInteractiveResult>;
|
|
21
|
+
writeStdin(sessionId: string, chars: string, opts?: WriteStdinOptions): Promise<WriteStdinResult>;
|
|
22
|
+
/** Kill a single session (idempotent). Kills the whole process GROUP so a detached grandchild dies too. */
|
|
23
|
+
kill(sessionId: string): void;
|
|
24
|
+
/** Reap every session — used by the process-exit reaper; also callable on `/clear`. */
|
|
25
|
+
killAll(): void;
|
|
26
|
+
/** Live session count — for observability / tests. */
|
|
27
|
+
activeSessionCount(): number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export { PtyInteractiveBackend, YIELD_MAX_MS, YIELD_MIN_MS, clampYield };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { existsSync } from 'fs';
|
|
3
|
+
import { createRequire } from 'module';
|
|
4
|
+
import { InteractiveBackend, InteractiveUnavailableError, NoSuchSessionError } from '@theokit/sdk/interactive';
|
|
5
|
+
|
|
6
|
+
// src/pty-interactive-backend.ts
|
|
7
|
+
var nodeRequire = createRequire(import.meta.url);
|
|
8
|
+
var YIELD_MIN_MS = 250;
|
|
9
|
+
var YIELD_MAX_MS = 3e4;
|
|
10
|
+
var DEFAULT_YIELD_MS = 500;
|
|
11
|
+
var DEFAULT_TTL_MS = 3e5;
|
|
12
|
+
var DEFAULT_MAX_BYTES = 1e5;
|
|
13
|
+
function clampYield(ms) {
|
|
14
|
+
const v = ms ?? DEFAULT_YIELD_MS;
|
|
15
|
+
return Math.max(YIELD_MIN_MS, Math.min(YIELD_MAX_MS, v));
|
|
16
|
+
}
|
|
17
|
+
function capTail(buf, max) {
|
|
18
|
+
return buf.length > max ? `\u2026(truncated)
|
|
19
|
+
${buf.slice(-max)}` : buf;
|
|
20
|
+
}
|
|
21
|
+
var PtyInteractiveBackend = class extends InteractiveBackend {
|
|
22
|
+
sessions = /* @__PURE__ */ new Map();
|
|
23
|
+
ptyModule;
|
|
24
|
+
exitReaperArmed = false;
|
|
25
|
+
/** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
|
|
26
|
+
loadPty() {
|
|
27
|
+
if (this.ptyModule !== void 0) return this.ptyModule;
|
|
28
|
+
try {
|
|
29
|
+
this.ptyModule = nodeRequire("node-pty");
|
|
30
|
+
} catch {
|
|
31
|
+
this.ptyModule = null;
|
|
32
|
+
}
|
|
33
|
+
return this.ptyModule;
|
|
34
|
+
}
|
|
35
|
+
/** Whether the interactive (PTY) path is usable in this environment. */
|
|
36
|
+
available() {
|
|
37
|
+
return this.loadPty() !== null;
|
|
38
|
+
}
|
|
39
|
+
/** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
|
|
40
|
+
* handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
|
|
41
|
+
armExitReaper() {
|
|
42
|
+
if (this.exitReaperArmed) return;
|
|
43
|
+
this.exitReaperArmed = true;
|
|
44
|
+
process.on("exit", () => this.killAll());
|
|
45
|
+
}
|
|
46
|
+
async collect(session, yieldMs, maxBytes) {
|
|
47
|
+
await new Promise((r) => setTimeout(r, clampYield(yieldMs)));
|
|
48
|
+
const out = session.pending;
|
|
49
|
+
session.pending = "";
|
|
50
|
+
return capTail(out, maxBytes);
|
|
51
|
+
}
|
|
52
|
+
armTtl(session, ttlMs) {
|
|
53
|
+
clearTimeout(session.ttlTimer);
|
|
54
|
+
session.ttlTimer = setTimeout(() => this.kill(session.id), ttlMs);
|
|
55
|
+
}
|
|
56
|
+
async startInteractive(command, opts) {
|
|
57
|
+
const pty = this.loadPty();
|
|
58
|
+
if (pty === null) {
|
|
59
|
+
throw new InteractiveUnavailableError(
|
|
60
|
+
"interactive shell unavailable: node-pty native module failed to load; use non-interactive exec"
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
this.armExitReaper();
|
|
64
|
+
const shell = process.env.SHELL ?? "/bin/bash";
|
|
65
|
+
const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;
|
|
66
|
+
const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
67
|
+
const cwd = opts?.cwd ?? process.cwd();
|
|
68
|
+
if (!existsSync(cwd)) {
|
|
69
|
+
throw new InteractiveUnavailableError(`interactive shell unavailable: cwd does not exist: ${cwd}`);
|
|
70
|
+
}
|
|
71
|
+
let proc;
|
|
72
|
+
try {
|
|
73
|
+
proc = pty.spawn(shell, ["-c", command], {
|
|
74
|
+
name: "xterm-color",
|
|
75
|
+
cols: opts?.cols ?? 80,
|
|
76
|
+
rows: opts?.rows ?? 24,
|
|
77
|
+
cwd,
|
|
78
|
+
env: process.env
|
|
79
|
+
});
|
|
80
|
+
} catch (err) {
|
|
81
|
+
throw new InteractiveUnavailableError(
|
|
82
|
+
`interactive shell unavailable: failed to spawn a PTY (${err instanceof Error ? err.message : String(err)})`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const id = `pty-${randomUUID()}`;
|
|
86
|
+
const session = {
|
|
87
|
+
id,
|
|
88
|
+
pty: proc,
|
|
89
|
+
pending: "",
|
|
90
|
+
alive: true,
|
|
91
|
+
ttlTimer: setTimeout(() => this.kill(id), ttlMs),
|
|
92
|
+
writeChain: Promise.resolve()
|
|
93
|
+
};
|
|
94
|
+
proc.onData((data) => {
|
|
95
|
+
session.pending = capTail(session.pending + data, maxBytes);
|
|
96
|
+
});
|
|
97
|
+
proc.onExit(() => {
|
|
98
|
+
session.alive = false;
|
|
99
|
+
clearTimeout(session.ttlTimer);
|
|
100
|
+
this.sessions.delete(id);
|
|
101
|
+
});
|
|
102
|
+
this.sessions.set(id, session);
|
|
103
|
+
const output = await this.collect(session, opts?.yieldMs ?? DEFAULT_YIELD_MS, maxBytes);
|
|
104
|
+
return { sessionId: id, output };
|
|
105
|
+
}
|
|
106
|
+
async writeStdin(sessionId, chars, opts) {
|
|
107
|
+
const session = this.sessions.get(sessionId);
|
|
108
|
+
if (session === void 0 || !session.alive) throw new NoSuchSessionError(sessionId);
|
|
109
|
+
const run = session.writeChain.then(async () => {
|
|
110
|
+
if (!session.alive) throw new NoSuchSessionError(sessionId);
|
|
111
|
+
this.armTtl(session, opts?.ttlMs ?? DEFAULT_TTL_MS);
|
|
112
|
+
if (chars.length > 0) session.pty.write(chars);
|
|
113
|
+
const output = await this.collect(
|
|
114
|
+
session,
|
|
115
|
+
opts?.yieldMs ?? DEFAULT_YIELD_MS,
|
|
116
|
+
opts?.maxBytes ?? DEFAULT_MAX_BYTES
|
|
117
|
+
);
|
|
118
|
+
return { output, alive: session.alive };
|
|
119
|
+
});
|
|
120
|
+
session.writeChain = run.catch(() => void 0);
|
|
121
|
+
return run;
|
|
122
|
+
}
|
|
123
|
+
/** Kill a single session (idempotent). Kills the whole process GROUP so a detached grandchild dies too. */
|
|
124
|
+
kill(sessionId) {
|
|
125
|
+
const session = this.sessions.get(sessionId);
|
|
126
|
+
if (session === void 0) return;
|
|
127
|
+
clearTimeout(session.ttlTimer);
|
|
128
|
+
session.alive = false;
|
|
129
|
+
this.sessions.delete(sessionId);
|
|
130
|
+
try {
|
|
131
|
+
process.kill(-session.pty.pid, "SIGKILL");
|
|
132
|
+
} catch {
|
|
133
|
+
try {
|
|
134
|
+
session.pty.kill();
|
|
135
|
+
} catch {
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Reap every session — used by the process-exit reaper; also callable on `/clear`. */
|
|
140
|
+
killAll() {
|
|
141
|
+
for (const id of [...this.sessions.keys()]) this.kill(id);
|
|
142
|
+
}
|
|
143
|
+
/** Live session count — for observability / tests. */
|
|
144
|
+
activeSessionCount() {
|
|
145
|
+
return this.sessions.size;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export { PtyInteractiveBackend, YIELD_MAX_MS, YIELD_MIN_MS, clampYield };
|
|
150
|
+
//# sourceMappingURL=index.js.map
|
|
151
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pty-interactive-backend.ts"],"names":[],"mappings":";;;;;;AAgCA,IAAM,WAAA,GAAc,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AAE1C,IAAM,YAAA,GAAe;AACrB,IAAM,YAAA,GAAe;AAC5B,IAAM,gBAAA,GAAmB,GAAA;AACzB,IAAM,cAAA,GAAiB,GAAA;AACvB,IAAM,iBAAA,GAAoB,GAAA;AAwBnB,SAAS,WAAW,EAAA,EAAgC;AACzD,EAAA,MAAM,IAAI,EAAA,IAAM,gBAAA;AAChB,EAAA,OAAO,KAAK,GAAA,CAAI,YAAA,EAAc,KAAK,GAAA,CAAI,YAAA,EAAc,CAAC,C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A,CAAQ,GAAA,CAAI,KAAK,SAAS,CAAA;AAAA,IAC1C,CAAA,CAAA,MAAQ;AACN,MAAA,IAAI;AACF,QAAA,OAAA,CAAQ,IAAI,IAAA,EAAK;AAAA,MACnB,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,OAAA,GAAgB;AACd,IAAA,KAAA,MAAW,EAAA,IAAM,CAAC,GAAG,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,EAAG,IAAA,CAAK,IAAA,CAAK,EAAE,CAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,kBAAA,GAA6B;AAC3B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AACF","file":"index.js","sourcesContent":["/**\n * `PtyInteractiveBackend` — the LOCAL implementation of `@theokit/sdk`'s\n * `InteractiveBackend`, backed by `node-pty`. This is the terminal-surface\n * backend: it allocates a real pseudo-terminal so REPLs, `git rebase -i`, and\n * prompting commands can be driven to completion. Ported from the AgentBuilder\n * Codex clone (M11) into the ecosystem (M14) so any terminal agent injects it.\n *\n * `node-pty` is an OPTIONAL dependency of this package — the ONLY place in the\n * theokit ecosystem that touches it. Core / sdk-tools / cluster / desktop never\n * do. When the native module is unavailable (or a spawn fails), every method\n * throws the SDK's typed {@link InteractiveUnavailableError} so the caller falls\n * back to non-interactive exec.\n *\n * Safety (mirrors M11): graceful typed degradation; per-session write\n * serialization (concurrent writes never steal each other's output); idle TTL\n * reaper; process-GROUP kill so detached grandchildren die; a process-exit\n * reaper; tail-capped output (the live prompt, not the stale banner).\n */\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport {\n InteractiveBackend,\n InteractiveUnavailableError,\n NoSuchSessionError,\n type StartInteractiveOptions,\n type StartInteractiveResult,\n type WriteStdinOptions,\n type WriteStdinResult,\n} from \"@theokit/sdk/interactive\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\nexport const YIELD_MIN_MS = 250;\nexport const YIELD_MAX_MS = 30_000;\nconst DEFAULT_YIELD_MS = 500;\nconst DEFAULT_TTL_MS = 300_000; // 5 min idle → reap\nconst DEFAULT_MAX_BYTES = 100_000;\n\n/** The minimal `node-pty` surface driven here (kept structural so the import stays lazy). */\ninterface PtyProcess {\n readonly pid: number;\n write(data: string): void;\n kill(signal?: string): void;\n onData(cb: (data: string) => void): void;\n onExit(cb: (e: { exitCode: number }) => void): void;\n}\ninterface PtyModule {\n spawn(file: string, args: string[], opts: Record<string, unknown>): PtyProcess;\n}\n\ninterface PtySession {\n id: string;\n pty: PtyProcess;\n pending: string;\n alive: boolean;\n ttlTimer: ReturnType<typeof setTimeout>;\n writeChain: Promise<unknown>;\n}\n\n/** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */\nexport function clampYield(ms: number | undefined): number {\n const v = ms ?? DEFAULT_YIELD_MS;\n return Math.max(YIELD_MIN_MS, Math.min(YIELD_MAX_MS, v));\n}\n\n/** Keep the TAIL of output — the newest bytes carry the live prompt. */\nfunction capTail(buf: string, max: number): string {\n return buf.length > max ? `…(truncated)\\n${buf.slice(-max)}` : buf;\n}\n\nexport class PtyInteractiveBackend extends InteractiveBackend {\n private readonly sessions = new Map<string, PtySession>();\n private ptyModule: PtyModule | null | undefined;\n private exitReaperArmed = false;\n\n /** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */\n private loadPty(): PtyModule | null {\n if (this.ptyModule !== undefined) return this.ptyModule;\n try {\n this.ptyModule = nodeRequire(\"node-pty\") as PtyModule;\n } catch {\n this.ptyModule = null;\n }\n return this.ptyModule;\n }\n\n /** Whether the interactive (PTY) path is usable in this environment. */\n available(): boolean {\n return this.loadPty() !== null;\n }\n\n /** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM\n * handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */\n private armExitReaper(): void {\n if (this.exitReaperArmed) return;\n this.exitReaperArmed = true;\n process.on(\"exit\", () => this.killAll());\n }\n\n private async collect(session: PtySession, yieldMs: number, maxBytes: number): Promise<string> {\n await new Promise((r) => setTimeout(r, clampYield(yieldMs)));\n const out = session.pending;\n session.pending = \"\";\n return capTail(out, maxBytes);\n }\n\n private armTtl(session: PtySession, ttlMs: number): void {\n clearTimeout(session.ttlTimer);\n session.ttlTimer = setTimeout(() => this.kill(session.id), ttlMs);\n }\n\n async startInteractive(\n command: string,\n opts?: StartInteractiveOptions,\n ): Promise<StartInteractiveResult> {\n const pty = this.loadPty();\n if (pty === null) {\n throw new InteractiveUnavailableError(\n \"interactive shell unavailable: node-pty native module failed to load; use non-interactive exec\",\n );\n }\n this.armExitReaper();\n const shell = process.env.SHELL ?? \"/bin/bash\";\n const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;\n // Validate cwd at the boundary: node-pty does NOT throw on a non-existent cwd (it spawns a broken\n // session), so fail-fast to the typed fallback the caller expects.\n const cwd = opts?.cwd ?? process.cwd();\n if (!existsSync(cwd)) {\n throw new InteractiveUnavailableError(`interactive shell unavailable: cwd does not exist: ${cwd}`);\n }\n let proc: PtyProcess;\n try {\n proc = pty.spawn(shell, [\"-c\", command], {\n name: \"xterm-color\",\n cols: opts?.cols ?? 80,\n rows: opts?.rows ?? 24,\n cwd,\n env: process.env,\n });\n } catch (err) {\n throw new InteractiveUnavailableError(\n `interactive shell unavailable: failed to spawn a PTY (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n const id = `pty-${randomUUID()}`;\n const session: PtySession = {\n id,\n pty: proc,\n pending: \"\",\n alive: true,\n ttlTimer: setTimeout(() => this.kill(id), ttlMs),\n writeChain: Promise.resolve(),\n };\n proc.onData((data) => {\n session.pending = capTail(session.pending + data, maxBytes);\n });\n proc.onExit(() => {\n session.alive = false;\n clearTimeout(session.ttlTimer);\n this.sessions.delete(id);\n });\n this.sessions.set(id, session);\n const output = await this.collect(session, opts?.yieldMs ?? DEFAULT_YIELD_MS, maxBytes);\n return { sessionId: id, output };\n }\n\n async writeStdin(\n sessionId: string,\n chars: string,\n opts?: WriteStdinOptions,\n ): Promise<WriteStdinResult> {\n const session = this.sessions.get(sessionId);\n if (session === undefined || !session.alive) throw new NoSuchSessionError(sessionId);\n // Serialize per session: chain onto the previous write so two concurrent calls run strictly in\n // order and each reads only its own output window (no stolen output).\n const run = session.writeChain.then(async () => {\n if (!session.alive) throw new NoSuchSessionError(sessionId);\n this.armTtl(session, opts?.ttlMs ?? DEFAULT_TTL_MS);\n if (chars.length > 0) session.pty.write(chars);\n const output = await this.collect(\n session,\n opts?.yieldMs ?? DEFAULT_YIELD_MS,\n opts?.maxBytes ?? DEFAULT_MAX_BYTES,\n );\n return { output, alive: session.alive };\n });\n session.writeChain = run.catch(() => undefined);\n return run;\n }\n\n /** Kill a single session (idempotent). Kills the whole process GROUP so a detached grandchild dies too. */\n kill(sessionId: string): void {\n const session = this.sessions.get(sessionId);\n if (session === undefined) return;\n clearTimeout(session.ttlTimer);\n session.alive = false;\n this.sessions.delete(sessionId);\n try {\n process.kill(-session.pty.pid, \"SIGKILL\");\n } catch {\n try {\n session.pty.kill();\n } catch {\n // already dead — nothing to do\n }\n }\n }\n\n /** Reap every session — used by the process-exit reaper; also callable on `/clear`. */\n killAll(): void {\n for (const id of [...this.sessions.keys()]) this.kill(id);\n }\n\n /** Live session count — for observability / tests. */\n activeSessionCount(): number {\n return this.sessions.size;\n }\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@theokit/sdk-pty",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Local interactive-shell backend for @theokit/sdk — a node-pty implementation of InteractiveBackend. Opt-in, terminal-surface only; node-pty is optional so install never fails on a native build.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"require": {
|
|
16
|
+
"types": "./dist/index.d.cts",
|
|
17
|
+
"default": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"./package.json": "./package.json"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsup",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"typecheck": "tsc --noEmit"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@theokit/sdk": ">=4.4.1"
|
|
29
|
+
},
|
|
30
|
+
"optionalDependencies": {
|
|
31
|
+
"node-pty": "^1.1.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@theokit/sdk": "workspace:*",
|
|
35
|
+
"node-pty": "^1.1.0",
|
|
36
|
+
"tsup": "^8.3.5",
|
|
37
|
+
"typescript": "^5.7.2",
|
|
38
|
+
"vitest": "^4.1.8"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"dist",
|
|
42
|
+
"README.md",
|
|
43
|
+
"LICENSE"
|
|
44
|
+
],
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
}
|
|
48
|
+
}
|