merge: update the MCP manager with master
This commit is contained in:
commit
4e796f736e
569 files changed
+13876
-2216
No files matched your search
@@ -15,8 +15,8 @@
|
||||
en: 1fdf707322fb6996
|
||||
zh: 0204f7e9d4aa3cce
|
||||
/session-controller/use-this-package:
|
||||
en: 8fcfa14545bd9d1c
|
||||
zh: c10c2bba792699ef
|
||||
en: fe242dda6579245e
|
||||
zh: cbd8c012135623de
|
||||
/session-controller/client-references:
|
||||
en: 41bdda1ac32df558
|
||||
zh: aa5d0e325924066b
|
||||
|
||||
@@ -33,7 +33,7 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se
|
||||
|
||||
The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host.
|
||||
|
||||
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`. 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.
|
||||
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`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. A prompt enters the Agent through [`ctx.agentController.deliver`](../../core/agent-controller/README.md#use-this-package), which runs the receipt resolution and attachment storage in the Agent's delivery order and binds the receipts immediately before the message enters the inbox, so the call stays open while an `agent-controller/admission` listener holds it. An image prompt takes the Session's image admission turn when its preparation starts and keeps it until the prompt settles, so a model selection lands either before its image check or after it entered the inbox, and waits while a listener holds that image prompt. A refusal returns `session/prompt-rejected` with the listener's `reason` and `presented`, a listener failure returns the same code with reason `agent-controller/admission-failed`, and an Agent disposed meanwhile returns `session/not-found`. A client that predates `session/prompt-rejected` shows it as an ordinary failure with its message and code. 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.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ kind: "package-reference"
|
||||
|
||||
Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。
|
||||
|
||||
每个 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 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。
|
||||
每个 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 重试直接返回原来的接受结果,不会重复插入消息。提示词经 [`ctx.agentController.deliver`](../../core/agent-controller/README.zh.md#use-this-package) 进入 Agent:控制器按该 Agent 的投递顺序完成凭证解析与附件存储,并在消息进入收件箱前一刻绑定凭证,因此 `agent-controller/admission` 监听器暂留它期间调用保持未完成。图片提示词在开始准备时取得该 Session 的图片准入顺位,并持有到提示词结束,因此模型切换要么发生在它的图片检查之前,要么发生在它进入收件箱之后;监听器暂留这条图片提示词期间,模型切换会等待。被拒绝时返回 `session/prompt-rejected`,并带上监听器给出的 `reason` 与 `presented`;监听器失败时返回同一错误码,reason 为 `agent-controller/admission-failed`;期间 Agent 被销毁则返回 `session/not-found`。早于 `session/prompt-rejected` 的旧客户端把它显示为普通失败,带消息与错误码。只有 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。
|
||||
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-agent": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-controller": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-default-model": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-preset-registry": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-gateway": "workspace:*",
|
||||
@@ -125,6 +126,7 @@
|
||||
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-agent": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-controller": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-default-model": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-loop": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-loop-testkit": "workspace:*",
|
||||
|
||||
@@ -387,6 +387,27 @@ export class ApiSessionAgentController {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Take the image admission turn for one Agent: wait until earlier image
|
||||
* admissions and model selections settled, then hold the turn until the
|
||||
* returned release runs.
|
||||
* @param agent - live Agent that owns the serialization chain.
|
||||
* @param signal - the waiting caller's cancellation; a caller cancelled by its turn passes the turn on.
|
||||
* @returns the release, which the caller runs once its image prompt settled.
|
||||
* @throws the cancellation reason when the caller was cancelled by its turn.
|
||||
*/
|
||||
acquireImageAdmission(agent: Agent, signal: AbortSignal): Promise<() => void> {
|
||||
const previous = this.imageAdmissionChains.get(agent) ?? Promise.resolve()
|
||||
const held = Promise.withResolvers<undefined>()
|
||||
this.imageAdmissionChains.set(agent, previous.then(() => held.promise))
|
||||
const release = (): void => { held.resolve(undefined) }
|
||||
return previous.then(() => {
|
||||
if (signal.aborted) release()
|
||||
signal.throwIfAborted()
|
||||
return release
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the preset id and pre-publication Agent setup for a create or resume.
|
||||
* @param presetId - requested preset or the configured default when omitted.
|
||||
|
||||
@@ -5,14 +5,15 @@ import { randomUUID } from 'node:crypto'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { Agent, ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent'
|
||||
import type { ADMISSION_AGENT_GONE, ADMISSION_REJECTED_CODE, AgentAdmissionRejected } from '@deepseek-ai/dsh-agent-controller'
|
||||
import { AttachmentError } from '@deepseek-ai/dsh-attachment'
|
||||
import type {
|
||||
AttachmentAdmissionPart, FileAttachmentRef, ImageAttachmentRef,
|
||||
} from '@deepseek-ai/dsh-attachment'
|
||||
import type { FileUploadReceiptId } from '@deepseek-ai/dsh-client-file-upload/types'
|
||||
import type {} from '@deepseek-ai/dsh-client-file-upload'
|
||||
import type { PromptFileBinding } from '@deepseek-ai/dsh-client-file-upload'
|
||||
import {
|
||||
ReasoningEffortId, assistantStreamChunks, createUserMessage, freezeMessage,
|
||||
ReasoningEffortId, assistantStreamChunks, freezeMessage,
|
||||
} from '@deepseek-ai/dsh-llm'
|
||||
import type { MessageSource } from '@deepseek-ai/dsh-llm'
|
||||
import { buildForkSeed } from '@deepseek-ai/dsh-session/fork'
|
||||
@@ -310,56 +311,72 @@ export class SessionCommandController {
|
||||
}
|
||||
|
||||
/**
|
||||
* Admit one prompt after Agent and attachment validation; the Remote method
|
||||
* has already validated the content and built the durable message source.
|
||||
* Deliver one prompt through the Agent controller, whose admission stage
|
||||
* may hold or refuse it; the Remote method has already validated the
|
||||
* content and built the durable message source. The controller runs this
|
||||
* Session's content preparation (image model check, upload receipts,
|
||||
* attachment storage) in the Agent's delivery order and binds the upload
|
||||
* receipts immediately before the message enters the inbox. A repeated
|
||||
* request identity is acknowledged without delivering it again. An image
|
||||
* prompt takes the Session's image admission turn when its preparation
|
||||
* starts and keeps it until the prompt settles, so a model selection lands
|
||||
* either before its image check or after it entered the inbox; a selection
|
||||
* waits while a listener holds that image prompt.
|
||||
* @param request - Session identity, prompt content, and delivery mode.
|
||||
* @param source - the `user-rpc` source recorded on the accepted message.
|
||||
* @param signal - the requesting client's cancellation; it stops a prompt that waits for its turn or is held at the admission stage.
|
||||
* @returns acknowledgement that the Agent accepted the prompt.
|
||||
* @throws `session/prompt-rejected` when an admission listener refuses the prompt or fails.
|
||||
*/
|
||||
async prompt(request: SessionPromptRequest, source: MessageSource): Promise<SessionPromptValue> {
|
||||
async prompt(request: SessionPromptRequest, source: MessageSource, signal: AbortSignal): Promise<SessionPromptValue> {
|
||||
const agent = await this.resolveAgent(request.sessionId)
|
||||
if (hasPromptRequest(agent, request.requestId)) return { accepted: true }
|
||||
const hasImage = request.content.some(part => part.type === 'image')
|
||||
const admit = async (): Promise<SessionPromptValue> => {
|
||||
try {
|
||||
if (hasImage) {
|
||||
const current = this.agents.selectionFor(agent).current
|
||||
const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model)
|
||||
if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {
|
||||
throw new RemoteError(
|
||||
'session/attachment-invalid',
|
||||
`Model "${current.model}" does not support image input.`,
|
||||
{ reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' },
|
||||
)
|
||||
const uploads: { receiptIds: readonly FileUploadReceiptId[]; binding?: PromptFileBinding } = { receiptIds: [] }
|
||||
const imageTurn: { release?: () => void } = {}
|
||||
try {
|
||||
await this.ctx.agentController.deliver(agent, {
|
||||
mode: request.mode === 'steer' ? 'steer' : 'followup',
|
||||
source,
|
||||
signal,
|
||||
prepare: async (preparing) => {
|
||||
if (hasImage) {
|
||||
// Taken in the Agent's delivery order, so a waiting image prompt keeps its place among the others.
|
||||
imageTurn.release = await this.agents.acquireImageAdmission(agent, preparing)
|
||||
await this.requireImageInput(agent)
|
||||
}
|
||||
}
|
||||
const admission = resolvePromptFileReceipts(
|
||||
request.content,
|
||||
receiptId => this.ctx.fileUploads.resolve(agent, receiptId),
|
||||
)
|
||||
const content = await this.ctx.attachments.admitPromptContent(admission.content)
|
||||
const message: UserMessage = createUserMessage({ content, source })
|
||||
if (this.ctx.agents.get(agent.id) !== agent) {
|
||||
throw new RemoteError(
|
||||
'session/not-found',
|
||||
`session "${agent.id}" was disposed during prompt admission`,
|
||||
{ sessionId: agent.id },
|
||||
const admission = resolvePromptFileReceipts(
|
||||
request.content,
|
||||
receiptId => this.ctx.fileUploads.resolve(agent, receiptId),
|
||||
)
|
||||
}
|
||||
using binding = this.ctx.fileUploads.bindPrompt(agent, admission.receiptIds, request.requestId)
|
||||
if (request.mode === 'steer') agent.steer(message)
|
||||
else agent.followup(message)
|
||||
binding.commit()
|
||||
} catch (error) {
|
||||
if (remoteErrorOf(error) !== undefined) throw error
|
||||
if (error instanceof AttachmentError) {
|
||||
throw new RemoteError('session/attachment-invalid', error.message, { reason: error.code })
|
||||
}
|
||||
throw new RemoteError('session/agent-busy', 'prompt rejected', { reason: String(error) })
|
||||
}
|
||||
return { accepted: true }
|
||||
uploads.receiptIds = admission.receiptIds
|
||||
return await this.ctx.attachments.admitPromptContent(admission.content)
|
||||
},
|
||||
beforeInsert: () => {
|
||||
uploads.binding = this.ctx.fileUploads.bindPrompt(agent, uploads.receiptIds, request.requestId)
|
||||
},
|
||||
})
|
||||
uploads.binding?.commit()
|
||||
} catch (error) {
|
||||
throw promptFailure(agent, error, signal)
|
||||
} finally {
|
||||
uploads.binding?.[Symbol.dispose]()
|
||||
imageTurn.release?.()
|
||||
}
|
||||
return { accepted: true }
|
||||
}
|
||||
|
||||
/** Refuse an image prompt when the Session's current model does not declare image input. */
|
||||
private async requireImageInput(agent: Agent): Promise<void> {
|
||||
const current = this.agents.selectionFor(agent).current
|
||||
const model = await this.ctx.llm.resolveModelInfo(current.provider, current.model)
|
||||
if (model.inputModalities !== undefined && !model.inputModalities.includes('image')) {
|
||||
throw new RemoteError(
|
||||
'session/attachment-invalid',
|
||||
`Model "${current.model}" does not support image input.`,
|
||||
{ reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' },
|
||||
)
|
||||
}
|
||||
return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit()
|
||||
}
|
||||
|
||||
private async requireModel(selection: Pick<AgentModelSelection, 'provider' | 'model'>): Promise<void> {
|
||||
@@ -560,6 +577,36 @@ export class SessionCommandController {
|
||||
}
|
||||
}
|
||||
|
||||
// Typed by the agent-controller constants, so a changed value fails this module's build while it imports no agent-controller value.
|
||||
const ADMISSION_REJECTED: typeof ADMISSION_REJECTED_CODE = 'AGENT_ADMISSION_REJECTED'
|
||||
const AGENT_GONE: typeof ADMISSION_AGENT_GONE = 'agent-controller/agent-gone'
|
||||
|
||||
/** Recognize an admission refusal by the code that the error of every copy of the agent-controller module carries. */
|
||||
function isAdmissionRejected(error: unknown): error is AgentAdmissionRejected {
|
||||
return error instanceof Error && 'code' in error && error.code === ADMISSION_REJECTED
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a failed prompt admission onto the Session Remote's failures: Remote
|
||||
* failures and the client's own cancellation pass unchanged, and an admission
|
||||
* refusal keeps its reason and whether its plugin presents it.
|
||||
*/
|
||||
function promptFailure(agent: Agent, error: unknown, signal: AbortSignal): unknown {
|
||||
if (remoteErrorOf(error) !== undefined || signal.aborted) return error
|
||||
if (isAdmissionRejected(error)) {
|
||||
if (error.reason === AGENT_GONE) {
|
||||
return new RemoteError('session/not-found', `session "${agent.id}" was disposed during prompt admission`, {
|
||||
sessionId: agent.id,
|
||||
})
|
||||
}
|
||||
return new RemoteError('session/prompt-rejected', error.message, { reason: error.reason, presented: error.presented })
|
||||
}
|
||||
if (error instanceof AttachmentError) {
|
||||
return new RemoteError('session/attachment-invalid', error.message, { reason: error.code })
|
||||
}
|
||||
return new RemoteError('session/agent-busy', 'prompt rejected', { reason: String(error) })
|
||||
}
|
||||
|
||||
function resolvePromptFileReceipts(
|
||||
content: SessionPromptRequest['content'],
|
||||
stagedFile: (receiptId: FileUploadReceiptId) => FileAttachmentRef | undefined,
|
||||
|
||||
@@ -117,6 +117,7 @@ export interface SessionControllerInternals {
|
||||
/** Host service backing the generated `ctx.remote.session` namespace. */
|
||||
export class SessionController extends TypertRemoteService {
|
||||
static inject = [
|
||||
'agentController',
|
||||
'agentDefaultModel',
|
||||
'agents',
|
||||
'attachments',
|
||||
@@ -458,10 +459,14 @@ export class SessionController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Admit one prompt after explicitly resuming its Session.
|
||||
* Admit one prompt after explicitly resuming its Session. The prompt is
|
||||
* delivered through `ctx.agentController`, whose `agent-controller/admission`
|
||||
* stage runs before it enters the inbox, so the call can wait for a listener
|
||||
* that holds it.
|
||||
* @param request - Session identity, prompt content, source metadata, and delivery mode.
|
||||
* @param signal - caller cancellation before prompt admission begins.
|
||||
* @param signal - caller cancellation; it also stops a prompt waiting for or held at the admission stage.
|
||||
* @returns acknowledgement that the Agent accepted the prompt.
|
||||
* @throws `session/prompt-rejected` when an admission listener refuses the prompt or fails.
|
||||
*/
|
||||
@Remote('prompt')
|
||||
async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue> {
|
||||
@@ -487,7 +492,7 @@ export class SessionController extends TypertRemoteService {
|
||||
...(clientTimeZone === undefined ? {} : { clientTimeZone }),
|
||||
...(principal === undefined ? {} : { principal }),
|
||||
}
|
||||
return this.commands.prompt(request, source)
|
||||
return this.commands.prompt(request, source, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -212,6 +212,12 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
'session/projections-unavailable': Record<string, never>
|
||||
'session/writer-held': { readonly sessionId: SessionId }
|
||||
'session/agent-busy': { readonly reason: string }
|
||||
'session/prompt-rejected': {
|
||||
/** Code of the refusal, owned by the plugin that refused, such as `forgePanel/worktree-missing`. */
|
||||
readonly reason: string
|
||||
/** Whether the refusing plugin shows its own explanation, so the client adds no notice. */
|
||||
readonly presented: boolean
|
||||
}
|
||||
'session/invalid-time-zone': { readonly value: string }
|
||||
'session/workspace-attach-failed': { readonly sessionId: SessionId; readonly workspaceId: string }
|
||||
'agent-preset/conflict': {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Context, FiberState } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import AgentController from '@deepseek-ai/dsh-agent-controller'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
|
||||
@@ -38,6 +39,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(AgentController)
|
||||
await ctx.plugin(CommandRuntime)
|
||||
const session = ctx.sessions.create(SESSION, {
|
||||
meta: { cwd: '/workspace', ...(origin === undefined ? {} : { origin }) },
|
||||
@@ -99,6 +101,8 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
selectionFor: () => selection,
|
||||
serializeImageAdmission: <Value>(_agent: Agent, operation: () => Promise<Value>) => operation(),
|
||||
} as unknown as ApiSessionAgentController
|
||||
// Image prompts take their admission turn at once; no model selection competes in these tests.
|
||||
Object.assign(agents, { acquireImageAdmission: () => Promise.resolve(() => {}) })
|
||||
const uploads = new FileUploads(ctx)
|
||||
if (uploadRoute === undefined) throw new Error('file upload route was not registered')
|
||||
return {
|
||||
@@ -117,6 +121,8 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
|
||||
/** The owner source `SessionController.prompt()` builds for {@link promptRequest}. */
|
||||
const USER_SOURCE: MessageSource = { kind: 'user', rpcId: 'req-1' as SessionRequestId }
|
||||
/** A client that stays connected for the whole prompt. */
|
||||
const SIGNAL = new AbortController().signal
|
||||
|
||||
function promptRequest(content: Parameters<SessionCommandController['prompt']>[0]['content']) {
|
||||
return {
|
||||
@@ -168,7 +174,7 @@ describe('Session file uploads', () => {
|
||||
{ type: 'file', receiptId: receipt.receiptId },
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
{ type: 'text', text: 'read it' },
|
||||
]), USER_SOURCE)
|
||||
]), USER_SOURCE, SIGNAL)
|
||||
expect(followup).toHaveBeenCalledTimes(1)
|
||||
const message = followup.mock.calls[0]?.[0] as UserMessage
|
||||
expect(message.content).toEqual([
|
||||
@@ -195,7 +201,7 @@ describe('Session file uploads', () => {
|
||||
name: 'huge.bin',
|
||||
}))
|
||||
expect(receipt.file).toMatchObject({ name: 'huge.bin', bytes: 5 })
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
|
||||
{ type: 'file', attachment: receipt.file },
|
||||
])
|
||||
@@ -222,7 +228,7 @@ describe('Session file uploads', () => {
|
||||
await expect(controller.prompt(promptRequest([
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
{ type: 'file', receiptId: 'missing-receipt' as FileUploadReceiptId },
|
||||
]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } })
|
||||
]), USER_SOURCE, SIGNAL)).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } })
|
||||
expect(followup).not.toHaveBeenCalled()
|
||||
expect(saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -320,7 +326,7 @@ describe('Session file uploads', () => {
|
||||
const { controller, uploads, agent } = await uploadHarness()
|
||||
uploads.retirePrompt(agent, 'not-staged')
|
||||
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
uploads.retirePrompt(agent, 'other-request')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
@@ -335,7 +341,7 @@ describe('Session file uploads', () => {
|
||||
{ data: 'AAAA' },
|
||||
new AbortController().signal,
|
||||
)
|
||||
await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }]), USER_SOURCE)
|
||||
await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
first.agent.session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: 'extension event' }],
|
||||
source: { kind: 'user', rpcId: 1 } as never,
|
||||
@@ -360,9 +366,9 @@ describe('Session file uploads', () => {
|
||||
it('deduplicates a retried rpcId already present in the Agent inbox', async () => {
|
||||
const { controller, agent, followup } = await uploadHarness()
|
||||
const request = promptRequest([{ type: 'text', text: 'once' }])
|
||||
await controller.prompt(request, USER_SOURCE)
|
||||
await controller.prompt(request, USER_SOURCE, SIGNAL)
|
||||
agent.inbox.append('next-turn', followup.mock.calls[0]?.[0] as UserMessage)
|
||||
await expect(controller.prompt(request, USER_SOURCE)).resolves.toEqual({ accepted: true })
|
||||
await expect(controller.prompt(request, USER_SOURCE, SIGNAL)).resolves.toEqual({ accepted: true })
|
||||
expect(followup).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
@@ -379,7 +385,7 @@ describe('Session file uploads', () => {
|
||||
source: { kind: 'user', rpcId: request.requestId },
|
||||
}), { surfaceOp: 'append' })
|
||||
|
||||
await expect(controller.prompt(request, USER_SOURCE)).resolves.toEqual({ accepted: true })
|
||||
await expect(controller.prompt(request, USER_SOURCE, SIGNAL)).resolves.toEqual({ accepted: true })
|
||||
expect(followup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -389,7 +395,7 @@ describe('Session file uploads', () => {
|
||||
saveImages.mockReturnValueOnce(admitted.promise)
|
||||
const prompting = controller.prompt(promptRequest([
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
]), USER_SOURCE)
|
||||
]), USER_SOURCE, SIGNAL)
|
||||
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
|
||||
await disposeAgent()
|
||||
admitted.resolve([{
|
||||
@@ -401,7 +407,7 @@ describe('Session file uploads', () => {
|
||||
it('rejects when a previously bound receipt retires during image admission', async () => {
|
||||
const { controller, uploads, agent, saveImages } = await uploadHarness()
|
||||
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
const admitted = Promise.withResolvers<readonly ImageAttachmentRef[]>()
|
||||
saveImages.mockReturnValueOnce(admitted.promise)
|
||||
const prompting = controller.prompt({
|
||||
@@ -410,7 +416,7 @@ describe('Session file uploads', () => {
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
]),
|
||||
requestId: 'req-2' as SessionRequestId,
|
||||
}, USER_SOURCE)
|
||||
}, USER_SOURCE, SIGNAL)
|
||||
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
admitted.resolve([{
|
||||
@@ -424,12 +430,12 @@ describe('Session file uploads', () => {
|
||||
it('keeps the prior receipt binding when a later prompt attempt fails', async () => {
|
||||
const { controller, uploads, agent, followup } = await uploadHarness()
|
||||
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
followup.mockImplementationOnce(() => { throw new Error('busy') })
|
||||
await expect(controller.prompt({
|
||||
...promptRequest([{ type: 'file', receiptId: receipt.receiptId }]),
|
||||
requestId: 'req-2' as SessionRequestId,
|
||||
}, USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
}, USER_SOURCE, SIGNAL)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined()
|
||||
})
|
||||
@@ -440,7 +446,7 @@ describe('Session file uploads', () => {
|
||||
followup.mockImplementationOnce(() => { throw new Error('busy') })
|
||||
await expect(controller.prompt(promptRequest([
|
||||
{ type: 'file', receiptId: receipt.receiptId },
|
||||
]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
]), USER_SOURCE, SIGNAL)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
})
|
||||
@@ -448,7 +454,7 @@ describe('Session file uploads', () => {
|
||||
it('retires a prompt-bound receipt when its queued occurrence is removed', async () => {
|
||||
const { controller, uploads, agent, followup } = await uploadHarness()
|
||||
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
const queued = followup.mock.calls[0]?.[0] as UserMessage
|
||||
agent.inbox.append('next-turn', queued)
|
||||
expect(await controller.updateQueue({
|
||||
@@ -469,7 +475,7 @@ describe('Session file uploads', () => {
|
||||
await controller.prompt(promptRequest([
|
||||
{ type: 'file', receiptId: first.receiptId },
|
||||
{ type: 'file', receiptId: second.receiptId },
|
||||
]), USER_SOURCE)
|
||||
]), USER_SOURCE, SIGNAL)
|
||||
|
||||
const message = followup.mock.calls[0]?.[0] as UserMessage
|
||||
expect(message.content).toEqual([
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Session prompts through the Agent controller's admission stage: how the
|
||||
* `session/prompt` Remote reports a held, refused, or failed admission to the
|
||||
* client.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import type { UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
|
||||
import { createSessionTestRemote } from './test-remote.ts'
|
||||
|
||||
let nextRequestId = 1
|
||||
|
||||
async function harness(options: { readonly refusal?: Error } = {}) {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
const session = ctx.sessions.create()
|
||||
const inbox = createInboxStub()
|
||||
const deliver = (target: 'next-turn' | 'next-step', message: UserMessage): void => {
|
||||
if (options.refusal !== undefined) throw options.refusal
|
||||
inbox.append(target, message)
|
||||
}
|
||||
const agent: Agent = {
|
||||
id: session.id,
|
||||
options: {},
|
||||
session,
|
||||
inbox,
|
||||
status: 'idle',
|
||||
ctx,
|
||||
send: () => {},
|
||||
followup: (message) => { deliver('next-turn', message) },
|
||||
steer: (message) => { deliver('next-step', message) },
|
||||
inject: () => {},
|
||||
cancel: () => {},
|
||||
runMaintenance: task => task(new AbortController().signal),
|
||||
whenIdle: () => Promise.resolve(),
|
||||
}
|
||||
const unregister = await ctx.agents.register(agent)
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'fixture', model: 'fixture-model' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
const prompt = (text: string, mode: SessionPromptRequest['mode'] = 'queue', requestId?: SessionRequestId) => ({
|
||||
requestId: requestId ?? `admission-${String(nextRequestId++)}` as SessionRequestId,
|
||||
sessionId: session.id,
|
||||
mode,
|
||||
content: [{ type: 'text' as const, text }],
|
||||
})
|
||||
return { ctx, agent, inbox, remote, prompt, unregister }
|
||||
}
|
||||
|
||||
function textsOf(messages: readonly UserMessage[]): string[] {
|
||||
return messages.map(message => message.content.map(block => block.type === 'text' ? block.text : '').join(''))
|
||||
}
|
||||
|
||||
describe('Session prompt admission', () => {
|
||||
it('admits a queued prompt into the next turn and a steered one into the next step', async () => {
|
||||
const { ctx, agent, inbox, remote, prompt } = await harness()
|
||||
const admitted: Agent[] = []
|
||||
ctx.on('agent-controller/admission', async ({ agent: subject }, next) => {
|
||||
admitted.push(subject)
|
||||
return await next()
|
||||
})
|
||||
|
||||
expect(await remote.prompt(prompt('later'))).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(await remote.prompt(prompt('now', 'steer'))).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(admitted).toEqual([agent, agent])
|
||||
expect(textsOf(inbox.nextTurn)).toEqual(['later'])
|
||||
expect(textsOf(inbox.nextStep)).toEqual(['now'])
|
||||
})
|
||||
|
||||
it('keeps the prompt call open while a listener holds it', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
ctx.on('agent-controller/admission', async (_admission, next) => {
|
||||
await release.promise
|
||||
return await next()
|
||||
})
|
||||
|
||||
let settled = false
|
||||
const pending = remote.prompt(prompt('held')).finally(() => { settled = true })
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
expect(settled).toBe(false)
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
release.resolve(undefined)
|
||||
expect(await pending).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(textsOf(inbox.nextTurn)).toEqual(['held'])
|
||||
})
|
||||
|
||||
it('returns a refusal with its reason and whether its plugin presents it, and keeps the inbox untouched', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
let presented = true
|
||||
ctx.on('agent-controller/admission', () => Promise.resolve({
|
||||
kind: 'reject' as const, reason: 'fixture/worktree-missing', message: 'The worktree was removed.', presented,
|
||||
}))
|
||||
|
||||
expect(await remote.prompt(prompt('refused'))).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'session/prompt-rejected',
|
||||
message: 'The worktree was removed.',
|
||||
details: { reason: 'fixture/worktree-missing', presented: true },
|
||||
},
|
||||
})
|
||||
presented = false
|
||||
expect(await remote.prompt(prompt('refused again'))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/prompt-rejected', details: { reason: 'fixture/worktree-missing', presented: false } },
|
||||
})
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a failed listener as a refusal the client explains', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
ctx.on('agent-controller/admission', () => Promise.reject(new Error('listener broke')))
|
||||
|
||||
const result = await remote.prompt(prompt('broken'))
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/prompt-rejected', details: { reason: 'agent-controller/admission-failed', presented: false } },
|
||||
})
|
||||
expect(result.ok ? '' : result.error.message).toContain('listener broke')
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
})
|
||||
|
||||
it('cancels a held prompt whose client went away', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
ctx.on('agent-controller/admission', async ({ signal }, next) => {
|
||||
await new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true })
|
||||
})
|
||||
return await next()
|
||||
})
|
||||
|
||||
const client = new AbortController()
|
||||
const pending = remote.prompt(prompt('abandoned'), client.signal)
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
client.abort(new Error('client left'))
|
||||
expect(await pending).toMatchObject({ ok: false, error: { code: 'gateway/cancelled' } })
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a Session whose Agent was disposed while its prompt was held as not found', async () => {
|
||||
const { ctx, agent, remote, prompt, unregister } = await harness()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
ctx.on('agent-controller/admission', async (_admission, next) => {
|
||||
await release.promise
|
||||
return await next()
|
||||
})
|
||||
|
||||
const pending = remote.prompt(prompt('orphaned'))
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
await unregister()
|
||||
release.resolve(undefined)
|
||||
expect(await pending).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/not-found', details: { sessionId: agent.id } },
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a refusal from another copy of the agent-controller module by its code', async () => {
|
||||
const { ctx, agent, remote, prompt } = await harness()
|
||||
// Another copy of the module raises the same fields from its own class.
|
||||
const refusal = (reason: string): Error => Object.assign(new Error('The worktree was removed.'), {
|
||||
name: 'AgentAdmissionRejected', code: 'AGENT_ADMISSION_REJECTED', reason, presented: true,
|
||||
})
|
||||
vi.spyOn(ctx.agentController, 'deliver')
|
||||
.mockRejectedValueOnce(refusal('fixture/worktree-missing'))
|
||||
.mockRejectedValueOnce(refusal('agent-controller/agent-gone'))
|
||||
|
||||
expect(await remote.prompt(prompt('refused'))).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'session/prompt-rejected',
|
||||
message: 'The worktree was removed.',
|
||||
details: { reason: 'fixture/worktree-missing', presented: true },
|
||||
},
|
||||
})
|
||||
expect(await remote.prompt(prompt('orphaned'))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/not-found', details: { sessionId: agent.id } },
|
||||
})
|
||||
})
|
||||
|
||||
it('acknowledges a repeated request without admitting it again', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
let admissions = 0
|
||||
ctx.on('agent-controller/admission', async (_admission, next) => {
|
||||
admissions += 1
|
||||
return await next()
|
||||
})
|
||||
|
||||
const first = prompt('once')
|
||||
expect(await remote.prompt(first)).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(await remote.prompt(prompt('once', 'queue', first.requestId))).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(admissions).toBe(1)
|
||||
expect(textsOf(inbox.nextTurn)).toEqual(['once'])
|
||||
})
|
||||
|
||||
it('reports the Agent refusing to queue a prompt as busy', async () => {
|
||||
const { remote, prompt } = await harness({ refusal: new Error('inbox closed') })
|
||||
|
||||
expect(await remote.prompt(prompt('rejected'))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/agent-busy', details: { reason: 'Error: inbox closed' } },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -137,6 +137,46 @@ async function harness(logged?: {
|
||||
return { ctx, agent, sessionId: session.id }
|
||||
}
|
||||
|
||||
/** An image store whose saved attachments are one-pixel PNGs. */
|
||||
function provideImageStore(ctx: Context): void {
|
||||
const attachments = {
|
||||
imageLimits: {
|
||||
maxImageBytes: 4,
|
||||
maxImagesPerMessage: 2,
|
||||
maxMessageImageBytes: 4,
|
||||
maxImagePixels: 4,
|
||||
maxImageDimension: 2000,
|
||||
mediaTypes: ['image/png'],
|
||||
},
|
||||
validateImage: () => Promise.resolve(),
|
||||
saveImage: (input: { data: Uint8Array; mediaType: 'image/png' }) => Promise.resolve({
|
||||
attachmentId: `att-${String(input.data[0])}`, mediaType: input.mediaType, bytes: input.data.byteLength, width: 1, height: 1,
|
||||
}),
|
||||
}
|
||||
ctx.provide('attachments', Object.setPrototypeOf(attachments, AttachmentStore.prototype) as never)
|
||||
}
|
||||
|
||||
/** A queued prompt with its text, after a one-pixel image when `withImage` is set. */
|
||||
function imagePrompt(sessionId: SessionId, text: string, withImage: boolean): SessionPromptRequest {
|
||||
return promptRequest({
|
||||
sessionId,
|
||||
mode: 'queue',
|
||||
content: [
|
||||
...withImage ? [{ type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==' }] : [],
|
||||
{ type: 'text' as const, text },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
function textOf(message: UserMessage): string {
|
||||
return message.content.map(block => block.type === 'text' ? block.text : '').join('')
|
||||
}
|
||||
|
||||
/** Let pending prompts run as far as they can. */
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
}
|
||||
|
||||
function expectValue<T>(result: { ok: true; value: T } | { ok: false }): T {
|
||||
if (!result.ok) throw new Error('expected successful response')
|
||||
return result.value
|
||||
@@ -313,6 +353,110 @@ describe('Web session model selection', () => {
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('admits image prompts in arrival order behind an image prompt that a listener holds', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
provideImageStore(ctx)
|
||||
const followed: string[] = []
|
||||
Object.assign(agent, { followup: (message: UserMessage) => { followed.push(textOf(message)) } })
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
ctx.on('agent-controller/admission', async ({ message }, next) => {
|
||||
if (textOf(message) === 'held') await release.promise
|
||||
return await next()
|
||||
})
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
|
||||
const prompts = [
|
||||
remote.prompt(imagePrompt(sessionId, 'held', true)),
|
||||
remote.prompt(imagePrompt(sessionId, 'second image', true)),
|
||||
remote.prompt(imagePrompt(sessionId, 'third text', false)),
|
||||
]
|
||||
await settle()
|
||||
expect(followed).toEqual([])
|
||||
release.resolve(undefined)
|
||||
expect((await Promise.all(prompts)).map(result => result.ok)).toEqual([true, true, true])
|
||||
expect(followed).toEqual(['held', 'second image', 'third text'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('keeps a model selection behind the image prompt being admitted but not behind one still queued', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
registerTextOnly(ctx)
|
||||
provideImageStore(ctx)
|
||||
const events: string[] = []
|
||||
Object.assign(agent, { followup: (message: UserMessage) => { events.push(`admitted ${textOf(message)}`) } })
|
||||
const releases = new Map([['held image', Promise.withResolvers<undefined>()], ['held text', Promise.withResolvers<undefined>()]])
|
||||
ctx.on('agent-controller/admission', async ({ message }, next) => {
|
||||
await releases.get(textOf(message))?.promise
|
||||
return await next()
|
||||
})
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
const select = () => remote.selectModel(request({ sessionId, provider: 'text-only', model: 'plain' }))
|
||||
.then((result) => { events.push('selected'); return result })
|
||||
|
||||
// A held image prompt was checked against the current model, so the selection waits for its append.
|
||||
const heldImage = remote.prompt(imagePrompt(sessionId, 'held image', true))
|
||||
await settle()
|
||||
const first = select()
|
||||
await settle()
|
||||
expect(events).toEqual([])
|
||||
releases.get('held image')?.resolve(undefined)
|
||||
expect((await heldImage).ok).toBe(true)
|
||||
expect((await first).ok).toBe(true)
|
||||
expect(events).toEqual(['admitted held image', 'selected'])
|
||||
|
||||
// An image prompt queued behind a held text prompt has not been checked yet, so the selection does not wait for it.
|
||||
const heldText = remote.prompt(imagePrompt(sessionId, 'held text', false))
|
||||
const queuedImage = remote.prompt(imagePrompt(sessionId, 'queued image', true))
|
||||
await settle()
|
||||
expect((await select()).ok).toBe(true)
|
||||
expect(events).toEqual(['admitted held image', 'selected', 'selected'])
|
||||
releases.get('held text')?.resolve(undefined)
|
||||
expect((await heldText).ok).toBe(true)
|
||||
expect(await queuedImage).toMatchObject({
|
||||
ok: false, error: { code: 'session/attachment-invalid', details: { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' } },
|
||||
})
|
||||
expect(events).toEqual(['admitted held image', 'selected', 'selected', 'admitted held text'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('passes the image admission turn on when the sender of a waiting image prompt leaves', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
provideImageStore(ctx)
|
||||
const followed: string[] = []
|
||||
Object.assign(agent, { followup: (message: UserMessage) => { followed.push(textOf(message)) } })
|
||||
const listing = Promise.withResolvers<readonly LlmModelInfo[]>()
|
||||
ctx.llm.registerAdapter(['gated'], new class extends CatalogAdapter {
|
||||
override listModels(): Promise<readonly LlmModelInfo[]> {
|
||||
return listing.promise
|
||||
}
|
||||
}('Gated', []))
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
|
||||
// The selection holds the image admission turn while the provider lists its models.
|
||||
const selection = remote.selectModel(request({ sessionId, provider: 'gated', model: 'slow' }))
|
||||
await settle()
|
||||
const sender = new AbortController()
|
||||
const leaving = remote.prompt(imagePrompt(sessionId, 'left', true), sender.signal)
|
||||
await settle()
|
||||
sender.abort(new Error('client left'))
|
||||
expect(await leaving).toMatchObject({ ok: false, error: { code: 'gateway/cancelled' } })
|
||||
|
||||
listing.resolve([{ provider: 'gated', id: 'slow', name: 'Slow' }])
|
||||
expect((await selection).ok).toBe(true)
|
||||
expect((await remote.prompt(imagePrompt(sessionId, 'after', true))).ok).toBe(true)
|
||||
expect(followed).toEqual(['after'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('authorizes attachment bytes only when the session event stream references the id', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
const ref = {
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
remoteErrorOf,
|
||||
type RemoteResult,
|
||||
} from '@deepseek-ai/dsh-typert-protocol'
|
||||
import AgentController from '@deepseek-ai/dsh-agent-controller'
|
||||
import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access'
|
||||
import SessionController from '../src/index.ts'
|
||||
import type {
|
||||
@@ -293,6 +294,7 @@ async function installControllers(
|
||||
} as never)
|
||||
}
|
||||
installSessionReadTestServices(ctx)
|
||||
if (ctx.get('agentController') === undefined) new AgentController(ctx)
|
||||
if (ctx.get('remoteAccess') === undefined) new RemoteAccessService(ctx)
|
||||
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd)
|
||||
class TestController extends SessionController {
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
{
|
||||
"path": "../../core/agent"
|
||||
},
|
||||
{
|
||||
"path": "../../core/agent-controller"
|
||||
},
|
||||
{
|
||||
"path": "../../core/agent-default-model"
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user