@deepseek-ai/dsh-terminal-bash 0.0.1-rc.3

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 ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, DeepSeek
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/terminal/terminal-bash/README.md
5
+ README.md: 36e725fd4ce86be09755768a9e21ccb66d025251
6
+ README.zh.md: 080f45eb03dfdeece91269a3253aeb3fb280864d
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # @deepseek-ai/dsh-terminal-bash
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ Persistent shell backend for `ctx.terminals` over `ctx.subprocess.spawnTerminal`. It starts an interactive shell under the shared `ctx.sandboxPolicy`, retains bounded line-oriented output, and detects readiness while the subprocess provider owns PTY allocation, environment scrubbing, foreground process groups, signalling, and complete terminal-session cleanup. The same PTY backend therefore composes with local or remote execution-world providers.
6
+
7
+ ## Plugin (`terminal-bash`)
8
+
9
+ The plugin injects `pty`, `sandboxPolicy`, and `subprocess`, then registers the configured backend type (`shell`). `danger-full-access` starts the shell directly without requiring a sandbox provider; confined modes require a same-world `ctx.sandbox` and wrap the exact shell argv through it, failing before spawn when none is mounted. At spawn, one `ctx.sandboxPolicy.resolve({ session })` call supplies both the effective mode and the session workspace root; the same root is the default shell cwd when the caller omits one. A change to a different effective mode is rejected before its `sandbox/mode` event commits while that owner has an open PTY or a spawn in progress; the fence is attached to the exact owner and therefore outlives a provider reload that retains existing sessions. Wait for creation to settle and close the sessions before changing modes, so a terminal opened with wider access cannot survive a downgrade.
10
+
11
+ Readiness combines a foreground-verified private bash prompt marker, provider-reported foreground stdin-wait facts, silence fallback, and absolute timeout. A marker is not ready until the printable tail after the latest owned marker exactly equals the controlled `PS1`, including when the OSC marker and prompt are split across data callbacks; echoed input or output following an earlier prompt therefore cannot settle the current send. Prompt and silence evidence collected before the provider write, including while pre-write foreground inspection is pending, is discarded at the write boundary. When bash prints the marker before the terminal provider publishes its return to the foreground process group, polling retains the candidate for `handoffGraceMs` past the ordinary silence bound so a coincident handoff can win. An interactive child that inherits `PROMPT_COMMAND` therefore cannot suppress inferred-idle readiness until the absolute timeout. Unknown foreground state is never a positive exact-idle signal. A foreground group's stdin wait that existed before a send is likewise not post-write readiness: the same group must be observed outside that wait before a later wait can settle the send, while a changed foreground group is new evidence. During unpublished startup, a fallback requires observed output; zero-output silence cannot publish an empty session, and timeout rejects the spawn. Cancellation closes the unpublished shell and rejects with the caller's exact abort reason; `TerminalBackendCleanupError` separately preserves a cleanup failure. The caller's signal is forwarded for terminal allocation and readiness initialization; after publication the handle owns its lifetime. Incomplete terminal-control sequences are bounded by `maxReadBytes` and discarded through their terminator after crossing that limit; malformed UTF-8 terminal output uses replacement characters, and a trailing carriage return is carried across callbacks so split CRLF becomes one newline.
12
+
13
+ Send cancellation marks queued input as canceled before asking the terminal handle to signal the current foreground process group with a real `SIGINT`; if asynchronous pre-write inspection later settles, it cannot execute that input. If a provider write is already in flight, signalling waits for it to settle; a rejected write sends no signal. The canceled send retains its slot until the write and foreground signalling settle, so a successor cannot receive either late bytes or that signal. A provider write or signal that never settles therefore retains the slot indefinitely; closing the session (`terminal_close`) is the recovery. The absolute deadline remains armed while cancellation waits. A signal failure is a terminal transport failure and rejects the active send. Cancellation never emulates interruption by writing `\x03`, so raw-mode programs remain cancellable. Close rejects new public signals, stops readiness polling, and awaits the handle's provider-owned complete-session termination before settling the active send as `session_exit`.
14
+
15
+ ## Model Experience
16
+
17
+ ### Current file policy and indirect consumer
18
+
19
+ #### What the model sees
20
+
21
+ The policy owner contributes capability-neutral `sandbox:policy` context. Through `@deepseek-ai/dsh-tool-terminal` or another PTY consumer, the model may also receive bounded MOTD, send deltas, scrollback pages, readiness reasons, and cleanup errors.
22
+
23
+ #### Token effect
24
+
25
+ The current-policy clause is present while this backend is mounted. Retained PTY scrollback is not placed in model history until a consumer returns bounded output.
26
+
27
+ #### KV Cache effect
28
+
29
+ A standing-policy change appends an owner-rendered superseding runtime-context snapshot after retained history; consumer results remain append-only.
30
+
31
+ ## Known Limitations and Deferred Work
32
+
33
+ - Line-oriented output is normalized; full-screen alternate-buffer interaction is unsupported.
34
+ - Exact stdin-wait detection depends on the mounted subprocess provider; providers that cannot prove it use prompt-marker and silence/timeout readiness.
35
+ - Cleanup guarantees are those of `SubprocessTerminalHandle`; provider-specific gaps belong to that implementation's contract rather than this PTY consumer.
36
+ - Sessions do not survive harness process exit.
package/README.zh.md ADDED
@@ -0,0 +1,36 @@
1
+ # @deepseek-ai/dsh-terminal-bash
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 这是一个基于 `ctx.subprocess.spawnTerminal`、为 `ctx.terminals` 提供的持久 shell 后端。它在共享 `ctx.sandboxPolicy` 下启动交互式 shell,保留有界的逐行输出并检测就绪状态;进程管理提供方则负责 PTY 分配、环境清理、前台进程组、信号发送和完整终端会话清理。因此,同一个 PTY 后端可以与本地或远程执行世界提供方组合。
6
+
7
+ ## 插件(`terminal-bash`)
8
+
9
+ 该插件注入 `pty`、`sandboxPolicy` 和 `subprocess`,然后注册所配置的后端类型(`shell`)。`danger-full-access` 无需沙箱提供方即可直接启动 shell;受限模式要求同一执行世界中存在 `ctx.sandbox`,并通过它包装确切的 shell argv,未挂载时会在 spawn 前失败。spawn 时,一次 `ctx.sandboxPolicy.resolve({ session })` 调用会同时给出实际模式与会话工作区根目录;调用方省略 cwd 时,同一根目录也是 shell 的默认 cwd。当某个所有者存在开放的 PTY 或正在进行 spawn 时,如果配置变更会得到不同的实际模式,系统会在对应 `sandbox/mode` 事件提交前拒绝该变更。该限制绑定到确切所有者,因此即使提供方重新加载并保留现有会话,它仍然有效。更改模式前,请等待创建完成并关闭会话,避免以更宽权限打开的终端在权限降级后继续存在。
10
+
11
+ 就绪检测结合以下机制:由前台状态验证的私有 bash 提示符标记、提供方报告的前台 stdin 等待事实、静默回退和绝对超时。只有最新自有标记之后的可打印尾部与受控 `PS1` 完全相等,标记才算就绪;即使 OSC 标记和提示符被拆到多个数据回调中也一样。因此,较早提示符之后的回显输入或输出无法使当前 send 完成。提供方写入前收集的提示符与静默证据,包括写入前前台检查仍在等待时收集的证据,都会在写入边界丢弃。如果 bash 在终端提供方发布其重新取得前台进程组的状态前打印标记,轮询会在普通静默上限之后再保留该候选状态 `handoffGraceMs`,使恰好同时发生的前台交接有机会胜出。因此,继承 `PROMPT_COMMAND` 的交互式子进程无法一直抑制推断空闲就绪直至绝对超时。未知的前台状态绝不会作为精确空闲的正向信号。同样,一次 send 之前就已存在的前台进程组 stdin 等待并不代表写入后就绪:必须先观察到同一进程组脱离该等待,之后再次进入等待才能使该次 send 完成;前台进程组发生变化则构成新的证据。尚未发布的启动过程中,回退路径要求已经观察到输出;零输出静默不能发布空会话,超时则拒绝 spawn。取消操作会关闭尚未发布的 shell,并以调用方提供的确切中止原因拒绝;`TerminalBackendCleanupError` 会单独保留清理失败。调用方的 signal 会转发给终端分配与就绪初始化;发布后,句柄负责其生命周期。未完成的终端控制序列受 `maxReadBytes` 限制;超过上限后,系统会丢弃内容直到其终止符。格式错误的 UTF-8 终端输出使用替换字符;末尾的回车会跨回调保留,使拆分的 CRLF 合并为一个换行。
12
+
13
+ 取消发送时,系统会先把排队输入标记为已取消,再要求终端句柄向当前前台进程组发送真正的 `SIGINT`;异步写入前检查即使随后结算,也无法执行该输入。如果提供方写入已在途,信号发送会等待其结算;写入被拒绝时不会发送信号。已取消的 send 会保留其位置,直到写入与前台信号发送都结算,因此后继 send 不会收到延迟字节或该信号。因此,永不结算的提供方写入或信号会无限期保留该位置;恢复手段是关闭会话(`terminal_close`)。取消等待期间,绝对 deadline 仍保持启用。信号发送失败是终端传输失败,会拒绝活跃 send。取消绝不会通过写入 `\x03` 模拟中断,因此,即使程序运行在 raw 模式下,也仍可取消。关闭操作会拒绝新的公开信号、停止就绪轮询,并等待由句柄提供方负责的完整会话终止,然后才把活跃 send 结算为 `session_exit`。
14
+
15
+ ## 模型体验
16
+
17
+ ### 当前文件策略与间接消费方
18
+
19
+ #### 模型看到的内容
20
+
21
+ 策略归属方会贡献与具体能力无关的 `sandbox:policy` 上下文。模型通过 `@deepseek-ai/dsh-tool-terminal` 或其他 PTY 消费方还可能收到有界的 MOTD、发送增量、scrollback 页、就绪原因和清理错误。
22
+
23
+ #### Token 影响
24
+
25
+ 装载该后端期间,当前策略子句会一直存在。消费方返回有界输出前,保留的 PTY scrollback 不会进入模型历史。
26
+
27
+ #### KV Cache 影响
28
+
29
+ 常驻策略发生变化时,会在保留的历史之后追加一份由归属方渲染、取代先前状态的运行时上下文快照;消费方结果保持仅追加。
30
+
31
+ ## 已知限制与暂缓事项
32
+
33
+ - 输出按行规范化;不支持全屏备用缓冲区交互。
34
+ - 精确 stdin 等待检测取决于已挂载的进程管理提供方;无法证明该状态的提供方使用提示符标记和静默/超时就绪机制。
35
+ - 清理保证以 `SubprocessTerminalHandle` 的保证为准;提供方特定的缺口属于该实现的约定,而非这个 PTY 消费方。
36
+ - harness 进程退出后,会话无法继续存在。
package/lib/index.js ADDED
@@ -0,0 +1,805 @@
1
+ import { TerminalBackendCleanupError, TerminalError } from "@deepseek-ai/dsh-terminal";
2
+ import { effectiveSandboxMode } from "@deepseek-ai/dsh-sandbox-policy";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { Buffer } from "node:buffer";
5
+ //#region lib/types/config.js
6
+ /** Validated configuration for the local PTY backend. */
7
+ /** Schemastery config exposed by the plugin. */
8
+ const Config = z.object({
9
+ backendType: z.string().default("shell"),
10
+ shellPath: z.string().default("/bin/bash"),
11
+ shellArgs: z.array(z.string()).default([
12
+ "--noprofile",
13
+ "--norc",
14
+ "-i"
15
+ ]),
16
+ rows: z.number().default(40),
17
+ cols: z.number().default(160),
18
+ scrollbackLines: z.number().default(1e4),
19
+ scrollbackMaxBytes: z.number().default(4 * 1024 * 1024),
20
+ maxReadBytes: z.number().default(256 * 1024),
21
+ pollIntervalMs: z.number().default(50),
22
+ exactProbeAfterMs: z.number().default(150),
23
+ idleSilenceMs: z.number().default(3e3),
24
+ handoffGraceMs: z.number().default(500),
25
+ timeoutMs: z.number().default(3e4),
26
+ disposeGraceMs: z.number().default(3e3)
27
+ });
28
+ /**
29
+ * Assert every numeric config field is a positive safe integer and bounds compose.
30
+ * @param config - Schemastery-resolved plugin configuration.
31
+ * @returns Narrows the input to the fully resolved configuration.
32
+ */
33
+ function validateConfig(config) {
34
+ const resolved = config;
35
+ if (resolved.backendType.length === 0) throw new Error("terminal-bash: backendType must be non-empty");
36
+ if (resolved.shellPath.length === 0) throw new Error("terminal-bash: shellPath must be non-empty");
37
+ for (const [name, value] of Object.entries(resolved)) if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) throw new Error(`terminal-bash: ${name} must be a positive safe integer`);
38
+ if (resolved.maxReadBytes > resolved.scrollbackMaxBytes) throw new Error("terminal-bash: maxReadBytes must not exceed scrollbackMaxBytes");
39
+ if (resolved.handoffGraceMs < resolved.pollIntervalMs) throw new Error("terminal-bash: handoffGraceMs must be at least pollIntervalMs so one readiness poll runs inside the grace window");
40
+ }
41
+ /** Exact printable prompt emitted after the private marker. */
42
+ const CONTROLLED_PROMPT = "dsh> ";
43
+ /**
44
+ * Remove CSI/OSC/short escape sequences while preserving split-sequence carry.
45
+ * Full terminal emulation is deliberately deferred; ordinary line output and
46
+ * the private prompt marker are the supported contract.
47
+ */
48
+ var TerminalSanitizer = class {
49
+ maxPendingBytes;
50
+ pending = "";
51
+ discardMode;
52
+ discardOscEscape = false;
53
+ trailingCarriageReturn = false;
54
+ trackingPromptTail = false;
55
+ constructor(maxPendingBytes) {
56
+ this.maxPendingBytes = maxPendingBytes;
57
+ }
58
+ /**
59
+ * Consume one decoded `node-pty` data chunk.
60
+ * @param chunk - decoded terminal data.
61
+ * @returns Printable text and whether the private prompt marker completed.
62
+ */
63
+ push(chunk) {
64
+ this.pending += this.discardPrefix(chunk);
65
+ let text = "";
66
+ let prompt = false;
67
+ let includePromptTail = this.trackingPromptTail;
68
+ let promptTail = "";
69
+ let index = 0;
70
+ const appendText = (value) => {
71
+ text += value;
72
+ if (this.trackingPromptTail) promptTail += value;
73
+ };
74
+ while (index < this.pending.length) {
75
+ const escape = this.pending.indexOf("\x1B", index);
76
+ if (escape < 0) {
77
+ appendText(this.pending.slice(index));
78
+ index = this.pending.length;
79
+ break;
80
+ }
81
+ appendText(this.pending.slice(index, escape));
82
+ if (escape + 1 >= this.pending.length) {
83
+ index = escape;
84
+ break;
85
+ }
86
+ const kind = this.pending[escape + 1];
87
+ if (kind === "]") {
88
+ const bel = this.pending.indexOf("\x07", escape + 2);
89
+ const stringTerminator = this.pending.indexOf("\x1B\\", escape + 2);
90
+ let end = -1;
91
+ if (bel >= 0 && stringTerminator >= 0) end = Math.min(bel + 1, stringTerminator + 2);
92
+ else if (bel >= 0) end = bel + 1;
93
+ else if (stringTerminator >= 0) end = stringTerminator + 2;
94
+ if (end < 0) {
95
+ index = escape;
96
+ break;
97
+ }
98
+ const terminatorBytes = this.pending[end - 1] === "\x07" ? 1 : 2;
99
+ if (this.pending.slice(escape + 2, end - terminatorBytes).startsWith("133;D;")) {
100
+ prompt = true;
101
+ this.trackingPromptTail = true;
102
+ includePromptTail = true;
103
+ promptTail = "";
104
+ }
105
+ index = end;
106
+ continue;
107
+ }
108
+ if (kind === "[") {
109
+ let end = escape + 2;
110
+ while (end < this.pending.length) {
111
+ const code = this.pending.charCodeAt(end);
112
+ if (code >= 64 && code <= 126) break;
113
+ end += 1;
114
+ }
115
+ if (end >= this.pending.length) {
116
+ index = escape;
117
+ break;
118
+ }
119
+ index = end + 1;
120
+ continue;
121
+ }
122
+ index = escape + 2;
123
+ }
124
+ this.pending = this.pending.slice(index);
125
+ this.enforcePendingBound();
126
+ return {
127
+ text: this.normalizeText(text),
128
+ prompt,
129
+ ...includePromptTail ? { promptTail } : {}
130
+ };
131
+ }
132
+ /**
133
+ * Flush a trailing printable fragment when the PTY exits.
134
+ * @returns Remaining printable text; incomplete escapes are discarded.
135
+ */
136
+ flush() {
137
+ const text = this.pending.startsWith("\x1B") ? "" : this.pending;
138
+ this.pending = "";
139
+ this.discardMode = void 0;
140
+ this.discardOscEscape = false;
141
+ this.trackingPromptTail = false;
142
+ const normalized = this.normalizeText(text);
143
+ if (!this.trailingCarriageReturn) return normalized;
144
+ this.trailingCarriageReturn = false;
145
+ return `${normalized}\n`;
146
+ }
147
+ normalizeText(text) {
148
+ let complete = this.trailingCarriageReturn ? `\r${text}` : text;
149
+ this.trailingCarriageReturn = false;
150
+ if (complete.endsWith("\r")) {
151
+ complete = complete.slice(0, -1);
152
+ this.trailingCarriageReturn = true;
153
+ }
154
+ return normalizeTerminalText(complete);
155
+ }
156
+ enforcePendingBound() {
157
+ if (Buffer.byteLength(this.pending) <= this.maxPendingBytes) return;
158
+ this.discardMode = this.pending[1] === "]" ? "osc" : "csi";
159
+ this.pending = "";
160
+ }
161
+ discardPrefix(chunk) {
162
+ if (this.discardMode === void 0) return chunk;
163
+ if (this.discardMode === "csi") {
164
+ for (let index = 0; index < chunk.length; index += 1) {
165
+ const code = chunk.charCodeAt(index);
166
+ if (code >= 64 && code <= 126) {
167
+ this.discardMode = void 0;
168
+ return chunk.slice(index + 1);
169
+ }
170
+ }
171
+ return "";
172
+ }
173
+ let index = 0;
174
+ if (this.discardOscEscape) {
175
+ this.discardOscEscape = false;
176
+ if (chunk.startsWith("\\")) {
177
+ this.discardMode = void 0;
178
+ return chunk.slice(1);
179
+ }
180
+ }
181
+ while (index < chunk.length) {
182
+ if (chunk[index] === "\x07") {
183
+ this.discardMode = void 0;
184
+ return chunk.slice(index + 1);
185
+ }
186
+ if (chunk[index] === "\x1B") {
187
+ if (chunk[index + 1] === "\\") {
188
+ this.discardMode = void 0;
189
+ return chunk.slice(index + 2);
190
+ }
191
+ if (index + 1 === chunk.length) this.discardOscEscape = true;
192
+ }
193
+ index += 1;
194
+ }
195
+ return "";
196
+ }
197
+ };
198
+ /**
199
+ * Normalize CRLF and standalone carriage returns for line-oriented rendering.
200
+ * @param text - sanitized terminal text.
201
+ * @returns Line-normalized text with BEL removed.
202
+ */
203
+ function normalizeTerminalText(text) {
204
+ return text.replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\x07", "");
205
+ }
206
+ //#endregion
207
+ //#region lib/types/session.js
208
+ /** Persistent PTY session over the subprocess seam's terminal primitive. */
209
+ function utf8Tail(text, maxBytes) {
210
+ if (Buffer.byteLength(text) <= maxBytes) return {
211
+ text,
212
+ truncated: false
213
+ };
214
+ const chars = Array.from(text);
215
+ let bytes = 0;
216
+ let start = chars.length;
217
+ while (start > 0) {
218
+ const next = Buffer.byteLength(chars[start - 1]);
219
+ if (bytes + next > maxBytes) break;
220
+ bytes += next;
221
+ start -= 1;
222
+ }
223
+ return {
224
+ text: chars.slice(start).join(""),
225
+ truncated: true
226
+ };
227
+ }
228
+ var BoundedTextBuffer = class {
229
+ maxBytes;
230
+ maxLines;
231
+ value = "";
232
+ dropped = false;
233
+ constructor(maxBytes, maxLines) {
234
+ this.maxBytes = maxBytes;
235
+ this.maxLines = maxLines;
236
+ }
237
+ append(text) {
238
+ if (text.length === 0) return;
239
+ this.value += text;
240
+ if (this.maxLines !== void 0) {
241
+ const lines = this.value.split("\n");
242
+ if (lines.length > this.maxLines) {
243
+ this.value = lines.slice(lines.length - this.maxLines).join("\n");
244
+ this.dropped = true;
245
+ }
246
+ }
247
+ const tail = utf8Tail(this.value, this.maxBytes);
248
+ this.value = tail.text;
249
+ this.dropped ||= tail.truncated;
250
+ }
251
+ consume() {
252
+ const delta = this.value;
253
+ const truncated = this.dropped;
254
+ this.value = "";
255
+ this.dropped = false;
256
+ return {
257
+ delta,
258
+ truncated
259
+ };
260
+ }
261
+ snapshot() {
262
+ return {
263
+ text: this.value,
264
+ truncated: this.dropped
265
+ };
266
+ }
267
+ };
268
+ var LocalSendOperation = class {
269
+ startedAt;
270
+ onCancel;
271
+ output;
272
+ promise;
273
+ finished = false;
274
+ cancellationRequested = false;
275
+ initialForegroundLeftWait;
276
+ initialForegroundPgid;
277
+ constructor(maxBytes, startedAt, onCancel) {
278
+ this.startedAt = startedAt;
279
+ this.onCancel = onCancel;
280
+ this.output = new BoundedTextBuffer(maxBytes);
281
+ this.promise = Promise.withResolvers();
282
+ this.initialForegroundLeftWait = true;
283
+ }
284
+ get done() {
285
+ return this.promise.promise;
286
+ }
287
+ get settled() {
288
+ return this.finished;
289
+ }
290
+ get cancelRequested() {
291
+ return this.cancellationRequested;
292
+ }
293
+ append(text) {
294
+ if (!this.finished) this.output.append(text);
295
+ }
296
+ settle(waitReason, sessionStatus, inheritedTruncation) {
297
+ if (this.finished) return;
298
+ this.finished = true;
299
+ const read = this.output.snapshot();
300
+ this.promise.resolve({
301
+ viewport: read.text,
302
+ waitReason,
303
+ sessionStatus,
304
+ truncated: read.truncated || inheritedTruncation
305
+ });
306
+ }
307
+ fail(error) {
308
+ if (this.finished) return;
309
+ this.finished = true;
310
+ this.promise.reject(error);
311
+ }
312
+ readOutput() {
313
+ return this.output.consume();
314
+ }
315
+ setInitialForeground(foreground) {
316
+ this.initialForegroundPgid = foreground?.processGroupId;
317
+ this.initialForegroundLeftWait = foreground?.inputWaiting !== true;
318
+ }
319
+ acceptsStdinWait(pgid, waiting) {
320
+ if (pgid !== this.initialForegroundPgid) return waiting;
321
+ if (!waiting) this.initialForegroundLeftWait = true;
322
+ return waiting && this.initialForegroundLeftWait;
323
+ }
324
+ cancel() {
325
+ if (this.finished) return false;
326
+ this.cancellationRequested = true;
327
+ this.onCancel();
328
+ return true;
329
+ }
330
+ };
331
+ /** Backend session wrapping one provider-owned terminal process. */
332
+ var LocalPtySession = class {
333
+ terminal;
334
+ config;
335
+ motd = "";
336
+ pid;
337
+ decoder = new TextDecoder();
338
+ sanitizer;
339
+ scrollback;
340
+ outputEnded = Promise.withResolvers();
341
+ completion;
342
+ statusValue = { kind: "running" };
343
+ active;
344
+ activeTimer;
345
+ activeDeadlineTimer;
346
+ activeAbort;
347
+ interrupting;
348
+ activeWrite;
349
+ pollingReady;
350
+ polling = false;
351
+ promptSeen = false;
352
+ promptTextSeen = false;
353
+ promptTail = "";
354
+ shellPgid;
355
+ initializing = false;
356
+ lastOutputAt = Date.now();
357
+ closing = false;
358
+ closePromise;
359
+ transportFailure;
360
+ constructor(terminal, config) {
361
+ this.terminal = terminal;
362
+ this.config = config;
363
+ this.pid = terminal.pid;
364
+ this.sanitizer = new TerminalSanitizer(config.maxReadBytes);
365
+ this.scrollback = new BoundedTextBuffer(config.scrollbackMaxBytes, config.scrollbackLines);
366
+ terminal.output.on("data", this.onTerminalData);
367
+ terminal.output.once("end", this.onTerminalEnd);
368
+ terminal.output.once("error", this.onTerminalError);
369
+ this.completion = terminal.done.then((outcome) => this.onExit(outcome), (error) => {
370
+ this.onTransportFailure(error);
371
+ });
372
+ }
373
+ /**
374
+ * Capture startup output through the same readiness contract as later sends.
375
+ * @param signal - optional cancellation while the shell reaches its first prompt.
376
+ * @returns Resolves after startup readiness; rejects on exit or readiness timeout.
377
+ */
378
+ async initialize(signal) {
379
+ this.initializing = true;
380
+ try {
381
+ const result = await this.startSend({
382
+ text: "",
383
+ submit: false,
384
+ ...signal !== void 0 ? { signal } : {}
385
+ }).done;
386
+ if (result.waitReason === "session_exit") throw new Error("PTY shell exited during startup");
387
+ if (result.waitReason === "timeout") throw new Error("PTY shell did not reach readiness before startup timeout");
388
+ this.motd = result.viewport;
389
+ } catch (error) {
390
+ signal?.throwIfAborted();
391
+ throw error;
392
+ } finally {
393
+ this.initializing = false;
394
+ }
395
+ }
396
+ startSend(request) {
397
+ if (this.closing) throw new Error("PTY session is closing");
398
+ if (this.statusValue.kind === "exited") throw new Error("PTY session has exited");
399
+ if (this.active !== void 0) throw new TerminalError(`PTY session already has an active send${this.activeWrite !== void 0 ? " or draining provider write" : this.interrupting !== void 0 ? " or draining foreground interrupt" : ""}`, "SEND_ACTIVE");
400
+ if (request.signal?.aborted === true) throw new Error("PTY send aborted before write");
401
+ const operation = new LocalSendOperation(this.config.maxReadBytes, Date.now(), () => {
402
+ this.interrupt(operation);
403
+ });
404
+ this.active = operation;
405
+ this.resetReadinessEvidence();
406
+ if (request.signal !== void 0) {
407
+ const onAbort = () => {
408
+ operation.cancel();
409
+ };
410
+ request.signal.addEventListener("abort", onAbort, { once: true });
411
+ this.activeAbort = () => request.signal?.removeEventListener("abort", onAbort);
412
+ }
413
+ this.activeDeadlineTimer = setTimeout(() => {
414
+ if (this.active === operation) this.settleActive("timeout", this.activeWrite !== void 0 || this.interrupting === operation);
415
+ }, this.config.timeoutMs);
416
+ this.beginSend(operation, request);
417
+ return operation;
418
+ }
419
+ async beginSend(operation, request) {
420
+ let foreground;
421
+ try {
422
+ foreground = await this.terminal.inspectForeground();
423
+ } catch (error) {
424
+ if (this.active === operation && !this.closing && this.interrupting !== operation) this.failActive(error);
425
+ return;
426
+ }
427
+ try {
428
+ if (this.active !== operation || this.closing || this.interrupting === operation) return;
429
+ operation.setInitialForeground(foreground);
430
+ const input = `${request.text}${request.submit ? "\r" : ""}`;
431
+ if (input.length > 0 && !operation.cancelRequested) {
432
+ this.resetReadinessEvidence();
433
+ const write = this.terminal.write(input);
434
+ this.activeWrite = write.then(() => true, () => false);
435
+ try {
436
+ await write;
437
+ } finally {
438
+ this.activeWrite = void 0;
439
+ }
440
+ }
441
+ if (operation.cancelRequested) return;
442
+ if (this.active === operation && operation.settled) {
443
+ this.clearActive();
444
+ return;
445
+ }
446
+ if (this.active === operation && !this.closing) {
447
+ this.pollingReady = operation;
448
+ this.schedulePoll(operation);
449
+ }
450
+ } catch (error) {
451
+ if (this.active === operation && !this.closing) if (operation.settled) this.clearActive();
452
+ else this.failActive(error);
453
+ }
454
+ }
455
+ resetReadinessEvidence() {
456
+ this.lastOutputAt = Date.now();
457
+ this.promptSeen = false;
458
+ this.promptTextSeen = false;
459
+ this.promptTail = "";
460
+ }
461
+ read(request) {
462
+ const snapshot = this.scrollback.snapshot();
463
+ const lines = snapshot.text.split("\n");
464
+ const totalLines = snapshot.text.length === 0 ? 0 : lines.length;
465
+ const offset = request.offset ?? 0;
466
+ const count = request.count ?? 500;
467
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("PTY read offset must be a non-negative safe integer");
468
+ if (!Number.isSafeInteger(count) || count <= 0) throw new Error("PTY read count must be a positive safe integer");
469
+ if (offset >= totalLines) return {
470
+ text: "",
471
+ totalLines,
472
+ lineBegin: offset,
473
+ lineEnd: offset,
474
+ truncated: snapshot.truncated
475
+ };
476
+ const end = totalLines - offset;
477
+ const start = Math.max(0, end - count);
478
+ const bounded = utf8Tail(lines.slice(start, end).join("\n"), this.config.maxReadBytes);
479
+ const returnedLines = bounded.text.length === 0 ? 0 : bounded.text.split("\n").length;
480
+ return {
481
+ text: bounded.text,
482
+ totalLines,
483
+ lineBegin: offset,
484
+ lineEnd: offset + returnedLines,
485
+ truncated: snapshot.truncated || bounded.truncated
486
+ };
487
+ }
488
+ async signal(signal) {
489
+ if (this.closing) throw new Error("PTY session is closing");
490
+ return {
491
+ delivered: true,
492
+ targetPgid: await this.terminal.signalForeground(signal)
493
+ };
494
+ }
495
+ status() {
496
+ return this.statusValue;
497
+ }
498
+ close(reason) {
499
+ this.closing = true;
500
+ if (this.closePromise !== void 0) return this.closePromise;
501
+ const closing = this.closeOnce(reason).catch((error) => {
502
+ this.closePromise = void 0;
503
+ this.failActive(error);
504
+ throw error;
505
+ });
506
+ this.closePromise = closing;
507
+ return closing;
508
+ }
509
+ onTerminalData = (chunk) => {
510
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
511
+ this.onData(this.decoder.decode(bytes, { stream: true }));
512
+ };
513
+ onTerminalEnd = () => {
514
+ this.onData(this.decoder.decode());
515
+ this.appendOutput(this.sanitizer.flush());
516
+ this.outputEnded.resolve();
517
+ };
518
+ onTerminalError = (error) => {
519
+ this.onTransportFailure(error);
520
+ this.outputEnded.resolve();
521
+ };
522
+ onData(data) {
523
+ const sanitized = this.sanitizer.push(data);
524
+ this.appendOutput(sanitized.text);
525
+ if (sanitized.prompt) {
526
+ this.promptSeen = true;
527
+ this.promptTail = "";
528
+ this.lastOutputAt = Date.now();
529
+ }
530
+ if (this.promptSeen && sanitized.promptTail !== void 0) {
531
+ const remaining = Math.max(0, 6 - this.promptTail.length);
532
+ this.promptTail += sanitized.promptTail.slice(0, remaining);
533
+ if (sanitized.promptTail.length > remaining) this.promptTail = `${CONTROLLED_PROMPT}\0`;
534
+ this.promptTextSeen = this.promptTail === CONTROLLED_PROMPT;
535
+ }
536
+ }
537
+ async onExit(outcome) {
538
+ await this.outputEnded.promise;
539
+ if (this.transportFailure !== void 0) return;
540
+ this.statusValue = {
541
+ kind: "exited",
542
+ exitCode: outcome.exitCode,
543
+ signal: outcome.signal
544
+ };
545
+ this.settleActive("session_exit");
546
+ }
547
+ onTransportFailure(error) {
548
+ const failure = error instanceof Error ? error : new Error(String(error));
549
+ this.transportFailure ??= failure;
550
+ this.statusValue = {
551
+ kind: "exited",
552
+ exitCode: null,
553
+ signal: null
554
+ };
555
+ this.failActive(failure);
556
+ this.terminal.terminate().catch(() => {});
557
+ }
558
+ appendOutput(text) {
559
+ if (text.length === 0) return;
560
+ this.lastOutputAt = Date.now();
561
+ this.scrollback.append(text);
562
+ this.active?.append(text);
563
+ }
564
+ schedulePoll(operation, delayMs = this.config.pollIntervalMs) {
565
+ if (this.active !== operation || this.interrupting === operation || this.polling) return;
566
+ if (this.activeTimer !== void 0) clearTimeout(this.activeTimer);
567
+ this.activeTimer = setTimeout(() => {
568
+ this.activeTimer = void 0;
569
+ this.pollReadiness(operation);
570
+ }, delayMs);
571
+ }
572
+ async pollReadiness(operation) {
573
+ if (this.active !== operation || this.polling) return;
574
+ this.polling = true;
575
+ try {
576
+ if (this.statusValue.kind === "exited") {
577
+ this.settleActive("session_exit");
578
+ return;
579
+ }
580
+ const foreground = await this.terminal.inspectForeground();
581
+ if (this.active !== operation || this.closing || this.interrupting === operation) return;
582
+ const idleFor = Date.now() - this.lastOutputAt;
583
+ if (this.promptSeen && foreground !== void 0 && this.shellPgid === void 0) this.shellPgid = foreground.processGroupId;
584
+ if (this.promptSeen && this.promptTextSeen && idleFor >= this.config.pollIntervalMs && foreground?.processGroupId === this.shellPgid) {
585
+ this.settleActive("stdin_read");
586
+ return;
587
+ }
588
+ const elapsed = Date.now() - operation.startedAt;
589
+ const startupHasOutput = !this.initializing || this.scrollback.snapshot().text.length > 0;
590
+ const acceptsStdinWait = startupHasOutput && foreground !== void 0 && operation.acceptsStdinWait(foreground.processGroupId, foreground.inputWaiting);
591
+ if (elapsed >= this.config.exactProbeAfterMs && acceptsStdinWait) {
592
+ this.settleActive("stdin_read");
593
+ return;
594
+ }
595
+ const handoffGrace = this.promptSeen ? this.config.handoffGraceMs : 0;
596
+ if (startupHasOutput && idleFor >= this.config.idleSilenceMs + handoffGrace) this.settleActive("inferred_idle");
597
+ } catch (error) {
598
+ if (this.active === operation && !this.closing && this.interrupting !== operation) this.failActive(error);
599
+ } finally {
600
+ this.polling = false;
601
+ const active = this.active;
602
+ if (active !== void 0 && this.pollingReady === active) this.schedulePoll(active);
603
+ }
604
+ }
605
+ settleActive(waitReason, retainOwnership = false) {
606
+ const operation = this.active;
607
+ if (operation === void 0) return;
608
+ const scrollbackTruncated = this.scrollback.snapshot().truncated;
609
+ if (retainOwnership) {
610
+ this.stopPolling();
611
+ this.activeAbort?.();
612
+ this.activeAbort = void 0;
613
+ } else this.clearActive();
614
+ operation.settle(waitReason, this.statusValue, scrollbackTruncated);
615
+ }
616
+ stopPolling() {
617
+ this.stopReadinessPolling();
618
+ if (this.activeDeadlineTimer !== void 0) clearTimeout(this.activeDeadlineTimer);
619
+ this.activeDeadlineTimer = void 0;
620
+ }
621
+ stopReadinessPolling() {
622
+ if (this.activeTimer !== void 0) clearTimeout(this.activeTimer);
623
+ this.activeTimer = void 0;
624
+ this.pollingReady = void 0;
625
+ }
626
+ clearActive() {
627
+ const operation = this.active;
628
+ this.stopPolling();
629
+ this.activeAbort?.();
630
+ this.activeAbort = void 0;
631
+ if (this.interrupting === operation) this.interrupting = void 0;
632
+ this.pollingReady = void 0;
633
+ this.active = void 0;
634
+ }
635
+ failActive(error) {
636
+ const operation = this.active;
637
+ if (operation === void 0) return;
638
+ this.clearActive();
639
+ operation.fail(error);
640
+ }
641
+ interrupt(operation) {
642
+ if (this.active !== operation) return;
643
+ this.interrupting = operation;
644
+ this.stopReadinessPolling();
645
+ this.interruptOnce(operation);
646
+ }
647
+ async interruptOnce(operation) {
648
+ try {
649
+ const activeWrite = this.activeWrite;
650
+ if (activeWrite !== void 0 && !await activeWrite) return;
651
+ await this.terminal.signalForeground("SIGINT");
652
+ } catch (error) {
653
+ if (this.active === operation && !this.closing) this.onTransportFailure(error);
654
+ return;
655
+ } finally {
656
+ if (this.interrupting === operation) this.interrupting = void 0;
657
+ }
658
+ if (this.active === operation && operation.settled) this.clearActive();
659
+ else if (this.active === operation && !this.closing) {
660
+ this.pollingReady = operation;
661
+ this.schedulePoll(operation, 0);
662
+ }
663
+ }
664
+ async closeOnce(reason) {
665
+ this.stopPolling();
666
+ try {
667
+ await this.terminal.terminate();
668
+ } catch (error) {
669
+ throw new Error(`PTY cleanup failed (${reason})`, { cause: error });
670
+ }
671
+ this.settleActive("session_exit");
672
+ await this.completion;
673
+ this.terminal.output.off("data", this.onTerminalData);
674
+ this.terminal.output.off("end", this.onTerminalEnd);
675
+ this.terminal.output.off("error", this.onTerminalError);
676
+ if (this.transportFailure !== void 0) throw this.transportFailure;
677
+ }
678
+ };
679
+ //#endregion
680
+ //#region lib/types/index.js
681
+ /**
682
+ * Persistent shell PTY backend over the subprocess terminal primitive, shared
683
+ * sandbox policy, bounded output, and provider-owned session cleanup.
684
+ * @module @deepseek-ai/dsh-terminal-bash
685
+ */
686
+ /** Cordis plugin name. */
687
+ const name = "terminal-bash";
688
+ /** Required services: PTY registry, shared confinement policy, and process substrate. */
689
+ const inject = [
690
+ "terminals",
691
+ "sandboxPolicy",
692
+ "subprocess"
693
+ ];
694
+ const sandboxModeFences = /* @__PURE__ */ new WeakMap();
695
+ function ensureSandboxModeFence(ctx, owner) {
696
+ const existing = sandboxModeFences.get(owner);
697
+ if (existing !== void 0) {
698
+ existing.pty = ctx.terminals;
699
+ existing.sandboxPolicy = ctx.sandboxPolicy;
700
+ return;
701
+ }
702
+ const state = {
703
+ pty: ctx.terminals,
704
+ sandboxPolicy: ctx.sandboxPolicy
705
+ };
706
+ sandboxModeFences.set(owner, state);
707
+ owner.ctx.on("internal/dispatch", (_mode, eventName, args) => {
708
+ if (eventName !== "session/event") return;
709
+ const [session, event] = args;
710
+ if (session !== owner.session || event.type !== "sandbox/mode") return;
711
+ const currentMode = effectiveSandboxMode(session.events) ?? state.sandboxPolicy.defaultMode;
712
+ if (event.data.mode === currentMode || !state.pty.hasOwnerActivity(owner)) return;
713
+ throw new Error(`cannot change sandbox mode from "${currentMode}" to "${event.data.mode}" while persistent terminal sessions are open or being created; wait for creation to settle and close them first`);
714
+ }, { global: true });
715
+ }
716
+ function childEnvironment(spec) {
717
+ return {
718
+ TERM: "dumb",
719
+ PAGER: "cat",
720
+ GIT_PAGER: "cat",
721
+ PS1: CONTROLLED_PROMPT,
722
+ PROMPT_COMMAND: "printf \"\\033]133;D;%s\\007\" \"$?\"",
723
+ BASH_SILENCE_DEPRECATION_WARNING: "1",
724
+ DSH_SHELL: "1",
725
+ DSH_SESSION_ID: spec.owner.id,
726
+ DSH_PTY_SESSION_ID: spec.sessionId
727
+ };
728
+ }
729
+ function spawnArgv(ctx, config, policy) {
730
+ const argv = [config.shellPath, ...config.shellArgs];
731
+ if (policy.mode === "danger-full-access") return argv;
732
+ const sandbox = ctx.get("sandbox");
733
+ if (sandbox === void 0) throw new Error(`terminal-bash: sandbox mode "${policy.mode}" requires a ctx.sandbox provider in the execution world`);
734
+ return sandbox.confine(argv, {
735
+ ...policy,
736
+ mode: policy.mode
737
+ }).argv;
738
+ }
739
+ async function initializeSession(session, signal) {
740
+ if (signal === void 0) {
741
+ await session.initialize(signal);
742
+ return;
743
+ }
744
+ const aborted = Promise.withResolvers();
745
+ const onAbort = () => {
746
+ aborted.reject(signal.reason);
747
+ };
748
+ signal.addEventListener("abort", onAbort, { once: true });
749
+ try {
750
+ signal.throwIfAborted();
751
+ await Promise.race([session.initialize(signal), aborted.promise]);
752
+ } finally {
753
+ signal.removeEventListener("abort", onAbort);
754
+ }
755
+ }
756
+ /** Local shell backend registered under the configured type. */
757
+ var BashTerminalBackend = class {
758
+ ctx;
759
+ config;
760
+ spawnTerminal;
761
+ createSession;
762
+ type;
763
+ constructor(ctx, config, spawnTerminal = (spec) => ctx.subprocess.spawnTerminal(spec), createSession = (terminal, config) => new LocalPtySession(terminal, config)) {
764
+ this.ctx = ctx;
765
+ this.config = config;
766
+ this.spawnTerminal = spawnTerminal;
767
+ this.createSession = createSession;
768
+ this.type = config.backendType;
769
+ }
770
+ async spawn(spec) {
771
+ spec.signal?.throwIfAborted();
772
+ ensureSandboxModeFence(this.ctx, spec.owner);
773
+ const policy = this.ctx.sandboxPolicy.resolve({ session: spec.owner.session });
774
+ const argv = spawnArgv(this.ctx, this.config, policy);
775
+ if (argv[0] === void 0) throw new Error("terminal-bash: sandbox returned empty argv");
776
+ const terminal = await this.spawnTerminal({
777
+ argv,
778
+ cwd: spec.cwd ?? policy.workspaceRoot,
779
+ env: childEnvironment(spec),
780
+ rows: this.config.rows,
781
+ cols: this.config.cols,
782
+ graceMs: this.config.disposeGraceMs,
783
+ signal: spec.signal
784
+ });
785
+ const session = this.createSession(terminal, this.config);
786
+ try {
787
+ await initializeSession(session, spec.signal);
788
+ return session;
789
+ } catch (error) {
790
+ try {
791
+ await session.close("PTY startup failed");
792
+ } catch (closeError) {
793
+ throw new TerminalBackendCleanupError(error, closeError);
794
+ }
795
+ throw error;
796
+ }
797
+ }
798
+ };
799
+ /** Register the local PTY backend. */
800
+ function apply(ctx, config) {
801
+ validateConfig(config);
802
+ ctx.terminals.registerBackend(new BashTerminalBackend(ctx, config));
803
+ }
804
+ //#endregion
805
+ export { BashTerminalBackend, Config, apply, inject, name };
@@ -0,0 +1,23 @@
1
+ //#region lib/types/invariant.js
2
+ /**
3
+ * Package-owned invariant companion for `@deepseek-ai/dsh-terminal-bash`.
4
+ * @module @deepseek-ai/dsh-terminal-bash/invariant
5
+ */
6
+ const PACKAGE_NAME = "@deepseek-ai/dsh-terminal-bash";
7
+ /** Cordis companion plugin name. */
8
+ const name = "terminal-bash-invariant";
9
+ /** Service required before the companion can reserve package ownership. */
10
+ const inject = ["invariants"];
11
+ /**
12
+ * No runtime invariant: readiness, terminal buffers, and process-tree state are private per-session
13
+ * implementation state, and the backend publishes no independent lifecycle stream or snapshot.
14
+ */
15
+ const install = () => {};
16
+ /**
17
+ * Register this package's invariant companion.
18
+ * @param ctx - Cordis context carrying the invariant service.
19
+ * @returns the installed registration's disposer after setup succeeds.
20
+ */
21
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
22
+ //#endregion
23
+ export { apply, inject, name };
@@ -0,0 +1,47 @@
1
+ /** Validated configuration for the local PTY backend. */
2
+ import z from '@deepseek-ai/schemastery';
3
+ /** Public plugin configuration. */
4
+ export interface Config {
5
+ /** Backend registry type (default: `shell`). */
6
+ backendType?: string;
7
+ /** Interactive shell executable (default: `/bin/bash`). */
8
+ shellPath?: string;
9
+ /** Shell arguments (default: `--noprofile --norc -i`). */
10
+ shellArgs?: string[];
11
+ /** Terminal rows. */
12
+ rows?: number;
13
+ /** Terminal columns. */
14
+ cols?: number;
15
+ /** Maximum retained logical lines. */
16
+ scrollbackLines?: number;
17
+ /** Maximum retained UTF-8 bytes. */
18
+ scrollbackMaxBytes?: number;
19
+ /** Maximum bytes returned by one read or settled viewport. */
20
+ maxReadBytes?: number;
21
+ /** Readiness polling interval. */
22
+ pollIntervalMs?: number;
23
+ /** Delay before Linux exact syscall probes. */
24
+ exactProbeAfterMs?: number;
25
+ /** Silence duration that yields `inferred_idle`. */
26
+ idleSilenceMs?: number;
27
+ /**
28
+ * Extra wait beyond `idleSilenceMs`, once a prompt marker was seen, for the shell to
29
+ * regain the foreground before `inferred_idle` settles; at least one `pollIntervalMs`.
30
+ */
31
+ handoffGraceMs?: number;
32
+ /** Absolute send wait bound. */
33
+ timeoutMs?: number;
34
+ /** Grace before teardown escalates to `SIGKILL`. */
35
+ disposeGraceMs?: number;
36
+ }
37
+ /** Configuration after Schemastery defaults. */
38
+ export type ResolvedConfig = Required<Config>;
39
+ /** Schemastery config exposed by the plugin. */
40
+ export declare const Config: z<Config>;
41
+ /**
42
+ * Assert every numeric config field is a positive safe integer and bounds compose.
43
+ * @param config - Schemastery-resolved plugin configuration.
44
+ * @returns Narrows the input to the fully resolved configuration.
45
+ */
46
+ export declare function validateConfig(config: Config): asserts config is ResolvedConfig;
47
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Persistent shell PTY backend over the subprocess terminal primitive, shared
3
+ * sandbox policy, bounded output, and provider-owned session cleanup.
4
+ * @module @deepseek-ai/dsh-terminal-bash
5
+ */
6
+ import { Context } from '@deepseek-ai/cordis';
7
+ import type { TerminalBackend, TerminalBackendSpawnSpec } from '@deepseek-ai/dsh-terminal';
8
+ import type { SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from '@deepseek-ai/dsh-subprocess';
9
+ import { type Config, type ResolvedConfig } from './config.ts';
10
+ import { LocalPtySession } from './session.ts';
11
+ export { Config } from './config.ts';
12
+ export type { Config as TerminalLocalConfig } from './config.ts';
13
+ /** Cordis plugin name. */
14
+ export declare const name = "terminal-bash";
15
+ /** Required services: PTY registry, shared confinement policy, and process substrate. */
16
+ export declare const inject: string[];
17
+ /** Local shell backend registered under the configured type. */
18
+ export declare class BashTerminalBackend implements TerminalBackend {
19
+ private readonly ctx;
20
+ private readonly config;
21
+ private readonly spawnTerminal;
22
+ private readonly createSession;
23
+ readonly type: string;
24
+ constructor(ctx: Context, config: ResolvedConfig, spawnTerminal?: (spec: SubprocessTerminalSpawnSpec) => Promise<SubprocessTerminalHandle>, createSession?: (terminal: SubprocessTerminalHandle, config: ResolvedConfig) => LocalPtySession);
25
+ spawn(spec: TerminalBackendSpawnSpec): Promise<LocalPtySession>;
26
+ }
27
+ /** Register the local PTY backend. */
28
+ export declare function apply(ctx: Context, config: Config): void;
29
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@deepseek-ai/dsh-terminal-bash`.
3
+ * @module @deepseek-ai/dsh-terminal-bash/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "terminal-bash-invariant";
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,47 @@
1
+ /** Streaming terminal-control sanitizer for the line-oriented first release. */
2
+ /** OSC marker emitted by the controlled bash before each prompt. */
3
+ export declare const PROMPT_MARKER_PREFIX = "133;D;";
4
+ /** Exact printable prompt emitted after the private marker. */
5
+ export declare const CONTROLLED_PROMPT = "dsh> ";
6
+ /** One sanitized chunk plus whether it contained the owned prompt marker. */
7
+ export interface SanitizedChunk {
8
+ text: string;
9
+ prompt: boolean;
10
+ /** Printable text after the latest owned marker in this chunk. */
11
+ promptTail?: string;
12
+ }
13
+ /**
14
+ * Remove CSI/OSC/short escape sequences while preserving split-sequence carry.
15
+ * Full terminal emulation is deliberately deferred; ordinary line output and
16
+ * the private prompt marker are the supported contract.
17
+ */
18
+ export declare class TerminalSanitizer {
19
+ private readonly maxPendingBytes;
20
+ private pending;
21
+ private discardMode;
22
+ private discardOscEscape;
23
+ private trailingCarriageReturn;
24
+ private trackingPromptTail;
25
+ constructor(maxPendingBytes: number);
26
+ /**
27
+ * Consume one decoded `node-pty` data chunk.
28
+ * @param chunk - decoded terminal data.
29
+ * @returns Printable text and whether the private prompt marker completed.
30
+ */
31
+ push(chunk: string): SanitizedChunk;
32
+ /**
33
+ * Flush a trailing printable fragment when the PTY exits.
34
+ * @returns Remaining printable text; incomplete escapes are discarded.
35
+ */
36
+ flush(): string;
37
+ private normalizeText;
38
+ private enforcePendingBound;
39
+ private discardPrefix;
40
+ }
41
+ /**
42
+ * Normalize CRLF and standalone carriage returns for line-oriented rendering.
43
+ * @param text - sanitized terminal text.
44
+ * @returns Line-normalized text with BEL removed.
45
+ */
46
+ export declare function normalizeTerminalText(text: string): string;
47
+ //# sourceMappingURL=sanitize.d.ts.map
@@ -0,0 +1,66 @@
1
+ /** Persistent PTY session over the subprocess seam's terminal primitive. */
2
+ import type { SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess';
3
+ import type { TerminalBackendSession, TerminalReadRequest, TerminalReadResult, TerminalSendOperation, TerminalSendRequest, TerminalSessionStatus, TerminalSignal, TerminalSignalResult } from '@deepseek-ai/dsh-terminal';
4
+ import type { ResolvedConfig } from './config.ts';
5
+ /** Backend session wrapping one provider-owned terminal process. */
6
+ export declare class LocalPtySession implements TerminalBackendSession {
7
+ private readonly terminal;
8
+ private readonly config;
9
+ motd: string;
10
+ readonly pid: number;
11
+ private readonly decoder;
12
+ private readonly sanitizer;
13
+ private readonly scrollback;
14
+ private readonly outputEnded;
15
+ private readonly completion;
16
+ private statusValue;
17
+ private active;
18
+ private activeTimer;
19
+ private activeDeadlineTimer;
20
+ private activeAbort;
21
+ private interrupting;
22
+ private activeWrite;
23
+ private pollingReady;
24
+ private polling;
25
+ private promptSeen;
26
+ private promptTextSeen;
27
+ private promptTail;
28
+ private shellPgid;
29
+ private initializing;
30
+ private lastOutputAt;
31
+ private closing;
32
+ private closePromise;
33
+ private transportFailure;
34
+ constructor(terminal: SubprocessTerminalHandle, config: ResolvedConfig);
35
+ /**
36
+ * Capture startup output through the same readiness contract as later sends.
37
+ * @param signal - optional cancellation while the shell reaches its first prompt.
38
+ * @returns Resolves after startup readiness; rejects on exit or readiness timeout.
39
+ */
40
+ initialize(signal?: AbortSignal): Promise<void>;
41
+ startSend(request: TerminalSendRequest): TerminalSendOperation;
42
+ private beginSend;
43
+ private resetReadinessEvidence;
44
+ read(request: TerminalReadRequest): TerminalReadResult;
45
+ signal(signal: TerminalSignal): Promise<TerminalSignalResult>;
46
+ status(): TerminalSessionStatus;
47
+ close(reason: string): Promise<void>;
48
+ private readonly onTerminalData;
49
+ private readonly onTerminalEnd;
50
+ private readonly onTerminalError;
51
+ private onData;
52
+ private onExit;
53
+ private onTransportFailure;
54
+ private appendOutput;
55
+ private schedulePoll;
56
+ private pollReadiness;
57
+ private settleActive;
58
+ private stopPolling;
59
+ private stopReadinessPolling;
60
+ private clearActive;
61
+ private failActive;
62
+ private interrupt;
63
+ private interruptOnce;
64
+ private closeOnce;
65
+ }
66
+ //# sourceMappingURL=session.d.ts.map
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@deepseek-ai/dsh-terminal-bash",
3
+ "description": "Persistent shell PTY backend over the DeepSeek Harness subprocess terminal primitive",
4
+ "version": "0.0.1-rc.3",
5
+ "publishConfig": {
6
+ "access": "restricted"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
11
+ "directory": "packages/terminal/terminal-bash"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./invariant": {
22
+ "types": "./lib/types/invariant.d.ts",
23
+ "default": "./lib/invariant.js"
24
+ },
25
+ "./src/*": "./src/*",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "lib/index.js",
30
+ "lib/invariant.js",
31
+ "lib/types/**/*.d.ts"
32
+ ],
33
+ "license": "BSD-3-Clause",
34
+ "peerDependencies": {
35
+ "@deepseek-ai/dsh-invariants": "^0.0.1-rc.3",
36
+ "@deepseek-ai/dsh-terminal": "^0.0.1-rc.3",
37
+ "@deepseek-ai/dsh-sandbox": "^0.0.1-rc.3",
38
+ "@deepseek-ai/dsh-sandbox-policy": "^0.0.1-rc.3",
39
+ "@deepseek-ai/dsh-session": "^0.0.1-rc.3",
40
+ "@deepseek-ai/dsh-agent": "^0.0.1-rc.3",
41
+ "@deepseek-ai/dsh-subprocess": "^0.0.1-rc.3",
42
+ "@deepseek-ai/cordis": "^4.0.1-rc.1"
43
+ },
44
+ "dependencies": {
45
+ "@deepseek-ai/schemastery": "^3.18.1-rc.1"
46
+ },
47
+ "devDependencies": {
48
+ "@deepseek-ai/dsh-agent": "^0.0.1-rc.3",
49
+ "@deepseek-ai/dsh-invariants": "^0.0.1-rc.3",
50
+ "@deepseek-ai/dsh-terminal": "^0.0.1-rc.3",
51
+ "@deepseek-ai/dsh-sandbox": "^0.0.1-rc.3",
52
+ "@deepseek-ai/dsh-sandbox-policy": "^0.0.1-rc.3",
53
+ "@deepseek-ai/dsh-session": "^0.0.1-rc.3",
54
+ "@deepseek-ai/dsh-subprocess": "^0.0.1-rc.3",
55
+ "@deepseek-ai/dsh-subprocess-local": "^0.0.1-rc.3",
56
+ "@deepseek-ai/cordis": "^4.0.1-rc.1"
57
+ }
58
+ }