Merge remote-tracking branch 'origin/master' into refactor/subagent

This commit is contained in:
Dudu-0223 committed 2026-09-21 11:59:58 +08:00
commit b3b0cd95cc
238 files changed
+6750 -2131

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/api/session-controller/README.md
README.md: 49f38e5af8f0939dd8f1ccafcd7928b10954ca33
README.zh.md: 57112fc5ce88567ecfe415ed7ee4dd5ac9d34224
README.md: 0516fd93f2887eedede30effde2b79e8c5adde10
README.zh.md: ef7db2e48a28671d56d408969c5f627e74cfafec
@@ -70,6 +70,8 @@ References keep local Session data, scoped Contexts, and history streams alive,
`SessionMediaReferences` mounts `GET|HEAD /api/file?path=<absolute path>` on the authenticated `connection.fetch` channel when `connection`, `fs`, and `attachments` are composed. It reads ordinary files through `ctx.fs`, including temporary paths outside registered workspaces and files in remote providers. Neither directory containment nor MIME categories restrict access; `mime-types` supplies the response type, with `application/octet-stream` for unknown extensions. GET reuses `readBytes` for preflight and ongoing byte limits; HEAD reads metadata only. All files use `ctx.attachments.imageLimits.maxImageBytes` (normally 20 MiB); exceeding this limit returns 413. Responses contain the complete file, ignore Range, and carry `private, no-store`, `nosniff`, and a sandbox CSP so directly opened HTML/SVG cannot execute with the API origin. The Client rewrite lives in `ui-chat` (`AssistantMarkdown`); audio/video responses are available, while Markdown audio/video player nodes remain separate work.
`workspacePathApplications({ path })` returns the serving desktop’s file handlers after the same filesystem mapping check used by `openWorkspacePath`. An optional `application` in the open request selects a currently registered handler without changing the system default. Application names, default selection, icons, and platform coverage come from [native-command](../../util/native-command/README.md). These operations do not activate an Agent or append Session events. Native failures return bounded messages; original command errors remain Host-side causes.
-----
<a id="configuration"></a>
@@ -70,6 +70,8 @@ Fork 复制 `atSeq` 所选的精确事件前缀,包含切点事件,允许在
当 `connection`、`fs` 与 `attachments` 均被组合时,`SessionMediaReferences` 在鉴权 `connection.fetch` 通道上挂载 `GET|HEAD /api/file?path=<绝对路径>`。它通过 `ctx.fs` 读取普通文件,包括已注册工作区之外的临时路径与远程提供方中的文件。目录包含关系与 MIME 类别均不限制访问;`mime-types` 提供响应类型,未知扩展名使用 `application/octet-stream`。GET 复用 `readBytes` 执行读取前及读取中的字节限制;HEAD 只读取元数据。所有文件均使用 `ctx.attachments.imageLimits.maxImageBytes`(通常为 20 MiB);超过此上限返回 413。响应包含完整文件,忽略 Range,并携带 `private, no-store`、`nosniff` 与沙箱 CSP,使直接打开的 HTML/SVG 无法以 API 源身份执行脚本。客户端重写位于 `ui-chat`(`AssistantMarkdown`);音视频文件响应已可用,Markdown 音视频播放器节点仍是独立工作。
`workspacePathApplications({ path })` 使用与 `openWorkspacePath` 相同的文件系统映射校验,返回服务端桌面上该文件的关联应用。打开请求中的可选 `application` 指定当前关联的应用,不修改系统默认应用。应用名称、默认项、图标和平台支持范围由 [native-command](../../util/native-command/README.zh.md) 提供。这些操作不激活 Agent,也不追加会话事件。原生操作失败时返回简短消息,原始命令异常作为 Host 端原因保留。
-----
<a id="configuration"></a>
+52 -19
View File
@@ -8,7 +8,7 @@ import { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { errorChain } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-client-file-upload'
import { canOpenNativePath, nativeFileManager, openNativeAssociatedPath, revealNativePath } from '@deepseek-ai/dsh-native-command'
import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativeFileApplication, openNativeAssociatedPath, revealNativePath } from '@deepseek-ai/dsh-native-command'
import type { SessionId } from '@deepseek-ai/dsh-session'
import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence'
import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query'
@@ -29,6 +29,7 @@ import { SessionSkillCatalog } from './skill-catalog.ts'
import { SessionMediaReferences } from './media-references.ts'
import type {
ModelCatalog,
SessionWorkspacePathApplication,
SessionAttachmentRequest,
SessionAttachmentValue,
SessionCancelRequest,
@@ -83,6 +84,10 @@ export interface Config {
export interface SessionControllerInternals {
/** Native default-application handoff. */
readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
/** Native file-association query. */
readonly fileApplications?: typeof nativeFileApplications
/** Explicit registered-application handoff. */
readonly openFileApplication?: typeof openNativeFileApplication
/** Native file-manager handoff. */
readonly revealPath?: (path: string, signal: AbortSignal) => Promise<void>
/** Native handoff availability probe. */
@@ -115,6 +120,8 @@ export class SessionController extends TypertRemoteService {
private readonly history: SessionHistoryController
private readonly listState: ApiSessionList
private readonly openPath: (path: string, signal: AbortSignal) => Promise<void>
private readonly fileApplications: typeof nativeFileApplications
private readonly openFileApplication: typeof openNativeFileApplication
private readonly revealPath: (path: string, signal: AbortSignal) => Promise<void>
private readonly canOpenPath: () => boolean
private readonly promotions = new Set<Promise<void>>()
@@ -142,6 +149,8 @@ export class SessionController extends TypertRemoteService {
}, 'session-controller.promotions')
this.history = new SessionHistoryController(ctx, (observation) => { this.promote(observation) })
this.listState = new ApiSessionList(ctx)
this.fileApplications = internals.fileApplications ?? nativeFileApplications
this.openFileApplication = internals.openFileApplication ?? openNativeFileApplication
this.openPath = internals.openPath ?? openNativeAssociatedPath
this.revealPath = internals.revealPath ?? revealNativePath
this.canOpenPath = internals.canOpenPath
@@ -309,35 +318,59 @@ export class SessionController extends TypertRemoteService {
request: SessionOpenWorkspacePathRequest,
signal: AbortSignal,
): Promise<SessionOpenWorkspacePathValue> {
if (request.path.length === 0) {
throw new RemoteError(
'gateway/bad-request',
'session.openWorkspacePath requires a non-empty path',
{},
)
}
signal.throwIfAborted()
try {
const hostPath = resolve(request.path)
const { fs } = this.ctx
const mapped = fs.processPathFromHostPath(hostPath)
if (mapped === undefined || fs.processPath(await fs.resolve(mapped, { signal })) !== hostPath) {
throw new Error('Path has no verified Host path')
}
signal.throwIfAborted()
if (request.action === 'reveal') await this.revealPath(request.path, signal)
else await this.openPath(request.path, signal)
const path = await this.verifyDesktopPath(request.path, signal)
if (request.action === 'reveal') await this.revealPath(path, signal)
else if (request.application !== undefined) await this.openFileApplication(path, request.application, signal)
else await this.openPath(path, signal)
return { opened: true }
} catch (error: unknown) {
if (signal.aborted) throw new RemoteError('gateway/cancelled', 'path open was aborted', {})
if (error instanceof RemoteError) throw error
throw new RemoteError(
'gateway/internal',
`path open failed: ${error instanceof Error ? error.message : String(error)}`,
'path open failed',
{},
{ cause: error },
)
}
}
/**
* Query current file handlers on the serving desktop without activating an Agent.
* @param request - file path in Host filesystem syntax.
* @param signal - caller lifetime, propagated to filesystem and desktop queries.
* @returns OS application names, icons, and default selection; empty when desktop opening is unavailable.
* @throws RemoteError when the path is invalid, the query is cancelled, or native discovery fails.
*/
@Remote('workspacePathApplications')
async workspacePathApplications(
request: { readonly path: string }, signal: AbortSignal,
): Promise<readonly SessionWorkspacePathApplication[]> {
if (!this.canOpenPath()) return []
try {
const path = await this.verifyDesktopPath(request.path, signal)
return await this.fileApplications(path, signal)
} catch (error: unknown) {
if (signal.aborted) throw new RemoteError('gateway/cancelled', 'application query was aborted', {})
if (error instanceof RemoteError) throw error
throw new RemoteError('gateway/internal', 'file application query failed', {}, { cause: error })
}
}
private async verifyDesktopPath(path: string, signal: AbortSignal): Promise<string> {
if (path.length === 0) throw new RemoteError('gateway/bad-request', 'A non-empty file path is required', {})
signal.throwIfAborted()
const hostPath = resolve(path)
const { fs } = this.ctx
const mapped = fs.processPathFromHostPath(hostPath)
if (mapped === undefined || fs.processPath(await fs.resolve(mapped, { signal })) !== hostPath) {
throw new RemoteError('gateway/bad-request', 'Path has no verified Host path', {})
}
signal.throwIfAborted()
return hostPath
}
/**
* Rename one Session after explicitly resuming it.
* @param request - Session identity and proposed title.
@@ -1,4 +1,5 @@
/** Browser-safe request, result, and lifecycle vocabulary for the Session Remote service. */
import type { NativeFileApplication } from '@deepseek-ai/dsh-native-command/types'
import type {
AttachmentIdType, ImageAttachmentLimits, ImageAttachmentRef, ImageMediaType,
@@ -381,6 +382,8 @@ export interface SessionCancelValue {
export interface SessionOpenWorkspacePathRequest {
/** File-manager navigation when requested; omission uses the default application. */
readonly action?: 'reveal'
/** Registered application identifier; ignored for reveal. Omission preserves the operating system default. */
readonly application?: string
/** Path after best-effort Session workspace resolution, in Host filesystem syntax. */
readonly path: string
}
@@ -624,3 +627,6 @@ declare module '@deepseek-ai/cordis' {
/** JSON-compatible projection value accepted by list consumers. */
export type SessionProjectionValue = JsonValue
/** Application metadata returned by the serving desktop for one file. */
export type SessionWorkspacePathApplication = NativeFileApplication
@@ -1,3 +1,4 @@
import { resolve } from 'node:path'
import * as nativeCommand from '@deepseek-ai/dsh-native-command'
import { Context } from '@deepseek-ai/cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
@@ -65,11 +66,11 @@ describe('session/openWorkspacePath', () => {
await expect(remote.openWorkspacePath({ path: '/workspace/project/src/a.ts' }, signal))
.resolves.toEqual({ ok: true, value: { opened: true } })
expect(openPath).toHaveBeenCalledWith('/workspace/project/src/a.ts', signal)
expect(openPath).toHaveBeenCalledWith(resolve('/workspace/project/src/a.ts'), signal)
expect(ctx.agents.list()).toEqual([])
})
it('preserves relative and absolute Host-resolvable paths', async () => {
it('normalizes relative and absolute Host-resolvable paths', async () => {
const ctx = await context()
const openPath = vi.fn((_path: string, _signal: AbortSignal) => Promise.resolve())
const remote = createSessionTestRemote(ctx, {
@@ -80,7 +81,7 @@ describe('session/openWorkspacePath', () => {
await remote.openWorkspacePath({ path: '/workspace/result.html' })
await remote.openWorkspacePath({ path: 'result.html' })
expect(openPath.mock.calls.map(call => call[0])).toEqual(['/workspace/result.html', 'result.html'])
expect(openPath.mock.calls.map(call => call[0])).toEqual([resolve('/workspace/result.html'), resolve('result.html')])
})
it('rejects empty paths before opening anything', async () => {
@@ -100,7 +101,7 @@ describe('session/openWorkspacePath', () => {
it('preserves native opener failure and cancellation results', async () => {
const ctx = await context()
const openPath = vi.fn((_path: string, _signal: AbortSignal) =>
Promise.reject(new Error('desktop unavailable')))
Promise.reject(new Error('Command failed: powershell.exe -EncodedCommand private-script-text')))
const remote = createSessionTestRemote(ctx, {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
cwd: '/default',
@@ -110,7 +111,7 @@ describe('session/openWorkspacePath', () => {
await expect(remote.openWorkspacePath({ path: 'result.html' }))
.resolves.toMatchObject({
ok: false,
error: { code: 'gateway/internal', message: 'path open failed: desktop unavailable' },
error: { code: 'gateway/internal', message: 'path open failed' },
})
const aborted = new AbortController()
@@ -139,7 +140,7 @@ describe('session/openWorkspacePath', () => {
await expect(controller.openWorkspacePath({
path: 'second.html',
}, new AbortController().signal)).rejects.toMatchObject({
code: 'gateway/internal', message: 'path open failed: desktop unavailable',
code: 'gateway/internal', message: 'path open failed',
})
})
})
@@ -156,7 +157,7 @@ it('reports Host file-manager metadata and dispatches reveal separately from def
expect(controller.workspaceDesktop()).toMatchObject({ available: true, name: expect.any(String) as string })
const signal = new AbortController().signal
await controller.openWorkspacePath({ path: '/workspace/report.txt', action: 'reveal' }, signal)
expect(revealPath).toHaveBeenCalledWith('/workspace/report.txt', signal)
expect(revealPath).toHaveBeenCalledWith(resolve('/workspace/report.txt'), signal)
expect(openPath).not.toHaveBeenCalled()
} finally { await ctx.fiber.dispose() }
})
@@ -186,7 +187,7 @@ it.each(['open', 'reveal'] as const)('rejects an unmapped remote path before nat
defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/default', openPath, revealPath,
})
await expect(controller.openWorkspacePath({ path: '/remote/report.html', ...(action === 'reveal' ? { action } : {}) }, new AbortController().signal))
.rejects.toMatchObject({ code: 'gateway/internal', message: 'path open failed: Path has no verified Host path' })
.rejects.toMatchObject({ code: 'gateway/bad-request', message: 'Path has no verified Host path' })
expect(openPath).not.toHaveBeenCalled()
expect(revealPath).not.toHaveBeenCalled()
})
@@ -200,7 +201,7 @@ it('rejects a filesystem mapping that resolves to another process path', async (
defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/default', openPath,
})
await expect(controller.openWorkspacePath({ path: '/report.html' }, new AbortController().signal))
.rejects.toMatchObject({ code: 'gateway/internal', message: 'path open failed: Path has no verified Host path' })
.rejects.toMatchObject({ code: 'gateway/bad-request', message: 'Path has no verified Host path' })
expect(openPath).not.toHaveBeenCalled()
})
@@ -213,5 +214,61 @@ it('dispatches default-app opening to the association adapter', async () => {
})
const signal = new AbortController().signal
await controller.openWorkspacePath({ path: '/report.html' }, signal)
expect(open).toHaveBeenCalledWith('/report.html', signal)
expect(open).toHaveBeenCalledWith(resolve('/report.html'), signal)
})
it('uses the same path verification for handler queries and explicit application opening', async () => {
const ctx = await context()
const applications = [{ id: '/Applications/Music.app', name: 'Music', default: true, icon: null }]
const fileApplications = vi.fn(async () => applications)
const openFileApplication = vi.fn(async () => {})
const controller = createSessionTestController(ctx, {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/default', nativeOpen: true,
fileApplications, openFileApplication,
})
const signal = new AbortController().signal
expect(await controller.workspacePathApplications({ path: '/file.mp3' }, signal)).toEqual(applications)
await controller.openWorkspacePath({ path: '/file.mp3', application: applications[0]!.id }, signal)
expect(openFileApplication).toHaveBeenCalledWith(expect.stringContaining('file.mp3'), applications[0]!.id, signal)
const mapping = vi.spyOn(ctx.fs, 'processPathFromHostPath').mockReturnValue(undefined)
onTestFinished(() => { mapping.mockRestore() })
await expect(controller.workspacePathApplications({ path: '/remote.mp3' }, signal)).rejects.toThrow('verified Host path')
await expect(controller.openWorkspacePath({ path: '/remote.mp3', application: applications[0]!.id }, signal)).rejects.toThrow('verified Host path')
expect(fileApplications).toHaveBeenCalledOnce()
expect(openFileApplication).toHaveBeenCalledOnce()
})
it('avoids desktop queries when unavailable and rejects an empty query path', async () => {
const fileApplications = vi.fn(async () => [])
const unavailable = createSessionTestController(await context(), {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/default', nativeOpen: false, fileApplications,
})
expect(await unavailable.workspacePathApplications({ path: '/file.mp3' }, new AbortController().signal)).toEqual([])
const available = createSessionTestController(await context(), {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/default', nativeOpen: true, fileApplications,
})
await expect(available.workspacePathApplications({ path: '' }, new AbortController().signal)).rejects.toMatchObject({ code: 'gateway/bad-request' })
expect(fileApplications).not.toHaveBeenCalled()
})
it('returns bounded query failures and classifies cancellation through the Remote', async () => {
const lifetime = new AbortController()
const fileApplications = vi.fn()
.mockRejectedValueOnce(new Error('Command failed: osascript -e private-script-text'))
.mockImplementationOnce(async () => {
lifetime.abort()
throw new Error('native query stopped')
})
const remote = createSessionTestRemote(await context(), {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/default', nativeOpen: true, fileApplications,
})
await expect(remote.workspacePathApplications({ path: '/file.mp3' })).resolves.toMatchObject({
ok: false, error: { code: 'gateway/internal', message: 'file application query failed' },
})
await expect(remote.workspacePathApplications({ path: '/file.mp3' }, lifetime.signal)).resolves.toMatchObject({
ok: false, error: { code: 'gateway/cancelled' },
})
})
@@ -1,4 +1,5 @@
/** Test-only direct Remote face over the Session Controller's internal controllers. */
import type { SessionControllerInternals } from '../src/index.ts'
import { SessionLogOffset } from '@deepseek-ai/dsh-session'
import type { Context } from '@deepseek-ai/cordis'
@@ -48,6 +49,7 @@ import type {
SessionListValue,
SessionOpenWorkspacePathRequest,
SessionOpenWorkspacePathValue,
SessionWorkspacePathApplication,
SessionPage,
SessionPageRequest,
SessionPromptRequest,
@@ -65,6 +67,9 @@ import type {
/** Direct test face matching the generated `ctx.remote.session` unary methods. */
export interface TestSessionRemote {
workspacePathApplications(
request: { readonly path: string }, signal?: AbortSignal,
): Promise<RemoteResult<readonly SessionWorkspacePathApplication[]>>
canOpenWorkspacePath(): Promise<RemoteResult<boolean>>
list(request: SessionListRequest, signal?: AbortSignal): Promise<RemoteResult<SessionListValue>>
search(request: SessionSearchRequest, signal?: AbortSignal): Promise<RemoteResult<SessionSearchValue>>
@@ -94,6 +99,8 @@ export interface TestSessionRemoteDefaults {
readonly nativeOpen?: boolean
readonly saveDefaultModelSelection?: (selection: AgentModelSelection) => void | Promise<void>
readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
readonly fileApplications?: SessionControllerInternals['fileApplications']
readonly openFileApplication?: SessionControllerInternals['openFileApplication']
readonly revealPath?: (path: string, signal: AbortSignal) => Promise<void>
readonly canOpenPath?: () => boolean
}
@@ -288,6 +295,8 @@ function installControllers(
},
{
...defaults.openPath === undefined ? {} : { openPath: defaults.openPath },
...defaults.fileApplications === undefined ? {} : { fileApplications: defaults.fileApplications },
...defaults.openFileApplication === undefined ? {} : { openFileApplication: defaults.openFileApplication },
...defaults.revealPath === undefined ? {} : { revealPath: defaults.revealPath },
...defaults.canOpenPath === undefined ? {} : { canOpenPath: defaults.canOpenPath },
},
@@ -334,6 +343,9 @@ export function createSessionTestRemote(
): TestSessionRemote {
const direct = createSessionTestController(ctx, defaults)
return {
workspacePathApplications: (request, signal = new AbortController().signal) => remoteResult(
() => direct.workspacePathApplications(request, signal), signal,
),
canOpenWorkspacePath: () => remoteResult(() => direct.canOpenWorkspacePath()),
list: (request, signal = new AbortController().signal) => remoteResult(
() => direct.list(request, signal),
@@ -28,6 +28,7 @@
{ "path": "../../util/crypto" },
{ "path": "../../util/workspace-path" },
{ "path": "../../workspace/workspace" },
{ "path": "../../typert/protocol" }
{ "path": "../../typert/protocol" },
{ "path": "../../util/native-command" }
]
}