@allbluecn/web-app 0.28.0 → 0.28.1
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/package.json +4 -3
- package/src/components/harness/__tests__/dock-registry.test.ts +43 -0
- package/src/components/harness/conversation-panel/messages/harness-chain/__tests__/use-harness-chat-adapter.test.ts +20 -0
- package/src/components/harness/conversation-panel/messages/harness-chain/use-agent-terminals.ts +116 -0
- package/src/components/harness/conversation-panel/messages/harness-chain/use-harness-chat-adapter.ts +17 -5
- package/src/components/harness/conversation-panel/messages/harness-chain/use-harness-session.ts +4 -1
- package/src/components/harness/conversation-panel/messages/tools/__tests__/tool-run.test.ts +26 -1
- package/src/components/harness/conversation-panel/messages/tools/tool-run.ts +11 -0
- package/src/components/harness/extension-panel/dock/__tests__/tab-strip.test.tsx +45 -0
- package/src/components/harness/extension-panel/dock/dock-registry.ts +34 -0
- package/src/components/harness/extension-panel/dock/dock-surface.tsx +33 -0
- package/src/components/harness/extension-panel/dock/guide-page.tsx +4 -1
- package/src/components/harness/extension-panel/dock/tab-strip.tsx +9 -1
- package/src/components/harness/extension-panel/panels/terminal/__tests__/kind.test.tsx +219 -2
- package/src/components/harness/extension-panel/panels/terminal/__tests__/terminal-instance.test.tsx +322 -19
- package/src/components/harness/extension-panel/panels/terminal/__tests__/use-agent-terminal-roster.test.tsx +393 -0
- package/src/components/harness/extension-panel/panels/terminal/__tests__/ws-transport.test.ts +25 -0
- package/src/components/harness/extension-panel/panels/terminal/kind.tsx +55 -1
- package/src/components/harness/extension-panel/panels/terminal/shell-pref.ts +7 -4
- package/src/components/harness/extension-panel/panels/terminal/sse-transport.ts +26 -6
- package/src/components/harness/extension-panel/panels/terminal/tab-control-state.tsx +114 -0
- package/src/components/harness/extension-panel/panels/terminal/terminal-instance.tsx +190 -96
- package/src/components/harness/extension-panel/panels/terminal/terminal-theme.ts +113 -0
- package/src/components/harness/extension-panel/panels/terminal/transport.ts +28 -6
- package/src/components/harness/extension-panel/panels/terminal/use-agent-terminal-roster.ts +107 -0
- package/src/components/harness/extension-panel/panels/terminal/ws-transport.ts +7 -5
- package/src/components/harness/extension-panel/panels/terminal/xterm-terminal.tsx +5 -67
- package/src/lib/changelog/sdk-versions.ts +2 -2
- package/src/lib/queries/harness-terminal.ts +77 -0
- package/src/paraglide/messages/_index.js +48 -0
- package/src/paraglide/messages/en.js +15 -0
- package/src/paraglide/messages/zh.js +15 -0
- package/src/routes/api/harness/$.ts +19 -2
- package/src/routes/api/harness/terminal/$.ts +37 -6
- package/src/routes/api/harness/terminal/__tests__/route.test.ts +120 -0
- package/src/server/harness/__tests__/agent-terminal.server.test.ts +448 -0
- package/src/server/harness/__tests__/builtin-tools-invariant.test.ts +22 -12
- package/src/server/harness/__tests__/first-contact-fakes.test.ts +103 -3
- package/src/server/harness/__tests__/terminal-manager.server.test.ts +761 -2
- package/src/server/harness/agent-terminal.server.ts +631 -0
- package/src/server/harness/first-contact-fakes.ts +115 -4
- package/src/server/harness/host.server.ts +28 -1
- package/src/server/harness/persistence/__tests__/session-index-store.server.test.ts +83 -0
- package/src/server/harness/persistence/prisma-persistence.server.ts +12 -3
- package/src/server/harness/persistence/session-index-store.server.ts +26 -0
- package/src/server/harness/plugins/__tests__/assemble-disable.test.ts +25 -17
- package/src/server/harness/plugins/__tests__/tool-risk-audit.test.ts +16 -6
- package/src/server/harness/plugins/assemble-app.ts +12 -0
- package/src/server/harness/plugins/base-patch.ts +9 -2
- package/src/server/harness/plugins/builtin/__tests__/agent-terminal.plugin.test.ts +702 -0
- package/src/server/harness/plugins/builtin/agent-terminal.plugin.ts +518 -0
- package/src/server/harness/terminal-frame-builder.server.ts +5 -3
- package/src/server/harness/terminal-manager.server.ts +772 -35
- package/src/server/harness/terminal-ws-handler.server.ts +8 -2
- package/src/server/harness/tool-risk.ts +20 -4
- package/src/components/harness/extension-panel/panels/terminal/__tests__/xterm-webgl.test.ts +0 -68
|
@@ -25,16 +25,58 @@
|
|
|
25
25
|
// · 进程内存态(单实例边界,同 server/lib/rate-limit.ts 声明):终端实例表不跨
|
|
26
26
|
// 实例共享,多实例部署的终端找回属独立后续任务(设计开放问题③)。
|
|
27
27
|
//
|
|
28
|
-
// 上限(设计 §4.2,AllBlue 口径):maxTerminals 8/thread
|
|
29
|
-
// ring ≤256KiB + scrollback
|
|
30
|
-
// ≤2MiB、activityPoll 30s + 无连接
|
|
31
|
-
// kill、幂等 kill。DSH 的 per-follower 2MiB
|
|
28
|
+
// 上限(设计 §4.2,AllBlue 口径):maxTerminals 8/thread(含已退出)、maxAgentTerminals
|
|
29
|
+
// 4/thread(仅 running ∧ agent-control 占额,T6)、快照序列化 ring ≤256KiB + scrollback
|
|
30
|
+
// 1000 行、maxInputBytes 64KiB/次、per-follower 缓冲 ≤2MiB、activityPoll 30s + 无连接
|
|
31
|
+
// idle>2h 连续两次确认 kill、thread 清理钩子 kill、幂等 kill。DSH 的 per-follower 2MiB
|
|
32
|
+
// 是独立于快照 ring 的下行缓冲上限。T7 起每实例另持 headless 屏幕(@xterm/headless,
|
|
33
|
+
// scrollback 1000 对齐)供 agent 读(readScreen,§5.5),随实例移除 dispose。
|
|
32
34
|
|
|
33
|
-
import { access as fsAccess } from 'node:fs/promises'
|
|
34
35
|
import { randomBytes } from 'node:crypto'
|
|
36
|
+
import { accessSync as fsAccessSync, constants as fsConstants, existsSync as fsExistsSync } from 'node:fs'
|
|
37
|
+
import { access as fsAccess } from 'node:fs/promises'
|
|
38
|
+
import { createRequire } from 'node:module'
|
|
39
|
+
import { basename as pathBasename, dirname as pathDirname, join as pathJoin, resolve as pathResolve } from 'node:path'
|
|
40
|
+
|
|
41
|
+
// headless 屏幕(§5.5,T7):纯 JS 同构包,无 native/DOM 依赖,仅本文件(服务端专用,
|
|
42
|
+
// 经路由 server.handlers 动态 import 消费,客户端永不加载)。**运行时经 createRequire
|
|
43
|
+
// 惰性加载**(见下方 loadHeadlessModules):@xterm/headless 与 @xterm/addon-serialize 是
|
|
44
|
+
// webpack CJS 构建,若顶层静态 import,在 Vite 8 + TanStack Start module-runner 的 dev SSR
|
|
45
|
+
// 中被 ESModulesEvaluator 内联按 ESM 求值 → `ReferenceError: exports is not defined`(模块
|
|
46
|
+
// 加载期崩溃,早于 node-pty 加载与错误分类,终端完全无法 spawn)。故顶层只保留 type-only
|
|
47
|
+
// import(编译期擦除、不触发 bundler 求值),运行时走 createRequire 惰性加载——形态对齐
|
|
48
|
+
// 本文件 node-pty 动态 import + resolveNodePtyPackageRoot 的既有 createRequire 用法。
|
|
49
|
+
// buffer 命名空间是 proposed API,构造时必须 allowProposedApi: true 才可读。
|
|
50
|
+
import type { Terminal as HeadlessTerminal } from '@xterm/headless'
|
|
51
|
+
import type { SerializeAddon } from '@xterm/addon-serialize'
|
|
35
52
|
|
|
36
53
|
import type { WorkspaceRootResolution } from '@/server/harness/workspace-binder.server'
|
|
37
54
|
|
|
55
|
+
/** 惰性加载的 headless 模块缓存(进程内一次,HMR 后新模块作用域重新加载可接受)。 */
|
|
56
|
+
let headlessModules: {
|
|
57
|
+
HeadlessTerminalCtor: typeof HeadlessTerminal
|
|
58
|
+
SerializeAddonCtor: typeof SerializeAddon
|
|
59
|
+
} | null = null
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 运行时惰性加载 @xterm/headless 与 @xterm/addon-serialize(createRequire 走 Node CJS
|
|
63
|
+
* 解析,规避 dev SSR 内联 ESM 求值崩溃,见文件头)。CJS 的 `module.exports.Terminal`
|
|
64
|
+
* 与潜在 `.default`(interop)两种形状都兼容——按 req 结果实际形状选定取值路径。
|
|
65
|
+
* 加载失败(包未安装 / 解析失败)由调用方(create 的 spawn 失败链)归入
|
|
66
|
+
* terminal_env_unavailable 降级态。
|
|
67
|
+
*/
|
|
68
|
+
async function loadHeadlessModules(): Promise<NonNullable<typeof headlessModules>> {
|
|
69
|
+
if (headlessModules) return headlessModules
|
|
70
|
+
const req = createRequire(import.meta.url)
|
|
71
|
+
const headless = req('@xterm/headless') as Record<string, unknown>
|
|
72
|
+
const serialize = req('@xterm/addon-serialize') as Record<string, unknown>
|
|
73
|
+
headlessModules = {
|
|
74
|
+
HeadlessTerminalCtor: (headless.Terminal ?? headless.default) as typeof HeadlessTerminal,
|
|
75
|
+
SerializeAddonCtor: (serialize.SerializeAddon ?? serialize.default) as typeof SerializeAddon,
|
|
76
|
+
}
|
|
77
|
+
return headlessModules
|
|
78
|
+
}
|
|
79
|
+
|
|
38
80
|
/** 单 ring 的序列化上限(256KiB,AllBlue 自定——DSH 无此机制,见文件头)。 */
|
|
39
81
|
const RING_MAX_BYTES = 256 * 1024
|
|
40
82
|
/** scrollback 行数上限(DSH 口径,ring 按行截断)。 */
|
|
@@ -43,10 +85,16 @@ const SCROLLBACK_MAX_LINES = 1000
|
|
|
43
85
|
const MAX_INPUT_BYTES = 64 * 1024
|
|
44
86
|
/** 每 thread 终端上限(含已退出,DSH 口径)。 */
|
|
45
87
|
const MAX_TERMINALS_PER_THREAD = 8
|
|
88
|
+
/** 每 thread agent 终端并发上限(设计 §5.4,DSH maxAgentTerminals=4):仅 running ∧ agent-control 占额。 */
|
|
89
|
+
const MAX_AGENT_TERMINALS_PER_THREAD = 4
|
|
46
90
|
/** activityPoll 间隔(30s)。 */
|
|
47
91
|
const ACTIVITY_POLL_MS = 30_000
|
|
48
92
|
/** 无连接 idle 阈值(2h,DSH unattendedTimeoutMs)。 */
|
|
49
93
|
const IDLE_KILL_MS = 2 * 60 * 60 * 1000
|
|
94
|
+
/** readScreen 默认返回行数(§6.2 terminal_read count 默认 500)。 */
|
|
95
|
+
const SCREEN_READ_DEFAULT_COUNT = 500
|
|
96
|
+
/** readScreen 默认字节上限(256KiB,与 ring 序列化上限同源;T9 服务层按需显式传)。 */
|
|
97
|
+
const SCREEN_READ_DEFAULT_MAX_BYTES = RING_MAX_BYTES
|
|
50
98
|
|
|
51
99
|
/** terminal-manager 结构化错误码(路由层映射 HTTP 状态)。 */
|
|
52
100
|
export type TerminalManagerErrorCode =
|
|
@@ -57,6 +105,7 @@ export type TerminalManagerErrorCode =
|
|
|
57
105
|
| 'invalid_sequence'
|
|
58
106
|
| 'invalid_shell'
|
|
59
107
|
| 'no_shell_available'
|
|
108
|
+
| 'invalid_signal'
|
|
60
109
|
| 'terminal_env_unavailable'
|
|
61
110
|
|
|
62
111
|
export class TerminalManagerError extends Error {
|
|
@@ -69,11 +118,125 @@ export class TerminalManagerError extends Error {
|
|
|
69
118
|
}
|
|
70
119
|
}
|
|
71
120
|
|
|
121
|
+
// ── origin/control 状态机(agent 终端接管翻转)────────────────────────────────
|
|
122
|
+
// 出生身份 origin:user = 用户手动创建(默认,现有调用方零改动);agent = agent 工具
|
|
123
|
+
// 创建(T6 createForAgent 复用同入参)。输入控制权 control:agent 终端出生即 'agent'
|
|
124
|
+
// (用户可旁观 output,写须带 typed 手势接管);用户首次 typed 写入在**写生效前**翻转
|
|
125
|
+
// 为 'user' 并广播 state 帧。无回转边(user 不可变回 agent)——终端归属一旦移交用户,
|
|
126
|
+
// agent 不再代写(T6 agentWrite 经 requireAgentControl 守卫拒绝)。
|
|
127
|
+
|
|
128
|
+
/** 终端出生身份(谁创建的)。 */
|
|
129
|
+
export type TerminalOrigin = 'user' | 'agent'
|
|
130
|
+
/** 输入控制权(谁可写)。 */
|
|
131
|
+
export type TerminalControl = 'user' | 'agent'
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 终端控制权错误:agent 试图写入已被用户接管的终端(control='user')或终端已退出时
|
|
135
|
+
* 抛出(reason 区分两态)。**骨架先行**(任务 5 只定义错误码形态,零运行时调用点),
|
|
136
|
+
* T6 的 agentWrite / requireAgentControl 接入消费。
|
|
137
|
+
*/
|
|
138
|
+
export type TerminalControlErrorReason = 'user-control' | 'not-running'
|
|
139
|
+
|
|
140
|
+
export class TerminalControlError extends Error {
|
|
141
|
+
constructor(
|
|
142
|
+
public readonly code: 'terminal/control-unavailable',
|
|
143
|
+
public readonly reason: TerminalControlErrorReason,
|
|
144
|
+
message: string,
|
|
145
|
+
) {
|
|
146
|
+
super(message)
|
|
147
|
+
this.name = 'TerminalControlError'
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* agent 终端配额错误(T6):createForAgent 在「running ∧ agent 控制」终端数达
|
|
153
|
+
* maxAgentTerminals(4) 时抛出(被接管 control='user' / 已退出 / 关闭中的终端不占额)。
|
|
154
|
+
* 形态参照 TerminalControlError(结构化 code + 附加字段),工具层(T9 terminal_open)映射
|
|
155
|
+
* terminal/limit-reached 失败语义。
|
|
156
|
+
*/
|
|
157
|
+
export class TerminalLimitError extends Error {
|
|
158
|
+
constructor(
|
|
159
|
+
public readonly code: 'terminal/limit-reached',
|
|
160
|
+
public readonly limit: number,
|
|
161
|
+
message: string,
|
|
162
|
+
) {
|
|
163
|
+
super(message)
|
|
164
|
+
this.name = 'TerminalLimitError'
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** agentClose 三态结果(§6.2 terminal_close 出参语义):closed 真杀 / already-closing 真杀已发起(exit 帧未广播)/ left-for-user 用户已接管(不杀,进程留给用户)。 */
|
|
169
|
+
export type TerminalAgentCloseOutcome = 'closed' | 'already-closing' | 'left-for-user'
|
|
170
|
+
|
|
171
|
+
/** agent 信号 v1 全集(§6.2 O3 偏离:仅 INT/TSTP 以控制字符送达,终止型统一拒——v1 无前景组定向)。 */
|
|
172
|
+
export type TerminalAgentSignal = 'SIGINT' | 'SIGTSTP' | 'SIGTERM' | 'SIGKILL' | 'SIGHUP'
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* agent 通道列表项(listForAgent / listUserControlled,§5.3 最小面 id/title/cwd/state)。
|
|
176
|
+
* 全字段形状(cols/rows/exitCode/origin/control 等)见 TerminalRosterEntry(T8 roster)。
|
|
177
|
+
*/
|
|
178
|
+
export interface AgentTerminalSummary {
|
|
179
|
+
id: string
|
|
180
|
+
title: string
|
|
181
|
+
cwd: string
|
|
182
|
+
state: 'running' | 'exited'
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* roster 端点列表项(listAll,§5.8 全量字段):thread 全部终端的展示形状(含已退出/
|
|
187
|
+
* 被接管/关闭中——用户 tab 对账需要全量,不像 agent 通道按域过滤)。title/cwd 为
|
|
188
|
+
* create 时落存值(§5.8 字段来源,agent 通道经 name/startCwd 覆盖)。state 类型保留
|
|
189
|
+
* 'failed' 三值字面量兼容 DSH 形态(§6.2 running 判定注记;运行时现仅产生 running/
|
|
190
|
+
* exited——spawn 失败不落实例表)。
|
|
191
|
+
*/
|
|
192
|
+
export interface TerminalRosterEntry {
|
|
193
|
+
id: string
|
|
194
|
+
title: string
|
|
195
|
+
shell: string
|
|
196
|
+
cwd: string
|
|
197
|
+
cols: number
|
|
198
|
+
rows: number
|
|
199
|
+
state: 'running' | 'exited' | 'failed'
|
|
200
|
+
exitCode: number | null
|
|
201
|
+
origin: TerminalOrigin
|
|
202
|
+
control: TerminalControl
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ── headless 屏幕(T7,§5.5)────────────────────────────────────────────────────
|
|
206
|
+
// 每实例 headless Terminal + SerializeAddon,onData 双喂(ring 不动 + screen.write)。
|
|
207
|
+
// readScreen = 屏幕序列化为逻辑行(wrap 拼接/trimEnd/备用屏取当前屏)→ newest-relative
|
|
208
|
+
// 分页 → maxBytes 从最旧行丢弃保最新。供 agent-terminal 服务层(T9 terminal_read /
|
|
209
|
+
// user_terminal_read)消费。
|
|
210
|
+
|
|
211
|
+
/** readScreen 入参(全部可选;§6.2 terminal_read 的 offset/count 与服务层 maxBytes)。 */
|
|
212
|
+
export interface TerminalScreenReadOptions {
|
|
213
|
+
/** newest-relative 偏移(0 = 从最新行向上取;默认 0)。 */
|
|
214
|
+
offset?: number
|
|
215
|
+
/** 返回行数(默认 500)。 */
|
|
216
|
+
count?: number
|
|
217
|
+
/** 返回文本字节上限(默认 256KiB):超限从窗口最旧行丢弃保最新并置 truncated。 */
|
|
218
|
+
maxBytes?: number
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** readScreen 出参:lineBegin/lineEnd 是返回窗口在逻辑行中的 1-based 闭区间(空窗口为 0)。 */
|
|
222
|
+
export interface TerminalScreenRead {
|
|
223
|
+
/** 逻辑行文本('\n' 连接,去 ANSI,行尾 trim)。 */
|
|
224
|
+
text: string
|
|
225
|
+
/** 当前保留的逻辑行总数(分页/裁剪前的全量)。 */
|
|
226
|
+
totalLines: number
|
|
227
|
+
/** 返回窗口首行 1-based 行号(空窗口为 0)。 */
|
|
228
|
+
lineBegin: number
|
|
229
|
+
/** 返回窗口末行 1-based 行号(空窗口为 0)。 */
|
|
230
|
+
lineEnd: number
|
|
231
|
+
/** maxBytes 裁剪发生(最旧行被丢弃,或保底单行自身超限)时为 true。 */
|
|
232
|
+
truncated: boolean
|
|
233
|
+
}
|
|
234
|
+
|
|
72
235
|
/** 下行帧(SSE):snapshot 首帧重建 → output 增量 → state → exit;slow 要求重连。 */
|
|
73
236
|
export type TerminalDownFrame =
|
|
74
237
|
| { type: 'snapshot'; sequence: number; screen: string; info: { cols: number; rows: number; shell: string }; writable: boolean }
|
|
75
238
|
| { type: 'output'; sequence: number; data: string }
|
|
76
|
-
| { type: 'state'; sequence: number; cols: number; rows: number }
|
|
239
|
+
| { type: 'state'; sequence: number; cols: number; rows: number; origin: TerminalOrigin; control: TerminalControl }
|
|
77
240
|
| { type: 'exit'; sequence: number; code: number }
|
|
78
241
|
|
|
79
242
|
/** 下行控制帧:慢消费者断开要求重连(不计入 sequence;重连走 snapshot 永不重放)。 */
|
|
@@ -101,6 +264,28 @@ interface TerminalInstance {
|
|
|
101
264
|
lastClientAt: number
|
|
102
265
|
/** 上行严格递增游标(write/resize 共用一条 seq 序列,DSH 口径)。 */
|
|
103
266
|
lastInputSeq: number
|
|
267
|
+
/** 出生身份(谁创建的):user 默认 / agent 由 T6 createForAgent 传入。 */
|
|
268
|
+
origin: TerminalOrigin
|
|
269
|
+
/** 输入控制权:agent 终端出生 'agent',用户首次 typed 写入翻转 'user'(无回转边)。 */
|
|
270
|
+
control: TerminalControl
|
|
271
|
+
/** create 时工作区 root(roster / user_terminal_list 展示用,出生即固化;agent 通道为 cwd 相对解析后的起始目录)。 */
|
|
272
|
+
cwd: string
|
|
273
|
+
/** 展示标题(默认 shell basename,出生即固化;agent 通道为 terminal_open 的 name;后续任务可改)。 */
|
|
274
|
+
title: string
|
|
275
|
+
/** headless 屏幕(agent 读 + T9 motd 的序列化源;allowProposedApi 开启供 buffer 读取)。 */
|
|
276
|
+
screen: HeadlessTerminal
|
|
277
|
+
/** 屏幕序列化插件(原样 serialize 保样式;随实例移除 dispose。T9 motd 消费点)。 */
|
|
278
|
+
screenSerializer: SerializeAddon
|
|
279
|
+
/**
|
|
280
|
+
* 最新一次喂屏块的解析完成 promise:xterm 写解析是异步管线(时间预算分片),write 的
|
|
281
|
+
* callback 在该块解析完成后触发——readScreen await 它保证读到的是已喂入数据的最终解析态。
|
|
282
|
+
*/
|
|
283
|
+
screenParsed: Promise<void>
|
|
284
|
+
/**
|
|
285
|
+
* 真杀已发起(agentClose 路径)且 exit 帧未广播:closing 窗口内 agentClose 幂等
|
|
286
|
+
* 'already-closing'、agentWrite/agentSignal 按 not-running 拒绝、列表不显示、配额让出。
|
|
287
|
+
*/
|
|
288
|
+
closing: boolean
|
|
104
289
|
subscribers: Set<(frame: TerminalFrame) => void>
|
|
105
290
|
/** activityPoll 连续 idle 确认计数(无连接 && idle>2h 连续两次 → kill)。 */
|
|
106
291
|
idleStrikes: number
|
|
@@ -115,11 +300,50 @@ export interface CreateTerminalInput {
|
|
|
115
300
|
shell?: string
|
|
116
301
|
cols?: number
|
|
117
302
|
rows?: number
|
|
303
|
+
/**
|
|
304
|
+
* 出生身份(默认 'user'):'agent' = agent 工具创建,出生即 control='agent'(用户
|
|
305
|
+
* 首次 typed 写入接管)。T6 的 createForAgent 复用同一入参——非提前实现,是本任务
|
|
306
|
+
* 翻转语义测试的预置途径。
|
|
307
|
+
*/
|
|
308
|
+
origin?: TerminalOrigin
|
|
309
|
+
/**
|
|
310
|
+
* 附加 env(合并于固定 env 之后,agent 通道注入用,如 PAGER/GIT_PAGER=cat)。HTTP 路由
|
|
311
|
+
* 不透传该字段(唯一消费方是 createForAgent),用户 create 语义零变化。
|
|
312
|
+
*/
|
|
313
|
+
env?: Record<string, string>
|
|
314
|
+
/**
|
|
315
|
+
* 展示标题覆盖(缺省 shell basename):agent 通道 terminal_open 的 name 传入。HTTP 路由
|
|
316
|
+
* 不透传(用户 create 标题语义零变化)。
|
|
317
|
+
*/
|
|
318
|
+
title?: string
|
|
319
|
+
/**
|
|
320
|
+
* 起始 cwd 覆盖(绝对路径,调用方已解析;缺省 = root.root):spawn cwd 与实例 cwd 一并
|
|
321
|
+
* 采用。agent 通道将 terminal_open 的相对 cwd 经 pathResolve 归一化后传入。
|
|
322
|
+
*/
|
|
323
|
+
startCwd?: string
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* createForAgent 入参:origin/env/title/startCwd 由本方法强制解析注入(T6 审查 Minor-2:
|
|
328
|
+
* env 从入参移除——硬编码 PAGER/GIT_PAGER 注入不再被调用方同名键静默覆盖;title/startCwd
|
|
329
|
+
* 由 name/cwd 推导),调用方只提供 threadId/userId/shell/cols/rows/name/cwd。
|
|
330
|
+
*/
|
|
331
|
+
export type CreateForAgentInput = Omit<CreateTerminalInput, 'origin' | 'env' | 'title' | 'startCwd'> & {
|
|
332
|
+
/** tab 标题(terminal_open name,缺省 shell basename;长度上限由 T9 工具层 zod 把关)。 */
|
|
333
|
+
name?: string
|
|
334
|
+
/**
|
|
335
|
+
* 起始目录:相对 workspace root 解析(pathResolve 归一化,绝对路径则原样采纳)。终端
|
|
336
|
+
* 本身可 cd 任意处,此参数不是安全边界——不做存在性/越界校验(不存在时走 spawn 失败
|
|
337
|
+
* 降级态 terminal_env_unavailable)。
|
|
338
|
+
*/
|
|
339
|
+
cwd?: string
|
|
118
340
|
}
|
|
119
341
|
|
|
120
342
|
export interface CreateTerminalResult {
|
|
121
343
|
terminalId: string
|
|
122
344
|
shell: string
|
|
345
|
+
/** 服务端实例代际戳(方案 C):客户端写入 binding,重连比对区分重启/回收。 */
|
|
346
|
+
serverEpoch: string
|
|
123
347
|
}
|
|
124
348
|
|
|
125
349
|
/** 候选 shell 探测结果(shells 端点 + create 的 shell 解析链共用)。 */
|
|
@@ -138,12 +362,30 @@ export interface TerminalManagerOptions {
|
|
|
138
362
|
idleKillMs?: number
|
|
139
363
|
ringMaxBytes?: number
|
|
140
364
|
maxTerminalsPerThread?: number
|
|
365
|
+
/** agent 终端并发上限(默认 4,设计 §5.4):仅 running ∧ agent-control 占额。 */
|
|
366
|
+
maxAgentTerminalsPerThread?: number
|
|
141
367
|
maxInputBytes?: number
|
|
142
368
|
}
|
|
143
369
|
|
|
144
370
|
/** globalThis 单例槽位(HMR 重复构造防护,模式同 host.server.ts)。 */
|
|
145
371
|
interface TerminalManagerGlobal {
|
|
146
372
|
__allblue_harness_terminal_manager__?: TerminalManager
|
|
373
|
+
/**
|
|
374
|
+
* 服务端实例代际戳(方案 C):与 manager 单例同生命周期(同 globalThis 槽位,非模块级
|
|
375
|
+
* const——否则 HMR 后 manager 存活而 epoch 重置会错位)。进程/宿主重启 → 新 epoch;
|
|
376
|
+
* 同进程内终端退出/2h idle 回收 → epoch 不变。客户端据此区分「换了服务端实例」与
|
|
377
|
+
* 「终端退出/回收」两类失效(设计 §5.9)。
|
|
378
|
+
*/
|
|
379
|
+
__allblue_harness_terminal_epoch__?: string
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** 取(或初始化)服务端实例代际戳。与 manager 单例同槽位惰性初始化,HMR 安全。 */
|
|
383
|
+
export function getServerEpoch(): string {
|
|
384
|
+
const g = globalThis as unknown as TerminalManagerGlobal
|
|
385
|
+
if (!g.__allblue_harness_terminal_epoch__) {
|
|
386
|
+
g.__allblue_harness_terminal_epoch__ = `epoch_${randomBytes(8).toString('hex')}`
|
|
387
|
+
}
|
|
388
|
+
return g.__allblue_harness_terminal_epoch__
|
|
147
389
|
}
|
|
148
390
|
|
|
149
391
|
const CANDIDATE_SHELLS: Array<{ name: string; path: string }> = [
|
|
@@ -235,6 +477,204 @@ function appendRing(inst: { ring: string; ringBytes: number }, data: string, rin
|
|
|
235
477
|
inst.ringBytes = bytes
|
|
236
478
|
}
|
|
237
479
|
|
|
480
|
+
/**
|
|
481
|
+
* 喂 headless 屏幕一块输出,返回该块解析完成的 promise。xterm 的写解析是异步管线
|
|
482
|
+
* (按时间预算分片处理,writeSync 在 headless 6 不可用),write 的 callback 在该块
|
|
483
|
+
* 解析完成后触发——记录最新块的 promise 供 readScreen await,读写时序确定(进程内
|
|
484
|
+
* 单写者:onData 串行喂入,await 最新块即等价于等全部先前块)。解析异常不扩散
|
|
485
|
+
* (resolve 而非 reject):屏幕落后/损坏不应阻断 ring 与下行广播主链路。
|
|
486
|
+
*/
|
|
487
|
+
function screenWriteParsed(screen: HeadlessTerminal, data: string): Promise<void> {
|
|
488
|
+
return new Promise<void>((resolve) => {
|
|
489
|
+
try {
|
|
490
|
+
screen.write(data, () => resolve())
|
|
491
|
+
} catch (err: unknown) {
|
|
492
|
+
console.warn('[terminal-manager] headless screen 写入异常:', err)
|
|
493
|
+
resolve()
|
|
494
|
+
}
|
|
495
|
+
})
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* 屏幕序列化为逻辑行(§5.5「serialize → 逻辑行」):读 active buffer(备用屏激活时即
|
|
500
|
+
* 当前屏——vim 等全屏应用的最终画面)逐行 translateToString(true)(行尾 trim,宽字符
|
|
501
|
+
* 安全),`isWrapped` 行拼接回前一逻辑行,最后去除尾部空行(viewport 余下的空白行不是
|
|
502
|
+
* 内容)。不用 SerializeAddon.serialize() 做本步:其输出含 ANSI 色码/光标序列需二次
|
|
503
|
+
* 有损剥离,且备用屏激活时输出的是「主屏重放 + 进入备用屏序列」而非当前屏内容,两项
|
|
504
|
+
* 均违背 agent 读的去 ANSI 逻辑行契约;addon 的原样 serialize(保样式)留给 T9 motd。
|
|
505
|
+
*/
|
|
506
|
+
function serializeLogicalLines(screen: HeadlessTerminal): string[] {
|
|
507
|
+
const buffer = screen.buffer.active
|
|
508
|
+
const logical: string[] = []
|
|
509
|
+
for (let y = 0; y < buffer.length; y++) {
|
|
510
|
+
const line = buffer.getLine(y)
|
|
511
|
+
if (!line) break
|
|
512
|
+
const text = line.translateToString(true)
|
|
513
|
+
if (line.isWrapped && logical.length > 0) {
|
|
514
|
+
logical[logical.length - 1] += text
|
|
515
|
+
} else {
|
|
516
|
+
logical.push(text)
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
while (logical.length > 0 && logical[logical.length - 1] === '') logical.pop()
|
|
520
|
+
return logical
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// ── spawn-helper 可执行位诊断 ───────────────────────────────────────────────────
|
|
524
|
+
// 背景(errno 吞失教训):node-pty 1.1.0 的 spawn 失败只报静态字符串
|
|
525
|
+
// `posix_spawnp failed.`,「helper 缺失 / helper 无执行位 / OS 拒绝」同签名,曾据此
|
|
526
|
+
// 误诊为 macOS 27.3 环境阻塞(实为 1.1.0 tarball 内 spawn-helper 0644)。故加载 / spawn
|
|
527
|
+
// 失败的 message 一律附「node-pty 实际执行的 helper 路径 + 可执行位结论」,一眼定位。
|
|
528
|
+
|
|
529
|
+
/** spawn-helper 诊断结果(node-pty 加载 / spawn 失败时拼入 terminal_env_unavailable 的 message)。 */
|
|
530
|
+
export interface SpawnHelperDiagnostic {
|
|
531
|
+
/** node-pty 实际执行的 helper 路径;未探测(平台不使用 / 包根解析失败)时为 null。 */
|
|
532
|
+
path: string | null
|
|
533
|
+
/** fs.accessSync(path, X_OK) 结论;未探测时为 null。 */
|
|
534
|
+
executable: boolean | null
|
|
535
|
+
/** 一行诊断文本:`spawn-helper=<路径> 可执行=是|否(原因)`,未探测时说明原因。 */
|
|
536
|
+
detail: string
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** 诊断的探测依赖(默认真 fs + createRequire 解析;测试注入以覆盖真机构造不出的分支)。 */
|
|
540
|
+
export interface SpawnHelperProbe {
|
|
541
|
+
/** node-pty 包根解析:默认 `createRequire(import.meta.url).resolve('node-pty/package.json')` 的所在目录。 */
|
|
542
|
+
resolvePackageRoot?: () => string
|
|
543
|
+
/** 等价 `fs.existsSync`(execPath 兄弟 helper 探测)。 */
|
|
544
|
+
existsSync?: (path: string) => boolean
|
|
545
|
+
/** 等价 `fs.accessSync(path, mode)`:不可执行时抛错(code 为 ENOENT / EACCES 等)。 */
|
|
546
|
+
accessSync?: (path: string, mode: number) => void
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** node-pty 包根(经 package.json 解析;模块未安装 / 被 bundle 内联时抛 MODULE_NOT_FOUND)。 */
|
|
550
|
+
function resolveNodePtyPackageRoot(): string {
|
|
551
|
+
return pathDirname(createRequire(import.meta.url).resolve('node-pty/package.json'))
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* node-pty 实际执行的 spawn-helper 路径。与 patches/node-pty@1.2.0-beta.15.patch
|
|
556
|
+
* (lib/unixTerminal.js 的 helperPath)解析同序——改补丁解析序必须同步改这里,否则
|
|
557
|
+
* 诊断探测的不是被执行的文件:① env 覆盖 ALLBLUE_NODE_PTY_SPAWN_HELPER → ② execPath
|
|
558
|
+
* 兄弟 `<宿主可执行文件>-spawn-helper` → ③ 包内 prebuilds/<platform>-<arch>/spawn-helper
|
|
559
|
+
* (asar 解包路径替换同 node-pty)。node-pty 在模块加载时一次性解析 helperPath,而诊断
|
|
560
|
+
* 在失败时刻读取——env 由启动器预设(先于首次 import)的正常形态下两者一致。
|
|
561
|
+
*/
|
|
562
|
+
function resolveSpawnHelperPath(
|
|
563
|
+
resolvePackageRoot: SpawnHelperProbe['resolvePackageRoot'],
|
|
564
|
+
existsSync: NonNullable<SpawnHelperProbe['existsSync']>,
|
|
565
|
+
): string {
|
|
566
|
+
const override = process.env.ALLBLUE_NODE_PTY_SPAWN_HELPER
|
|
567
|
+
if (override) return pathResolve(override)
|
|
568
|
+
const sibling = `${process.execPath}-spawn-helper`
|
|
569
|
+
if (existsSync(sibling)) return sibling
|
|
570
|
+
return pathJoin(
|
|
571
|
+
(resolvePackageRoot ?? resolveNodePtyPackageRoot)(),
|
|
572
|
+
'prebuilds',
|
|
573
|
+
`${process.platform}-${process.arch}`,
|
|
574
|
+
'spawn-helper',
|
|
575
|
+
)
|
|
576
|
+
.replace('app.asar', 'app.asar.unpacked')
|
|
577
|
+
.replace('node_modules.asar', 'node_modules.asar.unpacked')
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** fs / 模块解析错误的短标识(code 优先,退化到 message)。 */
|
|
581
|
+
function errorCodeOf(err: unknown): string {
|
|
582
|
+
if (typeof err === 'object' && err !== null && 'code' in err && typeof err.code === 'string') {
|
|
583
|
+
return err.code
|
|
584
|
+
}
|
|
585
|
+
return err instanceof Error ? err.message : String(err)
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* 构造 spawn-helper 可执行位诊断(**永不抛错**——诊断自身失败不得掩盖原始加载 / spawn
|
|
590
|
+
* 错误)。spawn-helper 仅 macOS 使用(node-pty src/unix/pty.cc 的 __APPLE__ 分支经
|
|
591
|
+
* posix_spawn 执行 helper;Linux 走 fork+execvp、Windows 走 ConPTY,prebuilds 内本就没有
|
|
592
|
+
* 该文件),其余平台不探测,免得「包内本无 helper」被误报成缺失。
|
|
593
|
+
*/
|
|
594
|
+
export function describeSpawnHelperDiagnostic(probe: SpawnHelperProbe = {}): SpawnHelperDiagnostic {
|
|
595
|
+
if (process.platform !== 'darwin') {
|
|
596
|
+
return {
|
|
597
|
+
path: null,
|
|
598
|
+
executable: null,
|
|
599
|
+
detail: `spawn-helper=(未探测:${process.platform}-${process.arch} 平台的 node-pty 不经 spawn-helper 启动,失败原因在别处)`,
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
let helperPath: string
|
|
603
|
+
try {
|
|
604
|
+
helperPath = resolveSpawnHelperPath(probe.resolvePackageRoot, probe.existsSync ?? fsExistsSync)
|
|
605
|
+
} catch (err) {
|
|
606
|
+
return {
|
|
607
|
+
path: null,
|
|
608
|
+
executable: null,
|
|
609
|
+
detail: `spawn-helper=(未探测:node-pty 包根解析失败 ${errorCodeOf(err)}——模块未安装或被 bundle 内联)`,
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const accessSync = probe.accessSync ?? fsAccessSync
|
|
613
|
+
try {
|
|
614
|
+
accessSync(helperPath, fsConstants.X_OK)
|
|
615
|
+
return {
|
|
616
|
+
path: helperPath,
|
|
617
|
+
executable: true,
|
|
618
|
+
detail: `spawn-helper=${helperPath} 可执行=是(helper 无异常,失败原因在别处)`,
|
|
619
|
+
}
|
|
620
|
+
} catch (err) {
|
|
621
|
+
// ENOENT(不存在)与 EACCES(无执行位)同归「不可执行」,原因各自标出——两者不再同签名
|
|
622
|
+
const code = errorCodeOf(err)
|
|
623
|
+
const reason =
|
|
624
|
+
code === 'EACCES'
|
|
625
|
+
? 'EACCES 无执行位——chmod 755 可修;node-pty 1.1.0 npm tarball 即此打包 bug'
|
|
626
|
+
: code === 'ENOENT'
|
|
627
|
+
? 'ENOENT 文件不存在——prebuilds 伴生二进制未随包分发或打包期被丢弃'
|
|
628
|
+
: code
|
|
629
|
+
return { path: helperPath, executable: false, detail: `spawn-helper=${helperPath} 可执行=否(${reason})` }
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** 默认 spawnPty 工厂的可注入依赖(测试用;不传 = 动态 import node-pty + 真 fs 探测)。 */
|
|
634
|
+
export interface DefaultSpawnPtyDeps {
|
|
635
|
+
/** node-pty 模块加载器:默认 `() => import('node-pty')`。 */
|
|
636
|
+
loadNodePty?: () => Promise<Pick<typeof import('node-pty'), 'spawn'>>
|
|
637
|
+
/** spawn-helper 诊断探测:默认真 fs(见 describeSpawnHelperDiagnostic)。 */
|
|
638
|
+
probe?: SpawnHelperProbe
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* 默认惰性加载工厂(生产路径):动态 import node-pty 后调其 spawn;加载 / spawn 失败
|
|
643
|
+
* 统一降级 terminal_env_unavailable 并附 spawn-helper 诊断。导出 + 依赖注入供测试直接
|
|
644
|
+
* 驱动其失败分支——经 options.spawnPty 注入的 fake 不经本工厂(抛错不会被包装成降级态)。
|
|
645
|
+
*/
|
|
646
|
+
export function createDefaultSpawnPty(
|
|
647
|
+
deps: DefaultSpawnPtyDeps = {},
|
|
648
|
+
): NonNullable<TerminalManagerOptions['spawnPty']> {
|
|
649
|
+
const loadNodePty = deps.loadNodePty ?? (() => import('node-pty'))
|
|
650
|
+
return async (file, args, ptyOptions) => {
|
|
651
|
+
// 原生模块惰性加载(生产路径):模块顶层不 import node-pty,避免把原生模块拉进
|
|
652
|
+
// 客户端预构建扫描面。加载失败(Electron 壳未装 node-pty / 原生 ABI 不匹配等)与
|
|
653
|
+
// spawn 失败 → 同分类降级态 terminal_env_unavailable(环境错误,非用户错误,路由层
|
|
654
|
+
// 503),前端提示重装——message 保留原始错误文本并附 spawn-helper 诊断。
|
|
655
|
+
//
|
|
656
|
+
// spawn 失败的已知根因(2026-11-20 取证更正此前的错误归因):node-pty 1.1.0 npm
|
|
657
|
+
// tarball 内 prebuilds/darwin-*/spawn-helper 为 0644(无可执行位)的打包 bug,
|
|
658
|
+
// macOS posix_spawn 以 EACCES 拒绝执行;且 1.1.0 pty.cc Apple 分支只抛静态字符串
|
|
659
|
+
// "posix_spawnp failed." 吞掉 errno,与「helper 缺失 / OS 拒绝」同签名——故曾被
|
|
660
|
+
// 误诊为「macOS 27.3 posix_spawnp 环境阻塞」,实与 OS 版本无关。已升级
|
|
661
|
+
// 1.2.0-beta.15 修复(tarball 内 0755、报错含真实 errno)。
|
|
662
|
+
let mod: Pick<typeof import('node-pty'), 'spawn'>
|
|
663
|
+
try {
|
|
664
|
+
mod = await loadNodePty()
|
|
665
|
+
return mod.spawn(file, args, ptyOptions)
|
|
666
|
+
} catch (err: unknown) {
|
|
667
|
+
// spawn 已抛 TerminalManagerError(如终端上限)则原样上抛,不吞分类
|
|
668
|
+
if (err instanceof TerminalManagerError) throw err
|
|
669
|
+
const original = err instanceof Error ? err.message : String(err)
|
|
670
|
+
throw new TerminalManagerError(
|
|
671
|
+
'terminal_env_unavailable',
|
|
672
|
+
`桌面终端环境不可用(node-pty 加载/启动失败):${original};${describeSpawnHelperDiagnostic(deps.probe).detail}`,
|
|
673
|
+
)
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
238
678
|
/** 单实例工厂(测试用注入;生产用 getTerminalManager 单例)。 */
|
|
239
679
|
export function createTerminalManager(options: TerminalManagerOptions = {}): TerminalManager {
|
|
240
680
|
return new TerminalManager(options)
|
|
@@ -248,34 +688,18 @@ export class TerminalManager {
|
|
|
248
688
|
private readonly idleKillMs: number
|
|
249
689
|
private readonly ringMaxBytes: number
|
|
250
690
|
private readonly maxTerminals: number
|
|
691
|
+
private readonly maxAgentTerminals: number
|
|
251
692
|
private readonly maxInputBytes: number
|
|
252
693
|
private pollTimer: ReturnType<typeof setInterval> | null = null
|
|
253
694
|
|
|
254
695
|
constructor(options: TerminalManagerOptions = {}) {
|
|
255
|
-
this.spawnPty = options.spawnPty ?? (
|
|
256
|
-
// 原生模块惰性加载(生产路径):模块顶层不 import node-pty,避免把原生模块
|
|
257
|
-
// 拉进客户端预构建扫描面;测试经 options.spawnPty 注入 fake,不触达真模块。
|
|
258
|
-
// 加载失败(Electron 壳未装 node-pty / 原生 ABI 不匹配等)与 spawn 失败
|
|
259
|
-
// (macOS 27.3 posix_spawnp 环境阻塞等)→ 同分类降级态 terminal_env_unavailable
|
|
260
|
-
// (环境错误,非用户错误,路由层 503),前端提示重装——不透传原始错误。
|
|
261
|
-
let mod: typeof import('node-pty')
|
|
262
|
-
try {
|
|
263
|
-
mod = await import('node-pty')
|
|
264
|
-
return mod.spawn(file, args, ptyOptions)
|
|
265
|
-
} catch (err: unknown) {
|
|
266
|
-
// spawn 已抛 TerminalManagerError(如终端上限)则原样上抛,不吞分类
|
|
267
|
-
if (err instanceof TerminalManagerError) throw err
|
|
268
|
-
throw new TerminalManagerError(
|
|
269
|
-
'terminal_env_unavailable',
|
|
270
|
-
`桌面终端环境不可用(node-pty 加载/启动失败):${err instanceof Error ? err.message : String(err)}`,
|
|
271
|
-
)
|
|
272
|
-
}
|
|
273
|
-
})
|
|
696
|
+
this.spawnPty = options.spawnPty ?? createDefaultSpawnPty()
|
|
274
697
|
this.now = options.now ?? (() => Date.now())
|
|
275
698
|
this.pollIntervalMs = options.pollIntervalMs ?? ACTIVITY_POLL_MS
|
|
276
699
|
this.idleKillMs = options.idleKillMs ?? IDLE_KILL_MS
|
|
277
700
|
this.ringMaxBytes = options.ringMaxBytes ?? RING_MAX_BYTES
|
|
278
701
|
this.maxTerminals = options.maxTerminalsPerThread ?? MAX_TERMINALS_PER_THREAD
|
|
702
|
+
this.maxAgentTerminals = options.maxAgentTerminalsPerThread ?? MAX_AGENT_TERMINALS_PER_THREAD
|
|
279
703
|
this.maxInputBytes = options.maxInputBytes ?? MAX_INPUT_BYTES
|
|
280
704
|
}
|
|
281
705
|
|
|
@@ -297,9 +721,9 @@ export class TerminalManager {
|
|
|
297
721
|
|
|
298
722
|
/**
|
|
299
723
|
* 创建终端(设计 §4.2):cwd = 路由层传入的 root(getWorkspaceRootStatus 解析,
|
|
300
|
-
* 与 agent bash
|
|
301
|
-
* TERM/COLORTERM/ALLBLUE_THREAD_ID。**上限
|
|
302
|
-
* terminal_limit(路由层 409)。
|
|
724
|
+
* 与 agent bash 工具同源;agent 通道经 startCwd 覆盖为相对解析后的起始目录);shell
|
|
725
|
+
* 解析链 显式 → $SHELL → zsh → bash;env TERM/COLORTERM/ALLBLUE_THREAD_ID。**上限
|
|
726
|
+
* 8/thread(含已退出)**:超限抛 terminal_limit(路由层 409)。
|
|
303
727
|
*/
|
|
304
728
|
async create(
|
|
305
729
|
input: CreateTerminalInput,
|
|
@@ -315,6 +739,7 @@ export class TerminalManager {
|
|
|
315
739
|
const shell = await resolveShell(input.shell)
|
|
316
740
|
const cols = clampDim(input.cols, 80)
|
|
317
741
|
const rows = clampDim(input.rows, 24)
|
|
742
|
+
const startCwd = input.startCwd ?? root.root
|
|
318
743
|
const terminalId = `term_${randomBytes(12).toString('hex')}`
|
|
319
744
|
// spawnPty 是惰性加载工厂(真实现动态 import node-pty 后调其 spawn):调用即返回
|
|
320
745
|
// IPty 的 Promise,await 拿到实例。模块顶层不 import node-pty,避免原生模块进入
|
|
@@ -322,17 +747,39 @@ export class TerminalManager {
|
|
|
322
747
|
// 加载或注入),此处非空断言安全。
|
|
323
748
|
const pty = await this.spawnPty!(shell, [], {
|
|
324
749
|
name: 'xterm-256color',
|
|
325
|
-
cwd:
|
|
750
|
+
cwd: startCwd,
|
|
326
751
|
env: {
|
|
327
752
|
...process.env,
|
|
328
753
|
TERM: 'xterm-256color',
|
|
329
754
|
COLORTERM: 'truecolor',
|
|
330
755
|
ALLBLUE_THREAD_ID: input.threadId,
|
|
756
|
+
...input.env,
|
|
331
757
|
} as Record<string, string>,
|
|
332
758
|
cols,
|
|
333
759
|
rows,
|
|
334
760
|
})
|
|
761
|
+
// headless 屏幕(§5.5):scrollback 与 ring 行上限对齐(1000);allowProposedApi
|
|
762
|
+
// 供 buffer 命名空间读取(readScreen 的逻辑行序列化源);SerializeAddon 随实例
|
|
763
|
+
// 挂载(原样 serialize 保样式,T9 motd 消费点)。模块经 createRequire 运行时惰性
|
|
764
|
+
// 加载(loadHeadlessModules),加载失败归入 terminal_env_unavailable(与 spawn
|
|
765
|
+
// 失败同 catch 链——loadHeadlessModules 抛错由 createDefaultSpawnPty 之外本方法
|
|
766
|
+
// 的调用方 catch,路由层统一降级)。
|
|
767
|
+
const { HeadlessTerminalCtor, SerializeAddonCtor } = await loadHeadlessModules().catch((err: unknown) => {
|
|
768
|
+
// headless 包加载失败(未安装 / 解析失败)归入 terminal_env_unavailable(与 spawn
|
|
769
|
+
// 失败同分类,路由层 503),不产生 terminal_error 500——环境错误非用户错误。
|
|
770
|
+
const original = err instanceof Error ? err.message : String(err)
|
|
771
|
+
throw new TerminalManagerError(
|
|
772
|
+
'terminal_env_unavailable',
|
|
773
|
+
`桌面终端环境不可用(headless 屏幕加载失败):${original}`,
|
|
774
|
+
)
|
|
775
|
+
})
|
|
776
|
+
const screen = new HeadlessTerminalCtor({ scrollback: SCROLLBACK_MAX_LINES, cols, rows, allowProposedApi: true })
|
|
777
|
+
const screenSerializer = new SerializeAddonCtor()
|
|
778
|
+
screen.loadAddon(screenSerializer)
|
|
335
779
|
const now = this.now()
|
|
780
|
+
// 出生即固化:origin 决定 control(user 出生即 user;agent 出生即 agent,待用户
|
|
781
|
+
// typed 接管);cwd/title 供 roster / user_terminal_list / agent 列表展示。
|
|
782
|
+
const origin: TerminalOrigin = input.origin ?? 'user'
|
|
336
783
|
const inst: TerminalInstance = {
|
|
337
784
|
id: terminalId,
|
|
338
785
|
threadId: input.threadId,
|
|
@@ -347,13 +794,23 @@ export class TerminalManager {
|
|
|
347
794
|
createdAt: now,
|
|
348
795
|
lastClientAt: now,
|
|
349
796
|
lastInputSeq: 0,
|
|
797
|
+
origin,
|
|
798
|
+
control: origin,
|
|
799
|
+
cwd: startCwd,
|
|
800
|
+
title: input.title ?? pathBasename(shell),
|
|
801
|
+
screen,
|
|
802
|
+
screenSerializer,
|
|
803
|
+
screenParsed: Promise.resolve(),
|
|
804
|
+
closing: false,
|
|
350
805
|
subscribers: new Set(),
|
|
351
806
|
idleStrikes: 0,
|
|
352
807
|
reaped: false,
|
|
353
808
|
}
|
|
354
|
-
// onData → 追加 ring(截断保 256KiB + scrollback 1000 行)+
|
|
809
|
+
// onData → 追加 ring(截断保 256KiB + scrollback 1000 行)+ 双喂 headless 屏幕
|
|
810
|
+
// (ring 字节重放链路不动,O4)+ 广播 output 帧
|
|
355
811
|
pty.onData((data: string) => {
|
|
356
812
|
appendRing(inst, data, this.ringMaxBytes)
|
|
813
|
+
inst.screenParsed = screenWriteParsed(inst.screen, data)
|
|
357
814
|
this.broadcast(inst, { type: 'output', sequence: ++inst.seq, data })
|
|
358
815
|
})
|
|
359
816
|
// onExit → 标记 exitCode + 广播 exit 帧(writable 翻 false)
|
|
@@ -363,7 +820,7 @@ export class TerminalManager {
|
|
|
363
820
|
})
|
|
364
821
|
this.instances.set(terminalId, inst)
|
|
365
822
|
this.ensurePoll()
|
|
366
|
-
return { terminalId, shell }
|
|
823
|
+
return { terminalId, shell, serverEpoch: getServerEpoch() }
|
|
367
824
|
}
|
|
368
825
|
|
|
369
826
|
/**
|
|
@@ -387,7 +844,8 @@ export class TerminalManager {
|
|
|
387
844
|
if (inst) inst.lastClientAt = this.now()
|
|
388
845
|
}
|
|
389
846
|
|
|
390
|
-
/** 快照(重连首帧):客户端 xterm reset+write 重建;writable =
|
|
847
|
+
/** 快照(重连首帧):客户端 xterm reset+write 重建;writable = 未退出。带 serverEpoch
|
|
848
|
+
* 供客户端比对 binding 存的代际(方案 C 区分重启/回收)。 */
|
|
391
849
|
snapshot(terminalId: string) {
|
|
392
850
|
const inst = this.instances.get(terminalId)
|
|
393
851
|
if (!inst) throw new TerminalManagerError('terminal_not_found', `终端不存在:${terminalId}`)
|
|
@@ -396,6 +854,7 @@ export class TerminalManager {
|
|
|
396
854
|
screen: inst.ring,
|
|
397
855
|
info: { cols: inst.cols, rows: inst.rows, shell: inst.shell },
|
|
398
856
|
writable: inst.exitCode === null,
|
|
857
|
+
serverEpoch: getServerEpoch(),
|
|
399
858
|
}
|
|
400
859
|
}
|
|
401
860
|
|
|
@@ -404,8 +863,14 @@ export class TerminalManager {
|
|
|
404
863
|
* **先于 seq 校验**——超限输入是断开级错误,不应被乱序错误掩盖,也不消耗 seq 游标);
|
|
405
864
|
* 再校验严格递增 seq(write/resize 共用一条序列,乱序即 invalid_sequence → 409)。
|
|
406
865
|
* 已退出终端拒绝写入(terminal_exited → 409)。
|
|
866
|
+
*
|
|
867
|
+
* typed 接管翻转(origin/control 状态机):`typed===true && control==='agent'` 时在
|
|
868
|
+
* **写生效前**(pty.write 收到数据前)置 control='user' 并广播 state 帧(帧携带
|
|
869
|
+
* origin + 翻转后的 control,订阅者可观测「帧先于写」的顺序)。typed!==true 不翻转;
|
|
870
|
+
* control 已是 user(含 user 终端)无操作;无回转边。seq 校验先于翻转——乱序 typed
|
|
871
|
+
* 写 409 拒绝,不产生半翻转态。
|
|
407
872
|
*/
|
|
408
|
-
write(terminalId: string, seq: number, data: string): { ack: number } {
|
|
873
|
+
write(terminalId: string, seq: number, data: string, typed?: boolean): { ack: number } {
|
|
409
874
|
const bytes = Buffer.byteLength(data, 'utf8')
|
|
410
875
|
if (bytes > this.maxInputBytes) {
|
|
411
876
|
throw new TerminalManagerError(
|
|
@@ -414,11 +879,22 @@ export class TerminalManager {
|
|
|
414
879
|
)
|
|
415
880
|
}
|
|
416
881
|
const inst = this.requireWritable(terminalId, seq)
|
|
882
|
+
if (typed === true && inst.control === 'agent') {
|
|
883
|
+
inst.control = 'user'
|
|
884
|
+
this.broadcast(inst, {
|
|
885
|
+
type: 'state',
|
|
886
|
+
sequence: ++inst.seq,
|
|
887
|
+
cols: inst.cols,
|
|
888
|
+
rows: inst.rows,
|
|
889
|
+
origin: inst.origin,
|
|
890
|
+
control: inst.control,
|
|
891
|
+
})
|
|
892
|
+
}
|
|
417
893
|
inst.pty.write(data)
|
|
418
894
|
return { ack: seq }
|
|
419
895
|
}
|
|
420
896
|
|
|
421
|
-
/** 调整尺寸(上行):与 write 共用严格递增 seq 游标;广播 state
|
|
897
|
+
/** 调整尺寸(上行):与 write 共用严格递增 seq 游标;广播 state 帧同步下行订阅者(不翻转 control)。 */
|
|
422
898
|
resize(terminalId: string, seq: number, cols: number, rows: number): { ack: number } {
|
|
423
899
|
const inst = this.requireWritable(terminalId, seq)
|
|
424
900
|
const c = clampDim(cols, inst.cols)
|
|
@@ -426,10 +902,250 @@ export class TerminalManager {
|
|
|
426
902
|
inst.cols = c
|
|
427
903
|
inst.rows = r
|
|
428
904
|
inst.pty.resize(c, r)
|
|
429
|
-
|
|
905
|
+
inst.screen.resize(c, r) // headless 屏幕同步(buffer 按新宽度重排,逻辑行拼接不受影响)
|
|
906
|
+
this.broadcast(inst, {
|
|
907
|
+
type: 'state',
|
|
908
|
+
sequence: ++inst.seq,
|
|
909
|
+
cols: c,
|
|
910
|
+
rows: r,
|
|
911
|
+
origin: inst.origin,
|
|
912
|
+
control: inst.control,
|
|
913
|
+
})
|
|
430
914
|
return { ack: seq }
|
|
431
915
|
}
|
|
432
916
|
|
|
917
|
+
// ── agent 操作通道(T6/T7,设计 §5.3/§5.4/§5.5)─────────────────────────────────
|
|
918
|
+
// agent-terminal 服务层专用:进程内调用,不走 HTTP、不经客户端 seq 协议(agentWrite
|
|
919
|
+
// 无 seq 语义——写前翻转只由用户 typed 写触发,agent 写永不翻转 control)。守卫失败
|
|
920
|
+
// 整拒,不产生半写入。
|
|
921
|
+
|
|
922
|
+
/** 列表项 state 归并:closing 窗口按 exited 语义呈现(进程将死且已不可写)。 */
|
|
923
|
+
private stateOf(inst: TerminalInstance): 'running' | 'exited' {
|
|
924
|
+
return inst.exitCode === null && !inst.closing ? 'running' : 'exited'
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/** agent 可见性谓词(listForAgent 与配额计数共用):agent 出生 ∧ agent 控制 ∧ running。 */
|
|
928
|
+
private isAgentVisible(inst: TerminalInstance): boolean {
|
|
929
|
+
return inst.origin === 'agent' && inst.control === 'agent' && this.stateOf(inst) === 'running'
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* agent 通道守卫(agentWrite/agentSignal 共用,§5.3):不存在/已退出/关闭中 →
|
|
934
|
+
* not-running;control!=='agent'(用户 typed 接管或用户终端)→ user-control。不存在的
|
|
935
|
+
* id 对 agent 通道呈 not-running(终端已被回收/从未创建,对工具语义等价「不可用」),
|
|
936
|
+
* 区别于 HTTP 侧 terminal_not_found(404)。
|
|
937
|
+
*/
|
|
938
|
+
private requireAgentControl(terminalId: string): TerminalInstance {
|
|
939
|
+
const inst = this.instances.get(terminalId)
|
|
940
|
+
if (!inst || inst.exitCode !== null || inst.closing) {
|
|
941
|
+
throw new TerminalControlError(
|
|
942
|
+
'terminal/control-unavailable',
|
|
943
|
+
'not-running',
|
|
944
|
+
`终端不存在、已退出或正在关闭,agent 通道不可用:${terminalId}`,
|
|
945
|
+
)
|
|
946
|
+
}
|
|
947
|
+
if (inst.control !== 'agent') {
|
|
948
|
+
throw new TerminalControlError(
|
|
949
|
+
'terminal/control-unavailable',
|
|
950
|
+
'user-control',
|
|
951
|
+
`终端输入控制权已归用户(typed 接管),agent 不再代写:${terminalId}`,
|
|
952
|
+
)
|
|
953
|
+
}
|
|
954
|
+
return inst
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/** agent 写入(§5.3):守卫通过即直写 pty;接管排序不变量——排在用户 typed 写之后的 agent 输入在此整拒(不执行)。 */
|
|
958
|
+
agentWrite(terminalId: string, data: string): void {
|
|
959
|
+
const inst = this.requireAgentControl(terminalId)
|
|
960
|
+
inst.pty.write(data)
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* agent 信号(§5.3 / §6.2 v1,O3 偏离):SIGINT→\x03、SIGTSTP→\x1a(控制字符送达,
|
|
965
|
+
* 诚实标注非 TIOCGPGRP 前景组定向);SIGTERM/SIGKILL/SIGHUP 统一拒(v1 无法区分前景组,
|
|
966
|
+
* DSH 同款),错误文案引导 terminal_close。
|
|
967
|
+
*/
|
|
968
|
+
agentSignal(terminalId: string, signal: TerminalAgentSignal): { delivered: true; method: 'control-char' } {
|
|
969
|
+
const inst = this.requireAgentControl(terminalId)
|
|
970
|
+
switch (signal) {
|
|
971
|
+
case 'SIGINT':
|
|
972
|
+
inst.pty.write('\x03')
|
|
973
|
+
break
|
|
974
|
+
case 'SIGTSTP':
|
|
975
|
+
inst.pty.write('\x1a')
|
|
976
|
+
break
|
|
977
|
+
default:
|
|
978
|
+
throw new TerminalManagerError(
|
|
979
|
+
'invalid_signal',
|
|
980
|
+
`信号 ${signal} 在 v1 无法定向到前景进程组,请改用 terminal_close 关闭终端`,
|
|
981
|
+
)
|
|
982
|
+
}
|
|
983
|
+
return { delivered: true, method: 'control-char' }
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* agent 关闭(§5.3,DSH §5.4 三态):调用开始查一次 control——已接管(或用户终端)不杀、
|
|
988
|
+
* 实例保留(进程留给用户,control='user' 已自然从 agent 可见集合除名)返回
|
|
989
|
+
* 'left-for-user';agent 控制 → 置 closing + 真杀(exit 帧经 onExit 既有链广播)返回
|
|
990
|
+
* 'closed';真杀已发起且 exit 帧未广播的再调用幂等返回 'already-closing'。关闭窗口与
|
|
991
|
+
* 退出后实例保留于表(同自然退出语义:占总 8 上限、不占 agent 配额);reaped 置位与
|
|
992
|
+
* kill() 同款兜底去重(后续 kill 路径不再重复 pty.kill)。
|
|
993
|
+
*/
|
|
994
|
+
agentClose(terminalId: string): TerminalAgentCloseOutcome {
|
|
995
|
+
const inst = this.instances.get(terminalId)
|
|
996
|
+
if (!inst) {
|
|
997
|
+
throw new TerminalControlError('terminal/control-unavailable', 'not-running', `终端不存在或已回收:${terminalId}`)
|
|
998
|
+
}
|
|
999
|
+
if (inst.control !== 'agent') return 'left-for-user'
|
|
1000
|
+
if (inst.exitCode !== null) return 'closed' // 已退出(含关闭窗口已结束):无进程可杀,幂等
|
|
1001
|
+
if (inst.closing) return 'already-closing' // 真杀已发起、exit 帧未广播
|
|
1002
|
+
inst.closing = true
|
|
1003
|
+
inst.reaped = true
|
|
1004
|
+
try {
|
|
1005
|
+
inst.pty.kill()
|
|
1006
|
+
} catch (err: unknown) {
|
|
1007
|
+
// kill 抛错(进程已死等)不阻断——exit 回调会补广播 + exitCode 落存
|
|
1008
|
+
console.warn(`[terminal-manager] agentClose kill ${terminalId} 异常:`, err)
|
|
1009
|
+
}
|
|
1010
|
+
return 'closed'
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/** agent 可见集合(§5.3):origin=agent ∧ control=agent ∧ running(含 id/title/cwd/state)。 */
|
|
1014
|
+
listForAgent(threadId: string): AgentTerminalSummary[] {
|
|
1015
|
+
const out: AgentTerminalSummary[] = []
|
|
1016
|
+
for (const inst of this.instances.values()) {
|
|
1017
|
+
if (inst.threadId === threadId && this.isAgentVisible(inst)) {
|
|
1018
|
+
out.push({ id: inst.id, title: inst.title, cwd: inst.cwd, state: 'running' })
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
return out
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/** user 控制集合(§5.3):control='user'(用户终端 + 被接管 agent 终端,含已退出——user_terminal_list 的 running:'no' 数据源)。 */
|
|
1025
|
+
listUserControlled(threadId: string): AgentTerminalSummary[] {
|
|
1026
|
+
const out: AgentTerminalSummary[] = []
|
|
1027
|
+
for (const inst of this.instances.values()) {
|
|
1028
|
+
if (inst.threadId === threadId && inst.control === 'user') {
|
|
1029
|
+
out.push({ id: inst.id, title: inst.title, cwd: inst.cwd, state: this.stateOf(inst) })
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return out
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* thread 全量终端 roster(§5.8,roster 端点数据源):该 thread 全部实例,**不过滤**
|
|
1037
|
+
* origin/control/退出态——已退出的 agent 终端不在 listForAgent / listUserControlled
|
|
1038
|
+
* 任一集合,用户 tab 对账(reconcile)需要全量。title/cwd 为 create 时落存值。
|
|
1039
|
+
*/
|
|
1040
|
+
listAll(threadId: string): TerminalRosterEntry[] {
|
|
1041
|
+
const out: TerminalRosterEntry[] = []
|
|
1042
|
+
for (const inst of this.instances.values()) {
|
|
1043
|
+
if (inst.threadId === threadId) {
|
|
1044
|
+
out.push({
|
|
1045
|
+
id: inst.id,
|
|
1046
|
+
title: inst.title,
|
|
1047
|
+
shell: inst.shell,
|
|
1048
|
+
cwd: inst.cwd,
|
|
1049
|
+
cols: inst.cols,
|
|
1050
|
+
rows: inst.rows,
|
|
1051
|
+
state: this.stateOf(inst),
|
|
1052
|
+
exitCode: inst.exitCode,
|
|
1053
|
+
origin: inst.origin,
|
|
1054
|
+
control: inst.control,
|
|
1055
|
+
})
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
return out
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* agent 终端配额计数(§5.4):agentPending(分配中——本任务无 pending 概念计 0,T7/T9
|
|
1063
|
+
* 引入分配期时在此加项)+ running ∧ agent-control。被接管(control='user')/已退出/
|
|
1064
|
+
* 关闭中不占额(DSH index.ts 同款口径)。
|
|
1065
|
+
*/
|
|
1066
|
+
private countAgentTerminals(threadId: string): number {
|
|
1067
|
+
let n = 0
|
|
1068
|
+
for (const inst of this.instances.values()) {
|
|
1069
|
+
if (inst.threadId === threadId && this.isAgentVisible(inst)) n += 1
|
|
1070
|
+
}
|
|
1071
|
+
return n
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* headless 屏幕读取(T7,§5.5 / §6.2 terminal_read 出参形态):实例不存在(含已 kill
|
|
1076
|
+
* 回收——屏幕 dispose 连带实例移除)→ TerminalControlError not-running(错误形态对齐
|
|
1077
|
+
* T6 agent 通道口径;不存在的 id 对 agent 通道语义等价「不可用」,区别于 HTTP 侧
|
|
1078
|
+
* terminal_not_found)。**不查 control / exitCode**:§5.3 agentRead 只查 screen 存活——
|
|
1079
|
+
* 用户可读 user_terminal_read(T9)复用本方法,被接管终端照读;自然退出但实例留表的
|
|
1080
|
+
* 终端尾屏可读(读最终输出)。返回前 await 最新喂屏块的解析 promise(xterm 异步写解析
|
|
1081
|
+
* 管线),保证读到已喂入数据的最终解析态。
|
|
1082
|
+
*/
|
|
1083
|
+
async readScreen(terminalId: string, options: TerminalScreenReadOptions = {}): Promise<TerminalScreenRead> {
|
|
1084
|
+
const inst = this.instances.get(terminalId)
|
|
1085
|
+
if (!inst) {
|
|
1086
|
+
throw new TerminalControlError(
|
|
1087
|
+
'terminal/control-unavailable',
|
|
1088
|
+
'not-running',
|
|
1089
|
+
`终端不存在或已回收,屏幕不可读:${terminalId}`,
|
|
1090
|
+
)
|
|
1091
|
+
}
|
|
1092
|
+
await inst.screenParsed
|
|
1093
|
+
const count = normalizePositiveInt(options.count, SCREEN_READ_DEFAULT_COUNT)
|
|
1094
|
+
const offset = normalizeNonNegativeInt(options.offset, 0)
|
|
1095
|
+
const maxBytes = normalizePositiveInt(options.maxBytes, SCREEN_READ_DEFAULT_MAX_BYTES)
|
|
1096
|
+
const lines = serializeLogicalLines(inst.screen)
|
|
1097
|
+
const totalLines = lines.length
|
|
1098
|
+
// newest-relative 分页:窗口 = [end-count, end)(0-based),end 随 offset 自最新端上移
|
|
1099
|
+
const end = Math.max(0, totalLines - offset)
|
|
1100
|
+
const window = lines.slice(Math.max(0, end - count), end)
|
|
1101
|
+
// maxBytes 裁剪:从窗口最旧行丢弃保最新(增量减字节避免逐轮 rejoin);保底单行
|
|
1102
|
+
// 自身超限时整行保留(不截半行)并置 truncated 表意
|
|
1103
|
+
let truncated = false
|
|
1104
|
+
let bytes = Buffer.byteLength(window.join('\n'), 'utf8')
|
|
1105
|
+
while (window.length > 1 && bytes > maxBytes) {
|
|
1106
|
+
const dropped = window.shift()
|
|
1107
|
+
bytes -= Buffer.byteLength(dropped ?? '', 'utf8') + 1 // +1 连接换行
|
|
1108
|
+
truncated = true
|
|
1109
|
+
}
|
|
1110
|
+
if (window.length === 1 && bytes > maxBytes) truncated = true
|
|
1111
|
+
return {
|
|
1112
|
+
text: window.join('\n'),
|
|
1113
|
+
totalLines,
|
|
1114
|
+
lineBegin: window.length > 0 ? end - window.length + 1 : 0,
|
|
1115
|
+
lineEnd: window.length > 0 ? end : 0,
|
|
1116
|
+
truncated,
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* agent 通道创建(§5.2/§5.4 完整形态):origin='agent'(出生即 control='agent',待
|
|
1122
|
+
* 用户 typed 接管)+ env 注入 PAGER=cat GIT_PAGER=cat(DSH config.ts 同款,防分页器
|
|
1123
|
+
* 卡屏;T6 审查 Minor-2:env/name/title/cwd 均从入参剥离或由本方法解析,无静默覆盖面)
|
|
1124
|
+
* + name→title、cwd 相对 workspace root 解析(pathResolve 归一化,起始目录落 spawn
|
|
1125
|
+
* cwd 与实例 cwd)。先查 agent 配额(4,超限 TerminalLimitError)再走 create(总 8
|
|
1126
|
+
* 上限语义不变,超限 terminal_limit)。
|
|
1127
|
+
*/
|
|
1128
|
+
async createForAgent(input: CreateForAgentInput, root: WorkspaceRootResolution): Promise<CreateTerminalResult> {
|
|
1129
|
+
if (this.countAgentTerminals(input.threadId) >= this.maxAgentTerminals) {
|
|
1130
|
+
throw new TerminalLimitError(
|
|
1131
|
+
'terminal/limit-reached',
|
|
1132
|
+
this.maxAgentTerminals,
|
|
1133
|
+
`agent 终端并发上限 ${this.maxAgentTerminals} 已满(仅运行中且 agent 控制的终端占额;被接管/已退出不占额,可先 terminal_close 或等待用户接管)`,
|
|
1134
|
+
)
|
|
1135
|
+
}
|
|
1136
|
+
const { name, cwd, ...rest } = input
|
|
1137
|
+
return this.create(
|
|
1138
|
+
{
|
|
1139
|
+
...rest,
|
|
1140
|
+
title: name,
|
|
1141
|
+
startCwd: cwd ? pathResolve(root.root, cwd) : root.root,
|
|
1142
|
+
origin: 'agent',
|
|
1143
|
+
env: { PAGER: 'cat', GIT_PAGER: 'cat' },
|
|
1144
|
+
},
|
|
1145
|
+
root,
|
|
1146
|
+
)
|
|
1147
|
+
}
|
|
1148
|
+
|
|
433
1149
|
/** 幂等 kill:已退出 / 已移除直接返回(幂等),否则 kill 并从表移除。 */
|
|
434
1150
|
kill(terminalId: string): { killed: boolean } {
|
|
435
1151
|
const inst = this.instances.get(terminalId)
|
|
@@ -528,7 +1244,16 @@ export class TerminalManager {
|
|
|
528
1244
|
return inst
|
|
529
1245
|
}
|
|
530
1246
|
|
|
1247
|
+
/** 移除实例并连带 dispose headless 屏幕(§5.5:屏幕随终端 dispose 一并 dispose)。 */
|
|
531
1248
|
private remove(terminalId: string): void {
|
|
1249
|
+
const inst = this.instances.get(terminalId)
|
|
1250
|
+
if (inst) {
|
|
1251
|
+
try {
|
|
1252
|
+
inst.screen.dispose() // 已加载的 addon(含 SerializeAddon)随之释放
|
|
1253
|
+
} catch (err: unknown) {
|
|
1254
|
+
console.warn(`[terminal-manager] 屏幕 dispose ${terminalId} 异常:`, err)
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
532
1257
|
this.instances.delete(terminalId)
|
|
533
1258
|
}
|
|
534
1259
|
}
|
|
@@ -538,6 +1263,18 @@ function clampDim(value: number | undefined, fallback: number): number {
|
|
|
538
1263
|
return Math.min(500, Math.max(2, n))
|
|
539
1264
|
}
|
|
540
1265
|
|
|
1266
|
+
/** readScreen 入参归一化:正整数(非法/非有限 → fallback),count/maxBytes 用。 */
|
|
1267
|
+
function normalizePositiveInt(value: number | undefined, fallback: number): number {
|
|
1268
|
+
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
|
1269
|
+
return Math.max(1, n)
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/** readScreen 入参归一化:非负整数(非法/非有限 → fallback),offset 用。 */
|
|
1273
|
+
function normalizeNonNegativeInt(value: number | undefined, fallback: number): number {
|
|
1274
|
+
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
|
1275
|
+
return Math.max(0, n)
|
|
1276
|
+
}
|
|
1277
|
+
|
|
541
1278
|
/**
|
|
542
1279
|
* 取(或构造)终端管理器单例。仅服务端经路由动态 import 调用;HMR 后模块重载时
|
|
543
1280
|
* globalThis 上的实例存活,实例表与 poll 计时器不重建(防泄漏 + 防双表)。
|