dsh-single-terminal 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.
Files changed (72) hide show
  1. package/README.md +144 -0
  2. package/README.zh.md +129 -0
  3. package/cordis.patch.yml +11 -0
  4. package/lib/client.js +11438 -0
  5. package/lib/client.js.map +1 -0
  6. package/lib/index.js +588 -0
  7. package/lib/types/client/controller.d.ts +86 -0
  8. package/lib/types/client/controller.d.ts.map +1 -0
  9. package/lib/types/client/controller.js +235 -0
  10. package/lib/types/client/drawer.d.ts +10 -0
  11. package/lib/types/client/drawer.d.ts.map +1 -0
  12. package/lib/types/client/drawer.js +84 -0
  13. package/lib/types/client/i18n.d.ts +8 -0
  14. package/lib/types/client/i18n.d.ts.map +1 -0
  15. package/lib/types/client/i18n.js +51 -0
  16. package/lib/types/client/index.d.ts +13 -0
  17. package/lib/types/client/index.d.ts.map +1 -0
  18. package/lib/types/client/index.js +13 -0
  19. package/lib/types/client/plugin.d.ts +23 -0
  20. package/lib/types/client/plugin.d.ts.map +1 -0
  21. package/lib/types/client/plugin.js +60 -0
  22. package/lib/types/client/protocol.d.ts +81 -0
  23. package/lib/types/client/protocol.d.ts.map +1 -0
  24. package/lib/types/client/protocol.js +5 -0
  25. package/lib/types/client/storage.d.ts +6 -0
  26. package/lib/types/client/storage.d.ts.map +1 -0
  27. package/lib/types/client/storage.js +21 -0
  28. package/lib/types/client/styles.d.ts +5 -0
  29. package/lib/types/client/styles.d.ts.map +1 -0
  30. package/lib/types/client/styles.js +103 -0
  31. package/lib/types/client/term.d.ts +15 -0
  32. package/lib/types/client/term.d.ts.map +1 -0
  33. package/lib/types/client/term.js +86 -0
  34. package/lib/types/client/toggle.d.ts +9 -0
  35. package/lib/types/client/toggle.d.ts.map +1 -0
  36. package/lib/types/client/toggle.js +19 -0
  37. package/lib/types/client/ws.d.ts +25 -0
  38. package/lib/types/client/ws.d.ts.map +1 -0
  39. package/lib/types/client/ws.js +79 -0
  40. package/lib/types/client/xterm-css.d.ts +7 -0
  41. package/lib/types/client/xterm-css.d.ts.map +1 -0
  42. package/lib/types/client/xterm-css.js +224 -0
  43. package/lib/types/host/hub.d.ts +39 -0
  44. package/lib/types/host/hub.d.ts.map +1 -0
  45. package/lib/types/host/hub.js +291 -0
  46. package/lib/types/host/index.d.ts +17 -0
  47. package/lib/types/host/index.d.ts.map +1 -0
  48. package/lib/types/host/index.js +66 -0
  49. package/lib/types/host/shells.d.ts +30 -0
  50. package/lib/types/host/shells.d.ts.map +1 -0
  51. package/lib/types/host/shells.js +202 -0
  52. package/lib/types/host/types.d.ts +109 -0
  53. package/lib/types/host/types.d.ts.map +1 -0
  54. package/lib/types/host/types.js +4 -0
  55. package/package.json +102 -0
  56. package/src/client/controller.ts +293 -0
  57. package/src/client/drawer.tsx +182 -0
  58. package/src/client/i18n.ts +58 -0
  59. package/src/client/index.ts +17 -0
  60. package/src/client/plugin.tsx +92 -0
  61. package/src/client/protocol.ts +40 -0
  62. package/src/client/storage.ts +21 -0
  63. package/src/client/styles.ts +106 -0
  64. package/src/client/term.tsx +95 -0
  65. package/src/client/toggle.tsx +43 -0
  66. package/src/client/ws.ts +81 -0
  67. package/src/client/xterm-css.ts +224 -0
  68. package/src/host/cordis-augment.d.ts +22 -0
  69. package/src/host/hub.ts +302 -0
  70. package/src/host/index.ts +78 -0
  71. package/src/host/shells.ts +216 -0
  72. package/src/host/types.ts +79 -0
@@ -0,0 +1,224 @@
1
+ /**
2
+ * xterm.css(@xterm/xterm 5.x 自带样式)· 生成期内嵌。
3
+ * 来源:node_modules/@xterm/xterm/css/xterm.css(MIT,xterm.js authors)。
4
+ * 升级 @xterm/xterm 后重跑 scripts/gen-xterm-css.mjs 再生成本文件。
5
+ */
6
+ export const XTERM_CSS = `/**
7
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
8
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
9
+ * https://github.com/chjj/term.js
10
+ * @license MIT
11
+ *
12
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ * of this software and associated documentation files (the "Software"), to deal
14
+ * in the Software without restriction, including without limitation the rights
15
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ * copies of the Software, and to permit persons to whom the Software is
17
+ * furnished to do so, subject to the following conditions:
18
+ *
19
+ * The above copyright notice and this permission notice shall be included in
20
+ * all copies or substantial portions of the Software.
21
+ *
22
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28
+ * THE SOFTWARE.
29
+ *
30
+ * Originally forked from (with the author's permission):
31
+ * Fabrice Bellard's javascript vt100 for jslinux:
32
+ * http://bellard.org/jslinux/
33
+ * Copyright (c) 2011 Fabrice Bellard
34
+ * The original design remains. The terminal itself
35
+ * has been extended to include xterm CSI codes, among
36
+ * other features.
37
+ */
38
+
39
+ /**
40
+ * Default styles for xterm.js
41
+ */
42
+
43
+ .xterm {
44
+ cursor: text;
45
+ position: relative;
46
+ user-select: none;
47
+ -ms-user-select: none;
48
+ -webkit-user-select: none;
49
+ }
50
+
51
+ .xterm.focus,
52
+ .xterm:focus {
53
+ outline: none;
54
+ }
55
+
56
+ .xterm .xterm-helpers {
57
+ position: absolute;
58
+ top: 0;
59
+ /**
60
+ * The z-index of the helpers must be higher than the canvases in order for
61
+ * IMEs to appear on top.
62
+ */
63
+ z-index: 5;
64
+ }
65
+
66
+ .xterm .xterm-helper-textarea {
67
+ padding: 0;
68
+ border: 0;
69
+ margin: 0;
70
+ /* Move textarea out of the screen to the far left, so that the cursor is not visible */
71
+ position: absolute;
72
+ opacity: 0;
73
+ left: -9999em;
74
+ top: 0;
75
+ width: 0;
76
+ height: 0;
77
+ z-index: -5;
78
+ /** Prevent wrapping so the IME appears against the textarea at the correct position */
79
+ white-space: nowrap;
80
+ overflow: hidden;
81
+ resize: none;
82
+ }
83
+
84
+ .xterm .composition-view {
85
+ /* TODO: Composition position got messed up somewhere */
86
+ background: #000;
87
+ color: #FFF;
88
+ display: none;
89
+ position: absolute;
90
+ white-space: nowrap;
91
+ z-index: 1;
92
+ }
93
+
94
+ .xterm .composition-view.active {
95
+ display: block;
96
+ }
97
+
98
+ .xterm .xterm-viewport {
99
+ /* On OS X this is required in order for the scroll bar to appear fully opaque */
100
+ background-color: #000;
101
+ overflow-y: scroll;
102
+ cursor: default;
103
+ position: absolute;
104
+ right: 0;
105
+ left: 0;
106
+ top: 0;
107
+ bottom: 0;
108
+ }
109
+
110
+ .xterm .xterm-screen {
111
+ position: relative;
112
+ }
113
+
114
+ .xterm .xterm-screen canvas {
115
+ position: absolute;
116
+ left: 0;
117
+ top: 0;
118
+ }
119
+
120
+ .xterm .xterm-scroll-area {
121
+ visibility: hidden;
122
+ }
123
+
124
+ .xterm-char-measure-element {
125
+ display: inline-block;
126
+ visibility: hidden;
127
+ position: absolute;
128
+ top: 0;
129
+ left: -9999em;
130
+ line-height: normal;
131
+ }
132
+
133
+ .xterm.enable-mouse-events {
134
+ /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
135
+ cursor: default;
136
+ }
137
+
138
+ .xterm.xterm-cursor-pointer,
139
+ .xterm .xterm-cursor-pointer {
140
+ cursor: pointer;
141
+ }
142
+
143
+ .xterm.column-select.focus {
144
+ /* Column selection mode */
145
+ cursor: crosshair;
146
+ }
147
+
148
+ .xterm .xterm-accessibility:not(.debug),
149
+ .xterm .xterm-message {
150
+ position: absolute;
151
+ left: 0;
152
+ top: 0;
153
+ bottom: 0;
154
+ right: 0;
155
+ z-index: 10;
156
+ color: transparent;
157
+ pointer-events: none;
158
+ }
159
+
160
+ .xterm .xterm-accessibility-tree:not(.debug) *::selection {
161
+ color: transparent;
162
+ }
163
+
164
+ .xterm .xterm-accessibility-tree {
165
+ user-select: text;
166
+ white-space: pre;
167
+ }
168
+
169
+ .xterm .live-region {
170
+ position: absolute;
171
+ left: -9999px;
172
+ width: 1px;
173
+ height: 1px;
174
+ overflow: hidden;
175
+ }
176
+
177
+ .xterm-dim {
178
+ /* Dim should not apply to background, so the opacity of the foreground color is applied
179
+ * explicitly in the generated class and reset to 1 here */
180
+ opacity: 1 !important;
181
+ }
182
+
183
+ .xterm-underline-1 { text-decoration: underline; }
184
+ .xterm-underline-2 { text-decoration: double underline; }
185
+ .xterm-underline-3 { text-decoration: wavy underline; }
186
+ .xterm-underline-4 { text-decoration: dotted underline; }
187
+ .xterm-underline-5 { text-decoration: dashed underline; }
188
+
189
+ .xterm-overline {
190
+ text-decoration: overline;
191
+ }
192
+
193
+ .xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
194
+ .xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
195
+ .xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
196
+ .xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
197
+ .xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
198
+
199
+ .xterm-strikethrough {
200
+ text-decoration: line-through;
201
+ }
202
+
203
+ .xterm-screen .xterm-decoration-container .xterm-decoration {
204
+ z-index: 6;
205
+ position: absolute;
206
+ }
207
+
208
+ .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
209
+ z-index: 7;
210
+ }
211
+
212
+ .xterm-decoration-overview-ruler {
213
+ z-index: 8;
214
+ position: absolute;
215
+ top: 0;
216
+ right: 0;
217
+ pointer-events: none;
218
+ }
219
+
220
+ .xterm-decoration-top {
221
+ z-index: 2;
222
+ position: relative;
223
+ }
224
+ `
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 宿主 Context 的服务类型增强(声明合并)。
3
+ *
4
+ * 说明:本插件只用 `ctx.get` 读取宿主服务(配合 src/host/types.ts 里的最小
5
+ * 服务视图),不引入对 @deepseek-ai/* 实现包的值依赖。@deepseek-ai/cordis
6
+ * 自带的 Context 增强经 `export *` 间接导出后在 TS 5.9 下不生效(同
7
+ * dsh-jenkins 的实测),这里在插件侧显式增强。
8
+ */
9
+ declare module '@deepseek-ai/cordis' {
10
+ interface Context {
11
+ /** 反射层提供的服务读取(context proxy 运行时委托给 reflect)。 */
12
+ get<T = unknown>(name: string): T | undefined
13
+ /**
14
+ * 注册随插件卸载/热重载自动清理的副作用(回调返回 disposer)。
15
+ * 运行时 Context 代理委托给 fiber.effect;npm cordis 4.x 仅在 Fiber
16
+ * 类型上声明,这里补充 Context 视图(同 vendored cordis 的形态)。
17
+ */
18
+ effect(execute: () => () => unknown, label?: string): () => unknown
19
+ }
20
+ }
21
+
22
+ export {}
@@ -0,0 +1,302 @@
1
+ /**
2
+ * dsh-single-terminal —— 终端 Hub:PTY 会话管理 + WebSocket 帧协议。
3
+ *
4
+ * - PTY 经插件自身依赖 node-pty(原生模块,external)直连 ConPTY/POSIX pty,
5
+ * 获得完整 resize/kill/数据流控制(宿主 ctx.subprocess 的 TerminalHandle
6
+ * 接口不暴露 resize,无法满足抽屉尺寸跟随);
7
+ * - 会话与 WebSocket 连接解耦:页面刷新/抽屉关闭后会话保活,重连后 attach
8
+ * 回放环形缓冲(容量 scrollbackLimit);
9
+ * - 多浏览器标签页可同时 attach 同一会话:输出广播、输入合并。
10
+ */
11
+
12
+ import { spawn } from 'node:child_process'
13
+ import { randomUUID } from 'node:crypto'
14
+ import { statSync } from 'node:fs'
15
+ import { createRequire } from 'node:module'
16
+ import { homedir } from 'node:os'
17
+ import { isAbsolute } from 'node:path'
18
+ import type { IncomingMessage } from 'node:http'
19
+ import type { Duplex } from 'node:stream'
20
+ import { WebSocket, WebSocketServer } from 'ws'
21
+ import type { IPty } from 'node-pty'
22
+ import type { ShellRegistry, ResolvedShell } from './shells.ts'
23
+ import type { ClientFrame, HostFrame, SessionInfo, TerminalPluginConfig } from './types.ts'
24
+
25
+ const require = createRequire(import.meta.url)
26
+ const nodePty = require('node-pty') as typeof import('node-pty')
27
+
28
+ interface Session {
29
+ id: string
30
+ shell: ResolvedShell
31
+ cwd: string
32
+ pty: IPty
33
+ buffer: string
34
+ alive: boolean
35
+ closing: boolean
36
+ exitCode: number | null
37
+ signal: number | null
38
+ }
39
+
40
+ const MAX_SESSIONS = 20
41
+ const INPUT_LIMIT = 1 << 16
42
+ const COLS_MIN = 2
43
+ const COLS_MAX = 500
44
+ const ROWS_MIN = 2
45
+ const ROWS_MAX = 300
46
+
47
+ const clamp = (value: number, min: number, max: number): number =>
48
+ Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : min
49
+
50
+ export class TerminalHub {
51
+ private readonly wss = new WebSocketServer({ noServer: true })
52
+ private readonly sockets = new Set<WebSocket>()
53
+ private readonly sessions = new Map<string, Session>()
54
+ private nextSocketId = 0
55
+
56
+ constructor(
57
+ private readonly config: TerminalPluginConfig,
58
+ private readonly registry: ShellRegistry,
59
+ ) {
60
+ this.wss.on('connection', (socket: WebSocket) => { this.handleConnection(socket) })
61
+ }
62
+
63
+ /** webServer.registerUpgrade 的 handler 入口(鉴权由插件入口完成后调用)。 */
64
+ handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {
65
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
66
+ this.wss.emit('connection', ws, req)
67
+ })
68
+ }
69
+
70
+ /** 插件卸载:终止全部会话并断开所有连接。 */
71
+ dispose(): void {
72
+ console.log(`[dsh-single-terminal] hub dispose (${this.sessions.size} sessions, ${this.sockets.size} sockets)`)
73
+ for (const session of this.sessions.values()) {
74
+ this.killSession(session)
75
+ }
76
+ this.sessions.clear()
77
+ for (const socket of this.sockets) {
78
+ try { socket.terminate() } catch { /* already gone */ }
79
+ }
80
+ this.sockets.clear()
81
+ }
82
+
83
+ /* ── 连接生命周期 ─────────────────────────────────────────────── */
84
+
85
+ private handleConnection(socket: WebSocket): void {
86
+ const sid = ++this.nextSocketId
87
+ this.sockets.add(socket)
88
+ console.log(`[dsh-single-terminal] ws#${sid} connected (total ${this.sockets.size})`)
89
+ socket.on('message', (raw: unknown) => { this.dispatch(socket, raw, sid) })
90
+ socket.on('close', () => { this.sockets.delete(socket); console.log(`[dsh-single-terminal] ws#${sid} closed (total ${this.sockets.size})`) })
91
+ socket.on('error', () => { this.sockets.delete(socket) })
92
+ this.send(socket, {
93
+ type: 'hello',
94
+ platform: process.platform,
95
+ defaultShell: this.registry.defaultShellId(this.config.defaultShell),
96
+ fontSize: this.config.fontSize,
97
+ fontFamily: this.config.fontFamily,
98
+ })
99
+ }
100
+
101
+ private dispatch(socket: WebSocket, raw: unknown, sid: number): void {
102
+ let frame: ClientFrame
103
+ try {
104
+ frame = JSON.parse(String(raw)) as ClientFrame
105
+ } catch {
106
+ return
107
+ }
108
+ if (frame.type !== 'input' && frame.type !== 'resize') {
109
+ const detail = 'id' in frame ? ` id=${String(frame.id).slice(0, 8)}` : ''
110
+ console.log(`[dsh-single-terminal] ws#${sid} <- ${frame.type}${detail}`)
111
+ }
112
+ switch (frame.type) {
113
+ case 'ping':
114
+ this.send(socket, { type: 'pong' })
115
+ break
116
+ case 'list':
117
+ this.send(socket, this.snapshotFrame())
118
+ break
119
+ case 'open':
120
+ this.open(frame.shellId, frame.cols, frame.rows, frame.cwd)
121
+ break
122
+ case 'input': {
123
+ const session = this.sessions.get(frame.id)
124
+ if (session === undefined || !session.alive) break
125
+ try {
126
+ session.pty.write(frame.data.length > INPUT_LIMIT ? frame.data.slice(0, INPUT_LIMIT) : frame.data)
127
+ } catch { /* dead pty: exit event follows */ }
128
+ break
129
+ }
130
+ case 'resize': {
131
+ const session = this.sessions.get(frame.id)
132
+ if (session === undefined || !session.alive) break
133
+ try {
134
+ session.pty.resize(clamp(frame.cols, COLS_MIN, COLS_MAX), clamp(frame.rows, ROWS_MIN, ROWS_MAX))
135
+ } catch { /* transient during teardown */ }
136
+ break
137
+ }
138
+ case 'attach': {
139
+ const session = this.sessions.get(frame.id)
140
+ if (session === undefined) break
141
+ this.send(socket, { type: 'replay', id: session.id, data: session.buffer })
142
+ if (!session.alive) {
143
+ this.send(socket, { type: 'exit', id: session.id, exitCode: session.exitCode, signal: session.signal })
144
+ }
145
+ break
146
+ }
147
+ case 'close':
148
+ this.close(frame.id)
149
+ break
150
+ }
151
+ }
152
+
153
+ /* ── 会话管理 ────────────────────────────────────────────────── */
154
+
155
+ private open(shellId: string, cols: number, rows: number, cwdOverride: string | undefined): void {
156
+ if (this.sessions.size >= MAX_SESSIONS) {
157
+ this.broadcast({ type: 'error', message: '终端数量已达上限 / terminal session limit reached' })
158
+ return
159
+ }
160
+ const shell = this.registry.resolve(shellId)
161
+ if (shell === null) {
162
+ this.broadcast({ type: 'error', message: `未知或不可用的 shell:「${shellId}」/ unknown or unavailable shell` })
163
+ return
164
+ }
165
+ const cwd = this.resolveCwd(cwdOverride)
166
+ const env: NodeJS.ProcessEnv = { ...process.env }
167
+ if (process.platform !== 'win32') env.TERM = 'xterm-256color'
168
+ let pty: IPty
169
+ try {
170
+ pty = nodePty.spawn(shell.file, shell.args, {
171
+ name: 'xterm-256color',
172
+ cols: clamp(cols, COLS_MIN, COLS_MAX),
173
+ rows: clamp(rows, ROWS_MIN, ROWS_MAX),
174
+ cwd,
175
+ env,
176
+ })
177
+ } catch (e) {
178
+ const message = e instanceof Error ? e.message : String(e)
179
+ this.broadcast({ type: 'error', message: `无法启动 ${shell.name} / failed to spawn ${shell.name}: ${message}` })
180
+ return
181
+ }
182
+ const session: Session = {
183
+ id: randomUUID(),
184
+ shell,
185
+ cwd,
186
+ pty,
187
+ buffer: '',
188
+ alive: true,
189
+ closing: false,
190
+ exitCode: null,
191
+ signal: null,
192
+ }
193
+ this.sessions.set(session.id, session)
194
+ console.log(`[dsh-single-terminal] session ${session.id.slice(0, 8)} opened shell=${shell.id} pid=${pty.pid} cwd=${cwd} (${this.sessions.size} total)`)
195
+ pty.onData((data: string) => {
196
+ this.appendBuffer(session, data)
197
+ this.broadcast({ type: 'data', id: session.id, data })
198
+ })
199
+ pty.onExit(({ exitCode, signal }: { exitCode: number; signal?: number }) => {
200
+ session.alive = false
201
+ session.exitCode = exitCode
202
+ session.signal = typeof signal === 'number' ? signal : null
203
+ if (this.sessions.has(session.id)) {
204
+ this.broadcast({ type: 'exit', id: session.id, exitCode: session.exitCode, signal: session.signal })
205
+ // 已广播 exit,客户端本地标记「已退出」;从快照移除,避免页面刷新后
206
+ // 被 adopt 成死标签。之后对该 id 的 close 帧静默忽略(客户端已删标签)。
207
+ this.sessions.delete(session.id)
208
+ console.log(`[dsh-single-terminal] session ${session.id.slice(0, 8)} (pid ${session.pty.pid}) exited code=${exitCode}`)
209
+ }
210
+ })
211
+ this.broadcast({ type: 'opened', session: this.sessionInfo(session) })
212
+ }
213
+
214
+ private close(id: string): void {
215
+ const session = this.sessions.get(id)
216
+ if (session === undefined) return
217
+ console.log(`[dsh-single-terminal] closing session ${id.slice(0, 8)} (pid ${session.pty.pid})`)
218
+ this.sessions.delete(id)
219
+ if (!session.alive) {
220
+ this.broadcast({ type: 'exit', id, exitCode: session.exitCode, signal: session.signal, closed: true })
221
+ return
222
+ }
223
+ session.closing = true
224
+ this.killSession(session)
225
+ this.broadcast({ type: 'exit', id, exitCode: null, signal: null, closed: true })
226
+ }
227
+
228
+ private killSession(session: Session): void {
229
+ try {
230
+ session.pty.kill()
231
+ } catch { /* already dead */ }
232
+ if (process.platform === 'win32') {
233
+ // node-pty 关闭 ConPTY 在部分 shell(powershell + PSReadLine)下不会结束
234
+ // 整棵进程树(实测 shell 存活、控制台子进程死亡),补 taskkill /T /F 兜底;
235
+ // 进程已死时 taskkill 静默失败。
236
+ try { spawn('taskkill', ['/T', '/F', '/PID', String(session.pty.pid)], { stdio: 'ignore' }) } catch { /* best effort */ }
237
+ } else {
238
+ // forkpty 使 shell 成为会话首进程(pid == pgid),负 pid 杀整个进程组。
239
+ try { process.kill(-session.pty.pid, 'SIGKILL') } catch { /* group gone */ }
240
+ }
241
+ }
242
+
243
+ private resolveCwd(override: string | undefined): string {
244
+ const validDirectory = (path: string): boolean => {
245
+ try { return statSync(path).isDirectory() } catch { return false }
246
+ }
247
+ if (override !== undefined) {
248
+ const trimmed = override.trim()
249
+ if (trimmed.length > 0 && isAbsolute(trimmed) && validDirectory(trimmed)) return trimmed
250
+ }
251
+ const configured = (this.config.defaultCwd ?? 'workspace').trim()
252
+ if (configured.length > 0 && configured !== 'workspace' && configured !== 'home' && isAbsolute(configured) && validDirectory(configured)) {
253
+ return configured
254
+ }
255
+ return homedir()
256
+ }
257
+
258
+ private appendBuffer(session: Session, data: string): void {
259
+ session.buffer += data
260
+ const limit = this.config.scrollbackLimit
261
+ if (session.buffer.length > limit) {
262
+ session.buffer = session.buffer.slice(session.buffer.length - limit)
263
+ }
264
+ }
265
+
266
+ /* ── 帧与快照 ────────────────────────────────────────────────── */
267
+
268
+ private snapshotFrame(): HostFrame {
269
+ return {
270
+ type: 'shells',
271
+ defaultShell: this.registry.defaultShellId(this.config.defaultShell),
272
+ shells: this.registry.list(),
273
+ sessions: [...this.sessions.values()].map((session) => this.sessionInfo(session)),
274
+ }
275
+ }
276
+
277
+ private sessionInfo(session: Session): SessionInfo {
278
+ return {
279
+ id: session.id,
280
+ shellId: session.shell.id,
281
+ label: session.shell.name,
282
+ cwd: session.cwd,
283
+ alive: session.alive,
284
+ pid: session.pty.pid,
285
+ exitCode: session.exitCode,
286
+ signal: session.signal,
287
+ }
288
+ }
289
+
290
+ private send(socket: WebSocket, frame: HostFrame): void {
291
+ if (socket.readyState !== WebSocket.OPEN) return
292
+ try {
293
+ socket.send(JSON.stringify(frame))
294
+ } catch { /* connection raced closed */ }
295
+ }
296
+
297
+ private broadcast(frame: HostFrame): void {
298
+ for (const socket of this.sockets) {
299
+ this.send(socket, frame)
300
+ }
301
+ }
302
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * dsh-single-terminal —— 插件宿主半边入口。
3
+ *
4
+ * - WebSocket 路由 /api/dsh-single-terminal.ws(webServer.registerUpgrade,exact path):
5
+ * 鉴权复用宿主 connection.requestRejection(Host/Origin 围栏 + dsh-auth cookie),
6
+ * 升级后交给 TerminalHub 处理 JSON 帧协议;
7
+ * - Config(schemastery)由宿主 Plugins 设置页渲染,热更新经 plugin 重载生效;
8
+ * - 卸载清理:注销路由 + 终止全部 PTY 会话(ctx.effect disposer)。
9
+ */
10
+
11
+ import type { IncomingMessage } from 'node:http'
12
+ import type { Duplex } from 'node:stream'
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import Schema from '@deepseek-ai/schemastery'
15
+ import { TerminalHub } from './hub.ts'
16
+ import { ShellRegistry } from './shells.ts'
17
+ import type { ConnectionService, CustomShellConfig, TerminalPluginConfig, WebServerService } from './types.ts'
18
+
19
+ export const name = 'dsh-single-terminal'
20
+ export const inject = ['webServer', 'connection']
21
+
22
+ /* ── 配置(docs/develop/basic/config)────────────────────────────── */
23
+
24
+ const CustomShellSchema = Schema.object({
25
+ id: Schema.string().required().description('唯一 id,如 my-shell'),
26
+ name: Schema.string().required().description('菜单显示名,如 My Shell'),
27
+ command: Schema.string().required().description('可执行文件路径或 PATH 上的命令名,如 nu'),
28
+ args: Schema.array(Schema.string()).default([]).description('启动参数'),
29
+ })
30
+
31
+ export const Config: import('@deepseek-ai/schemastery').default<TerminalPluginConfig> = Schema.object({
32
+ defaultShell: Schema.string().default('powershell')
33
+ .description('默认 shell id:powershell | pwsh | cmd | gitbash | wsl(或自定义 shell 的 id)。非 Windows 下自动回退到 $SHELL/bash'),
34
+ defaultCwd: Schema.string().default('workspace')
35
+ .description('终端初始目录:workspace(当前工作区根,未知时回退用户主目录)| home | 绝对路径'),
36
+ scrollbackLimit: Schema.number().default(200_000)
37
+ .description('重连回放缓冲的字符上限(每会话)'),
38
+ fontSize: Schema.number().default(13).description('终端字号'),
39
+ fontFamily: Schema.string().default('Consolas, "Cascadia Mono", "Courier New", monospace').description('终端字体'),
40
+ customShells: Schema.array(CustomShellSchema).default([]).description('自定义 shell 列表'),
41
+ }) as unknown as import('@deepseek-ai/schemastery').default<TerminalPluginConfig>
42
+
43
+ /* ── apply ───────────────────────────────────────────────────────── */
44
+
45
+ const WS_PATH = '/api/dsh-single-terminal.ws'
46
+
47
+ export function apply(ctx: Context, config: TerminalPluginConfig): void {
48
+ const webServer = ctx.get<WebServerService>('webServer')
49
+ const connection = ctx.get<ConnectionService>('connection')
50
+ if (webServer === undefined || connection === undefined) return
51
+
52
+ const registry = new ShellRegistry(config.customShells ?? [])
53
+ const hub = new TerminalHub(config, registry)
54
+
55
+ let unregister: (() => void) | undefined
56
+ try {
57
+ unregister = webServer.registerUpgrade({
58
+ path: WS_PATH,
59
+ handler: (req: IncomingMessage, socket: Duplex, head: Buffer) => {
60
+ const rejection = connection.requestRejection(req)
61
+ if (rejection !== undefined) {
62
+ socket.destroy()
63
+ return
64
+ }
65
+ hub.handleUpgrade(req, socket, head)
66
+ },
67
+ })
68
+ } catch (e) {
69
+ console.warn('[dsh-single-terminal] register upgrade route failed:', e instanceof Error ? e.message : String(e))
70
+ }
71
+
72
+ ctx.effect(() => () => {
73
+ try { unregister?.() } catch { /* already unregistered */ }
74
+ hub.dispose()
75
+ })
76
+ }
77
+
78
+ export type { CustomShellConfig, TerminalPluginConfig }