Merge master and reconcile translation records
This commit is contained in:
commit
00a2e76b87
127 files changed
+4167
-557
No files matched your search
@@ -15,8 +15,8 @@
|
||||
en: 1fdf707322fb6996
|
||||
zh: 0204f7e9d4aa3cce
|
||||
/session-controller/use-this-package:
|
||||
en: 413cb0808730d48a
|
||||
zh: cfff51724b9dc2bf
|
||||
en: 495c01b3ae16ff22
|
||||
zh: 09848c0fe8384ba9
|
||||
/session-controller/client-references:
|
||||
en: e8979a803ec3e194
|
||||
zh: c567efcd971728ba
|
||||
|
||||
@@ -35,7 +35,7 @@ The Client journal validates current Session event envelopes before publishing f
|
||||
|
||||
Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values.
|
||||
|
||||
Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers the `session` resource kind with the default field `sessionId` through `typert.resources`. `session/page` and `session/follow` declare a `session` reader in `@Remote({ resources })` that reads `request.address.sessionId` for an ordinary Session address and `request.address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner.
|
||||
Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers a default resolver for the `session` resource kind through `typert.resources`. It reads a named `sessionId` parameter, otherwise the first object argument's `sessionId` or `address`; unrelated string parameters name no Session. An object containing both `sessionId` and `address` is invalid, even when they name the same Session. `session/page` and `session/follow` use this resolver to read `address.sessionId` for an ordinary Session address and `address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner.
|
||||
|
||||
List rows carry `formatStatus` when available, so Clients can identify migration-required Sessions without requesting their projections.
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ Client journal 在发布 follow 快照、live entry 或历史页之前验证当
|
||||
|
||||
每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。
|
||||
|
||||
每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `sessionId` 登记 `session` 资源种类。`session/page` 与 `session/follow` 在 `@Remote({ resources })` 中声明 `session` 读取函数:对普通 Session 地址读 `request.address.sessionId`,对 subagent 地址读 `request.address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。
|
||||
每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 为 `session` 资源种类登记默认 resolver。它读取具名 `sessionId` 参数,否则读取第一个对象参数的 `sessionId` 或 `address`;无关字符串参数不指明 Session。对象同时包含 `sessionId` 和 `address` 时无效,即使两者指向同一 Session。`session/page` 与 `session/follow` 使用该 resolver:对普通 Session 地址读 `address.sessionId`,对 subagent 地址读 `address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。
|
||||
|
||||
列表行在状态可用时携带 `formatStatus`,Client 无需请求其投影即可识别需要迁移的 Session。
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import { installModelSelection } from '@deepseek-ai/dsh-agent'
|
||||
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { Session, 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'
|
||||
import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type {} from '@deepseek-ai/dsh-typert-registry'
|
||||
@@ -123,40 +122,6 @@ export function apiSessionSubagentOwnershipError(sessionId: SessionId): ApiSessi
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect one cold Session without repairing, resuming, or publishing it.
|
||||
* @param ctx - Host context carrying Session persistence.
|
||||
* @param sessionId - durable Session identity.
|
||||
* @param signal - optional cancellation for persistence reads.
|
||||
* @returns the persisted header and complete event prefix.
|
||||
*/
|
||||
export async function inspectApiSession(
|
||||
ctx: Context,
|
||||
sessionId: SessionId,
|
||||
signal?: AbortSignal,
|
||||
): Promise<SessionInspection> {
|
||||
try {
|
||||
using observation = await ctx.sessionQuery.observeSession(sessionId, {
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
projectionMode: 'none',
|
||||
})
|
||||
if (observation.header.cwd === undefined) {
|
||||
throw new ApiSessionNotFound(`session "${sessionId}" not found`)
|
||||
}
|
||||
return {
|
||||
meta: observation.header,
|
||||
inheritedEventCount: observation.inheritedEventCount,
|
||||
events: [...observation.events],
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SessionQueryError
|
||||
&& error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
|
||||
throw new ApiSessionNotFound(`session "${sessionId}" not found`)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** Owns every operation that may create, resume, or configure a Web Agent. */
|
||||
export class ApiSessionAgentController {
|
||||
private readonly resumes = new Map<SessionId, Promise<Agent>>()
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
ApiSessionSubagentOwnership,
|
||||
apiSessionSubagentOwnershipError,
|
||||
hasApiSessionSubagentOwner,
|
||||
inspectApiSession,
|
||||
type ApiSessionCreated,
|
||||
} from './agent.ts'
|
||||
import type {
|
||||
@@ -54,12 +53,6 @@ import type {
|
||||
SessionRequestId,
|
||||
} from './types.ts'
|
||||
|
||||
interface SessionReadState {
|
||||
readonly id: SessionId
|
||||
readonly header: SessionHeader
|
||||
readonly events: readonly SessionEvent[]
|
||||
}
|
||||
|
||||
type PromptContentCandidate =
|
||||
| SessionPromptRequest['content'][number]
|
||||
| Extract<SessionUpdateQueueRequest['action'], { readonly kind: 'edit' }>['content'][number]
|
||||
@@ -371,11 +364,16 @@ export class SessionCommandController {
|
||||
* @returns the durable attachment reference and base64-encoded bytes.
|
||||
*/
|
||||
async attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue> {
|
||||
let source: SessionReadState
|
||||
let ref: ImageAttachmentRef | undefined
|
||||
try {
|
||||
source = await this.readSessionState(request.sessionId)
|
||||
using observation = await this.ctx.sessionQuery.observeSession(request.sessionId, { projectionMode: 'none' })
|
||||
if (observation.source === 'prepared' && observation.header.cwd === undefined) {
|
||||
throw new ApiSessionNotFound(`session "${request.sessionId}" not found`)
|
||||
}
|
||||
ref = referencedImage(observation.events, String(request.attachmentId))
|
||||
} catch (error) {
|
||||
if (error instanceof ApiSessionNotFound) {
|
||||
if (error instanceof ApiSessionNotFound
|
||||
|| (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND')) {
|
||||
throw new RemoteError('session/not-found', error.message, { sessionId: request.sessionId })
|
||||
}
|
||||
throw new RemoteError(
|
||||
@@ -384,7 +382,6 @@ export class SessionCommandController {
|
||||
{},
|
||||
)
|
||||
}
|
||||
const ref = referencedImage(source.events, String(request.attachmentId))
|
||||
if (ref === undefined) {
|
||||
throw new RemoteError(
|
||||
'session/attachment-invalid',
|
||||
@@ -533,16 +530,6 @@ export class SessionCommandController {
|
||||
throw new RemoteError('gateway/internal', `failed to create session: ${String(error)}`, {})
|
||||
}
|
||||
|
||||
private async readSessionState(sessionId: SessionId): Promise<SessionReadState> {
|
||||
const attached = this.ctx.sessions.get(sessionId)
|
||||
if (attached !== undefined) {
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
|
||||
return { id: attached.id, header: attached.header, events: attached.snapshotEvents() }
|
||||
}
|
||||
const inspected = await inspectApiSession(this.ctx, sessionId)
|
||||
return { id: inspected.meta.id, header: inspected.meta, events: inspected.events }
|
||||
}
|
||||
|
||||
private async forkWorkspace(source: SessionHeader): Promise<Workspace | undefined> {
|
||||
const workspaces = this.ctx.workspaceRegistry.list()
|
||||
const direct = workspaces.find(workspace => workspace.sessionIds.includes(source.id))
|
||||
|
||||
@@ -10,16 +10,14 @@ import { errorChain, ReasoningEffortId, type MessageSource } from '@deepseek-ai/
|
||||
import type {} from '@deepseek-ai/dsh-client-file-upload'
|
||||
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 type {} from '@deepseek-ai/dsh-session-projection-cache'
|
||||
import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query'
|
||||
import { Remote, RemoteError, TypertRemoteService, principalOf } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { Remote, RemoteError, TypertRemoteService, principalOf, type TypertResourceResolveInput } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import type {} from '@deepseek-ai/dsh-api-remote-access'
|
||||
import {
|
||||
ApiSessionAgentController,
|
||||
inspectApiSession,
|
||||
type ApiSessionAgentResult,
|
||||
} from './agent.ts'
|
||||
import { SessionCommandController, hasPromptContent } from './commands.ts'
|
||||
@@ -80,13 +78,31 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the Session resource a history address names: the Session itself, or
|
||||
* the child Session whose transcript a subagent address reads.
|
||||
* @param request - history request carrying the durable address.
|
||||
* @returns the Session whose access the read requires.
|
||||
* Extract the Session resource from an ID or a history address.
|
||||
*
|
||||
* Registers as the `session` kind default, so it applies to every Remote method of
|
||||
* every namespace: a top-level `sessionId` parameter, otherwise the first object
|
||||
* parameter carrying `sessionId` or an `address`. A new request type whose first
|
||||
* object parameter has an unrelated `address` field would be read as an address.
|
||||
* @param input - validated wire arguments and their ordered parameter descriptions.
|
||||
* @returns the named Session identity, otherwise the first object's Session identity or history address.
|
||||
* @throws Error when the request object supplies both sessionId and address.
|
||||
*/
|
||||
function addressedSession(request: { readonly address: SessionAddress }): SessionId {
|
||||
return request.address.kind === 'session' ? request.address.sessionId : request.address.childSessionId
|
||||
function resolveSessionResource({ args, parameters }: TypertResourceResolveInput): SessionId | undefined {
|
||||
const sessionParameter = parameters.find(parameter => parameter.name === 'sessionId' || parameter.wire === 'sessionId')
|
||||
if (sessionParameter !== undefined) return args[sessionParameter.wire] as SessionId | undefined
|
||||
for (const parameter of parameters) {
|
||||
const value = args[parameter.wire]
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) continue
|
||||
const request = value as { readonly sessionId?: SessionId; readonly address?: SessionAddress }
|
||||
const address = request.address
|
||||
if (request.sessionId !== undefined && address !== undefined) {
|
||||
throw new Error('Session resource request must not contain both sessionId and address')
|
||||
}
|
||||
return request.sessionId ?? (address === undefined ? undefined
|
||||
: address.kind === 'session' ? address.sessionId : address.childSessionId)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Session Controller deployment policy. */
|
||||
@@ -167,7 +183,7 @@ export class SessionController extends TypertRemoteService {
|
||||
|
||||
protected async [Service.init](): Promise<void> {
|
||||
const ctx = this.ctx
|
||||
ctx.typert.resources.register('session', { field: 'sessionId' })
|
||||
ctx.typert.resources.register('session', { resolve: resolveSessionResource })
|
||||
this.agents = new ApiSessionAgentController(ctx)
|
||||
this.agents.initialize()
|
||||
this.commands = new SessionCommandController(ctx, this.agents, process.cwd())
|
||||
@@ -240,28 +256,6 @@ export class SessionController extends TypertRemoteService {
|
||||
return this.agents.resolveAgent(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect one attached or persisted Session without activating its Agent.
|
||||
* @param sessionId - durable Session identity.
|
||||
* @param signal - optional caller cancellation for persistence reads.
|
||||
* @returns the current attached state or persisted header and event prefix.
|
||||
*/
|
||||
inspect(
|
||||
sessionId: SessionId,
|
||||
signal?: AbortSignal,
|
||||
): Promise<SessionInspection> {
|
||||
const attached = this.ctx.sessions.get(sessionId)
|
||||
if (attached !== undefined) {
|
||||
return Promise.resolve({
|
||||
meta: attached.header,
|
||||
inheritedEventCount: attached.inheritedEventCount,
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
|
||||
events: attached.snapshotEvents(),
|
||||
})
|
||||
}
|
||||
return inspectApiSession(this.ctx, sessionId, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read all visible Session rows without resuming an Agent.
|
||||
* @param _request - reserved empty list request.
|
||||
@@ -517,7 +511,7 @@ export class SessionController extends TypertRemoteService {
|
||||
* @param signal - cancellation for persistence reads.
|
||||
* @returns one chronological page.
|
||||
*/
|
||||
@Remote({ name: 'page', resources: { session: addressedSession } })
|
||||
@Remote('page')
|
||||
page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage> {
|
||||
return this.history.page(request, signal)
|
||||
}
|
||||
@@ -529,7 +523,7 @@ export class SessionController extends TypertRemoteService {
|
||||
* @returns a complete opening snapshot followed by gap-free durable event
|
||||
* frames and optional cursorless assistant-stream frames.
|
||||
*/
|
||||
@Remote({ mode: 'stream', resources: { session: addressedSession } })
|
||||
@Remote({ mode: 'stream' })
|
||||
follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame> {
|
||||
return this.history.follow(request, signal)
|
||||
}
|
||||
@@ -610,9 +604,6 @@ export class SessionController extends TypertRemoteService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
export { buildModelCatalog }
|
||||
export default SessionController
|
||||
@@ -6,7 +6,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionObservation } from '@deepseek-ai/dsh-session-query'
|
||||
@@ -15,8 +15,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
ApiSessionAgentController,
|
||||
ApiSessionCwdConflict,
|
||||
ApiSessionNotFound,
|
||||
inspectApiSession,
|
||||
} from '../src/agent.ts'
|
||||
import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts'
|
||||
|
||||
@@ -83,61 +81,6 @@ describe('ApiSession identity failures', () => {
|
||||
expect(new ApiSessionCwdConflict(SessionId('wrong-cwd'), '/wanted', '/existing').message)
|
||||
.toContain('belongs to "/existing"')
|
||||
})
|
||||
|
||||
it('maps absent and cwd-less point observations to not found', async () => {
|
||||
const ctx = new Context()
|
||||
roots.push(ctx)
|
||||
await ctx.plugin(SessionStore)
|
||||
installSessionReadTestServices(ctx)
|
||||
await expect(inspectApiSession(ctx, SessionId('missing')))
|
||||
.rejects.toBeInstanceOf(ApiSessionNotFound)
|
||||
|
||||
const inspect = vi.fn(() => Promise.resolve(undefined))
|
||||
const stat = vi.fn(() => Promise.resolve(undefined))
|
||||
const disposeMissing = providePersistence(ctx, {
|
||||
list: () => Promise.resolve([]),
|
||||
stat,
|
||||
inspect,
|
||||
})
|
||||
await expect(inspectApiSession(ctx, SessionId('missing'))).rejects.toBeInstanceOf(ApiSessionNotFound)
|
||||
// Absence is decided by the stat preflight; the log itself is never opened.
|
||||
expect(stat).toHaveBeenCalledOnce()
|
||||
expect(inspect).not.toHaveBeenCalled()
|
||||
disposeMissing()
|
||||
|
||||
const listed = header('cwd-less-catalog', null)
|
||||
const disposeListed = providePersistence(ctx, {
|
||||
list: () => Promise.resolve([listed]),
|
||||
inspect: () => Promise.resolve({ meta: listed, events: [] }),
|
||||
})
|
||||
await expect(inspectApiSession(ctx, listed.id)).rejects.toBeInstanceOf(ApiSessionNotFound)
|
||||
disposeListed()
|
||||
|
||||
const catalog = header('cwd-less-inspect')
|
||||
const inspected = header('cwd-less-inspect', null)
|
||||
providePersistence(ctx, {
|
||||
list: () => Promise.resolve([catalog]),
|
||||
inspect: () => Promise.resolve({ meta: inspected, events: [] }),
|
||||
})
|
||||
await expect(inspectApiSession(ctx, catalog.id)).rejects.toBeInstanceOf(ApiSessionNotFound)
|
||||
})
|
||||
|
||||
it('forwards an explicit inspection signal', async () => {
|
||||
const ctx = new Context()
|
||||
roots.push(ctx)
|
||||
await ctx.plugin(SessionStore)
|
||||
installSessionReadTestServices(ctx)
|
||||
const meta = header('signalled-inspection')
|
||||
const inspect = vi.fn(() => Promise.resolve({ meta, inheritedEventCount: SessionLogOffset(0), events: [] }))
|
||||
providePersistence(ctx, {
|
||||
list: () => Promise.resolve([meta]),
|
||||
inspect,
|
||||
})
|
||||
const signal = new AbortController().signal
|
||||
|
||||
await expect(inspectApiSession(ctx, meta.id, signal)).resolves.toEqual({ meta, inheritedEventCount: SessionLogOffset(0), events: [] })
|
||||
expect(inspect).toHaveBeenCalledWith(meta.id, signal)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ApiSession Agent lookup and recovery', () => {
|
||||
|
||||
@@ -342,6 +342,7 @@ function event(type: string, seq: SessionSeq, data: unknown): SessionEvent {
|
||||
async function persistedController(
|
||||
events: SessionEvent[],
|
||||
readImage: (ref: ImageAttachmentRef) => Promise<{ ref: ImageAttachmentRef; data: Uint8Array }>,
|
||||
workspace: Pick<SessionHeader, 'cwd'> = { cwd: '/workspace' },
|
||||
): Promise<{ ctx: Context; controller: SessionCommandController; sessionId: SessionId }> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
@@ -350,7 +351,7 @@ async function persistedController(
|
||||
version: SESSION_FORMAT_VERSION,
|
||||
id: sessionId,
|
||||
createdAt: 1,
|
||||
cwd: '/workspace',
|
||||
...workspace,
|
||||
isSeeded: false,
|
||||
}
|
||||
ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
|
||||
@@ -563,6 +564,23 @@ describe('Session attachment authorization', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a cold Session without cwd before reading its referenced image', async () => {
|
||||
const ref = imageRef('missing-cwd')
|
||||
const readImage = vi.fn(async () => ({ ref, data: new Uint8Array([1]) }))
|
||||
const fixture = await persistedController(
|
||||
[event('user/message', SessionSeq(0), { id: 'image', role: 'user', source: { kind: 'user' }, content: [{ type: 'image', attachment: ref }] })],
|
||||
readImage,
|
||||
{},
|
||||
)
|
||||
try {
|
||||
await expect(fixture.controller.attachment({ sessionId: fixture.sessionId, attachmentId: ref.attachmentId }))
|
||||
.rejects.toMatchObject({ code: 'session/not-found', details: { sessionId: fixture.sessionId } })
|
||||
expect(readImage).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
await fixture.ctx.fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('maps a cold observation failure to an internal authorization error', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
|
||||
@@ -63,13 +63,6 @@ describe('SessionController facade', () => {
|
||||
ctx.on('api-session/error', failure)
|
||||
ctx.on('api-session/activity', activity)
|
||||
|
||||
await expect(controller.inspect(sessionId)).resolves.toEqual({
|
||||
meta: header,
|
||||
inheritedEventCount: SessionLogOffset(0),
|
||||
events,
|
||||
})
|
||||
expect(inspect).toHaveBeenCalledOnce()
|
||||
|
||||
const session = ctx.sessions.create(sessionId, { meta: header })
|
||||
const agent = {
|
||||
id: sessionId,
|
||||
@@ -91,12 +84,6 @@ describe('SessionController facade', () => {
|
||||
await expect(resolveUploadAgent(sessionId)).rejects.toBe(activationError)
|
||||
|
||||
await expect(controller.resolveAgent(sessionId)).resolves.toEqual({ agent })
|
||||
await expect(controller.inspect(sessionId)).resolves.toEqual({
|
||||
meta: header,
|
||||
inheritedEventCount: SessionLogOffset(0),
|
||||
events,
|
||||
})
|
||||
expect(inspect).toHaveBeenCalledOnce()
|
||||
ctx.emit('agent/status', { agent, status: 'running' })
|
||||
ctx.emit('agent/error', { agent, turn: 1, step: 0, error: new Error('fixture failure') })
|
||||
session.append('user/message', createUserMessage({
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Session Controller under non-owner callers: the Session resource kind it
|
||||
* registers, the Session readers of `session/page` and `session/follow`,
|
||||
* `session/list`, `session/search`, and `session/control` called through a
|
||||
* `global` role and filtered per Session through `remoteAccess.allows()`, the caller recorded
|
||||
* on prompt sources, and `session/projections` admitted per Session through
|
||||
* the Gateway.
|
||||
* registers and its default resolver, which supplies the identities of
|
||||
* `session/page` and `session/follow`, `session/list`, `session/search`, and
|
||||
* `session/control` called through a `global` role and filtered per Session
|
||||
* through `remoteAccess.allows()`, the caller recorded on prompt sources, and
|
||||
* `session/projections` admitted per Session through the Gateway.
|
||||
*/
|
||||
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
@@ -86,8 +86,8 @@ async function harness(): Promise<{
|
||||
await ctx.plugin(TypertRegistry)
|
||||
await mountAgentLoopTestDependencies(ctx)
|
||||
const loop = await mountAgentLoopTestHarness(ctx)
|
||||
const shared = await loop.create(SHARED)
|
||||
const hidden = await loop.create(PRIVATE)
|
||||
const shared = await loop.create(SHARED, {}, { cwd: '/tmp' })
|
||||
const hidden = await loop.create(PRIVATE, {}, { cwd: '/tmp' })
|
||||
const controller = await createSessionTestController(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
|
||||
const as = (principal: Principal, method: string): Context => {
|
||||
const invocation: RemoteInvocation = {
|
||||
@@ -107,18 +107,77 @@ function message(text: string) {
|
||||
}
|
||||
|
||||
describe('Session Controller access', () => {
|
||||
it('owns the Session resource kind and its default sessionId field', async () => {
|
||||
it('owns the Session resource kind and its default resolver', async () => {
|
||||
const { ctx } = await harness()
|
||||
expect(() => ctx.typert.resources.register('session', { field: 'sessionId' })).toThrow(/already registered/)
|
||||
})
|
||||
|
||||
it('reads the Session resource of page and follow requests from the addressed Session', async () => {
|
||||
const { controller } = await harness()
|
||||
const { ctx, controller } = await harness()
|
||||
const resource = ctx.typert.resources.get('session')
|
||||
if (resource?.resolve === undefined) throw new Error('Session resource resolver is missing')
|
||||
for (const method of ['page', 'follow']) {
|
||||
const reader = remoteMethods(controller).find(marker => marker.method === method)?.resources?.['session']
|
||||
expect(reader?.({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED)
|
||||
// A subagent address reads the child transcript; whether the parent's access covers it is the policy's rule.
|
||||
expect(reader?.({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE)
|
||||
const marker = remoteMethods(controller).find(marker => marker.method === method)
|
||||
expect(marker).toBeDefined()
|
||||
expect(marker?.resources?.['session']).toBeUndefined()
|
||||
}
|
||||
const resolve = (request: unknown) => resource.resolve({ args: { request }, parameters: [{ name: 'request', wire: 'request' }] })
|
||||
expect(resolve({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED)
|
||||
expect(resolve({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE)
|
||||
})
|
||||
|
||||
it('resolves named Session IDs and first-object requests without treating unrelated strings as identities', async () => {
|
||||
const { ctx } = await harness()
|
||||
const resource = ctx.typert.resources.get('session')
|
||||
if (resource?.resolve === undefined) throw new Error('Session resource resolver is missing')
|
||||
const resolve = (args: Readonly<Record<string, unknown>>, ...names: string[]) => resource.resolve({
|
||||
args, parameters: names.map(name => ({ name, wire: name })),
|
||||
})
|
||||
expect(resolve({ sessionId: SHARED, zzz: 'other' }, 'sessionId', 'zzz')).toBe(SHARED)
|
||||
expect(resolve({ options: { sessionId: SHARED }, yyy: 'other' }, 'options', 'yyy')).toBe(SHARED)
|
||||
expect(resolve({ options: { address: { kind: 'session', sessionId: SHARED } }, xxx: 'other' }, 'options', 'xxx')).toBe(SHARED)
|
||||
expect(resolve({ options: { address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } } }, 'options')).toBe(PRIVATE)
|
||||
expect(resolve({ ns: SHARED, value: 'other' }, 'ns', 'value')).toBeUndefined()
|
||||
expect(resolve({ ref: SHARED, value: 'other' }, 'ref', 'value')).toBeUndefined()
|
||||
expect(resolve({ zzz: 'other', sessionId: SHARED }, 'zzz', 'sessionId')).toBe(SHARED)
|
||||
expect(resolve({ first: {}, later: { sessionId: SHARED } }, 'first', 'later')).toBeUndefined()
|
||||
expect(resolve({ count: 1, tags: [], empty: null, options: { sessionId: SHARED } }, 'count', 'tags', 'empty', 'options')).toBe(SHARED)
|
||||
expect(resolve({}, 'sessionId')).toBeUndefined()
|
||||
expect(resolve({})).toBeUndefined()
|
||||
expect(resource.resolve({ args: { target: SHARED }, parameters: [{ name: 'sessionId', wire: 'target' }] })).toBe(SHARED)
|
||||
})
|
||||
|
||||
it.each(['page', 'follow'])('authorizes %s by Address and rejects coexisting Session IDs through SRC dispatch', async (method) => {
|
||||
const { ctx, shared, hidden } = await harness()
|
||||
shared.inbox.append('next-turn', message('shared history'))
|
||||
hidden.inbox.append('next-turn', message('private history'))
|
||||
await ctx.plugin(TypertGatewayService)
|
||||
guestPolicy(ctx, {
|
||||
role: { name: 'test:history-reader', resource: 'session', actions: ['session/page', 'session/follow'] },
|
||||
resource: { kind: 'session', id: SHARED },
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const peer: PeerScope = { id: 'history-access-peer' as PeerId, ctx, principal: GUEST, interactions: 'answer', signal: abort.signal, dispose: async () => {} }
|
||||
const invoke = async (request: Record<string, unknown>): Promise<unknown> => {
|
||||
const call = { peer, namespace: 'session', method, args: { request }, signal: abort.signal }
|
||||
if (method === 'page') return ctx.typertGateway.invoke(call)
|
||||
const stream = (await ctx.typertGateway.stream(call))[Symbol.asyncIterator]()
|
||||
try {
|
||||
return (await stream.next()).value
|
||||
} finally {
|
||||
await stream.return?.()
|
||||
}
|
||||
}
|
||||
const request = (sessionId: SessionId) => ({ address: { kind: 'session', sessionId }, throughSeq: 0 })
|
||||
try {
|
||||
await expect(invoke(request(SHARED))).resolves.toBeDefined()
|
||||
await expect(invoke(request(PRIVATE))).rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'no-allow' } })
|
||||
for (const target of [SHARED, PRIVATE]) {
|
||||
await expect(invoke({ ...request(target), sessionId: SHARED }))
|
||||
.rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'resource-invalid' } })
|
||||
}
|
||||
} finally {
|
||||
abort.abort()
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user