index.ts 17 KB

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