fix(terminal-controller): delete confined Agent shell history and stop pointing read-only shells at it
read-only confinement cannot write /tmp, so the per-terminal history path did nothing there; read-only shells now get an empty HISTFILE, which also keeps them from loading the person's history. workspace-write shells keep their per-terminal history file, and the controller now deletes it through the same execution environment after the shell ends, including a failed allocation; a failed deletion is logged.
This commit is contained in:
1 parent
9eb4144222
commit
454a3f7a88
6 files changed
+91
-10
No files matched your search
@@ -18,8 +18,8 @@
|
||||
en: d58b01bd0473b8fd
|
||||
zh: 02ce6a743f999ed9
|
||||
/deepseek-ai-dsh-api-terminal-controller/use-this-package/agent-terminals:
|
||||
en: 9e970d5709e5e68c
|
||||
zh: 7f1bcb09e9a026ce
|
||||
en: edec6162110da8d1
|
||||
zh: 4eff2ba807083417
|
||||
/deepseek-ai-dsh-api-terminal-controller/understand-the-implementation:
|
||||
en: a999243c0b908442
|
||||
zh: 8772eb61a32adeb0
|
||||
|
||||
@@ -48,7 +48,7 @@ An open tab in any connected window retains its terminal, including hidden tabs
|
||||
|
||||
### Agent terminals
|
||||
|
||||
Host code opens a terminal for a Session's Agent with `openForAgent(agent, request, signal)`. The caller supplies the sandbox policy it resolved for the Session: `danger-full-access` launches the shell directly, confined modes wrap it through the execution environment's `ctx.sandbox` provider, and a missing provider fails before allocation. Confined POSIX shells use `/tmp/dsh-agent-history-<id>` as `HISTFILE` because the person's history file is outside the writable roots; only `workspace-write` can write it, so `read-only` shells do not save history. `preferredShells` names executables tried among discovered shells before the default, and `env` adds variables to the shell environment; it cannot replace `DSH_SESSION_ID`, nor `HISTFILE` in confined POSIX shells, while unconfined shells keep the inherited `HISTFILE` unless `env` sets one. The terminal records `origin: 'agent'`, `control: 'agent'` and its `sandboxMode`; it counts toward `maxTerminals` and, while the Agent controls it and it runs, toward `maxAgentTerminals`. Its title must contain 1–120 characters after surrounding whitespace is removed.
|
||||
Host code opens a terminal for a Session's Agent with `openForAgent(agent, request, signal)`. The caller supplies the sandbox policy it resolved for the Session: `danger-full-access` launches the shell directly, confined modes wrap it through the execution environment's `ctx.sandbox` provider, and a missing provider fails before allocation. Confined POSIX shells never load or write the person's history file, which is outside the writable roots: a `workspace-write` shell keeps its history in `/tmp/dsh-agent-history-<id>`, which the controller deletes after the shell ends, and a `read-only` shell gets an empty `HISTFILE` and keeps none. `preferredShells` names executables tried among discovered shells before the default, and `env` adds variables to the shell environment; it cannot replace `DSH_SESSION_ID`, nor `HISTFILE` in confined POSIX shells, while unconfined shells keep the inherited `HISTFILE` unless `env` sets one. The terminal records `origin: 'agent'`, `control: 'agent'` and its `sandboxMode`; it counts toward `maxTerminals` and, while the Agent controls it and it runs, toward `maxAgentTerminals`. Its title must contain 1–120 characters after surrounding whitespace is removed.
|
||||
|
||||
The returned `AgentTerminal` reports the top-level process id, writes input, renders the screen as text, marks a screen position to render later output, waits for output or state changes, inspects and signals the foreground process group, and closes the terminal. Its screen reads and marks are synchronous and see output applied so far; `drain` waits until output received before the call is applied. Agent input neither needs nor takes Web input control. The first browser write marked `typed` passes control to the person; afterwards writes, signals and closing fail with `AgentTerminalError` code `user-control`, while reads continue. The controller's `readScreen` drains before rendering, and it and `inspectActivity` read any terminal of the Agent's Session, including terminals the person opened. `readScreen` fails with `RemoteError` code `terminal/unavailable` when the terminal is missing or closes before its screen is read.
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provide
|
||||
|
||||
### Agent 终端
|
||||
|
||||
Host 代码通过 `openForAgent(agent, request, signal)` 为 Session 的 Agent 打开终端。调用方传入它为该 Session 解析出的沙箱策略:`danger-full-access` 直接启动 shell,受限模式通过执行环境的 `ctx.sandbox` provider 包裹 shell,缺少 provider 时在分配前失败。受限的 POSIX shell 把 `HISTFILE` 设为 `/tmp/dsh-agent-history-<id>`,因为人的历史文件不在可写目录内;只有 `workspace-write` 能写入该文件,因此 `read-only` 下的 shell 不保存历史。`preferredShells` 列出在已探测 shell 中优先尝试的可执行文件,之后才用默认 shell;`env` 向 shell 环境添加变量,但不能替换 `DSH_SESSION_ID`,也不能替换受限 POSIX shell 的 `HISTFILE`;不受限的 shell 沿用继承的 `HISTFILE`,除非 `env` 另行设置。终端记录 `origin: 'agent'`、`control: 'agent'` 和 `sandboxMode`;它计入 `maxTerminals`,在 Agent 控制且仍在运行期间也计入 `maxAgentTerminals`。标题去掉首尾空白后必须为 1–120 个字符。
|
||||
Host 代码通过 `openForAgent(agent, request, signal)` 为 Session 的 Agent 打开终端。调用方传入它为该 Session 解析出的沙箱策略:`danger-full-access` 直接启动 shell,受限模式通过执行环境的 `ctx.sandbox` provider 包裹 shell,缺少 provider 时在分配前失败。受限的 POSIX shell 不会读写人的历史文件,因为它不在可写目录内:`workspace-write` 下的 shell 把历史保存在 `/tmp/dsh-agent-history-<id>`,shell 结束后由控制器删除;`read-only` 下的 shell 得到空的 `HISTFILE`,不保存历史。`preferredShells` 列出在已探测 shell 中优先尝试的可执行文件,之后才用默认 shell;`env` 向 shell 环境添加变量,但不能替换 `DSH_SESSION_ID`,也不能替换受限 POSIX shell 的 `HISTFILE`;不受限的 shell 沿用继承的 `HISTFILE`,除非 `env` 另行设置。终端记录 `origin: 'agent'`、`control: 'agent'` 和 `sandboxMode`;它计入 `maxTerminals`,在 Agent 控制且仍在运行期间也计入 `maxAgentTerminals`。标题去掉首尾空白后必须为 1–120 个字符。
|
||||
|
||||
返回的 `AgentTerminal` 提供顶层进程 id,可以写入输入、把屏幕渲染为文本、标记屏幕位置以便之后渲染新输出、等待输出或状态变化、查询并向前台进程组发信号,以及关闭终端。它的读屏和标记是同步的,只看到已处理的输出;`drain` 会等到调用前收到的输出处理完。Agent 输入既不需要也不抢占 Web 的输入控制权。浏览器第一次发出标记为 `typed` 的写入后,控制权转给人;此后写入、发信号和关闭都会以 `AgentTerminalError` 的 `user-control` 代码失败,读取不受影响。控制器的 `readScreen` 会先等输出处理完再渲染;它和 `inspectActivity` 可读取 Agent 所在 Session 的任意终端,包括人自己打开的终端。终端不存在或在读取屏幕前关闭时,`readScreen` 以 `RemoteError` 失败,错误码为 `terminal/unavailable`。
|
||||
|
||||
|
||||
@@ -89,6 +89,8 @@ interface TerminalLaunch {
|
||||
readonly argv: readonly string[]
|
||||
readonly env: Record<string, string>
|
||||
readonly info: WebTerminalInfo
|
||||
/** Removes files the launch created once the process has ended; it must not throw. */
|
||||
readonly release?: () => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -449,14 +451,38 @@ export class TerminalController extends TypertRemoteService {
|
||||
const shell = await this.agentShell(agent, request.preferredShells, signal)
|
||||
const argv = await this.confine(agent, [shell.path, ...shell.args], request.policy, signal)
|
||||
const { platform } = await subprocess.terminalEnvironment(signal)
|
||||
// Confined shells cannot write the person's history file; workspace-write grants /tmp.
|
||||
const history = request.policy.mode !== 'danger-full-access' && platform === 'posix' ? { HISTFILE: `/tmp/dsh-agent-history-${id}` } : {}
|
||||
// Confined shells cannot write the person's history file and must not load it. Only workspace-write grants /tmp,
|
||||
// so a read-only shell gets an empty HISTFILE and keeps no history file.
|
||||
const historyFile = `/tmp/dsh-agent-history-${id}`
|
||||
const keepsHistory = platform === 'posix' && request.policy.mode === 'workspace-write'
|
||||
const confined = platform === 'posix' && request.policy.mode !== 'danger-full-access'
|
||||
const history = confined ? { HISTFILE: keepsHistory ? historyFile : '' } : {}
|
||||
return {
|
||||
argv, env: { ...request.env, DSH_SESSION_ID: agent.id, ...history },
|
||||
info: {
|
||||
id, shell, title: request.title, cwd, cols: request.cols, rows: request.rows, state: 'running', exitCode: null,
|
||||
origin: 'agent', control: 'agent', sandboxMode: request.policy.mode,
|
||||
},
|
||||
...keepsHistory ? { release: () => this.removeHistory(subprocess, historyFile) } : {},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a confined Agent shell's history file in its execution environment after the shell ends.
|
||||
* @param subprocess - the execution environment that ran the shell.
|
||||
* @param path - history file the shell was given.
|
||||
* @returns after deletion; a failure is logged because the file only holds the ended shell's own history.
|
||||
*/
|
||||
private async removeHistory(subprocess: Context['subprocess'], path: string): Promise<void> {
|
||||
try {
|
||||
const { exitCode, signal } = await subprocess.spawn({
|
||||
argv: ['rm', '-f', '--', path], cwd: '/',
|
||||
stdio: { stdin: 'ignore', stdout: { maxBytes: 4096 }, stderr: { maxBytes: 4096 } },
|
||||
graceMs: this.config.disposeGraceMs,
|
||||
}).done
|
||||
if (exitCode !== 0) throw new Error(`rm ended with ${exitCode ?? signal}`)
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('Agent terminal history cleanup failed', { path, error })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,7 +536,7 @@ export class TerminalController extends TypertRemoteService {
|
||||
private async spawn(
|
||||
agent: Agent, owner: OwnedSession, id: WebTerminalId, prepare: (signal: AbortSignal) => Promise<TerminalLaunch>, signal: AbortSignal,
|
||||
): Promise<BrowserTerminal> {
|
||||
const { info, argv, env } = await prepare(signal)
|
||||
const { info, argv, env, release } = await prepare(signal)
|
||||
const handle = await this.execution(agent).subprocess.spawnTerminal({
|
||||
argv, cwd: info.cwd, cols: info.cols, rows: info.rows,
|
||||
terminalType: 'xterm-256color', env,
|
||||
@@ -519,11 +545,12 @@ export class TerminalController extends TypertRemoteService {
|
||||
})
|
||||
try {
|
||||
signal.throwIfAborted()
|
||||
return new BrowserTerminal(handle, info, this.config.scrollback, this.config.maxBufferedBytes)
|
||||
return new BrowserTerminal(handle, info, this.config.scrollback, this.config.maxBufferedBytes, release)
|
||||
} catch (error) {
|
||||
const cleanup = new TerminalRetention(this.config, handle.inspectActivity.bind(handle), async () => {
|
||||
owner.closedIds.add(id)
|
||||
await handle.terminate()
|
||||
await release?.()
|
||||
owner.allocations.delete(id)
|
||||
this.changed(agent.id)
|
||||
}, (cleanupError) => { this.ctx.logger.error('Browser terminal allocation cleanup failed', cleanupError) })
|
||||
|
||||
@@ -40,12 +40,14 @@ export class BrowserTerminal {
|
||||
* @param info - initial metadata.
|
||||
* @param scrollback - maximum retained scrollback rows.
|
||||
* @param maxBufferedBytes - per-follower queue cap.
|
||||
* @param release - removes files the launch created once the process has ended; it must not throw.
|
||||
*/
|
||||
constructor(
|
||||
private readonly handle: SubprocessTerminalHandle,
|
||||
public info: WebTerminalInfo,
|
||||
scrollback: number,
|
||||
private readonly maxBufferedBytes: number,
|
||||
private readonly release: () => Promise<void> = () => Promise.resolve(),
|
||||
) {
|
||||
const { Terminal } = requireHeadless()
|
||||
const { SerializeAddon } = requireSerialize()
|
||||
@@ -340,6 +342,7 @@ export class BrowserTerminal {
|
||||
this.closing = (async () => {
|
||||
await this.handle.terminate()
|
||||
await this.drained
|
||||
await this.release()
|
||||
for (const follower of this.followers) follower.finish()
|
||||
this.followers.clear()
|
||||
this.screenDisposed = true
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
|
||||
import { SubprocessExecutableNotFoundError, type SubprocessRuntime, type SubprocessTerminalEnvironment, type SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess'
|
||||
import { SubprocessExecutableNotFoundError, type SubprocessRuntime, type SubprocessSpawnSpec, type SubprocessTerminalEnvironment, type SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess'
|
||||
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { TerminalController, type Config } from '../src/index.ts'
|
||||
@@ -51,7 +51,13 @@ function fixture(overrides: Partial<Config> = {}) {
|
||||
ctx.provide('sandboxPolicy', sandboxPolicy as never)
|
||||
ctx.provide('workingDirectory', workingDirectory as never)
|
||||
const { handle, checked } = fakeHandle()
|
||||
const subprocess = { terminalEnvironment: vi.fn(async (): Promise<SubprocessTerminalEnvironment> => ({ platform: 'posix', defaultShell: '/bin/bash' })), resolveExecutable: vi.fn(async (path: string) => path), spawnTerminal: vi.fn(async () => checked) }
|
||||
const subprocess = {
|
||||
terminalEnvironment: vi.fn(async (): Promise<SubprocessTerminalEnvironment> => ({ platform: 'posix', defaultShell: '/bin/bash' })),
|
||||
resolveExecutable: vi.fn(async (path: string) => path), spawnTerminal: vi.fn(async () => checked),
|
||||
spawn: vi.fn((_spec: SubprocessSpawnSpec) => ({
|
||||
done: Promise.resolve<{ exitCode: number | null; signal: NodeJS.Signals | null }>({ exitCode: 0, signal: null }),
|
||||
})),
|
||||
}
|
||||
ctx.provide('subprocess', subprocess as never)
|
||||
const controller = new TerminalController(ctx, { ...config, ...overrides })
|
||||
const disposeEffect = (label: string): Promise<void> => {
|
||||
@@ -771,6 +777,51 @@ describe('Agent terminals', () => {
|
||||
expect(terminal.id).toMatch(/^[\w-]{1,128}$/u)
|
||||
expect(terminal.info).toMatchObject({ title: 'dev server', origin: 'agent', control: 'agent', sandboxMode: 'workspace-write', state: 'running' })
|
||||
expect(controller.list(agent.id)).toEqual([terminal.info])
|
||||
expect(subprocess.spawn).not.toHaveBeenCalled()
|
||||
await terminal.close()
|
||||
expect(subprocess.spawn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
|
||||
argv: ['rm', '-f', '--', `/tmp/dsh-agent-history-${terminal.id}`], cwd: '/',
|
||||
}))
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a read-only POSIX shell an empty HISTFILE', 'posix', { mode: 'read-only', workspaceRoot: '/workspace' }, { HISTFILE: '' }],
|
||||
['a confined Windows shell no HISTFILE', 'windows', confined, {}],
|
||||
] as const)('gives %s and removes no history file', async (_name, platform, policy, history) => {
|
||||
const { ctx, controller, agent, subprocess } = fixture()
|
||||
withSandbox(ctx)
|
||||
subprocess.terminalEnvironment.mockResolvedValue({ platform, defaultShell: '/bin/bash' })
|
||||
const terminal = await controller.openForAgent(agent, { ...agentRequest, policy }, signal())
|
||||
expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ env: { DSH_SESSION_ID: 'session', ...history } }))
|
||||
await terminal.close()
|
||||
expect(subprocess.spawn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('logs a failed history cleanup and still closes the terminal', async () => {
|
||||
const { ctx, controller, agent, subprocess } = fixture()
|
||||
withSandbox(ctx)
|
||||
subprocess.spawnTerminal.mockImplementation(async () => fakeHandle().checked)
|
||||
const warn = vi.spyOn(ctx.logger, 'warn')
|
||||
subprocess.spawn.mockReturnValueOnce({ done: Promise.resolve({ exitCode: 1, signal: null }) })
|
||||
subprocess.spawn.mockReturnValueOnce({ done: Promise.resolve({ exitCode: null, signal: 'SIGKILL' }) })
|
||||
subprocess.spawn.mockImplementationOnce(() => { throw new Error('spawn unavailable') })
|
||||
for (let index = 0; index < 3; index++) await (await controller.openForAgent(agent, agentRequest, signal())).close()
|
||||
expect(controller.list(agent.id)).toEqual([])
|
||||
expect(warn.mock.calls.map(call => String((call[1] as { error: unknown }).error)))
|
||||
.toEqual(['Error: rm ended with 1', 'Error: rm ended with SIGKILL', 'Error: spawn unavailable'])
|
||||
})
|
||||
|
||||
it('removes the history file of a failed Agent allocation after its cleanup', async () => {
|
||||
const { ctx, controller, agent, subprocess } = fixture()
|
||||
withSandbox(ctx)
|
||||
const abort = new AbortController()
|
||||
subprocess.spawnTerminal.mockImplementationOnce(async () => { abort.abort(new Error('request disconnected')); return fakeHandle().checked })
|
||||
await expect(controller.openForAgent(agent, agentRequest, abort.signal)).rejects.toThrow('request disconnected')
|
||||
expect(subprocess.spawn).toHaveBeenCalledOnce()
|
||||
const [cleanup] = subprocess.spawn.mock.calls[0]!
|
||||
expect(cleanup.argv.slice(0, 3)).toEqual(['rm', '-f', '--'])
|
||||
expect(cleanup.argv[3]).toMatch(/^\/tmp\/dsh-agent-history-/u)
|
||||
expect(controller.list(agent.id)).toEqual([])
|
||||
})
|
||||
|
||||
it('starts a full-access agent terminal in the requested directory and environment, keeping its own variables', async () => {
|
||||
|
||||
Reference in new issue
Block a user