index.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /** Session-owned user terminals with the execution environment's system-user permissions. */
  2. import type { Context } from '@deepseek-ai/cordis'
  3. import z from '@deepseek-ai/schemastery'
  4. import type { Agent } from '@deepseek-ai/dsh-agent'
  5. import type { SessionId } from '@deepseek-ai/dsh-session'
  6. import type {} from '@deepseek-ai/dsh-sandbox-policy'
  7. import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
  8. import { discoverShells, resolveShell } from './shells.ts'
  9. import { BrowserTerminal } from './terminal.ts'
  10. import { TerminalRetention } from './retention.ts'
  11. import type {
  12. TerminalShell, TerminalAttachmentId, TerminalCreateRequest, TerminalEnvironment, TerminalFrame, TerminalRetentionFrame,
  13. WebTerminalId, WebTerminalInfo,
  14. } from './types.ts'
  15. export type * from './types.ts'
  16. declare module '@deepseek-ai/cordis' {
  17. interface Context {
  18. /** Interactive user terminals, separate from the Agent terminal tool registry. */
  19. terminalController: TerminalController
  20. }
  21. }
  22. /** Deployment limits and an optional shell profile. */
  23. export interface Config {
  24. /** Explicit shell profile; omission uses the execution environment's default shell. */
  25. readonly shell?: {
  26. /** Executable path or PATH name, verified by the subprocess provider. */
  27. path: string
  28. /** User-visible profile name. */
  29. name: string
  30. /** Arguments passed to the interactive shell. */
  31. args: string[]
  32. } | undefined
  33. /** Executable names or paths checked for the new-terminal shell selector. */
  34. readonly shellCandidates: string[]
  35. /** Maximum retained terminals and pending allocations per Session. */
  36. readonly maxTerminals: number
  37. /** Maximum terminal width in columns. */
  38. readonly maxCols: number
  39. /** Maximum terminal height in rows. */
  40. readonly maxRows: number
  41. /** Screen history rows retained for reconnecting clients. */
  42. readonly scrollback: number
  43. /** Maximum queued UTF-8 frame bytes per output follower before disconnection. */
  44. readonly maxBufferedBytes: number
  45. /** Maximum UTF-8 bytes in one input request. */
  46. readonly maxInputBytes: number
  47. /** Provider process-termination grace period in milliseconds. */
  48. readonly disposeGraceMs: number
  49. /** Continuous confirmed idle time without window holds before reclamation; zero disables reclamation. */
  50. readonly unattendedTimeoutMs: number
  51. /** Interval between unattended shell and process observations. */
  52. readonly activityPollIntervalMs: number
  53. /** Delay before retrying failed owned terminal cleanup. */
  54. readonly cleanupRetryMs: number
  55. }
  56. interface TerminalAllocation {
  57. info: WebTerminalInfo
  58. readonly cleanup: TerminalRetention
  59. }
  60. interface OwnedSession {
  61. readonly lifetime: AbortController
  62. readonly closedIds: Set<WebTerminalId>
  63. cleanup?: Promise<void>
  64. readonly terminals: Map<WebTerminalId, BrowserTerminal>
  65. readonly pending: Map<WebTerminalId, Promise<BrowserTerminal>>
  66. readonly allocations: Map<WebTerminalId, TerminalAllocation>
  67. }
  68. /** Typed Remote control of transient Session-owned terminal processes. */
  69. export class TerminalController extends TypertRemoteService {
  70. static inject = ['subprocess', 'sandboxPolicy', 'typert']
  71. static Config: z<Config> = z.object({
  72. shell: z.union([z.object({
  73. path: z.string().required(), name: z.string().required(), args: z.array(z.string()).default([]),
  74. }), z.const(undefined)]),
  75. shellCandidates: z.array(z.string().min(1)).default(['zsh', 'bash', 'fish', 'pwsh', 'powershell', 'cmd']),
  76. maxTerminals: z.number().step(1).min(1).default(8),
  77. maxCols: z.number().step(1).min(2).default(500),
  78. maxRows: z.number().step(1).min(1).default(200),
  79. scrollback: z.number().step(1).min(0).default(1000),
  80. maxBufferedBytes: z.number().step(1).min(1024).default(2 * 1024 * 1024),
  81. maxInputBytes: z.number().step(1).min(1).default(64 * 1024),
  82. disposeGraceMs: z.number().step(1).min(1).default(1000),
  83. unattendedTimeoutMs: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(7_200_000),
  84. activityPollIntervalMs: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(30_000),
  85. cleanupRetryMs: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(60_000),
  86. })
  87. private readonly owners = new Map<SessionId, OwnedSession>()
  88. private readonly lifetime = new AbortController()
  89. /**
  90. * @param ctx - Host context carrying typed Remote and execution providers.
  91. * @param config - validated terminal limits and optional shell profile.
  92. */
  93. constructor(ctx: Context, private readonly config: Config) {
  94. super(ctx, 'terminalController', { namespace: 'terminal' })
  95. ctx.effect(() => async () => {
  96. this.lifetime.abort(new Error('Terminal controller disposed'))
  97. const results = await Promise.allSettled([...this.owners].map(([id, owner]) => this.disposeOwner(id, owner)))
  98. const errors = results.filter(result => result.status === 'rejected').map(result => result.reason as unknown)
  99. if (errors.length > 0) throw new AggregateError(errors, 'Browser terminal cleanup failed')
  100. }, 'terminal-controller.processes')
  101. }
  102. /**
  103. * Read the Session working directory and terminal limits without resolving a shell.
  104. * @param agent - Session owner supplied by the Gateway.
  105. * @param signal - request cancellation.
  106. * @returns the Session workspace directory and terminal limits.
  107. */
  108. @Remote
  109. environment(agent: Agent, signal: AbortSignal): TerminalEnvironment {
  110. signal.throwIfAborted()
  111. const { sandboxPolicy } = this.execution(agent)
  112. return { cwd: agent.session.header.cwd ?? sandboxPolicy.workspaceRoot,
  113. maxInputBytes: this.config.maxInputBytes, maxCols: this.config.maxCols,
  114. maxRows: this.config.maxRows, scrollback: this.config.scrollback }
  115. }
  116. /**
  117. * Discover installed shells in the Session's execution environment.
  118. * @param agent - Session owner supplied by the Gateway.
  119. * @param signal - request cancellation.
  120. * @returns verified profiles, with the configured or system default first.
  121. */
  122. @Remote
  123. shells(agent: Agent, signal: AbortSignal): Promise<TerminalShell[]> {
  124. signal.throwIfAborted()
  125. return discoverShells(this.execution(agent).subprocess, this.config.shell, this.config.shellCandidates, signal)
  126. }
  127. /**
  128. * List retained terminals without resolving or activating an Agent.
  129. * @param sessionId - displayed Session identity, including offline history.
  130. * @returns terminals retained for this Host lifetime.
  131. */
  132. @Remote
  133. list(sessionId: SessionId): WebTerminalInfo[] {
  134. const owner = this.owners.get(sessionId)
  135. if (owner === undefined) return []
  136. return [...owner.terminals.values(), ...owner.allocations.values()].map(terminal => terminal.info)
  137. }
  138. /**
  139. * Allocate a user shell once for a caller-generated identity, without Agent sandbox or approval restrictions.
  140. * @param agent - Session owner supplied by the Gateway.
  141. * @param request - initial dimensions and idempotency identity.
  142. * @param signal - allocation cancellation; committed terminals survive disconnection.
  143. * @returns the existing or newly committed terminal.
  144. */
  145. @Remote
  146. async create(agent: Agent, request: TerminalCreateRequest, signal: AbortSignal): Promise<WebTerminalInfo> {
  147. this.lifetime.signal.throwIfAborted()
  148. if (!/^[\w-]{1,128}$/u.test(request.id)) throw new Error('Invalid terminal identity')
  149. this.dimensions(request.cols, request.rows)
  150. const owner = this.owner(agent)
  151. owner.lifetime.signal.throwIfAborted()
  152. this.requireOpen(owner, request.id)
  153. const existing = owner.terminals.get(request.id)
  154. if (existing !== undefined) return existing.info
  155. const pending = owner.pending.get(request.id)
  156. if (pending !== undefined) {
  157. const terminal = await pending
  158. this.requireOpen(owner, request.id)
  159. return terminal.info
  160. }
  161. if (new Set([...owner.terminals.keys(), ...owner.pending.keys(), ...owner.allocations.keys()]).size >= this.config.maxTerminals) throw new RemoteError('terminal/limit-reached', 'Session terminal limit reached', { limit: this.config.maxTerminals })
  162. const allocation = this.spawn(agent, owner, request, AbortSignal.any([signal, this.lifetime.signal, owner.lifetime.signal]))
  163. owner.pending.set(request.id, allocation)
  164. try {
  165. const terminal = await allocation
  166. owner.terminals.set(request.id, terminal)
  167. owner.allocations.delete(request.id)
  168. terminal.monitor(this.config, () => { owner.closedIds.add(request.id) }, () => {
  169. owner.terminals.delete(request.id)
  170. }, (error) => { this.ctx.logger.error('Browser terminal cleanup failed', error) })
  171. this.requireOpen(owner, request.id)
  172. return terminal.info
  173. } finally {
  174. owner.pending.delete(request.id)
  175. }
  176. }
  177. /**
  178. * Retain an existing terminal for a window without activating its Agent or taking input control.
  179. * @param sessionId - owning Session identity, including an inactive saved layout.
  180. * @param id - retained Host terminal identity.
  181. * @param signal - physical Remote stream cancellation.
  182. * @returns a hold acknowledgement followed by an open lifetime stream.
  183. */
  184. @Remote({ mode: 'stream' })
  185. retain(sessionId: SessionId, id: WebTerminalId, signal: AbortSignal): AsyncIterable<TerminalRetentionFrame> {
  186. const owner = this.owners.get(sessionId)
  187. const terminal = owner?.terminals.get(id)
  188. if (terminal === undefined || owner?.closedIds.has(id) === true || owner?.lifetime.signal.aborted === true) {
  189. throw new RemoteError('terminal/unavailable', 'Terminal is closing or unavailable', {})
  190. }
  191. return terminal.retain(signal)
  192. }
  193. /**
  194. * Attach to a terminal without binding its process lifetime to the transport.
  195. * @param agent - Session owner supplied by the Gateway.
  196. * @param id - terminal identity.
  197. * @param attachmentId - new exclusive input attachment.
  198. * @param signal - physical stream cancellation.
  199. * @returns screen recovery followed by output and metadata changes.
  200. */
  201. @Remote({ mode: 'stream' })
  202. follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable<TerminalFrame> {
  203. if (!/^[\w-]{1,128}$/u.test(attachmentId)) throw new Error('Invalid terminal attachment identity')
  204. return this.terminal(agent, id).follow(attachmentId, signal)
  205. }
  206. /**
  207. * Deliver raw input, including Tab completion and control characters.
  208. * @param agent - Session owner supplied by the Gateway.
  209. * @param id - terminal identity.
  210. * @param attachmentId - current writable attachment.
  211. * @param data - input bytes represented as UTF-8 text.
  212. * @returns after provider input acceptance.
  213. */
  214. @Remote
  215. async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise<void> {
  216. if (Buffer.byteLength(data, 'utf8') > this.config.maxInputBytes) throw new Error('Terminal input exceeds the configured limit')
  217. await this.terminal(agent, id).write(attachmentId, data)
  218. }
  219. /**
  220. * Update the dimensions of the PTY and recovery screen.
  221. * @param agent - Session owner supplied by the Gateway.
  222. * @param id - terminal identity.
  223. * @param attachmentId - current writable attachment.
  224. * @param cols - column count.
  225. * @param rows - row count.
  226. * @returns after the resize completes.
  227. */
  228. @Remote
  229. async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise<void> {
  230. this.dimensions(cols, rows)
  231. await this.terminal(agent, id).resize(attachmentId, cols, rows)
  232. }
  233. /**
  234. * Rename a terminal without changing its shell.
  235. * @param agent - Session owner supplied by the Gateway.
  236. * @param id - terminal identity.
  237. * @param title - nonempty display title, at most 120 characters.
  238. */
  239. @Remote
  240. rename(agent: Agent, id: WebTerminalId, title: string): void {
  241. if (title.trim().length === 0 || title.length > 120) throw new Error('Terminal title must contain 1–120 characters')
  242. this.terminal(agent, id).rename(title.trim())
  243. }
  244. /**
  245. * Close an identity to future creation and kill its process range; repeated closes succeed.
  246. * @param agent - Session owner supplied by the Gateway.
  247. * @param id - terminal identity.
  248. * @returns after provider cleanup succeeds. A failure retains the terminal for retry.
  249. */
  250. @Remote
  251. async close(agent: Agent, id: WebTerminalId): Promise<void> {
  252. const owner = this.owner(agent)
  253. owner.closedIds.add(id)
  254. // create publishes the allocation before this wait settles; close owns it even if create then rejects.
  255. await owner.pending.get(id)?.catch(() => { /* Creation reports its failure; close still owns any allocated process. */ })
  256. const terminal = owner.terminals.get(id)
  257. if (terminal !== undefined) {
  258. await terminal.close()
  259. owner.terminals.delete(id)
  260. } else {
  261. const allocation = owner.allocations.get(id)
  262. if (allocation === undefined) return
  263. await allocation.cleanup.close()
  264. owner.allocations.delete(id)
  265. }
  266. }
  267. private owner(agent: Agent): OwnedSession {
  268. let owner = this.owners.get(agent.id)
  269. if (owner === undefined) {
  270. owner = { terminals: new Map(), pending: new Map(), allocations: new Map(), closedIds: new Set(), lifetime: new AbortController() }
  271. this.owners.set(agent.id, owner)
  272. const owned = owner
  273. agent.ctx.effect(() => async () => { await this.disposeOwner(agent.id, owned) }, 'terminal-controller.owner')
  274. }
  275. return owner
  276. }
  277. private disposeOwner(id: SessionId, owner: OwnedSession): Promise<void> {
  278. if (owner.cleanup !== undefined) return owner.cleanup
  279. owner.lifetime.abort(new Error('Terminal Session owner disposed'))
  280. owner.cleanup = (async () => {
  281. await Promise.allSettled(owner.pending.values())
  282. const results = await Promise.allSettled([
  283. ...[...owner.terminals.values()].map(terminal => terminal.dispose()),
  284. ...[...owner.allocations.values()].map(allocation => allocation.cleanup.dispose()),
  285. ])
  286. const errors = results.filter(result => result.status === 'rejected').map(result => result.reason as unknown)
  287. if (errors.length > 0) throw new AggregateError(errors, 'Session terminal cleanup failed')
  288. owner.terminals.clear()
  289. owner.allocations.clear()
  290. this.owners.delete(id)
  291. })().catch((error: unknown) => { delete owner.cleanup; throw error })
  292. return owner.cleanup
  293. }
  294. private terminal(agent: Agent, id: WebTerminalId): BrowserTerminal {
  295. const terminal = this.owners.get(agent.id)?.terminals.get(id)
  296. if (terminal === undefined) throw new RemoteError('terminal/unavailable', 'Terminal no longer exists in this Session', {})
  297. this.requireOpen(this.owners.get(agent.id) as OwnedSession, id)
  298. return terminal
  299. }
  300. private requireOpen(owner: OwnedSession, id: WebTerminalId): void {
  301. if (owner.closedIds.has(id)) throw new RemoteError('terminal/unavailable', 'Terminal was closed in this Session', {})
  302. }
  303. private dimensions(cols: number, rows: number): void {
  304. if (!Number.isSafeInteger(cols) || cols < 2 || cols > this.config.maxCols
  305. || !Number.isSafeInteger(rows) || rows < 1 || rows > this.config.maxRows) throw new Error('Terminal dimensions exceed the configured limits')
  306. }
  307. private execution(agent: Agent): { subprocess: Context['subprocess']; sandboxPolicy: Context['sandboxPolicy'] } {
  308. // The Agent context selects execution providers but does not inject consumer services.
  309. const subprocess = agent.ctx.get('subprocess')
  310. const sandboxPolicy = agent.ctx.get('sandboxPolicy')
  311. if (subprocess === undefined || sandboxPolicy === undefined) throw new Error('The Session execution environment requires subprocess and sandbox policy providers')
  312. return { subprocess, sandboxPolicy }
  313. }
  314. private async spawn(agent: Agent, owner: OwnedSession, request: TerminalCreateRequest, signal: AbortSignal): Promise<BrowserTerminal> {
  315. const environment = this.environment(agent, signal)
  316. const { subprocess } = this.execution(agent)
  317. const shell = request.shellPath === undefined
  318. ? await resolveShell(subprocess, this.config.shell, signal)
  319. : (await this.shells(agent, signal)).find(candidate => candidate.path === request.shellPath)
  320. if (shell === undefined) throw new Error('Selected shell is not available in this execution environment')
  321. const handle = await subprocess.spawnTerminal({
  322. argv: [shell.path, ...shell.args], cwd: environment.cwd, cols: request.cols, rows: request.rows,
  323. terminalType: 'xterm-256color', env: { DSH_SESSION_ID: agent.id },
  324. shellActivity: true,
  325. graceMs: this.config.disposeGraceMs, signal,
  326. })
  327. const info: WebTerminalInfo = {
  328. id: request.id, shell, title: shell.name, cwd: environment.cwd,
  329. cols: request.cols, rows: request.rows, state: 'running', exitCode: null,
  330. }
  331. try {
  332. signal.throwIfAborted()
  333. return new BrowserTerminal(handle, info, this.config.scrollback, this.config.maxBufferedBytes)
  334. } catch (error) {
  335. const cleanup = new TerminalRetention(this.config, handle.inspectActivity.bind(handle), async () => {
  336. owner.closedIds.add(request.id)
  337. await handle.terminate()
  338. owner.allocations.delete(request.id)
  339. }, (cleanupError) => { this.ctx.logger.error('Browser terminal allocation cleanup failed', cleanupError) })
  340. owner.allocations.set(request.id, {
  341. info: { ...info, state: 'failed', error: error instanceof Error ? error.message : String(error) }, cleanup,
  342. })
  343. try {
  344. await cleanup.close()
  345. } catch (cleanupError) {
  346. throw new AggregateError([error, cleanupError], 'Terminal allocation cleanup failed')
  347. }
  348. throw error
  349. }
  350. }
  351. }
  352. /** Browser terminal service plugin. */
  353. export default TerminalController