diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml index 8e0de6c4de..69f284f402 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 478742169aa04c50 zh: 3324d99f4206d1fc /sdk-run-accepts-native-commands/migration: - en: 484261a946a13012 - zh: bab28bbde44fbc61 + en: 0298fc31efa6466c + zh: ab99db4beaa86a14 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md index 4ceab1e4fd..deb605d80e 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md @@ -20,5 +20,5 @@ Content-block arrays no longer bypass native routing. A recognized command requi 1. Keep the existing `result.final_response` / `result.finalResponse` access for prompts and commands. Inspect `finish_reason` / `finishReason` for failure; command ids and native outcomes remain in `command/run` and `command/done` events. Save the result's Session id to continue or restore it. 2. Keep the user-question callback alive for plan review. State-changing command failures appear in `RunResult`; routing, malformed protocol data and transport failures still raise or reject. A timeout or observer failure does not roll back runtime work. 3. For literal queued input, use Python `client.session_prompt(session_id, blocks)` or TypeScript `client.prompt(sessionId, blocks)`, and manage its subsequent activity. Runtime skill recognition still applies. -4. Custom `session/query` clients send `{ sessionId, contentBlocks, delivery }`. Command responses acknowledge the native handler; the matching `session.query.completed` notification carries the final input outcome. Preserve notification order and subscribe before sending. `session/command` retains its strict, attachment-free behavior. +4. Custom `session/query` clients send `{ sessionId, contentBlocks }`. Command responses acknowledge the native handler; the matching `session.query.completed` notification carries the final input outcome. Preserve notification order and subscribe before sending. 5. Filter empty input before calling `run()`. Use an image-capable model and the existing `run([text_block, image_block])` form for images. Python malformed native command responses raise `SdkProtocolError`, preserving their validation cause; generic caller-selected response models retain their validation behavior. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md index aaefe1939c..3af3c36ed3 100644 --- a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md @@ -20,5 +20,5 @@ Python 和 TypeScript 的 `run()` 通过原有入口接受字符串和内容块 1. 普通提示词和命令均继续使用 `result.final_response` / `result.finalResponse`。通过 `finish_reason` / `finishReason` 检查失败;命令 id 和原生结果保留在 `command/run` 与 `command/done` 事件中。保存结果的 Session id,以便继续或恢复会话。 2. 计划审阅期间保持用户问题回调可用。状态变更命令的失败体现在 `RunResult` 中;路由、协议数据格式和传输失败仍抛出或拒绝。超时或观察回调失败不会回滚运行时工作。 3. 需要按原文排队输入时,使用 Python `client.session_prompt(session_id, blocks)` 或 TypeScript `client.prompt(sessionId, blocks)`,并管理后续活动。运行时技能识别仍然适用。 -4. 自定义 `session/query` 客户端发送 `{ sessionId, contentBlocks, delivery }`。命令响应确认原生 handler 完成;对应的 `session.query.completed` 通知携带本次输入的最终结果。保持通知顺序,并在发送前订阅。`session/command` 保持严格、无附件的行为。 +4. 自定义 `session/query` 客户端发送 `{ sessionId, contentBlocks }`。命令响应确认原生 handler 完成;对应的 `session.query.completed` 通知携带本次输入的最终结果。保持通知顺序,并在发送前订阅。 5. 调用 `run()` 前过滤空输入。图片使用支持图片的模型及原有 `run([text_block, image_block])` 形式。Python 对格式错误的原生命令响应抛出 `SdkProtocolError`,保留校验原因;调用者自行选择的通用响应模型保留原有校验行为。 diff --git a/packages/sdk/client/README.i18n.yaml b/packages/sdk/client/README.i18n.yaml index 8242cf3956..17aee01d87 100644 --- a/packages/sdk/client/README.i18n.yaml +++ b/packages/sdk/client/README.i18n.yaml @@ -18,14 +18,14 @@ en: 6c37c21a2e53376b zh: e707d3e81c1242bd /deepseek-ai-dsh-sdk-client/use-this-package/running-agent-turns-with-deepseekharness: - en: 917f83f3388eaef4 - zh: 457977edc30d14fd + en: 1a36c54463e17340 + zh: ad67f9cbccc56def /deepseek-ai-dsh-sdk-client/use-this-package/run-text-and-native-commands: - en: 10f612a3a7b62d29 - zh: 2a6d8248c7e02097 + en: 0a0c9f44ccf17841 + zh: 1f881e22a10dbe49 /deepseek-ai-dsh-sdk-client/use-this-package/lower-level-control-with-harnessclient: - en: 52ec138e57a66472 - zh: fc6f6ea086f7d850 + en: 93f5f28fa70aa1d8 + zh: 224b850b2f801bf2 /deepseek-ai-dsh-sdk-client/use-this-package/native-user-questions: en: f5b9d6a7363bd9e5 zh: f53b3786d22a729d diff --git a/packages/sdk/client/README.md b/packages/sdk/client/README.md index bff7e18831..dd50f06e4e 100644 --- a/packages/sdk/client/README.md +++ b/packages/sdk/client/README.md @@ -52,11 +52,11 @@ const result = await harness.run('say hi') console.log(result.finalResponse) ``` -The subprocess starts lazily on first use and stays owned by the instance across `run()` calls; call `close()` (or use `await using`) so the child is always reaped. `start()` memoizes the bounded `initialize` handshake, which carries the workspace cwd, provider/model route, optional adapter-owned `reasoningEffort`, and optional positive `maxTokens` output cap. The server validates that exact route before it accepts prompts; an omitted effort preserves the model's default. `initializeTimeoutMs` defaults to 10 seconds, and its diagnostic names the selected profile with the retained stderr tail. `run(input, { sessionId?, onNotification?, delivery? })` accepts text or `SdkPromptContentBlock[]`; an inline raster block carries canonical base64 plus `mimeType` and becomes a durable attachment inside the runtime. For ordinary input, the call owns one activity interval: it queues the prompt, waits until its message id appears in a durable inbox receipt, then collects through the next whole-agent `idle`. That path returns `RunResult { sessionId, finalResponse, finishReason, events, notifications }`, where `finalResponse` is the last committed root-session assistant text in that interval — not a response causally assigned to the prompt, because steering, injected context, and other queued work may contribute before idle. `session(id?)` opens a named or fresh session handle. When a failed handshake is cleaned up successfully, the instance installs a fresh client so a later call retries with a new process until terminal `close()`; if initialization and cleanup both fail, `start()` returns an ordered `AggregateError` and retains the failed client instead of spawning beside a process whose exit is unproved. `maxTokens` caps each root-agent request output and is inherited by in-process descendants; compaction plugins own their separate summary limits. +The subprocess starts lazily on first use and stays owned by the instance across `run()` calls; call `close()` (or use `await using`) so the child is always reaped. `start()` memoizes the bounded `initialize` handshake, which carries the workspace cwd, provider/model route, optional adapter-owned `reasoningEffort`, and optional positive `maxTokens` output cap. The server validates that exact route before it accepts prompts; an omitted effort preserves the model's default. `initializeTimeoutMs` defaults to 10 seconds, and its diagnostic names the selected profile with the retained stderr tail. `run(input, { sessionId?, onNotification? })` accepts text or `SdkPromptContentBlock[]`; an inline raster block carries canonical base64 plus `mimeType` and becomes a durable attachment inside the runtime. For ordinary input, the call owns one activity interval: it queues the prompt, waits until its message id appears in a durable inbox receipt, then collects through the next whole-agent `idle`. That path returns `RunResult { sessionId, finalResponse, finishReason, events, notifications }`, where `finalResponse` is the last committed root-session assistant text in that interval — not a response causally assigned to the prompt, because steering, injected context, and other queued work may contribute before idle. `session(id?)` opens a named or fresh session handle. When a failed handshake is cleaned up successfully, the instance installs a fresh client so a later call retries with a new process until terminal `close()`; if initialization and cleanup both fail, `start()` returns an ordered `AggregateError` and retains the failed client instead of spawning beside a process whose exit is unproved. `maxTokens` caps each root-agent request output and is inherited by in-process descendants; compaction plugins own their separate summary limits. ### Run text and native commands -`await session.run(input, { delivery: 'queue', onNotification })` accepts a string or `SdkPromptContentBlock[]` and routes both through the runtime's [supported command forms and Desktop aliases](../server/README.md#command-input). Unrecognized input remains an ordinary prompt with its original block order. Delivery defaults to `queue`; `steer` targets the next available step for ordinary input, including images. Commands retain their native admission and timing. +`await session.run(input, { onNotification })` accepts a string or `SdkPromptContentBlock[]` and routes both through the runtime's [supported command forms and Desktop aliases](../server/README.md#command-input). Unrecognized input remains an ordinary prompt with its original block order. Ordinary input, including images, uses the existing prompt queue. Commands retain their native admission and timing. Select a model that supports image input. Submit a command and image in the existing content-block array, for example `session.run([{ type: 'text', text: '/plan Analyze this image.' }, { type: 'image', data: imageBase64, mimeType: 'image/png' }])`; `harness.run()` accepts the same input. Plan input and goal creation or editing accept images; `/plan off`, goal controls, compact, and permission commands reject them through the [native attachment rules](../server/README.md#command-input). Native command input supports encoded raster images, not general file uploads or client-supplied attachment references. @@ -79,10 +79,6 @@ Launch options supply initial values. A permission command changes only its targ ### Lower-level control with HarnessClient -`client.executeCommand(sessionId, line)` accepts ASCII registered names or canonical English aliases of supported builtin definitions, without prompt fallback or attachments; it requires a non-blank permission preset and returns the native `CommandExecution`. Use `run()` for Chinese aliases. A non-blank unknown preset reaches the native handler and returns `result.kind === "error"`. Subscribe before the command call when notifications are needed. A request timeout abandons only the local wait; runtime work can continue afterward. - -With `client.executeCommand()`, goal creation and resume can start automatic rounds after the call returns. Subscribe before sending; observe a terminal `goal/change` operation before using `session/wait` for the closing reply. Idle between rounds is not goal completion. See the [server semantics](../server/README.md) for pause, clear, restoration, and permission behavior. - `HarnessClient` is the protocol client under the run API: explicit `start()`, `initialize()`, `prompt()`, `request()`, and `close()`, plus notification subscriptions. `prompt()` returns the queued message id as soon as the runtime accepts it and never waits for agent activity. `subscribe(filter?)` returns a `NotificationSubscription` (awaitable `next()`, non-blocking `tryNext()`, async iteration); `subscribeSessionTree(id)` scopes to one session and the descendants discovered from `subagent.started` lineage edges — the runtime notifies for every session in its context, and scoping is client-side, exactly like the Python SDK. Task-owning consumers can subscribe before `prompt()`, then call `request('session/wait', { sessionId })` and drain queued notifications with `tryNext()`. This waits for managed descendants and their root summary turns; `HarnessSession.run()` retains its next-idle interval for ordinary prompts. `validatedSessionEvent()` validates the event envelope and the assistant/turn fields consumed by SDK readers before they enter an output fold. diff --git a/packages/sdk/client/README.zh.md b/packages/sdk/client/README.zh.md index 0fa71da4f3..38b9ba77e7 100644 --- a/packages/sdk/client/README.zh.md +++ b/packages/sdk/client/README.zh.md @@ -52,11 +52,11 @@ const result = await harness.run('say hi') console.log(result.finalResponse) ``` -子进程在首次使用时惰性启动,并在多次 `run()` 调用之间持续归实例所有;请调用 `close()`(或使用 `await using`),子进程才总能被回收。`start()` 会记忆化有界的 `initialize` 握手,其中包含工作区 cwd、提供方/模型路由、可选且由适配器持有的 `reasoningEffort`,以及可选的正整数 `maxTokens` 输出上限。服务器会在接受提示词前校验该确切路由;省略推理强度时保留模型自身的默认值。`initializeTimeoutMs` 默认 10 秒,诊断会写明所选 profile 并附带保留的 stderr 尾部。`run(input, { sessionId?, onNotification?, delivery? })` 接受文本或 `SdkPromptContentBlock[]`;内联栅格图像块携带规范 base64 与 `mimeType`,并在运行时内变成持久附件。对于普通输入,该调用拥有一个活动区间:它将提示词排入队列,等待其消息 id 出现在持久入队回执中,然后持续收集到整个 agent 下一次进入 `idle`。该路径返回 `RunResult { sessionId, finalResponse, finishReason, events, notifications }`,其中 `finalResponse` 是该区间内根会话最后提交的助手文本——并非因果上归属于该提示词的响应,因为 steering(中途引导)、注入的上下文和其他排队工作都可能在 idle 前参与其中。`session(id?)` 打开具名或全新的会话句柄。握手失败且清理成功时,实例会换入全新客户端,使后续调用用新进程重试,直到终结性的 `close()`;如果初始化和清理均失败,`start()` 会返回保留两个原因的有序 `AggregateError`,并继续保留失败的客户端,避免在原进程退出尚未得到证明时启动另一个进程。`maxTokens` 限制每个根 agent 请求的输出量,并由进程内后代继承;压缩(compaction)插件单独持有摘要上限。 +子进程在首次使用时惰性启动,并在多次 `run()` 调用之间持续归实例所有;请调用 `close()`(或使用 `await using`),子进程才总能被回收。`start()` 会记忆化有界的 `initialize` 握手,其中包含工作区 cwd、提供方/模型路由、可选且由适配器持有的 `reasoningEffort`,以及可选的正整数 `maxTokens` 输出上限。服务器会在接受提示词前校验该确切路由;省略推理强度时保留模型自身的默认值。`initializeTimeoutMs` 默认 10 秒,诊断会写明所选 profile 并附带保留的 stderr 尾部。`run(input, { sessionId?, onNotification? })` 接受文本或 `SdkPromptContentBlock[]`;内联栅格图像块携带规范 base64 与 `mimeType`,并在运行时内变成持久附件。对于普通输入,该调用拥有一个活动区间:它将提示词排入队列,等待其消息 id 出现在持久入队回执中,然后持续收集到整个 agent 下一次进入 `idle`。该路径返回 `RunResult { sessionId, finalResponse, finishReason, events, notifications }`,其中 `finalResponse` 是该区间内根会话最后提交的助手文本——并非因果上归属于该提示词的响应,因为 steering(中途引导)、注入的上下文和其他排队工作都可能在 idle 前参与其中。`session(id?)` 打开具名或全新的会话句柄。握手失败且清理成功时,实例会换入全新客户端,使后续调用用新进程重试,直到终结性的 `close()`;如果初始化和清理均失败,`start()` 会返回保留两个原因的有序 `AggregateError`,并继续保留失败的客户端,避免在原进程退出尚未得到证明时启动另一个进程。`maxTokens` 限制每个根 agent 请求的输出量,并由进程内后代继承;压缩(compaction)插件单独持有摘要上限。 ### 运行文本与原生命令 -`await session.run(input, { delivery: 'queue', onNotification })` 接受字符串或 `SdkPromptContentBlock[]`,两者都交给运行时的[命令形式与 Desktop 别名](../server/README.zh.md#command-input)识别规则。未识别的输入保持普通提示词及原始内容块顺序。delivery 默认为 `queue`;对普通输入,包括图片,`steer` 指向下一个可用步骤。命令保留原生接纳规则与执行时序。 +`await session.run(input, { onNotification })` 接受字符串或 `SdkPromptContentBlock[]`,两者都交给运行时的[命令形式与 Desktop 别名](../server/README.zh.md#command-input)识别规则。未识别的输入保持普通提示词及原始内容块顺序。普通输入(包括图片)使用既有的提示词队列。命令保留原生接纳规则与执行时序。 先选择支持图片输入的模型。通过现有内容块数组同时提交命令和图片,例如 `session.run([{ type: 'text', text: '/plan Analyze this image.' }, { type: 'image', data: imageBase64, mimeType: 'image/png' }])`;`harness.run()` 接受相同输入。计划输入和目标创建、编辑接受图片;`/plan off`、目标控制、压缩和权限命令按[原生附件规则](../server/README.zh.md#command-input)拒绝图片。原生命令输入支持编码栅格图片,不支持一般文件上传或客户端提供的附件引用。 @@ -79,10 +79,6 @@ console.log(result.finalResponse) ### 用 HarnessClient 做低层控制 -`client.executeCommand(sessionId, line)` 接受受支持内置定义的 ASCII 注册名或英文规范别名,不回退为提示词,也不接受附件;permission preset 必须非空,返回原生 `CommandExecution`。中文别名使用 `run()`。非空的未知 preset 会进入原生 handler,返回 `result.kind === "error"`。需要通知时,应在命令调用前订阅。请求超时仅放弃本地等待,运行时工作仍可继续。 - -使用 `client.executeCommand()` 时,目标创建和恢复可在调用返回后启动自动轮次。发送前应订阅;先观察终态 `goal/change` 操作,再用 `session/wait` 等待收尾回复。轮次之间的 idle 不代表目标完成。暂停、清除、恢复和权限行为见[服务端语义](../server/README.zh.md)。 - `HarnessClient` 是运行 API 之下的协议客户端:显式 `start()`、`initialize()`、`prompt()`、`request()` 与 `close()`,外加通知订阅。`prompt()` 在运行时接受排队消息后立即返回该消息的 id,绝不等待 agent 活动。`subscribe(filter?)` 返回 `NotificationSubscription`(可等待的 `next()`、非阻塞 `tryNext()`、异步迭代);`subscribeSessionTree(id)` 把范围限定到一个会话及从 `subagent.started` 血缘边发现的后代——运行时对上下文内每个会话都发通知,范围限定在客户端完成,与 Python SDK 完全一致。 拥有完整任务的消费者可以先订阅,再调用 `prompt()`,随后调用 `request('session/wait', { sessionId })`,并通过 `tryNext()` 取完已排队的通知。这会等待受管理后代及其触发的根 Agent 摘要轮次;`HarnessSession.run()` 对普通提示词仍以首次空闲作为活动区间终点。`validatedSessionEvent()` 在事件进入输出折叠前,校验事件封装及 SDK 读取方使用的 assistant/turn 字段。 diff --git a/packages/sdk/client/src/api.ts b/packages/sdk/client/src/api.ts index 6a17843e20..34b644aadf 100644 --- a/packages/sdk/client/src/api.ts +++ b/packages/sdk/client/src/api.ts @@ -121,7 +121,7 @@ export class DeepSeekHarness implements AsyncDisposable { /** * Run text or content blocks on a fresh or named Session through native input routing. * @param input - prompt or command text, optionally accompanied by image content blocks. - * @param options - optional Session identity, delivery and notification observer. + * @param options - optional Session identity and notification observer. * @returns the completed input's RunResult, including its Session id. */ run(input: string | SdkPromptContentBlock[], options?: RunOptions): Promise { @@ -162,12 +162,10 @@ export function createProcessDeepSeekHarness( }, () => createProcessHarnessClient(runtime)) } -/** Per-run Session identity, input delivery, and notification observer. */ +/** Per-run Session identity and notification observer. */ export interface RunOptions { /** Session id to run on; omitted mints a fresh session per call. */ sessionId?: string - /** Ordinary prompt delivery, defaulting to queue; commands retain their native execution timing. */ - delivery?: 'queue' | 'steer' /** * Observe the input's Session-tree activity in wire order until completion. * The interval can include overlapping work from other inputs. @@ -175,11 +173,6 @@ export interface RunOptions { onNotification?: (notification: HarnessNotification) => void } -/** Resolve omitted delivery to the ordinary prompt queue. */ -function resolveRunDelivery(requested: RunOptions['delivery']): 'queue' | 'steer' { - return requested ?? 'queue' -} - /** Collect one input's root events and Session-tree notifications from its admission. */ class RunActivity { commandDone = false @@ -258,19 +251,18 @@ export class HarnessSession { /** * Run text or content blocks through native prompt-or-command routing. * @param input - prompt or command text, optionally accompanied by image content blocks; image-only input is an ordinary prompt. - * @param options - input delivery and a per-notification observer. + * @param options - a per-notification observer. * @returns RunResult after prompt activity, a state-only command, or command-started model work ends. * Goal creation and resume include automatic rounds through goal termination and the closing reply. * Native handler refusals return finishReason="error". * @throws on routing, protocol, transport or observer failure; runtime work is not rolled back. */ - async run(input: string | SdkPromptContentBlock[], options?: Omit): Promise { - const delivery = resolveRunDelivery(options?.delivery) + async run(input: string | SdkPromptContentBlock[], options?: Pick): Promise { await this.harness.start() const client = this.harness.client const subscription = client.subscribeSessionTree(this.id) try { - const response = await queryInput(client, this.id, input, delivery) + const response = await queryInput(client, this.id, input) if (response.kind === 'command') { const activity = new RunActivity(this.id, { commandId: response.execution.commandId }) while (true) { diff --git a/packages/sdk/client/src/client.ts b/packages/sdk/client/src/client.ts index 9c7995ff38..078acbbff6 100644 --- a/packages/sdk/client/src/client.ts +++ b/packages/sdk/client/src/client.ts @@ -20,7 +20,6 @@ import { type InitializeParams, type InitializeResult, type SessionPromptParams, - type SessionCommandParams, type SessionQueryParams, type SessionQueryResult, type SdkPromptContentBlock, @@ -361,19 +360,6 @@ export class HarnessClient { return result.messageId } - /** - * Execute a strict command without waiting for an inbox receipt or Agent idle. - * @param sessionId - target Session; an unknown id creates it. - * @param line - supported compact, permission, plan, or goal input; handlers validate arguments. - * @returns the native command result, including a business error when the handler refuses it. - * @throws on protocol rejection, malformed response, timeout or transport loss; never retries. - */ - async executeCommand(sessionId: string, line: string): Promise { - const params: SessionCommandParams = { sessionId: SessionId(sessionId), line } - const value = await this.request('session/command', { ...params }) - return commandExecution(value, 'session/command') - } - /** * Restore persisted history without sending a prompt; failures propagate without creating a session. * @param sessionId - persisted identity in this runtime's configured persistence store. @@ -599,17 +585,15 @@ export function createProcessHarnessClient(options: RuntimeProcessOptions): Harn * @param client - client owning the initialized runtime connection. * @param sessionId - target Session; an unknown id creates it. * @param input - text or content blocks, without client-side command interpretation. - * @param delivery - ordinary prompt delivery; commands retain their own admission rules. * @returns the validated prompt receipt or native command execution. */ export async function queryInput( client: HarnessClient, sessionId: string, input: string | SdkPromptContentBlock[], - delivery: SessionQueryParams['delivery'], ): Promise { const params: SessionQueryParams = { - sessionId: SessionId(sessionId), contentBlocks: normalizeInput(input), delivery, + sessionId: SessionId(sessionId), contentBlocks: normalizeInput(input), } const value = await client.request('session/query', params) if (isRecord(value)) { @@ -617,7 +601,7 @@ export async function queryInput( return { kind: 'prompt', messageId: value.messageId } } if (value.kind === 'command') { - return { kind: 'command', execution: commandExecution(value.execution, 'session/query') } + return { kind: 'command', execution: commandExecution(value.execution) } } } throw new SdkProtocolError(`session/query returned an invalid routing result: ${JSON.stringify(value)}`) @@ -641,8 +625,8 @@ export function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } -/** Decode the native command result shared by strict execution and unified input. */ -function commandExecution(value: unknown, method: string): CommandExecution { +/** Decode the native handler result returned by session/query. */ +function commandExecution(value: unknown): CommandExecution { if (isRecord(value) && typeof value.commandId === 'string' && value.commandId.length > 0 && isRecord(value.result)) { const commandId = value.commandId as CommandExecution['commandId'] const { kind, text, sourceEventSeq } = value.result @@ -659,7 +643,7 @@ function commandExecution(value: unknown, method: string): CommandExecution { return { commandId, result: { kind, text } } } } - throw new SdkProtocolError(`${method} returned an invalid command result: ${JSON.stringify(value)}`) + throw new SdkProtocolError(`session/query returned an invalid command result: ${JSON.stringify(value)}`) } /** The message of a thrown value (the transport only throws `Error`s; `String` covers the rest). */ diff --git a/packages/sdk/client/src/index.ts b/packages/sdk/client/src/index.ts index b4b01de4a5..ef1a319cc4 100644 --- a/packages/sdk/client/src/index.ts +++ b/packages/sdk/client/src/index.ts @@ -21,7 +21,6 @@ export type { NotificationSubscription } from './client.ts' export { JsonRpcResponseError } from '@deepseek-ai/dsh-sdk-protocol' export type { ContentBlock, - CommandExecution, SdkEncodedImageBlock, SdkPromptContentBlock, SdkUserQuestionAnswer, diff --git a/packages/sdk/client/src/types.ts b/packages/sdk/client/src/types.ts index 369eb4250c..e7e75895d3 100644 --- a/packages/sdk/client/src/types.ts +++ b/packages/sdk/client/src/types.ts @@ -6,7 +6,7 @@ */ import type { ContentBlock, ReasoningEffortId } from '@deepseek-ai/dsh-llm' -import type { CommandExecution, SdkPromptContentBlock, SdkUserQuestionResult, SdkUserQuestionRequest } from '@deepseek-ai/dsh-sdk-protocol' +import type { SdkPromptContentBlock, SdkUserQuestionResult, SdkUserQuestionRequest } from '@deepseek-ai/dsh-sdk-protocol' import type { SessionEvent } from '@deepseek-ai/dsh-session' /** One server-to-client notification as received off the wire. */ @@ -86,7 +86,6 @@ export interface RunResult { /** Re-exported content-block alias so SDK callers need no extra import. */ export type { ContentBlock } -export type { CommandExecution } export type { SdkPromptContentBlock } export type { SdkEncodedImageBlock } from '@deepseek-ai/dsh-sdk-protocol' export type { SdkUserQuestionAnswer, SdkUserQuestionResult, SdkUserQuestionRequest } from '@deepseek-ai/dsh-sdk-protocol' diff --git a/packages/sdk/client/tests/fake-runtime.ts b/packages/sdk/client/tests/fake-runtime.ts index 04f4917453..8ff3cd6445 100644 --- a/packages/sdk/client/tests/fake-runtime.ts +++ b/packages/sdk/client/tests/fake-runtime.ts @@ -50,8 +50,6 @@ * - `FAKE_STDERR_NO_NEWLINE`: write this to stderr WITHOUT a newline (buffer-flush probe). * - `FAKE_APPROVAL`: send one server approval request after initialization and echo its response as a notification. * - `FAKE_RECORD_INIT`: append each `initialize` params JSON to this file (handshake probe). - * - `FAKE_COMMAND_RESULT`: command response JSON; omission echoes the requested line. - * - `FAKE_COMMAND_ERROR`: reject a command with a JSON-RPC error. */ import { appendFileSync, existsSync, writeFileSync } from 'node:fs' @@ -319,26 +317,13 @@ reader.on('line', (line) => { respond({ cwd }) return } - case 'session/command': { - if (env.FAKE_COMMAND_ERROR !== undefined) { - write({ jsonrpc: '2.0', id: frame.id, error: { code: -32603, message: 'command unavailable' } }) - } else { - const result: unknown = env.FAKE_COMMAND_RESULT === undefined - ? { commandId: 'command-1', result: { kind: 'success', text: frame.params?.line } } - : JSON.parse(env.FAKE_COMMAND_RESULT) - respond(result) - } - return - } case 'session/query': case 'session/prompt': { const blocks = frame.params?.contentBlocks as { type: string; text?: string }[] const text = blocks.filter(block => block.type === 'text').map(block => block.text).join('\n') if (frame.method === 'session/query' && text === '/compact') { - const execution: unknown = env.FAKE_COMMAND_RESULT === undefined - ? { commandId: 'command-1', result: { kind: 'success', text: '/compact' } } - : JSON.parse(env.FAKE_COMMAND_RESULT) - const completed = execution as { commandId?: string; result?: { kind?: string; text?: string } } + const execution = { commandId: 'command-1', result: { kind: 'success', text: '/compact' } } + const completed = execution event(sessionIdOf(frame.params), 'command/run', { commandId: completed.commandId }) event(sessionIdOf(frame.params), 'command/done', { commandId: completed.commandId, ...completed.result }) notify('session.query.completed', { sessionId: frame.params?.sessionId, commandId: completed.commandId, diff --git a/packages/sdk/client/tests/fixtures/query.ts b/packages/sdk/client/tests/fixtures/query.ts index e0c7746d18..9da6651d6b 100644 --- a/packages/sdk/client/tests/fixtures/query.ts +++ b/packages/sdk/client/tests/fixtures/query.ts @@ -8,7 +8,6 @@ interface Frame { } const queries: Record[] = [] -const commands: Record[] = [] const methods: string[] = [] const promptFinishes = new Map void>() const commandFinishes = new Map void>() @@ -113,7 +112,7 @@ createInterface({ input: process.stdin }).on('line', (line) => { const messageId = `input-${queries.length}` event(sessionId, 'assistant/message', { message: { content: [{ type: 'text', text: 'before receipt' }] } }) event(sessionId, 'agent/inbox/spliced', { - target: params.delivery === 'steer' ? 'next-step' : 'next-turn', + target: 'next-turn', start: 0, inserted: [{ id: messageId, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] }], }) @@ -136,12 +135,8 @@ createInterface({ input: process.stdin }).on('line', (line) => { finish() respond({ kind: 'prompt', messageId }) } - } else if (frame.method === 'session/command') { - const params = frame.params ?? {} - commands.push(params) - respond({ commandId: `strict-command-${commands.length}`, result: { kind: 'success' } }) } else if (frame.method === 'test/state') { - respond({ queries, commands, methods, waitingPrompts: promptFinishes.size, waitingCommands: commandFinishes.size }) + respond({ queries, methods, waitingPrompts: promptFinishes.size, waitingCommands: commandFinishes.size }) } else if (frame.method === 'test/release') { for (const finish of [...promptFinishes.values(), ...commandFinishes.values()]) finish() respond({}) diff --git a/packages/sdk/client/tests/run.spec.ts b/packages/sdk/client/tests/run.spec.ts index b42aedd060..84faa9a512 100644 --- a/packages/sdk/client/tests/run.spec.ts +++ b/packages/sdk/client/tests/run.spec.ts @@ -44,9 +44,9 @@ it('returns generated Session identities that can receive subsequent input', asy expect(continued.sessionId).toBe(first.sessionId) expect(continued.finalResponse).toBe('reply:continue') expect(await harness.client.request('test/state')).toHaveProperty('queries', [ - { sessionId: first.sessionId, contentBlocks: [{ type: 'text', text: '/compact' }], delivery: 'queue' }, - { sessionId: second.sessionId, contentBlocks: [{ type: 'text', text: '/compact' }], delivery: 'queue' }, - { sessionId: first.sessionId, contentBlocks: [{ type: 'text', text: 'continue' }], delivery: 'queue' }, + { sessionId: first.sessionId, contentBlocks: [{ type: 'text', text: '/compact' }] }, + { sessionId: second.sessionId, contentBlocks: [{ type: 'text', text: '/compact' }] }, + { sessionId: first.sessionId, contentBlocks: [{ type: 'text', text: 'continue' }] }, ]) }) @@ -83,24 +83,24 @@ it.each(['session', 'harness'])('forwards native command content blocks through : await harness.run(contentBlocks, { sessionId: 'images' }) expect(result).toMatchObject({ sessionId: 'images', finalResponse: '', finishReason: 'completed' }) expect(await harness.client.request('test/state')).toHaveProperty('queries', [ - { sessionId: 'images', contentBlocks, delivery: 'queue' }, + { sessionId: 'images', contentBlocks }, ]) }) it.each([ - { entry: 'session', text: ' explain the diagram\n', delivery: 'queue' }, - { entry: 'harness', text: 'explain the diagram', delivery: 'steer' }, - { entry: 'harness', text: '/unknown explain the diagram', delivery: 'queue' }, - { entry: 'session', text: undefined, delivery: 'steer' }, -] as const)('preserves image content for $entry text "$text" with $delivery delivery', async ({ entry, text, delivery }) => { + { entry: 'session', text: ' explain the diagram\n' }, + { entry: 'harness', text: 'explain the diagram' }, + { entry: 'harness', text: '/unknown explain the diagram' }, + { entry: 'session', text: undefined }, +] as const)('preserves image content for $entry text "$text"', async ({ entry, text }) => { const harness = harnessWith() const contentBlocks: SdkPromptContentBlock[] = text === undefined ? images : [{ type: 'text', text }, ...images] const result = entry === 'session' - ? await harness.session('images').run(contentBlocks, { delivery }) - : await harness.run(contentBlocks, { sessionId: 'images', delivery }) + ? await harness.session('images').run(contentBlocks) + : await harness.run(contentBlocks, { sessionId: 'images' }) expect(result.finalResponse).toBe(`reply:${text ?? ''}`) expect(await harness.client.request('test/state')).toHaveProperty('queries', [ - { sessionId: 'images', contentBlocks, delivery }, + { sessionId: 'images', contentBlocks }, ]) }) @@ -110,17 +110,13 @@ it('normalizes text and preserves block order through run', async () => { const contentBlocks: SdkPromptContentBlock[] = [ images[0], { type: 'text', text: 'inspect ' }, images[1], { type: 'text', text: 'both' }, ] - expect((await harness.run(' inspect\n', { sessionId: 'images', delivery: 'steer' })).finalResponse).toBe('reply: inspect\n') + expect((await harness.run(' inspect\n', { sessionId: 'images' })).finalResponse).toBe('reply: inspect\n') expect((await harness.run(contentBlocks, { sessionId: 'images' })).finalResponse).toBe('reply:inspect \nboth') - expect(await harness.client.executeCommand('images', ' /plan inspect ')).toEqual({ - commandId: 'strict-command-1', result: { kind: 'success' }, - }) const state = await harness.client.request('test/state') expect(state).toHaveProperty('queries', [ - { sessionId: 'images', contentBlocks: [{ type: 'text', text: ' inspect\n' }], delivery: 'steer' }, - { sessionId: 'images', contentBlocks, delivery: 'queue' }, + { sessionId: 'images', contentBlocks: [{ type: 'text', text: ' inspect\n' }] }, + { sessionId: 'images', contentBlocks }, ]) - expect(state).toHaveProperty('commands', [{ sessionId: 'images', line: ' /plan inspect ' }]) }) it('returns native command results for text-only blocks', async () => { @@ -130,7 +126,7 @@ it('returns native command results for text-only blocks', async () => { sessionId: 'blocks', finalResponse: 'compacted', finishReason: 'completed', }) expect(await harness.client.request('test/state')).toHaveProperty('queries', [ - { sessionId: 'blocks', contentBlocks, delivery: 'queue' }, + { sessionId: 'blocks', contentBlocks }, ]) }) @@ -142,13 +138,6 @@ it('retains a rejected command outcome without retrying its content as a prompt' expect(await harness.client.request('test/state')).toHaveProperty('methods', ['initialize', 'session/query', 'test/state']) }) -it('steers ordinary text when delivery requests the next step', async () => { - const result = await harnessWith().session('main').run('next', { delivery: 'steer' }) - expect(result.notifications[0]).toMatchObject({ params: { event: { - type: 'agent/inbox/spliced', data: { target: 'next-step' }, - } } }) -}) - it('keeps root result events separate from descendant notifications', async () => { const result = await harnessWith().session('main').run('with-child') expect(result.finalResponse).toBe('reply:with-child') @@ -263,6 +252,23 @@ it.each([ .rejects.toThrow(SdkProtocolError) }) +it.each([ + null, + {}, + { commandId: '', result: { kind: 'success' } }, + { commandId: 'c', result: { kind: 'unknown' } }, + { commandId: 'c', result: { kind: 'success', text: 1 } }, + { commandId: 'c', result: { kind: 'success', text: null } }, + { commandId: 'c', result: { kind: 'success', sourceEventSeq: -1 } }, + { commandId: 'c', result: { kind: 'success', sourceEventSeq: '1' } }, + { commandId: 'c', result: { kind: 'success', sourceEventSeq: null } }, + { commandId: 'c', result: { kind: 'success', sourceEventSeq: Number.MAX_SAFE_INTEGER + 1 } }, + { commandId: 'c', result: { kind: 'error', text: ' ' } }, +])('rejects an invalid native result through run: %j', async (execution) => { + await expect(harnessWith({ QUERY_RESULT: JSON.stringify({ kind: 'command', execution }) }).session('main').run('/compact')) + .rejects.toThrow(SdkProtocolError) +}) + it('reports command timeout without cancelling the runtime operation', async () => { const harness = harnessWith({ QUERY_HOLD_COMMAND: '1' }, 50) await expect(harness.session('main').run('/compact')).rejects.toThrow(RequestTimeoutError) @@ -274,13 +280,6 @@ it('reports runtime loss from run', async () => { await expect(harnessWith({ QUERY_DISCONNECT: '1' }).session('main').run('disconnect')).rejects.toThrow(TransportClosedError) }) -it('steers text content blocks when delivery requests the next step', async () => { - const result = await harnessWith().session('main').run([{ type: 'text', text: 'next' }], { delivery: 'steer' }) - expect(result.notifications[0]).toMatchObject({ params: { event: { - type: 'agent/inbox/spliced', data: { target: 'next-step' }, - } } }) -}) - it('keeps run pending after the plan command until its model output arrives', async () => { const harness = harnessWith() const admitted = Promise.withResolvers() diff --git a/packages/sdk/client/tests/sdk-client.spec.ts b/packages/sdk/client/tests/sdk-client.spec.ts index df6df11694..227b58e38a 100644 --- a/packages/sdk/client/tests/sdk-client.spec.ts +++ b/packages/sdk/client/tests/sdk-client.spec.ts @@ -80,51 +80,12 @@ describe('DeepSeekHarness', () => { const harness = harnessWith() await harness.start() const session = harness.session('commands') - expect(await harness.client.executeCommand(session.id, ' /compact ')).toEqual({ - commandId: 'command-1', result: { kind: 'success', text: ' /compact ' }, - }) const result = await session.run('/compact') expect(result).toMatchObject({ finalResponse: '/compact', finishReason: 'completed' }) expect(result.events.map(event => event.type)).toEqual(['command/run', 'command/done']) expect(result.notifications.some(notification => notification.method === 'session.status')).toBe(false) }) - it.each([ - { kind: 'success' }, - { kind: 'success', text: 'compacted', sourceEventSeq: 0 }, - { kind: 'error', text: 'busy' }, - ])('preserves the native command outcome %j', async (result) => { - const execution = { commandId: 'command-2', result } - const harness = harnessWith({ FAKE_COMMAND_RESULT: JSON.stringify(execution) }) - await harness.start() - expect(await harness.client.executeCommand('commands', '/compact')).toEqual(execution) - }) - - it.each([ - null, - {}, - { commandId: '', result: { kind: 'success' } }, - { commandId: 'c', result: { kind: 'unknown' } }, - { commandId: 'c', result: { kind: 'success', text: 1 } }, - { commandId: 'c', result: { kind: 'success', text: null } }, - { commandId: 'c', result: { kind: 'success', sourceEventSeq: -1 } }, - { commandId: 'c', result: { kind: 'success', sourceEventSeq: '1' } }, - { commandId: 'c', result: { kind: 'success', sourceEventSeq: null } }, - { commandId: 'c', result: { kind: 'success', sourceEventSeq: Number.MAX_SAFE_INTEGER + 1 } }, - { commandId: 'c', result: { kind: 'error' } }, - { commandId: 'c', result: { kind: 'error', text: ' ' } }, - ])('rejects an invalid command response %j', async (result) => { - const harness = harnessWith({ FAKE_COMMAND_RESULT: JSON.stringify(result) }) - await harness.start() - await expect(harness.client.executeCommand('commands', '/compact')).rejects.toThrow(SdkProtocolError) - }) - - it('propagates command rejection without submitting a prompt', async () => { - const harness = harnessWith({ FAKE_COMMAND_ERROR: '1', FAKE_HANG_PROMPT: '1' }) - await harness.start() - await expect(harness.client.executeCommand('commands', '/plan')).rejects.toMatchObject({ code: -32603, message: 'command unavailable' }) - }) - it('returns a restored handle that can run followups on the same identity', async () => { const harness = harnessWith() const session = await harness.resumeSession('saved-session') diff --git a/packages/sdk/protocol/README.i18n.yaml b/packages/sdk/protocol/README.i18n.yaml index 1f901be85f..ba459efb4c 100644 --- a/packages/sdk/protocol/README.i18n.yaml +++ b/packages/sdk/protocol/README.i18n.yaml @@ -21,8 +21,8 @@ en: be53c71505c0d1b4 zh: 6210dee577715539 /deepseek-ai-dsh-sdk-protocol/use-this-package/the-sdk-methods: - en: d8b9cebcdcb86da8 - zh: e686a2d5baebb4dd + en: 5f739d9a99c579d7 + zh: 1f58e9123396f68a /deepseek-ai-dsh-sdk-protocol/use-this-package/native-user-questions: en: 65ea66231b17b6cf zh: 8e1c57d0c27f842f diff --git a/packages/sdk/protocol/README.md b/packages/sdk/protocol/README.md index 5b761cdcf0..f4cc2e90a3 100644 --- a/packages/sdk/protocol/README.md +++ b/packages/sdk/protocol/README.md @@ -42,7 +42,6 @@ Both wire ends share one method set: client-to-server requests, opt-in server-to | client→server | `initialize` | `InitializeParams` → `InitializeResult` | | client→server | `session/prompt` | `SessionPromptParams` → `SessionPromptResult` (durable enqueue receipt) | | client→server | `session/query` | `SessionQueryParams` → `SessionQueryResult` | -| client→server | `session/command` | `SessionCommandParams` → `CommandExecution` | | client→server | `session/resume` | `SessionResumeParams` → `{}` | | client→server | `session/wait` | `SessionWaitParams` → `{}` | | client→server | `session/working-directory/get` | `SessionWorkingDirectoryParams` → `SessionWorkingDirectoryResult` | @@ -61,11 +60,11 @@ Both wire ends share one method set: client-to-server requests, opt-in server-to `session/wait` accepts `{ sessionId }` for an existing SDK-owned session and returns `{}` after the root stays idle and progressing managed descendant work finishes. Idle descendants with parked input remain resident without blocking this wait. Unknown ids and live Agent failures without a newer committed terminal are rejected. Notifications committed during the wait precede its response on the same transport; raw `session.status` transitions retain their whole-agent meaning. -`session/query` accepts `{ sessionId, contentBlocks, delivery }`, where `contentBlocks` uses `SdkPromptContentBlock[]` and delivery is `queue` or `steer`. Both SDKs normalize string input into a text block and send content-block arrays through this same entry. The runtime replies with `{ kind: "prompt", messageId }` for ordinary input, preserving its block order, or `{ kind: "command", execution }` after a supported command settles. A recognized command requires one complete text block with only encoded images beside it; other combinations reject before execution or enqueue. The images go through native attachment admission and handler validation. Empty arrays and arrays containing only blank text are rejected; image-only input is allowed. A prompt receipt is not a model result; command completion does not require an inbox receipt or idle notification. Recognition and the supported command set belong to the [SDK server](../server/README.md). +`session/query` accepts `{ sessionId, contentBlocks }`, where `contentBlocks` uses `SdkPromptContentBlock[]`. Both SDKs normalize string input into a text block and send content-block arrays through this same entry. The runtime replies with `{ kind: "prompt", messageId }` for queued ordinary input, preserving its block order, or `{ kind: "command", execution }` after a supported command settles. A recognized command requires one complete text block with only encoded images beside it; other combinations reject before execution or enqueue. The images go through native attachment admission and handler validation. Empty arrays and arrays containing only blank text are rejected; image-only input is allowed. A prompt receipt is not a model result; command completion does not require an inbox receipt or idle notification. Recognition and the supported command set belong to the [SDK server](../server/README.md). -`session/command` accepts `{ sessionId, line }` after initialization and delegates the [supported builtin definitions through their ASCII registered names or canonical English aliases](../server/README.md#command-input) to the native registry. Leading whitespace is ignored. Chinese aliases use `session/query`. A non-blank preset is required; bare `/permission` is rejected. It returns `CommandExecution` after the handler settles, including an unknown preset or other business failure as `result.kind: "error"`. Unavailable or unsupported commands and malformed requests reject with a JSON-RPC error. There is no prompt fallback or attachment input; use `session/query` to submit commands with encoded images. No inbox receipt or ordinary turn is required. `session/prompt` queues content blocks without native slash-command routing; runtime skill recognition still applies. +`session/prompt` queues content blocks without native slash-command routing; runtime skill recognition still applies. -Command lifecycle notifications precede the native handler response for both `session/command` and `session/query`. A command query additionally ends high-level observation with `session.query.completed` for the same `commandId`, after model activity it starts; goal creation and resume include goal termination and closing activity. State-only commands need no model turn, and their completion notification can precede the response. SDKs consume this receipt internally and return `RunResult`; forwarders must preserve order. Shutdown cancels unfinished observation. +Command lifecycle notifications precede the `session/query` handler response. A command query ends high-level observation with `session.query.completed` for the same `commandId`, after model activity it starts; goal creation and resume include goal termination and closing activity. State-only commands need no model turn, and their completion notification can precede the response. SDKs consume this receipt internally and return `RunResult`; forwarders must preserve order. Shutdown cancels unfinished observation. `session/resume` accepts a non-empty persisted `{ sessionId }` and returns `{}` after restoring that exact session. It requires initialization and the original persistence store, sends no new input, and rejects missing, unreadable, incompatible, or occupied sessions without creating a replacement. Historical events remain in the stored log; notifications report newly committed events. diff --git a/packages/sdk/protocol/README.zh.md b/packages/sdk/protocol/README.zh.md index a40e4a19fb..993a05f03e 100644 --- a/packages/sdk/protocol/README.zh.md +++ b/packages/sdk/protocol/README.zh.md @@ -42,7 +42,6 @@ kind: "package-library" | client→server | `initialize` | `InitializeParams` → `InitializeResult` | | client→server | `session/prompt` | `SessionPromptParams` → `SessionPromptResult`(持久入队回执) | | client→server | `session/query` | `SessionQueryParams` → `SessionQueryResult` | -| client→server | `session/command` | `SessionCommandParams` → `CommandExecution` | | client→server | `session/resume` | `SessionResumeParams` → `{}` | | client→server | `session/wait` | `SessionWaitParams` → `{}` | | 客户端→服务端 | `session/working-directory/get` | `SessionWorkingDirectoryParams` → `SessionWorkingDirectoryResult` | @@ -61,11 +60,11 @@ kind: "package-library" `session/wait` 接受已有 SDK 会话的 `{ sessionId }`,在根 Agent 持续空闲且活跃的受管理后代工作结束后返回 `{}`。带有停放输入的空闲后代保持驻留,不阻塞这次等待。未知 id,以及没有后续终止事件记录的 Agent 运行时错误,都会使请求失败。等待期间提交的通知在同一传输上先于响应到达;原始 `session.status` 转换仍表示整个 Agent 的状态。 -`session/query` 接受 `{ sessionId, contentBlocks, delivery }`,其中 `contentBlocks` 使用 `SdkPromptContentBlock[]`,delivery 为 `queue` 或 `steer`。两个 SDK 都将字符串规范化为文本块,并通过同一入口发送内容块数组。普通输入保留内容块顺序,返回 `{ kind: "prompt", messageId }`;受支持命令结束后返回 `{ kind: "command", execution }`。已识别命令要求一个完整文本块,其他块只能是编码图片;其他组合会在执行或入队前被拒绝。图片经过原生附件接纳与处理器校验。空数组和只包含空白文本的数组会被拒绝;允许仅图片输入。Prompt 回执不是模型结果,命令完成也不要求 inbox 回执或 idle 通知。识别规则及受支持命令由 [SDK 服务端](../server/README.zh.md)定义。 +`session/query` 接受 `{ sessionId, contentBlocks }`,其中 `contentBlocks` 使用 `SdkPromptContentBlock[]`。两个 SDK 都将字符串规范化为文本块,并通过同一入口发送内容块数组。普通输入保留内容块顺序排队,返回 `{ kind: "prompt", messageId }`;受支持命令结束后返回 `{ kind: "command", execution }`。已识别命令要求一个完整文本块,其他块只能是编码图片;其他组合会在执行或入队前被拒绝。图片经过原生附件接纳与处理器校验。空数组和只包含空白文本的数组会被拒绝;允许仅图片输入。Prompt 回执不是模型结果,命令完成也不要求 inbox 回执或 idle 通知。识别规则及受支持命令由 [SDK 服务端](../server/README.zh.md)定义。 -`session/command` 在初始化后接受 `{ sessionId, line }`,将[支持内置定义的 ASCII 注册名或英文规范别名](../server/README.zh.md#command-input)委托给原生注册器。忽略前导空白。中文别名使用 `session/query`。preset 必须非空,裸 `/permission` 会被拒绝。Handler 结束后返回 `CommandExecution`,未知 preset 或其他业务失败以 `result.kind: "error"` 返回。命令不可用、不受支持或请求格式错误时返回 JSON-RPC 错误。不回退为普通 prompt,也不接受附件;携带编码图片的命令使用 `session/query`。不要求 inbox 回执或普通 turn。`session/prompt` 将内容块排入队列,不经过原生 slash command 路由;运行时 skill(技能)识别仍然适用。 +`session/prompt` 将内容块排入队列,不经过原生 slash command 路由;运行时 skill(技能)识别仍然适用。 -`session/command` 和 `session/query` 的命令生命周期通知先于原生 handler 响应到达。命令查询另以同一 `commandId` 的 `session.query.completed` 通知结束高层观察,等待命令启动的模型活动;目标创建和恢复还等待目标终止及收尾活动。状态命令无需模型 turn,其完成通知可以先于响应到达。SDK 内部消费该回执并返回 `RunResult`,转发器必须保持顺序。关闭会取消尚未结束的观察。 +命令生命周期通知先于 `session/query` 的 handler 响应到达。命令查询以同一 `commandId` 的 `session.query.completed` 通知结束高层观察,等待命令启动的模型活动;目标创建和恢复还等待目标终止及收尾活动。状态命令无需模型 turn,其完成通知可以先于响应到达。SDK 内部消费该回执并返回 `RunResult`,转发器必须保持顺序。关闭会取消尚未结束的观察。 `session/resume` 接受非空的持久化 `{ sessionId }`,恢复该会话后返回 `{}`。它要求先完成初始化并使用原持久化存储,不发送新输入;会话缺失、不可读、不兼容或被占用时,请求失败且不创建替代会话。历史事件保留在存储日志中,通知只报告新提交的事件。 diff --git a/packages/sdk/protocol/src/index.ts b/packages/sdk/protocol/src/index.ts index 0849309830..7118353739 100644 --- a/packages/sdk/protocol/src/index.ts +++ b/packages/sdk/protocol/src/index.ts @@ -28,7 +28,6 @@ export type { SdkUserQuestionResult, SdkUserQuestionCancelled, SessionEventNotification, - SessionCommandParams, SessionQueryParams, SessionQueryResult, SessionStatusNotification, diff --git a/packages/sdk/protocol/src/types.ts b/packages/sdk/protocol/src/types.ts index 1485eaddf6..6bcd2de704 100644 --- a/packages/sdk/protocol/src/types.ts +++ b/packages/sdk/protocol/src/types.ts @@ -95,25 +95,12 @@ export interface SessionPromptResult { messageId: string } -/** Strict invocation of the supported compact, permission, plan, or goal commands. */ -export interface SessionCommandParams { - /** SDK-owned Session identity; an unknown id creates its Agent. */ - sessionId: SessionId - /** - * Complete line using an ASCII registered name or canonical English alias. - * Leading whitespace is ignored; the native command validates arguments. - */ - line: string -} - /** Content submitted through the SDK's ordinary-input and slash-command entry. */ export interface SessionQueryParams { /** SDK-owned Session identity; an unknown id creates its Agent. */ sessionId: SessionId /** Ordered prompt blocks; a native command occupies its only text block and may accompany encoded images. */ contentBlocks: SdkPromptContentBlock[] - /** Ordinary prompt delivery; commands keep their native execution timing. */ - delivery: 'queue' | 'steer' } /** @@ -223,7 +210,6 @@ export interface HarnessSdkNotificationMap { export interface HarnessSdkRequestMap { 'initialize': { params: InitializeParams; result: InitializeResult } 'session/prompt': { params: SessionPromptParams; result: SessionPromptResult } - 'session/command': { params: SessionCommandParams; result: CommandExecution } 'session/query': { params: SessionQueryParams; result: SessionQueryResult } 'session/resume': { params: SessionResumeParams; result: Record } 'session/wait': { params: SessionWaitParams; result: Record } diff --git a/packages/sdk/server/README.i18n.yaml b/packages/sdk/server/README.i18n.yaml index 70fa7c67a9..3823474e12 100644 --- a/packages/sdk/server/README.i18n.yaml +++ b/packages/sdk/server/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package: - en: f8caa6b998e5e306 - zh: ecd701dec7b9a90d + en: d229158284c7e2af + zh: cd9b226792f30eaa /deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package/wiring: en: 47a33e9397e36e15 zh: e6d173820f9ea6e5 @@ -60,8 +60,8 @@ en: 04d1b73cd8e06dfe zh: cd67fbbfdf39f776 /deepseek-ai-dsh-sdk-jsonrpc-server/model-experience/sdk-user-message/what-the-model-sees: - en: fd31787017832f45 - zh: b70ed1535363dc42 + en: 04c09df4f7053490 + zh: 236f0f0b97892821 /deepseek-ai-dsh-sdk-jsonrpc-server/model-experience/sdk-user-message/token-effect: en: 372ed851986b76d2 zh: 075b94a565275368 diff --git a/packages/sdk/server/README.md b/packages/sdk/server/README.md index e15eaab16e..08d99fa160 100644 --- a/packages/sdk/server/README.md +++ b/packages/sdk/server/README.md @@ -37,13 +37,13 @@ The plugin publishes the `sdkSessionActivation` readiness marker once its remind The supported commands below are existing Desktop native operations that can execute without a GUI. `/permission ` uses that native path; the Desktop `/model` picker uses a separate model-selection API. -`session/query` is the wire entry used by high-level SDK `run()` for strings and content-block arrays. Ordinary inputs retain their blocks and use the selected queue/steer operation. The full SDK recognizes bare `/compact`, `/permission ` with a non-blank preset, `/plan [off|message]`, and `/goal [objective|clear|edit objective|pause|resume]` identified by their official definition IDs. Bare `/permission` or `/权限`, `/compact extra`, and all other input including `/model` remain ordinary prompts. A missing command also preserves the prompt path; a selected handler's failure never falls back. An unknown preset is a native command error. Encoded image blocks accompany recognized commands through native attachment admission. `session/prompt` remains the low-level queued-input entry without native slash-command routing. +`session/query` is the wire entry used by high-level SDK `run()` for strings and content-block arrays. Ordinary inputs retain their blocks and use the existing prompt queue. The full SDK recognizes bare `/compact`, `/permission ` with a non-blank preset, `/plan [off|message]`, and `/goal [objective|clear|edit objective|pause|resume]` identified by their official definition IDs. Bare `/permission` or `/权限`, `/compact extra`, and all other input including `/model` remain ordinary prompts. A missing command also preserves the prompt path; a selected handler's failure never falls back. An unknown preset is a native command error. Encoded image blocks accompany recognized commands through native attachment admission. `session/prompt` remains the low-level queued-input entry without native slash-command routing. Host and Desktop adapters share `dsh-commands/builtin` for definition identity and English/Chinese aliases. The aliases `/压缩`, `/权限`, `/计划`, and `/目标` follow their official definitions after renaming; execution uses the current registered name. Exact names take precedence, but an unrelated same-name definition is not an SDK builtin and remains an ordinary prompt. Other builtin capabilities remain outside the SDK command set. The first text block supplies the complete command line; encoded images may precede or follow it. When that line matches a supported command, it must be the only text block and every other block must be an encoded image. Additional text blocks, durable image references, and other content types reject with a JSON-RPC error before execution or enqueue, without prompt fallback. Ordinary prompts preserve all block content and ordering. Empty arrays and arrays containing only blank text are rejected; image-only input is allowed. -`session/command` accepts `{ sessionId, line }` using ASCII registered names or canonical English aliases of the same four builtin definitions; Leading whitespace is ignored. Chinese aliases use `session/query`. Unsupported identities are rejected with a JSON-RPC error. Command identity checks use the initialized receiving Agent's catalog; identity rejection retains that Session, executes no handler and submits no prompt. It requires a non-blank permission preset and lets native handlers validate other arguments. The full sdk profile composes these native handlers; profiles without the requested command reject it. The server resolves its own live Agent and calls `commands.execute()` without queueing a prompt or waiting for idle. Compaction owns its auxiliary model request, history replacement and checkpoint, and refuses a busy Agent. Permission changes retain their native state and notification behavior. Shutdown cancels pending commands and drains SDK command waiters before releasing Agents. Timeout is not rollback; clients must not retry automatically. See the [protocol](../protocol/README.md) for results and errors. +Recognized commands execute through the receiving Agent's native command registry. Handlers validate command arguments and attachments. Compaction owns its auxiliary model request, history replacement and checkpoint, and refuses a busy Agent. Permission changes retain their native state and notification behavior. Shutdown cancels pending commands and drains SDK command waiters before releasing Agents. Timeout is not rollback; clients must not retry automatically. See the [protocol](../protocol/README.md) for results and errors. Permission commands change only the receiving Session. Later queries and restored Sessions retain its persisted permission facts; other Sessions keep their own state and new Sessions use the configured defaults. Neither the caller's launch configuration nor saved user defaults are rewritten. Model selection is not an SDK slash command; its resume override remains the separate behavior described above. @@ -140,7 +140,7 @@ Read these pages when the plugin contract is not enough. They move from the wire #### What the model sees -Ordinary `session/query` input and accepted `session/prompt` content enter a user message with their original block order. Ordinary delivery selects a queued turn or the next available step without reapplying permission defaults. Inline `SdkEncodedImageBlock` values are validated and committed through the composition's attachment store first, so the session log retains content-addressed image references rather than base64 bytes. This package adds no system-prompt prose or tool schema; those come from the other plugins in the composition. +Ordinary `session/query` input and accepted `session/prompt` content enter a user message with their original block order. Ordinary input enters the prompt queue without reapplying permission defaults. Inline `SdkEncodedImageBlock` values are validated and committed through the composition's attachment store first, so the session log retains content-addressed image references rather than base64 bytes. This package adds no system-prompt prose or tool schema; those come from the other plugins in the composition. #### Token effect diff --git a/packages/sdk/server/README.zh.md b/packages/sdk/server/README.zh.md index d59d636270..d08135de11 100644 --- a/packages/sdk/server/README.zh.md +++ b/packages/sdk/server/README.zh.md @@ -37,13 +37,13 @@ kind: "package-reference" 下列支持范围是桌面已有、无需图形界面即可执行的原生命令。`/permission ` 使用这条原生调用路径;Desktop 的 `/model` 选择器使用独立的模型选择 API。 -`session/query` 是高层 SDK `run()` 发送字符串和内容块数组时使用的协议入口。普通输入保留内容块,使用选定的 queue/steer 操作。完整 SDK 识别裸 `/compact`、带非空 preset 的 `/permission `、`/plan [off|message]` 和 `/goal [objective|clear|edit objective|pause|resume]`,这些命令按官方定义 ID 识别。裸 `/permission` 或 `/权限`、`/compact extra` 以及 `/model` 等其余输入仍是普通提示词。命令缺失时也保留提示词路径;选中的 handler 失败后绝不回退。未知 preset 是原生命令错误。随已识别命令提交的编码图片块经过原生附件接纳。`session/prompt` 保留为低层排队输入入口,不经过原生 slash command 路由。 +`session/query` 是高层 SDK `run()` 发送字符串和内容块数组时使用的协议入口。普通输入保留内容块,使用既有的提示词队列。完整 SDK 识别裸 `/compact`、带非空 preset 的 `/permission `、`/plan [off|message]` 和 `/goal [objective|clear|edit objective|pause|resume]`,这些命令按官方定义 ID 识别。裸 `/permission` 或 `/权限`、`/compact extra` 以及 `/model` 等其余输入仍是普通提示词。命令缺失时也保留提示词路径;选中的 handler 失败后绝不回退。未知 preset 是原生命令错误。随已识别命令提交的编码图片块经过原生附件接纳。`session/prompt` 保留为低层排队输入入口,不经过原生 slash command 路由。 Host 与桌面适配器共用 `dsh-commands/builtin` 的定义身份及中英文别名解析。`/压缩`、`/权限`、`/计划` 和 `/目标` 跟随重命名后的官方定义,执行使用当前注册名。精确名称优先,但无关的同名定义不是 SDK 内置命令,仍作为普通提示词。其他内置能力仍不属于 SDK 命令集合。 第一个文本块提供完整命令行;编码图片可位于它之前或之后。该行匹配到受支持命令时,它必须是唯一的文本块,其余块必须为编码图片。额外文本块、持久图片引用及其他内容类型会在执行或入队前返回 JSON-RPC 错误,不回退为普通提示词。普通提示词保留全部内容块及其顺序。空数组和只包含空白文本的数组会被拒绝;允许仅图片输入。 -`session/command` 接受 `{ sessionId, line }`,使用同样四类内置定义的 ASCII 注册名或英文规范别名;忽略前导空白。中文别名使用 `session/query`。不支持的定义身份返回 JSON-RPC 错误。命令身份校验使用已初始化的接收 Agent 目录;身份校验拒绝会保留该 Session,不执行 handler,也不提交 prompt。它要求 permission preset 非空,其余参数由原生 handler 校验。完整 sdk profile 组成这些原生 handler;缺少所请求命令的 profile 会拒绝调用。服务端解析自己拥有的存活 Agent,并调用 `commands.execute()`,不排入普通 prompt,也不等待 idle。压缩负责其辅助模型请求、历史替换和 checkpoint,并拒绝忙碌 Agent。权限变更保留原生状态和通知行为。Shutdown 取消待决命令,在释放 Agent 前排空 SDK 命令等待者。超时不等于回滚,客户端不能自动重试。结果和错误见[协议](../protocol/README.zh.md)。 +已识别的命令通过接收 Agent 的原生命令注册器执行。Handler 校验命令参数和附件。压缩负责其辅助模型请求、历史替换和 checkpoint,并拒绝忙碌 Agent。权限变更保留原生状态和通知行为。Shutdown 取消待决命令,在释放 Agent 前排空 SDK 命令等待者。超时不等于回滚,客户端不能自动重试。结果和错误见[协议](../protocol/README.zh.md)。 权限命令只修改接收命令的 Session。后续输入和恢复的 Session 保留其持久化权限事实;其他 Session 保留各自状态,新 Session 使用配置的默认值。调用方的启动配置和已保存的用户默认值均不会被重写。模型选择不是 SDK slash 命令;恢复时的模型覆盖仍按上文描述的独立行为执行。 @@ -140,7 +140,7 @@ Stdout 只承载 JSON-RPC 帧,客户端可以逐字节解析;诊断信息应 #### 模型看到什么 -普通 `session/query` 输入和已接受的 `session/prompt` 内容按原始内容块顺序进入用户消息。普通输入的递送选择排队的新 turn 或下个可用 step,不会重新应用权限默认值。内联 `SdkEncodedImageBlock` 会先通过组合中的附件存储完成校验与提交,因此会话日志保留内容寻址的图片引用而不是 base64 字节。此包不会添加系统提示词文本或工具 schema;这些内容来自组合中的其他插件。 +普通 `session/query` 输入和已接受的 `session/prompt` 内容按原始内容块顺序进入用户消息。普通输入进入提示队列,不会重新应用权限默认值。内联 `SdkEncodedImageBlock` 会先通过组合中的附件存储完成校验与提交,因此会话日志保留内容寻址的图片引用而不是 base64 字节。此包不会添加系统提示词文本或工具 schema;这些内容来自组合中的其他插件。 #### Token 影响 diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index 87074a7f6d..1879b23e2e 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -13,8 +13,6 @@ import { SdkUserQuestionBridge } from './user-questions.ts' import { queryCommand } from './query-input.ts' import { queryCommandImages, queryContent } from './query-content.ts' import { brandString } from '@deepseek-ai/dsh-brand' -import { parseCommand } from '@deepseek-ai/dsh-commands' -import { builtinCommandName, resolveCommand } from '@deepseek-ai/dsh-commands/builtin' import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent' import { admitEncodedImages, type EncodedImageAttachment, type ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { createUserMessage, ReasoningEffortId, type ContentBlock, type LlmRuntime } from '@deepseek-ai/dsh-llm' @@ -34,7 +32,6 @@ import type { InitializeResult, JsonRpcTransportPeer, SessionEventNotification, - SessionCommandParams, SessionQueryParams, SessionQueryResult, SessionPromptParams, @@ -49,8 +46,6 @@ import type { SubagentStartedNotification, } from '@deepseek-ai/dsh-sdk-protocol' -const COMMAND_USAGE = 'The SDK command endpoint supports only /compact, /permission , /plan [off|message], or /goal [objective|clear|edit objective|pause|resume]' - interface SessionRecord { handle: AgentHandle /** Latest live failure not superseded by a subsequently committed terminal. */ @@ -273,10 +268,6 @@ export class HarnessSdkJsonRpcServer { * @returns the durable message identity. */ async prompt(params: SessionPromptParams): Promise { - return this.submitPrompt(params, 'queue') - } - - private async submitPrompt(params: SessionPromptParams, delivery: 'queue' | 'steer'): Promise { if (!this.initialized) throw new Error('SDK server is not initialized') const rec = await this.getOrCreateSession(params.sessionId) this.lifetime.signal.throwIfAborted() @@ -293,14 +284,13 @@ export class HarnessSdkJsonRpcServer { content, source: { kind: 'user' }, }) - if (delivery === 'steer') rec.handle.agent.steer(message) - else rec.handle.agent.followup(message) + rec.handle.agent.followup(message) return { messageId: message.id } } /** * Dispatch text as a Desktop-style input; native commands own Session state changes. - * @param params - ordered content blocks, receiving Session and ordinary-prompt delivery. + * @param params - ordered content blocks and receiving Session. * @returns a prompt receipt or native command acknowledgment; command activity completes by notification. * @throws on runtime failure; a recognized command failure never falls back to a prompt. */ @@ -322,10 +312,19 @@ export class HarnessSdkJsonRpcServer { (current) => { this.queryActivities.delete(current) }) this.queryActivities.add(activity) try { - const execution = await this.queryInvocation.run(activity, - () => this.runCommand({ sessionId: params.sessionId, line }, images)) - activity.accept(execution) - return { kind: 'command', execution } + const task = this.queryInvocation.run(activity, () => commands.execute(rec.handle.agent, line, images.map(image => ({ + type: 'image', data: image.data, mediaType: image.mimeType, + ...image.name === undefined ? {} : { name: image.name }, + })), this.lifetime.signal)) + this.commandTasks.add(task) + try { + const execution = await task + if (execution === undefined) throw new Error('The selected command is unavailable in this SDK profile') + activity.accept(execution) + return { kind: 'command', execution } + } finally { + this.commandTasks.delete(task) + } } catch (error) { activity.close() throw error @@ -333,62 +332,13 @@ export class HarnessSdkJsonRpcServer { } } } - const receipt = await this.submitPrompt({ + const receipt = await this.prompt({ sessionId: params.sessionId, contentBlocks: params.contentBlocks, - }, params.delivery) + }) return { kind: 'prompt', ...receipt } } - /** - * Execute supported compact, permission, plan, or goal input through the native command registry. - * ASCII registered names and canonical English aliases are accepted; Chinese aliases use query. - * @param params - target Session and complete command line. - * @returns the native handler result; command errors remain result values. - * @throws for unsupported input, unavailable commands, or runtime/transport failure. - */ - async executeCommand(params: SessionCommandParams): Promise { - return this.runCommand(params, []) - } - - private async runCommand(params: SessionCommandParams, images: SdkEncodedImageBlock[]): Promise { - if (!this.initialized) throw new Error('SDK server is not initialized') - if (this.shuttingDown) throw new Error('SDK server is shutting down') - const parsed = parseCommand(params.line.trimStart()) - if (parsed === undefined) { - throw new TypeError(COMMAND_USAGE) - } - const commands = this.ctx.get('commands') - if (commands === undefined) { - throw new Error('Commands are unavailable in this SDK profile') - } - const rec = await this.getOrCreateSession(params.sessionId) - this.lifetime.signal.throwIfAborted() - this.assertLiveAgent(rec, params.sessionId) - const descriptor = resolveCommand(parsed.name, commands.list(rec.handle.agent)) - if (descriptor === undefined) throw new Error(`/${parsed.name} is unavailable in this SDK profile`) - const builtin = builtinCommandName(descriptor) - if (builtin !== 'compact' && builtin !== 'plan' && builtin !== 'goal' - && (builtin !== 'permission' || parsed.rawInput.trim() === '')) { - throw new TypeError(COMMAND_USAGE) - } - const line = `/${descriptor.name}${parsed.rawInput}` - const task = commands.execute(rec.handle.agent, line, images.map(image => ({ - type: 'image', data: image.data, mediaType: image.mimeType, - ...image.name === undefined ? {} : { name: image.name }, - })), this.lifetime.signal) - this.commandTasks.add(task) - try { - const result = await task - if (result === undefined) { - throw new Error(`/${parsed.name} is unavailable in this SDK profile`) - } - return result - } finally { - this.commandTasks.delete(task) - } - } - /** * Restore a persisted session and repair its interrupted final turn without sending input. * Uses the initialized model route while preserving the stored session identity and directory. @@ -553,22 +503,13 @@ export class HarnessSdkJsonRpcServer { return this.prompt(params as unknown as SessionPromptParams) case 'session/query': { if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0 - || (params.delivery !== 'queue' && params.delivery !== 'steer') - || Object.keys(params).some(key => key !== 'sessionId' && key !== 'contentBlocks' && key !== 'delivery')) { - throw new TypeError('session/query requires only a non-empty sessionId, contentBlocks and queue/steer delivery') + || Object.keys(params).some(key => key !== 'sessionId' && key !== 'contentBlocks')) { + throw new TypeError('session/query requires only a non-empty sessionId and contentBlocks') } return this.query({ - sessionId: brandString(params.sessionId), contentBlocks: queryContent(params.contentBlocks), delivery: params.delivery, + sessionId: brandString(params.sessionId), contentBlocks: queryContent(params.contentBlocks), }) } - case 'session/command': { - if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0 - || typeof params.line !== 'string' - || Object.keys(params).some(key => key !== 'sessionId' && key !== 'line')) { - throw new TypeError('session/command requires only a non-empty sessionId and a line string') - } - return this.executeCommand({ sessionId: brandString(params.sessionId), line: params.line }) - } case 'session/resume': { const sessionId = params?.sessionId if (typeof sessionId !== 'string' || sessionId.length === 0) { diff --git a/packages/sdk/server/tests/commands.spec.ts b/packages/sdk/server/tests/commands.spec.ts index 37cb8fa38b..4c6b277f07 100644 --- a/packages/sdk/server/tests/commands.spec.ts +++ b/packages/sdk/server/tests/commands.spec.ts @@ -7,7 +7,7 @@ import CommandRuntime, { CommandDefinitionId, type CommandDefinition, type Comma import { AttachmentId, type AttachmentStore, type ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { LlmAdapter, type GenerateOptions, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' -import { JsonRpcLineTransport, JsonRpcResponseError, type JsonRpcTransportPeer } from '@deepseek-ai/dsh-sdk-protocol' +import { JsonRpcLineTransport, type JsonRpcTransportPeer } from '@deepseek-ai/dsh-sdk-protocol' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { HarnessSdkJsonRpcServer } from '../src/server.ts' @@ -54,18 +54,22 @@ async function setup(registry = true, peer?: JsonRpcTransportPeer) { const register = (handler: CommandDefinition['handler']) => { ctx.effect(() => ctx.commands.register({ name: 'compact', definitionId: CommandDefinitionId('@deepseek-ai/dsh-command-compact'), description: 'Fixture command', handler })) } - const command = () => server.executeCommand({ sessionId: SessionId('commands'), line: '/compact' }) + const command = async () => { + const result = await server.query({ sessionId: SessionId('commands'), contentBlocks: [{ type: 'text', text: '/compact' }] }) + if (result.kind !== 'command') throw new Error('Fixture command was routed as a prompt') + return result.execution + } return { ctx, server, loop, initialize, register, command } } describe('SDK command dispatch', () => { - it.each([' ', '\t\n', '\u3000'])('accepts leading whitespace through the strict wire endpoint: %j', async (prefix) => { + it.each([' ', '\t\n', '\u3000'])('accepts leading whitespace through the query wire endpoint: %j', async (prefix) => { const h = await setup() await h.initialize() const handler = vi.fn((_invocation: CommandInvocation) => ({ kind: 'success' as const })) h.register(handler) - await expect(h.server.handleRequest('session/command', { sessionId: 'strict-space', line: `${prefix}/compact` })) - .resolves.toMatchObject({ result: { kind: 'success' } }) + await expect(h.server.handleRequest('session/query', { sessionId: 'query-space', contentBlocks: [{ type: 'text', text: `${prefix}/compact` }] })) + .resolves.toMatchObject({ kind: 'command', execution: { result: { kind: 'success' } } }) expect(handler).toHaveBeenCalledOnce() expect(handler.mock.calls[0]![0].rawInput).toBe('') }) @@ -90,14 +94,6 @@ describe('SDK command dispatch', () => { ]) }) - it.each([undefined, {}, { sessionId: '' }, { sessionId: 's', line: 1 }, - { sessionId: 's', line: '/compact', extra: true }, { sessionId: 's', line: '/compact', attachments: [] }])('rejects malformed wire parameters %j before creating a Session', async (params) => { - const h = await setup() - await h.initialize() - await expect(h.server.handleRequest('session/command', params)).rejects.toThrow('requires only') - expect(h.ctx.agents.list()).toEqual([]) - }) - it('rejects malformed content before creating a Session', async () => { const h = await setup() await h.initialize() @@ -112,7 +108,7 @@ describe('SDK command dispatch', () => { [{ ...image, attachment: { attachmentId: 'other-session' } }]] for (const contentBlocks of invalid) { await expect(h.server.handleRequest('session/query', { - sessionId: 'invalid-content', delivery: 'queue', contentBlocks, + sessionId: 'invalid-content', contentBlocks, })).rejects.toThrow(TypeError) expect(h.ctx.agents.list()).toEqual([]) } @@ -124,7 +120,7 @@ describe('SDK command dispatch', () => { const handler = vi.fn(() => ({ kind: 'success' as const })) h.register(handler) const response = await h.server.handleRequest('session/query', { - sessionId: 'refused-image', delivery: 'queue', + sessionId: 'refused-image', contentBlocks: [{ type: 'text', text: '/compact' }, { type: 'image', data: 'AQ==', mimeType, ...mimeType === 'image/png' ? {} : { name: 'example' } }], }) @@ -152,7 +148,7 @@ describe('SDK command dispatch', () => { const attachments = [{ type: 'image', data: 'AQ==', mimeType: 'image/png', name: 'diagram.png' }] const text = { type: 'text', text: '/plan inspect' } const response = await h.server.handleRequest('session/query', { - sessionId: 'images', delivery: 'steer', + sessionId: 'images', contentBlocks: order === 'image-first' ? [...attachments, text] : [text, ...attachments], }) expect(response).toMatchObject({ kind: 'command', execution: { result: { kind: 'success' } } }) @@ -177,7 +173,7 @@ describe('SDK command dispatch', () => { name: 'plan', definitionId: CommandDefinitionId('@deepseek-ai/dsh-plan-mode'), description: 'Plan', input: { hint: 'Task', attachments: true }, handler, })) await expect(h.server.handleRequest('session/query', { - sessionId: 'refused-content', delivery: 'queue', contentBlocks: [ + sessionId: 'refused-content', contentBlocks: [ { type: 'image', data: 'AQ==', mimeType: 'image/png' }, { type: 'text', text: '/plan off' }, extra, ], @@ -199,7 +195,7 @@ describe('SDK command dispatch', () => { h.ctx.effect(() => h.ctx.commands.register({ name: 'plan', definitionId: CommandDefinitionId('@deepseek-ai/dsh-plan-mode'), description: 'Plan', input: { hint: 'Task', attachments: true }, handler, })) - const request = h.server.query({ sessionId: SessionId('image-shutdown'), delivery: 'queue', + const request = h.server.query({ sessionId: SessionId('image-shutdown'), contentBlocks: [{ type: 'text', text: '/plan inspect' }, { type: 'image', data: 'AQ==', mimeType: 'image/png' }], }) const rejected = expect(request).rejects.toThrow('shutting down') @@ -211,23 +207,12 @@ describe('SDK command dispatch', () => { expect(h.ctx.agents.list()).toEqual([]) }) - it.each(['text', '/model', '/unknown', '/permission', '/permission \t\n'])('rejects unsupported input %s without invoking another command', async (line) => { - const h = await setup() - await h.initialize() - const handler = vi.fn(() => ({ kind: 'success' as const })) - h.register(handler) - await expect(h.server.handleRequest('session/command', { sessionId: 's', line })).rejects.toThrow() - expect(handler).not.toHaveBeenCalled() - expect(h.ctx.agents.list().flatMap(agent => agent.session.snapshotEvents())).toEqual([]) - expect(h.ctx.agents.list()).toHaveLength(line === 'text' ? 0 : 1) - }) - it.each([ ['compact', '@deepseek-ai/dsh-command-compact', '/compact', '/压缩'], ['permission', '@deepseek-ai/dsh-permission-presets', '/permission read-only', '/权限 read-only'], ['plan', '@deepseek-ai/dsh-plan-mode', '/plan', '/计划'], ['goal', '@deepseek-ai/dsh-command-goal', '/goal', '/目标'], - ])('accepts the %s alias only through query and delivers its lifecycle before resolution', async (name, definitionId, line, alias) => { + ])('accepts the %s English and Chinese aliases and delivers their lifecycle before resolution', async (name, definitionId, line, alias) => { const input = new PassThrough() const output = new PassThrough() const serverWire = new JsonRpcLineTransport(input, output) @@ -257,19 +242,11 @@ describe('SDK command dispatch', () => { name, definitionId: CommandDefinitionId(definitionId), description: 'Fixture command', handler, })) const sessionId = SessionId('alias-command') - const rejected = client.request('session/command', { sessionId, line: alias }) - await expect(rejected).rejects.toBeInstanceOf(JsonRpcResponseError) - await expect(rejected).rejects.toMatchObject({ code: -32603 }) - await expect(rejected).rejects.toThrow('only /compact') - expect(handler).not.toHaveBeenCalled() - expect(received).toEqual([]) - expect(h.ctx.agents.list()).toEqual([]) - - await expect(client.request('session/command', { sessionId, line })) - .resolves.toMatchObject({ result: { kind: 'success', text: 'native outcome' } }) + await expect(client.request('session/query', { sessionId, contentBlocks: [{ type: 'text', text: line }] })) + .resolves.toMatchObject({ kind: 'command', execution: { result: { kind: 'success', text: 'native outcome' } } }) expect(handler).toHaveBeenCalledOnce() received.length = 0 - const result = await client.request('session/query', { sessionId, contentBlocks: [{ type: 'text', text: alias }], delivery: 'queue' }) + const result = await client.request('session/query', { sessionId, contentBlocks: [{ type: 'text', text: alias }] }) expect(handler).toHaveBeenCalledTimes(2) const commandId = handler.mock.calls[1]![0].commandId expect(result).toMatchObject({ kind: 'command', execution: { commandId, result: { kind: 'success', text: 'native outcome' } } }) @@ -286,7 +263,7 @@ describe('SDK command dispatch', () => { ['permission', '@deepseek-ai/dsh-permission-presets', '权限', ' read-only'], ['plan', '@deepseek-ai/dsh-plan-mode', '计划', ' task'], ['goal', '@deepseek-ai/dsh-command-goal', '目标', ' task'], - ])('dispatches the renamed %s definition through both SDK entries', async (name, id, alias, args) => { + ])('dispatches the renamed %s definition through its registered name and aliases', async (name, id, alias, args) => { const h = await setup() await h.initialize() const registered = `renamed-${name}` @@ -297,18 +274,14 @@ describe('SDK command dispatch', () => { const sessionId = SessionId('renamed') for (const token of [name, alias, registered]) { await expect(h.server.handleRequest('session/query', { - sessionId, contentBlocks: [{ type: 'text', text: `/${token}${args}` }], delivery: 'queue', + sessionId, contentBlocks: [{ type: 'text', text: `/${token}${args}` }], })).resolves.toMatchObject({ kind: 'command', execution: { result: { kind: 'success' } } }) } - for (const token of [name, registered]) { - await expect(h.server.handleRequest('session/command', { sessionId, line: `/${token}${args}` })) - .resolves.toMatchObject({ result: { kind: 'success' } }) - } - expect(handler).toHaveBeenCalledTimes(5) - expect(handler.mock.calls.map(([invocation]) => invocation.rawInput)).toEqual(Array.from({ length: 5 }, () => args)) + expect(handler).toHaveBeenCalledTimes(3) + expect(handler.mock.calls.map(([invocation]) => invocation.rawInput)).toEqual(Array.from({ length: 3 }, () => args)) const events = h.ctx.agents.get(sessionId)!.session.snapshotEvents() expect(events.filter(event => event.type === 'command/run').map(event => event.data.name)) - .toEqual(Array.from({ length: 5 }, () => registered)) + .toEqual(Array.from({ length: 3 }, () => registered)) expect(events.every(event => event.type === 'command/run' || event.type === 'command/done')).toBe(true) }) @@ -325,10 +298,8 @@ describe('SDK command dispatch', () => { })) const sessionId = SessionId('unrelated') const line = `/${name}${args}` - await expect(h.server.handleRequest('session/command', { sessionId, line })).rejects.toThrow('only /compact') - expect(h.ctx.agents.get(sessionId)!.session.snapshotEvents()).toEqual([]) await expect(h.server.handleRequest('session/query', { - sessionId, contentBlocks: [{ type: 'text', text: line }], delivery: 'queue', + sessionId, contentBlocks: [{ type: 'text', text: line }], })).resolves.toMatchObject({ kind: 'prompt' }) await h.server.wait({ sessionId }) expect(handler).not.toHaveBeenCalled() @@ -338,18 +309,23 @@ describe('SDK command dispatch', () => { expect(h.ctx.agents.get(sessionId)!.session.snapshotEvents().some(event => event.type === 'command/run')).toBe(false) }) - it('requires a preset for a renamed permission definition', async () => { + it('keeps a renamed permission command without a preset as ordinary input', async () => { const h = await setup() - await h.initialize() + const model = new TextModel() + h.ctx.effect(() => h.ctx.llm.registerAdapter(['query-model'], model)) + await h.server.initialize({ cwd: process.cwd(), provider: 'query-model', model: 'model' }) const handler = vi.fn(() => ({ kind: 'success' as const })) h.ctx.effect(() => h.ctx.commands.register({ name: 'access', definitionId: CommandDefinitionId('@deepseek-ai/dsh-permission-presets'), description: 'Permission', handler, })) - await expect(h.server.executeCommand({ sessionId: SessionId('empty-preset'), line: '/access' })) - .rejects.toThrow('only /compact') + const sessionId = SessionId('empty-preset') + await expect(h.server.query({ sessionId, contentBlocks: [{ type: 'text', text: '/access' }] })) + .resolves.toMatchObject({ kind: 'prompt' }) + await h.server.wait({ sessionId }) expect(handler).not.toHaveBeenCalled() - expect(h.ctx.agents.get(SessionId('empty-preset'))!.session.snapshotEvents()).toEqual([]) + expect(model.requests[0]!.messages.some(message => message.content.some(block => block.type === 'text' && block.text === '/access'))).toBe(true) + expect(h.ctx.agents.get(sessionId)!.session.snapshotEvents().some(event => event.type === 'command/run')).toBe(false) }) it('reports an execution unavailable after catalog resolution', async () => { @@ -357,35 +333,21 @@ describe('SDK command dispatch', () => { await h.initialize() h.register(() => ({ kind: 'success' })) vi.spyOn(h.ctx.commands, 'execute').mockResolvedValue(undefined) - await expect(h.command()).rejects.toThrow('/compact is unavailable') + await expect(h.command()).rejects.toThrow('selected command is unavailable') }) - it('requires initialization and the composed registry and command', async () => { - const absent = await setup(false) - await expect(absent.command()).rejects.toThrow('not initialized') - await absent.initialize() - await expect(absent.command()).rejects.toThrow('Commands are unavailable') - const empty = await setup() - await empty.initialize() - await expect(empty.command()).rejects.toThrow('/compact is unavailable') - await expect(empty.server.executeCommand({ sessionId: SessionId('commands'), line: '/permission read-only' })) - .rejects.toThrow('/permission is unavailable') - }) - - it.each(['strict', 'query'] as const)('passes explicit permission input to the native handler through %s', async (entry) => { + it('passes explicit permission input to the native handler', async () => { const h = await setup() await h.initialize() const handler = vi.fn((_invocation: CommandInvocation) => ({ kind: 'error' as const, text: 'native preset refusal' })) h.ctx.effect(() => h.ctx.commands.register({ name: 'permission', definitionId: CommandDefinitionId('@deepseek-ai/dsh-permission-presets'), description: 'Fixture permission', input: { hint: 'Preset' }, handler })) const sessionId = SessionId('permission') const line = '/permission deployment-preset' - const result = entry === 'strict' - ? await h.server.executeCommand({ sessionId, line }) - : await h.server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }], delivery: 'steer' }) + const result = await h.server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }] }) expect(handler).toHaveBeenCalledOnce() expect(handler.mock.calls[0]![0].rawInput).toBe(' deployment-preset') const expected = { result: { kind: 'error', text: 'native preset refusal' } } - expect(result).toMatchObject(entry === 'strict' ? expected : { kind: 'command', execution: expected }) + expect(result).toMatchObject({ kind: 'command', execution: expected }) expect(h.ctx.agents.get(sessionId)!.session.snapshotEvents().map(event => event.type)) .toEqual(['command/run', 'command/done']) }) @@ -395,7 +357,7 @@ describe('SDK command dispatch', () => { await h.initialize() const handler = vi.fn((_invocation: CommandInvocation) => ({ kind: 'success' as const, text: 'native plan result' })) h.ctx.effect(() => h.ctx.commands.register({ name: 'plan', definitionId: CommandDefinitionId('@deepseek-ai/dsh-plan-mode'), description: 'Plan', input: { hint: '[off|message]' }, handler })) - const result = await h.server.query({ sessionId: SessionId('plan'), contentBlocks: [{ type: 'text', text: line }], delivery: 'queue' }) + const result = await h.server.query({ sessionId: SessionId('plan'), contentBlocks: [{ type: 'text', text: line }] }) expect(result).toMatchObject({ kind: 'command', execution: { result: { kind: 'success', text: 'native plan result' } } }) expect(handler.mock.calls[0]![0].rawInput).toBe(line.slice('/plan'.length)) expect(h.ctx.agents.get(SessionId('plan'))!.session.snapshotEvents().map(event => event.type)) @@ -417,7 +379,7 @@ describe('SDK command dispatch', () => { name, definitionId: CommandDefinitionId(definitionId), description: 'Fixture command', input: { hint: 'Input' }, handler, })) const sessionId = SessionId('unicode-command') - const result = await h.server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }], delivery: 'queue' }) + const result = await h.server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }] }) expect(result).toMatchObject({ kind: 'command', execution: { result: { kind: 'success', text: 'native outcome' } } }) expect(handler).toHaveBeenCalledOnce() expect(handler.mock.calls[0]![0].rawInput).toBe(rawInput) @@ -430,8 +392,11 @@ describe('SDK command dispatch', () => { it('passes arguments unchanged and propagates handler failures', async () => { const h = await setup() await h.initialize() - h.register(({ rawInput }) => { throw new Error(`handler saw:${rawInput}`) }) - await expect(h.server.handleRequest('session/command', { sessionId: 'commands', line: '/compact extra' })) + h.ctx.effect(() => h.ctx.commands.register({ + name: 'plan', definitionId: CommandDefinitionId('@deepseek-ai/dsh-plan-mode'), description: 'Plan', + handler: ({ rawInput }) => { throw new Error(`handler saw:${rawInput}`) }, + })) + await expect(h.server.handleRequest('session/query', { sessionId: 'commands', contentBlocks: [{ type: 'text', text: '/plan extra' }] })) .rejects.toThrow('handler saw: extra') expect(h.ctx.agents.get(SessionId('commands'))!.session.snapshotEvents().at(-1)?.type).toBe('command/done') }) @@ -443,8 +408,6 @@ describe('SDK command dispatch', () => { await h.command() await h.loop.dispose() await expect(h.command()).rejects.toThrow('disposed outside the server') - await expect(h.server.query({ sessionId: SessionId('commands'), contentBlocks: [{ type: 'text', text: '/compact' }], delivery: 'queue' })) - .rejects.toThrow('disposed outside the server') }) it('cancels an in-flight command on shutdown and rejects later admission', async () => { @@ -467,7 +430,7 @@ describe('SDK command dispatch', () => { await expect(h.command()).rejects.toThrow('shutting down') }) - it.each(['command', 'query-command', 'query-prompt'] as const)('does not execute %s while its Session is being created at shutdown', async (entry) => { + it.each(['command', 'prompt'] as const)('does not execute %s while its Session is being created at shutdown', async (entry) => { const h = await setup() await h.initialize() const handler = vi.fn(() => ({ kind: 'success' as const })) @@ -482,8 +445,9 @@ describe('SDK command dispatch', () => { await release.promise return handle }) - const execution = entry === 'command' ? h.command() - : h.server.query({ sessionId: SessionId('commands'), contentBlocks: [{ type: 'text', text: entry === 'query-command' ? '/compact' : 'ordinary input' }], delivery: 'queue' }) + const execution = h.server.query({ sessionId: SessionId('commands'), + contentBlocks: [{ type: 'text', text: entry === 'command' ? '/compact' : 'ordinary input' }], + }) const rejected = expect(execution).rejects.toThrow('shutting down') await created.promise const shutdown = h.server.shutdown() @@ -495,11 +459,11 @@ describe('SDK command dispatch', () => { }) describe('SDK query dispatch', () => { - it.each([undefined, {}, { sessionId: '', contentBlocks: [{ type: 'text', text: 'go' }], delivery: 'queue' }, - { sessionId: 'q', text: 'go', delivery: 'queue' }, - { sessionId: 'q', contentBlocks: [{ type: 'text', text: 'go' }], delivery: 'later' }, - { sessionId: 'q', contentBlocks: [{ type: 'text', text: 'go' }], delivery: 'queue', permission: 'full' }, - { sessionId: 'q', contentBlocks: [{ type: 'text', text: 'go' }], delivery: 'queue', attachments: [] }, + it.each([undefined, {}, { sessionId: '', contentBlocks: [{ type: 'text', text: 'go' }] }, + { sessionId: 'q', text: 'go' }, + { sessionId: 'q', contentBlocks: [{ type: 'text', text: 'go' }], delivery: 'queue' }, + { sessionId: 'q', contentBlocks: [{ type: 'text', text: 'go' }], permission: 'full' }, + { sessionId: 'q', contentBlocks: [{ type: 'text', text: 'go' }], attachments: [] }, ])('rejects invalid query fields %j', async (params) => { const h = await setup() await h.initialize() @@ -509,7 +473,7 @@ describe('SDK query dispatch', () => { it.each(['/compact', '/permission read-only'])('preserves %s without a command registry and requires a live initialized server', async (text) => { const h = await setup(false) - const params = { sessionId: SessionId('q'), contentBlocks: [{ type: 'text' as const, text }], delivery: 'queue' as const } + const params = { sessionId: SessionId('q'), contentBlocks: [{ type: 'text' as const, text }] } await expect(h.server.query(params)).rejects.toThrow('not initialized') const model = new TextModel() h.ctx.effect(() => h.ctx.llm.registerAdapter(['query-model'], model)) @@ -526,7 +490,7 @@ describe('SDK query dispatch', () => { await h.initialize() h.register(() => ({ kind: 'error', text: 'native refusal' })) const response = await h.server.handleRequest('session/query', { - sessionId: 'q', contentBlocks: [{ type: 'text', text: ' \n/compact\t ' }], delivery: 'queue', + sessionId: 'q', contentBlocks: [{ type: 'text', text: ' \n/compact\t ' }], }) expect(response).toMatchObject({ kind: 'command', execution: { result: { kind: 'error', text: 'native refusal' } } }) expect(h.ctx.agents.get(SessionId('q'))!.session.snapshotEvents().map(event => event.type)) @@ -539,7 +503,7 @@ describe('SDK query dispatch', () => { const model = new TextModel() h.ctx.effect(() => h.ctx.llm.registerAdapter(['query-model'], model)) await h.server.initialize({ cwd: process.cwd(), provider: 'query-model', model: 'model' }) - expect(await h.server.query({ sessionId: SessionId('q'), contentBlocks: [{ type: 'text', text }], delivery: 'queue' })).toMatchObject({ kind: 'prompt' }) + expect(await h.server.query({ sessionId: SessionId('q'), contentBlocks: [{ type: 'text', text }] })).toMatchObject({ kind: 'prompt' }) await h.server.wait({ sessionId: 'q' }) expect(model.requests).toHaveLength(1) expect(model.requests[0]!.messages.some(message => message.role === 'user' @@ -547,7 +511,7 @@ describe('SDK query dispatch', () => { expect(h.ctx.agents.get(SessionId('q'))!.session.snapshotEvents().some(event => event.type === 'command/run')).toBe(false) }) - it.each(['queue', 'steer'] as const)('preserves ordinary mixed blocks in order with %s delivery', async (delivery) => { + it('queues ordinary mixed blocks in their original order', async () => { const h = await setup() await h.initialize() h.register(() => ({ kind: 'success' })) @@ -572,34 +536,18 @@ describe('SDK query dispatch', () => { { type: 'reasoning', text: 'existing content' }, ] expect(await h.server.handleRequest('session/query', { - sessionId: 'commands', contentBlocks, delivery, + sessionId: 'commands', contentBlocks, })).toMatchObject({ kind: 'prompt' }) expect(saveImages).toHaveBeenCalledWith([ { data: Uint8Array.of(1), mediaType: 'image/png' }, { data: Uint8Array.of(2), mediaType: 'image/png' }, ]) const admitted = [contentBlocks[0], { type: 'image', attachment: refs[0] }, contentBlocks[2], contentBlocks[3], { type: 'image', attachment: refs[1] }, contentBlocks[5], contentBlocks[6]] - const selected = delivery === 'queue' ? queued : steer - const other = delivery === 'queue' ? steer : queued - expect(selected).toHaveBeenCalledWith(expect.objectContaining({ content: admitted })) - expect(other).not.toHaveBeenCalled() + expect(queued).toHaveBeenCalledWith(expect.objectContaining({ content: admitted })) + expect(steer).not.toHaveBeenCalled() expect(agent.session.snapshotEvents().map(event => event.type)).toEqual(['command/run', 'command/done']) }) - it('delivers a steer query through the existing Agent operation', async () => { - const h = await setup() - await h.initialize() - h.register(() => ({ kind: 'success' })) - await h.command() - const agent = h.ctx.agents.get(SessionId('commands'))! - const steer = vi.spyOn(agent, 'steer').mockImplementation(() => {}) - const queued = vi.spyOn(agent, 'followup').mockImplementation(() => {}) - const result = await h.server.query({ sessionId: SessionId('commands'), contentBlocks: [{ type: 'text', text: 'next step' }], delivery: 'steer' }) - expect(result).toMatchObject({ kind: 'prompt' }) - expect(steer).toHaveBeenCalledWith(expect.objectContaining({ content: [{ type: 'text', text: 'next step' }] })) - expect(queued).not.toHaveBeenCalled() - }) - it.each(['/feedback inspect', '/model', '/file', '/export', '/permission', ' \n/权限\t '])('preserves existing prompt behavior for unimplemented input %s', async (text) => { const h = await setup() const model = new TextModel() @@ -608,7 +556,7 @@ describe('SDK query dispatch', () => { const handler = vi.fn(() => ({ kind: 'success' as const })) h.ctx.effect(() => h.ctx.commands.register({ name: 'feedback', description: 'Feedback', input: { hint: 'Task' }, handler })) h.ctx.effect(() => h.ctx.commands.register({ name: 'permission', definitionId: CommandDefinitionId('@deepseek-ai/dsh-permission-presets'), description: 'Permission', input: { hint: 'Preset' }, handler })) - await expect(h.server.query({ sessionId: SessionId('q'), contentBlocks: [{ type: 'text', text }], delivery: 'queue' })).resolves.toMatchObject({ kind: 'prompt' }) + await expect(h.server.query({ sessionId: SessionId('q'), contentBlocks: [{ type: 'text', text }] })).resolves.toMatchObject({ kind: 'prompt' }) await h.server.wait({ sessionId: 'q' }) expect(handler).not.toHaveBeenCalled() expect(model.requests[0]!.messages.some(message => message.content.some(block => block.type === 'text' && block.text === text))).toBe(true) diff --git a/packages/sdk/server/tests/compact-parity.spec.ts b/packages/sdk/server/tests/compact-parity.spec.ts index c2d988df64..2ff610ce82 100644 --- a/packages/sdk/server/tests/compact-parity.spec.ts +++ b/packages/sdk/server/tests/compact-parity.spec.ts @@ -86,7 +86,7 @@ async function compactAndContinue(path: 'sdk' | 'native', cwd: string) { if (agent === undefined) throw new Error('SDK prompt did not create its Agent') const routed = path === 'sdk' - ? await server.query({ sessionId, contentBlocks: [{ type: 'text', text: '/compact' }], delivery: 'queue' }) + ? await server.query({ sessionId, contentBlocks: [{ type: 'text', text: '/compact' }] }) : undefined const execution = path === 'sdk' ? routed?.kind === 'command' ? routed.execution : undefined diff --git a/packages/sdk/server/tests/goal-parity.spec.ts b/packages/sdk/server/tests/goal-parity.spec.ts index c50d703a0d..86a877e337 100644 --- a/packages/sdk/server/tests/goal-parity.spec.ts +++ b/packages/sdk/server/tests/goal-parity.spec.ts @@ -45,7 +45,7 @@ async function scenario(path: 'sdk' | 'native', cwd: string) { }) const line = '/goal Verify the change.' const result = path === 'sdk' - ? await server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }], delivery: 'queue' }) + ? await server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }] }) : await ctx.commands.execute(agent, line, [], new AbortController().signal) if (result === undefined) throw new Error('The goal command was not found') const command = 'kind' in result && result.kind === 'command' ? result.execution : result diff --git a/packages/sdk/server/tests/permission-parity.spec.ts b/packages/sdk/server/tests/permission-parity.spec.ts index ec22ede782..a3b6da2e44 100644 --- a/packages/sdk/server/tests/permission-parity.spec.ts +++ b/packages/sdk/server/tests/permission-parity.spec.ts @@ -105,7 +105,7 @@ async function switchAndContinue(path: 'sdk' | 'native', cwd: string) { if (agent === undefined) throw new Error('The initial prompt did not create its Agent') const dispatch = async (line: string) => { if (path === 'native') return ctx.commands.execute(agent, line, [], new AbortController().signal) - const routed = await runtime.query({ sessionId, contentBlocks: [{ type: 'text', text: line }], delivery: 'queue' }) + const routed = await runtime.query({ sessionId, contentBlocks: [{ type: 'text', text: line }] }) if (routed.kind !== 'command') throw new Error('The explicit permission input was submitted as a prompt') return routed.execution } diff --git a/packages/sdk/server/tests/plan-parity.spec.ts b/packages/sdk/server/tests/plan-parity.spec.ts index 1bb96bc7b9..edb559ab54 100644 --- a/packages/sdk/server/tests/plan-parity.spec.ts +++ b/packages/sdk/server/tests/plan-parity.spec.ts @@ -59,7 +59,7 @@ async function scenario(path: 'sdk' | 'native', outcome: 'approve' | 'dismiss', if (agent === undefined) throw new Error('The initial prompt did not create its Agent') const line = '/plan Design the change.' const result = path === 'sdk' - ? await server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }], delivery: 'queue' }) + ? await server.query({ sessionId, contentBlocks: [{ type: 'text', text: line }] }) : await ctx.commands.execute(agent, line, [], new AbortController().signal) if (result === undefined) throw new Error('The plan command was not found') const command = 'kind' in result && result.kind === 'command' ? result.execution : result diff --git a/packages/sdk/server/tests/query-activity.spec.ts b/packages/sdk/server/tests/query-activity.spec.ts index 2c5bf3f75f..b6eab7a375 100644 --- a/packages/sdk/server/tests/query-activity.spec.ts +++ b/packages/sdk/server/tests/query-activity.spec.ts @@ -61,7 +61,7 @@ async function setup(model = new MockAdapter([]), goal = false) { onTestFinished(async () => { try { await server.shutdown() } finally { await ctx.fiber.dispose() } }) await server.initialize({ cwd: process.cwd(), provider: 'query-activity', model: 'model' }) const sessionId = SessionId('query-activity') - const run = (text: string) => server.query({ sessionId, contentBlocks: [{ type: 'text', text }], delivery: 'queue' }) + const run = (text: string) => server.query({ sessionId, contentBlocks: [{ type: 'text', text }] }) const register = (handler: CommandDefinition['handler']) => ctx.commands.register({ name: 'plan', definitionId: CommandDefinitionId('@deepseek-ai/dsh-plan-mode'), description: 'Plan', handler, }) @@ -276,7 +276,7 @@ describe('SDK query activity completion', () => { const releaseMaintenance = Promise.withResolvers() const maintenance = agent.runMaintenance(() => releaseMaintenance.promise) try { - const response = await h.server.query({ sessionId: h.sessionId, delivery: 'queue', contentBlocks: [ + const response = await h.server.query({ sessionId: h.sessionId, contentBlocks: [ { type: 'text', text: '/goal inspect the reference' }, { type: 'image', data: 'AQ==', mimeType: 'image/png' }, ] }) diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts index 633ebf4079..2badce07be 100644 --- a/packages/sdk/server/tests/server.spec.ts +++ b/packages/sdk/server/tests/server.spec.ts @@ -353,7 +353,7 @@ describe('HarnessSdkJsonRpcServer', () => { if (entry === 'prompt') { await server.prompt({ sessionId: 'image', contentBlocks }) } else { - await server.handleRequest('session/query', { sessionId: 'image', contentBlocks, delivery: 'queue' }) + await server.handleRequest('session/query', { sessionId: 'image', contentBlocks }) } expect(saveImages).toHaveBeenCalledWith([{ data: Uint8Array.of(1), mediaType: 'image/png', name: 'diagram.png' }]) diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index 20260abf83..c9fc440589 100644 --- a/python/sdk/README.i18n.yaml +++ b/python/sdk/README.i18n.yaml @@ -12,8 +12,8 @@ en: ac793c588b13ce87 zh: 502015cda46de3ac /deepseek-harness-python-sdk/run-text-and-commands: - en: 23d4637337dc069a - zh: 2ecc60324f67c8fc + en: b2c847c1452e137d + zh: c595c5e82151d0cb /deepseek-harness-python-sdk/client-approvals: en: fc69be1beb8abff1 zh: 91b56781931a6f68 diff --git a/python/sdk/README.md b/python/sdk/README.md index bec8f16e87..64b47a8191 100644 --- a/python/sdk/README.md +++ b/python/sdk/README.md @@ -61,7 +61,7 @@ with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness: ## Run text and commands -`session.run(input, on_notification=..., delivery="queue")` is the public prompt-or-command input entry for strings and content-block arrays. Both use the runtime's [supported command forms and Desktop aliases](../../packages/sdk/server/README.md#command-input); unrecognized input remains an ordinary prompt with its original block order. `delivery="steer"` targets the next available step for ordinary input, including images. Command admission and timing remain owned by the native handler. +`session.run(input, on_notification=...)` is the public prompt-or-command input entry for strings and content-block arrays. Both use the runtime's [supported command forms and Desktop aliases](../../packages/sdk/server/README.md#command-input); unrecognized input remains an ordinary prompt with its original block order. Ordinary input, including images, uses the existing prompt queue. Command admission and timing remain owned by the native handler. Every call returns `RunResult`, including the receiving `session_id`, root events and Session-tree notifications. `final_response` contains the final assistant text, or an empty string when the activity emits none. State-only commands return the native handler's result text. `finish_reason` reports the terminal outcome. Native command identities and outcomes remain in `command/run` and `command/done` events. A completion without its matching command lifecycle events raises `SdkProtocolError` instead of returning a partial result. @@ -71,7 +71,7 @@ Select a model that supports image input. Submit a command and image in the exis Each call subscribes before sending and releases its subscription before returning or raising. `on_notification` receives the input's Session-tree activity in wire order; the interval can include overlapping work. Calls may overlap without consuming each other's results. Native refusals return `finish_reason="error"`; routing, protocol, transport and observer failures raise. Malformed native-command responses raise `SdkProtocolError`, retaining their validation cause. A timeout or observer failure does not roll back runtime work or authorize an automatic retry. `request_timeout_seconds` bounds the protocol response wait, not later input activity. -The default full `sdk` profile provides the supported native commands; `sdk-minimal` keeps unsupported input on its ordinary prompt path. `/compact` can make an auxiliary model request and completes without a normal turn or idle notification; empty history can succeed without a summary. The lower-level `HarnessClient.session_command(session_id, line)` accepts ASCII registered names or canonical English aliases of supported builtin definitions, without prompt fallback or attachments, and returns the native `CommandExecution`. Use `run()` for Chinese aliases. See the [compaction example](examples/README.md#compact-a-full-sdk-session). +The default full `sdk` profile provides the supported native commands; `sdk-minimal` keeps unsupported input on its ordinary prompt path. `/compact` can make an auxiliary model request and completes without a normal turn or idle notification; empty history can succeed without a summary. See the [compaction example](examples/README.md#compact-a-full-sdk-session). `/permission ` changes only the receiving Session. An unknown preset returns a command error without changing policy. Later input and restoration retain successful changes; other Sessions and the caller's `DeepSeekHarnessConfig` keep their own values. A running approval-policy change can inject a notice and cause another model step. See the [permission example](examples/README.md#change-session-permissions). diff --git a/python/sdk/README.zh.md b/python/sdk/README.zh.md index 0d777b96fa..6a1139f16e 100644 --- a/python/sdk/README.zh.md +++ b/python/sdk/README.zh.md @@ -61,7 +61,7 @@ with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness: ## 运行文本与命令 -`session.run(input, on_notification=..., delivery="queue")` 是字符串和内容块数组共用的公开提示词/命令输入入口。两者都使用运行时的[命令形式与 Desktop 别名](../../packages/sdk/server/README.zh.md#command-input)识别规则;未识别的输入保持普通提示词及原始内容块顺序。对普通输入,包括图片,`delivery="steer"` 指向下一个可用步骤。命令的接纳规则与执行时序仍由原生处理器负责。 +`session.run(input, on_notification=...)` 是字符串和内容块数组共用的公开提示词/命令输入入口。两者都使用运行时的[命令形式与 Desktop 别名](../../packages/sdk/server/README.zh.md#command-input)识别规则;未识别的输入保持普通提示词及原始内容块顺序。普通输入(包括图片)使用既有的提示词队列。命令的接纳规则与执行时序仍由原生处理器负责。 每次调用都返回 `RunResult`,包含接收输入的 `session_id`、根会话事件和会话树通知。`final_response` 包含最终助手文本;活动未输出助手文本时为空字符串。仅改变状态的命令返回原生 handler 的结果文本。`finish_reason` 表示结束结果。原生命令身份与结果保留在 `command/run` 和 `command/done` 事件中。完成通知缺少匹配的命令生命周期事件时抛出 `SdkProtocolError`,不会返回不完整的结果。 @@ -71,7 +71,7 @@ with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness: 每次调用在发送前订阅,并在返回或抛出异常前释放订阅。`on_notification` 按传输顺序接收本次输入的会话树活动;区间可以包含重叠工作。调用可以重叠,不会消耗彼此的结果。原生拒绝返回 `finish_reason="error"`;路由、协议、传输和观察回调失败则抛出异常。格式错误的原生命令响应抛出 `SdkProtocolError`,保留校验原因。超时或观察回调失败不回滚运行时工作,也不授权自动重试。`request_timeout_seconds` 限制协议响应等待,不限制之后的输入活动。 -默认的完整 `sdk` profile 提供已支持的原生命令;`sdk-minimal` 将未支持的输入保留在普通提示词路径。`/compact` 可以发起辅助模型请求,其完成不需要普通 turn 或 idle 通知;空历史可以在不生成摘要时成功。底层 `HarnessClient.session_command(session_id, line)` 接受受支持内置定义的 ASCII 注册名或英文规范别名,不回退为提示词,也不接受附件,返回原生 `CommandExecution`。中文别名使用 `run()`。见[压缩示例](examples/README.zh.md#compact-a-full-sdk-session)。 +默认的完整 `sdk` profile 提供已支持的原生命令;`sdk-minimal` 将未支持的输入保留在普通提示词路径。`/compact` 可以发起辅助模型请求,其完成不需要普通 turn 或 idle 通知;空历史可以在不生成摘要时成功。见[压缩示例](examples/README.zh.md#compact-a-full-sdk-session)。 `/permission ` 只修改接收命令的 Session。未知 preset 返回命令错误,不改变策略。后续输入与恢复保留成功的修改,其他 Session 和调用方的 `DeepSeekHarnessConfig` 保留自己的值。运行中的审批策略变化可以注入通知并触发下一模型步骤。见[权限示例](examples/README.zh.md#change-session-permissions)。 diff --git a/python/sdk/src/deepseek_harness/__init__.py b/python/sdk/src/deepseek_harness/__init__.py index fdc6bda037..0a30ca830d 100644 --- a/python/sdk/src/deepseek_harness/__init__.py +++ b/python/sdk/src/deepseek_harness/__init__.py @@ -2,8 +2,7 @@ from .api import DeepSeekHarness, DeepSeekHarnessConfig, RunResult, Session from .client import HarnessClient, HarnessConfig, UserQuestionHandler from .errors import SdkProtocolError from .models import ( - ApprovalRequestParams, ApprovalRequestResult, CommandErrorResult, CommandExecution, - CommandResult, CommandSuccessResult, IncomingRequest, InitializeResponse, + ApprovalRequestParams, ApprovalRequestResult, IncomingRequest, InitializeResponse, JsonObject, Notification, ServerInfo, UserQuestionAnswer, UserQuestionAnswerItem, UserQuestionRequest, ) @@ -12,10 +11,6 @@ __all__ = [ "DeepSeekHarnessConfig", "Session", "RunResult", - "CommandExecution", - "CommandResult", - "CommandSuccessResult", - "CommandErrorResult", "HarnessClient", "HarnessConfig", "UserQuestionHandler", diff --git a/python/sdk/src/deepseek_harness/api.py b/python/sdk/src/deepseek_harness/api.py index 315eddc48f..fdf46e1bfa 100644 --- a/python/sdk/src/deepseek_harness/api.py +++ b/python/sdk/src/deepseek_harness/api.py @@ -191,10 +191,9 @@ class DeepSeekHarness: *, session_id: str | None = None, on_notification: Callable[[Notification], None] | None = None, - delivery: Literal["queue", "steer"] = "queue", ) -> RunResult: """Run input to completion on a fresh or named Session and return its RunResult.""" - return self.start_session(session_id).run(input, on_notification=on_notification, delivery=delivery) + return self.start_session(session_id).run(input, on_notification=on_notification) class Session: @@ -217,7 +216,6 @@ class Session: input: str | list[JsonObject], *, on_notification: Callable[[Notification], None] | None = None, - delivery: Literal["queue", "steer"] = "queue", ) -> RunResult: """Run text or content blocks through native input routing. @@ -228,17 +226,15 @@ class Session: The first text block selects native commands. Matched commands require one text block with only encoded images beside it; native handlers decide which commands accept those images. Ordinary prompts retain block order - and use the requested queue or steer delivery. Notifications retain + and are queued through the existing prompt operation. Notifications retain wire order. Every result retains this Session id, its root events and Session-tree notifications, including overlapping work. Native refusals return finish_reason="error". Routing, transport and observer failures raise without rolling back work. """ - if delivery not in ("queue", "steer"): - raise ValueError("run delivery must be queue or steer") self.harness.start() with self.harness.client.subscribe_session_notifications(self.id) as subscription: - response = self.harness.client._query(self.id, input, delivery) + response = self.harness.client._query(self.id, input) if isinstance(response, CommandExecution): activity = _RunActivity(self.id, "command", response.command_id) while True: diff --git a/python/sdk/src/deepseek_harness/client.py b/python/sdk/src/deepseek_harness/client.py index 17637e257b..2717eb85c8 100644 --- a/python/sdk/src/deepseek_harness/client.py +++ b/python/sdk/src/deepseek_harness/client.py @@ -10,7 +10,7 @@ import uuid from collections import deque from dataclasses import dataclass from pathlib import Path -from typing import Callable, Literal, TypeAlias, TypeVar +from typing import Callable, TypeAlias, TypeVar from pydantic import BaseModel, ValidationError @@ -225,24 +225,19 @@ class HarnessClient: response_model=_EmptyResponse, ) - def session_command(self, session_id: str, line: str) -> CommandExecution: - """Execute an explicit command and return its handler result without waiting for a turn.""" - result = self._request_raw("session/command", {"sessionId": session_id, "line": line}) - return _command_execution(result, "session/command") - def _query( - self, session_id: str, input: str | list[JsonObject], delivery: Literal["queue", "steer"], + self, session_id: str, input: str | list[JsonObject], ) -> str | CommandExecution: """Return a validated prompt receipt or command result for high-level run callers.""" blocks = [{"type": "text", "text": input}] if isinstance(input, str) else input result = self._request_raw("session/query", { - "sessionId": session_id, "contentBlocks": blocks, "delivery": delivery, + "sessionId": session_id, "contentBlocks": blocks, }) if isinstance(result, dict): if result.get("kind") == "prompt" and isinstance(result.get("messageId"), str) and result["messageId"]: return result["messageId"] if result.get("kind") == "command": - return _command_execution(result.get("execution"), "session/query") + return _command_execution(result.get("execution")) raise SdkProtocolError("session/query requires a prompt messageId or command execution result") def get_working_directory(self, session_id: str) -> str: @@ -732,9 +727,9 @@ def _int_or_none(value: object) -> int | None: return value if isinstance(value, int) else None -def _command_execution(value: JsonValue, method: str) -> CommandExecution: +def _command_execution(value: JsonValue) -> CommandExecution: """Decode native command results and report malformed data as a protocol error.""" try: return CommandExecution.model_validate(value) except ValidationError as error: - raise SdkProtocolError(f"{method} returned an invalid command result") from error + raise SdkProtocolError("session/query returned an invalid command result") from error diff --git a/python/sdk/tests/test_command_attachments_runtime.py b/python/sdk/tests/test_command_attachments_runtime.py index 5bf4d0450e..05e7db63f7 100644 --- a/python/sdk/tests/test_command_attachments_runtime.py +++ b/python/sdk/tests/test_command_attachments_runtime.py @@ -9,7 +9,8 @@ from pathlib import Path import pytest -from deepseek_harness import CommandExecution, RunResult +from deepseek_harness.models import CommandExecution +from deepseek_harness import RunResult from deepseek_harness.errors import JsonRpcError from test_commands_runtime import ( _Completion, _SESSION_ID, _WAIT_SECONDS, _command_pair, _native_result, _of_type, @@ -122,10 +123,10 @@ def test_goal_create_and_edit_images_reach_following_requests_as_durable_referen second = _Completion("REVISED_GOAL_IMAGE", blocked=True) with _runtime(tmp_path, [first, second], model=_IMAGE_MODEL) as runtime: session = runtime.harness.start_session(_SESSION_ID) - created = runtime.call(runtime.harness.client._query, session.id, [original, {"type": "text", "text": "/goal Inspect the original picture."}], "queue") + created = runtime.call(runtime.harness.client._query, session.id, [original, {"type": "text", "text": "/goal Inspect the original picture."}]) assert isinstance(created, CommandExecution) and created.result.kind == "success" assert first.entered.wait(_WAIT_SECONDS), runtime.model.failures - edited = runtime.call(runtime.harness.client._query, session.id, [revised, {"type": "text", "text": "/goal edit Inspect the revised picture."}], "queue") + edited = runtime.call(runtime.harness.client._query, session.id, [revised, {"type": "text", "text": "/goal edit Inspect the revised picture."}]) assert isinstance(edited, CommandExecution) and edited.result.kind == "success" _command(runtime, session, "/goal clear") assert not first.release.is_set() @@ -209,11 +210,11 @@ def test_goal_controls_with_images_leave_the_active_request_and_goal_unchanged(t assert not _image_messages(events) -@pytest.mark.parametrize("delivery", ["queue", "steer"]) -def test_prompt_images_use_the_requested_delivery_during_an_active_turn(tmp_path: Path, delivery: str) -> None: +@pytest.mark.parametrize("image_first", [False, True]) +def test_prompt_images_queue_during_an_active_turn(tmp_path: Path, image_first: bool) -> None: picture = _image() text = {"type": "text", "text": "Inspect the image."} - content = [text, picture] if delivery == "queue" else [picture, text] + content = [picture, text] if image_first else [text, picture] first = _Completion("BEFORE_IMAGE", blocked=True) with _runtime(tmp_path, [first, _Completion("IMAGE_RECEIVED")], model=_IMAGE_MODEL) as runtime: session = runtime.harness.start_session(_SESSION_ID) @@ -221,7 +222,7 @@ def test_prompt_images_use_the_requested_delivery_during_an_active_turn(tmp_path assert first.entered.wait(_WAIT_SECONDS), runtime.model.failures accepted = threading.Event() following = runtime.workers.submit( - session.run, content, delivery=delivery, + session.run, content, on_notification=lambda _notification: accepted.set(), ) assert accepted.wait(_WAIT_SECONDS), "image prompt did not reach its inbox receipt" @@ -240,10 +241,9 @@ def test_prompt_images_use_the_requested_delivery_during_an_active_turn(tmp_path assert [block["type"] for block in recorded] == [block["type"] for block in content] assert [block for block in recorded if block["type"] == "text"] == [text] assert not _of_type(events, "command/run") - assert [event["data"] for event in _of_type(events, "step/start")] == ( - [{"turn": 1, "step": 1}, {"turn": 2, "step": 1}] if delivery == "queue" - else [{"turn": 1, "step": 1}, {"turn": 1, "step": 2}] - ) + assert [event["data"] for event in _of_type(events, "step/start")] == [ + {"turn": 1, "step": 1}, {"turn": 2, "step": 1}, + ] def test_top_level_run_accepts_an_image_without_text(tmp_path: Path) -> None: diff --git a/python/sdk/tests/test_commands.py b/python/sdk/tests/test_commands.py deleted file mode 100644 index 574b6b46d6..0000000000 --- a/python/sdk/tests/test_commands.py +++ /dev/null @@ -1,138 +0,0 @@ -"""Explicit command transport, results, and ordinary prompt compatibility.""" -from __future__ import annotations - -import json -import sys -from pathlib import Path - -import pytest -from pydantic import ValidationError - -from deepseek_harness import CommandErrorResult, CommandExecution, CommandSuccessResult, DeepSeekHarness -from deepseek_harness.errors import JsonRpcError, SdkProtocolError - - -@pytest.fixture -def peer(tmp_path: Path) -> Path: - script = tmp_path / "commands.py" - script.write_text('''import json -import os -import sys - -def send(frame): - print(json.dumps({"jsonrpc": "2.0", **frame}), flush=True) - -for line in sys.stdin: - frame = json.loads(line) - with open(os.environ["REQUEST_LOG"], "a", encoding="utf-8") as log: - log.write(line) - method = frame["method"] - params = frame.get("params") or {} - if method == "initialize": - send({"id": frame["id"], "result": {"serverInfo": {"name": "command-peer"}}}) - elif method == "session/command": - for event_type in ("command/run", "command/done"): - send({"method": "session.event", "params": {"sessionId": params["sessionId"], - "event": {"type": event_type, "data": {"commandId": "command-1"}}}}) - send({"id": frame["id"], **json.loads(os.environ["COMMAND_RESPONSE"])}) - elif method == "session/prompt": - session = params["sessionId"] - send({"id": frame["id"], "result": {"messageId": "input-1"}}) - events = [ - {"type": "agent/inbox/spliced", "data": {"inserted": [{"id": "input-1"}]}}, - {"type": "assistant/message", "data": {"message": {"content": [{"type": "text", "text": "ordinary prompt"}]}}}, - {"type": "turn/end", "data": {"turn": 1, "reason": {"kind": "completed"}}}, - ] - for event in events: - send({"method": "session.event", "params": {"sessionId": session, "event": event}}) - send({"method": "session.status", "params": {"sessionId": session, "status": "idle"}}) - elif method == "shutdown": - send({"id": frame["id"], "result": {}}) - break - else: - raise AssertionError(method) -''', encoding="utf-8") - return script - - -def harness(peer: Path, tmp_path: Path, response: dict) -> DeepSeekHarness: - return DeepSeekHarness( - cwd=str(tmp_path), - dsh_home=str(tmp_path / "home"), - request_timeout_seconds=5, - _launch_args=(sys.executable, str(peer)), - env={"REQUEST_LOG": str(tmp_path / "requests.jsonl"), "COMMAND_RESPONSE": json.dumps(response)}, - ) - - -def frames(tmp_path: Path) -> list[dict]: - return [json.loads(line) for line in (tmp_path / "requests.jsonl").read_text(encoding="utf-8").splitlines()] - - -@pytest.mark.parametrize("result", [ - {"kind": "success"}, - {"kind": "success", "text": "Compacted.", "sourceEventSeq": 0}, - {"kind": "success", "sourceEventSeq": 2**53 - 1}, - {"kind": "error", "text": "The agent is busy."}, - {"kind": "error", "text": " The agent is busy.\n"}, -]) -def test_command_returns_without_turn_or_idle_and_preserves_events(peer: Path, tmp_path: Path, result: dict) -> None: - response = {"commandId": "command-1", "result": result} - with harness(peer, tmp_path, {"result": response}) as sdk: - session = sdk.start_session("main") - with sdk.client.subscribe_session_notifications(session.id) as subscription: - execution = sdk.client.session_command(session.id, "/compact") - notifications = [] - subscription.drain(notifications.append) - assert isinstance(execution, CommandExecution) - assert execution.command_id == "command-1" - assert isinstance(execution.result, CommandSuccessResult if result["kind"] == "success" else CommandErrorResult) - assert execution.model_dump(by_alias=True, exclude_none=True) == response - assert [item.payload["event"]["type"] for item in notifications] == ["command/run", "command/done"] - sent = frames(tmp_path) - assert [frame["method"] for frame in sent] == ["initialize", "session/command", "shutdown"] - assert sent[1]["params"] == {"sessionId": "main", "line": "/compact"} - - -def test_low_level_command_preserves_the_line(peer: Path, tmp_path: Path) -> None: - with harness(peer, tmp_path, {"result": {"commandId": "command-1", "result": {"kind": "success"}}}) as sdk: - assert sdk.client.session_command("other", "/compact \t").result.kind == "success" - assert frames(tmp_path)[1]["params"] == {"sessionId": "other", "line": "/compact \t"} - - -def test_command_rpc_rejection_does_not_fall_back_to_prompt(peer: Path, tmp_path: Path) -> None: - with harness(peer, tmp_path, {"error": {"code": -32602, "message": "unsupported command"}}) as sdk: - with pytest.raises(JsonRpcError, match="unsupported command") as raised: - sdk.client.session_command("main", "/model") - assert raised.value.code == -32602 - assert [frame["method"] for frame in frames(tmp_path)] == ["initialize", "session/command", "shutdown"] - - -@pytest.mark.parametrize("response", [ - {}, - {"commandId": "command-1"}, - {"commandId": "", "result": {"kind": "success"}}, - {"commandId": "command-1", "result": {"kind": "unknown"}}, - {"commandId": "command-1", "result": {"kind": "error"}}, - {"commandId": "command-1", "result": {"kind": "error", "text": ""}}, - {"commandId": "command-1", "result": {"kind": "error", "text": " \t\n"}}, - {"commandId": "command-1", "result": {"kind": "success", "text": None}}, - {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": None}}, - {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": "4"}}, - {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": True}}, - {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": -1}}, - {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": 2**53}}, -]) -def test_command_rejects_malformed_results(peer: Path, tmp_path: Path, response: dict) -> None: - with harness(peer, tmp_path, {"result": response}) as sdk: - with pytest.raises(SdkProtocolError) as raised: - sdk.client.session_command("main", "/compact") - assert isinstance(raised.value.__cause__, ValidationError) - - -def test_low_level_prompt_keeps_slash_text_as_an_ordinary_prompt(peer: Path, tmp_path: Path) -> None: - with harness(peer, tmp_path, {"result": {}}) as sdk: - assert sdk.client.session_prompt("main", [{"type": "text", "text": "/compact"}]) == "input-1" - sent = frames(tmp_path) - assert [frame["method"] for frame in sent] == ["initialize", "session/prompt", "shutdown"] - assert sent[1]["params"] == {"sessionId": "main", "contentBlocks": [{"type": "text", "text": "/compact"}]} diff --git a/python/sdk/tests/test_commands_runtime.py b/python/sdk/tests/test_commands_runtime.py index 15ad0764d7..529cb57c63 100644 --- a/python/sdk/tests/test_commands_runtime.py +++ b/python/sdk/tests/test_commands_runtime.py @@ -23,7 +23,8 @@ from typing import Callable, Iterator, TypeVar import pytest from pydantic import BaseModel -from deepseek_harness import CommandExecution, DeepSeekHarness, Notification, RunResult, Session +from deepseek_harness.models import CommandExecution +from deepseek_harness import DeepSeekHarness, Notification, RunResult, Session from deepseek_harness.client import UserQuestionHandler @@ -353,7 +354,7 @@ def test_compact_without_history_returns_without_a_model_turn(tmp_path: Path) -> session = runtime.harness.start_session(_SESSION_ID) observer = runtime.harness.client.subscribe_session_notifications(_SESSION_ID) try: - execution = runtime.call(session.run, " \n/压缩\t ", delivery="queue") + execution = runtime.call(session.run, " \n/压缩\t ") done = runtime.call(_wait_command_done, observer.next) except BaseException: # Wake a timed-out observer before unregistering its otherwise blocking queue. @@ -379,11 +380,11 @@ def test_compact_rejects_busy_agent_before_the_model_is_released(tmp_path: Path) with _runtime(tmp_path, [response]) as runtime: session = runtime.harness.start_session(_SESSION_ID) running = runtime.workers.submit( - session.run, "Hold this request while compaction is attempted.", delivery="queue", + session.run, "Hold this request while compaction is attempted.", ) assert response.entered.wait(_WAIT_SECONDS), runtime.model.failures assert not running.done() and not response.release.is_set() - execution = runtime.call(session.run, "/compact", delivery="queue") + execution = runtime.call(session.run, "/compact") assert isinstance(execution, RunResult) execution = _native_result(execution) assert execution.result.kind == "error" @@ -410,11 +411,11 @@ def run_compaction_scenario(tmp_path: Path, *, capture_patch: Path | None = None session = runtime.harness.start_session(_SESSION_ID) # The replaced span is deliberately larger than the framed summary. prompt = _HISTORY_MARKER + "\n" + "Keep the original request only in the stored history. " * 256 - first_result = runtime.call(session.run, prompt, delivery="queue") + first_result = runtime.call(session.run, prompt) assert isinstance(first_result, RunResult) assert first_result.final_response == _FIRST_REPLY - compacting = runtime.workers.submit(session.run, "/compact", delivery="queue") + compacting = runtime.workers.submit(session.run, "/compact") assert summary_response.entered.wait(_WAIT_SECONDS), runtime.model.failures assert not summary_response.release.is_set() assert not compacting.done(), "command returned before its summary request completed" @@ -450,7 +451,7 @@ def run_compaction_scenario(tmp_path: Path, *, capture_patch: Path | None = None assert "" in checkpoint_text and "" in checkpoint_text assert len(_of_type(checkpointed, "turn/start")) == len(_of_type(checkpointed, "turn/end")) == 1 - continued = runtime.call(session.run, _CONTINUE_PROMPT, delivery="queue") + continued = runtime.call(session.run, _CONTINUE_PROMPT) assert isinstance(continued, RunResult) assert continued.final_response == _CONTINUE_REPLY first, compaction, following = runtime.model.captured() @@ -486,7 +487,7 @@ def test_unknown_slash_and_compact_arguments_follow_the_plain_prompt_path(tmp_pa with _runtime(tmp_path, [_Completion(text) for text in replies]) as runtime: session = runtime.harness.start_session(_SESSION_ID) for prompt, reply in zip(prompts, replies): - result = runtime.call(session.run, prompt, delivery="queue") + result = runtime.call(session.run, prompt) assert isinstance(result, RunResult) assert result.final_response == reply requests = runtime.model.captured() @@ -506,11 +507,11 @@ def test_unimplemented_slash_remains_plain_text_without_recording_feedback(tmp_p reply = "DSH_AFTER_PLAN_TEXT_REPLY" with _runtime(tmp_path, [_Completion(reply_before), _Completion(reply)]) as runtime: session = runtime.harness.start_session(_SESSION_ID) - first = runtime.call(session.run, input_text, delivery="queue") + first = runtime.call(session.run, input_text) assert isinstance(first, RunResult) assert first.final_response == reply_before - result = runtime.call(session.run, following, delivery="queue") + result = runtime.call(session.run, following) assert isinstance(result, RunResult) assert result.final_response == reply initial, continued = runtime.model.captured() diff --git a/python/sdk/tests/test_goal_runtime.py b/python/sdk/tests/test_goal_runtime.py index f3b13051c8..03e68b06a9 100644 --- a/python/sdk/tests/test_goal_runtime.py +++ b/python/sdk/tests/test_goal_runtime.py @@ -9,7 +9,8 @@ import threading import pytest from pathlib import Path -from deepseek_harness import CommandExecution, RunResult, Session +from deepseek_harness.models import CommandExecution +from deepseek_harness import RunResult, Session from deepseek_harness.client import NotificationSubscription from test_commands_runtime import ( _Completion, _Runtime, _SESSION_ID, _WAIT_SECONDS, _WaitResult, _assert_request_permission, @@ -19,7 +20,7 @@ from test_commands_runtime import ( def _command(runtime: _Runtime, session: Session, text: str, *, kind: str = "success") -> CommandExecution: - result = runtime.call(runtime.harness.client._query, session.id, text, "queue") + result = runtime.call(runtime.harness.client._query, session.id, text) assert isinstance(result, CommandExecution) assert result.result.kind == kind, result.result.text return result diff --git a/python/sdk/tests/test_plan_runtime.py b/python/sdk/tests/test_plan_runtime.py index 3d73d7d3e7..d2cbfa482a 100644 --- a/python/sdk/tests/test_plan_runtime.py +++ b/python/sdk/tests/test_plan_runtime.py @@ -7,7 +7,8 @@ from pathlib import Path import pytest -from deepseek_harness import CommandExecution, RunResult, Session, UserQuestionRequest +from deepseek_harness.models import CommandExecution +from deepseek_harness import RunResult, Session, UserQuestionRequest from test_commands_runtime import ( _Completion, _Runtime, _SESSION_ID, _WAIT_SECONDS, _assert_request_permission, _command_pair, _native_result, _of_type, _permission_facts, _read_events, @@ -20,7 +21,7 @@ _GUIDANCE = "You are in plan mode." def _command(runtime: _Runtime, session: Session, text: str) -> CommandExecution: - result = runtime.call(runtime.harness.client._query, session.id, text, "queue") + result = runtime.call(runtime.harness.client._query, session.id, text) assert isinstance(result, CommandExecution) assert result.result.kind == "success", result.result.text return result diff --git a/python/sdk/tests/test_run.py b/python/sdk/tests/test_run.py index f9d2976bce..c90c8b41b1 100644 --- a/python/sdk/tests/test_run.py +++ b/python/sdk/tests/test_run.py @@ -10,7 +10,8 @@ from concurrent.futures import ThreadPoolExecutor import pytest from pydantic import BaseModel, ValidationError -from deepseek_harness import CommandExecution, DeepSeekHarness, Notification, RunResult, SdkProtocolError +from deepseek_harness.models import CommandExecution +from deepseek_harness import DeepSeekHarness, Notification, RunResult, SdkProtocolError from deepseek_harness.errors import JsonRpcError @@ -68,11 +69,12 @@ for line in sys.stdin: method = frame["method"] if method == "initialize": send({"id": frame["id"], "result": {"serverInfo": {"name": "query-peer"}}}) + elif method == "session/prompt": + send({"id": frame["id"], "result": {"messageId": "literal-input"}}) elif method == "session/query": serial += 1 params = frame["params"] - assert set(params) == {"sessionId", "contentBlocks", "delivery"} - assert params["delivery"] in ("queue", "steer") + assert set(params) == {"sessionId", "contentBlocks"} text = input_text(frame) if text == "/plan hold": identity = "plan-" + str(serial) @@ -225,7 +227,7 @@ def test_run_adds_session_identity_without_changing_command_results(peer: Path, assert returned.session_id assert returned.final_response == result.get("text", "") assert returned.finish_reason == ("error" if result["kind"] == "error" else "completed") - low_level = sdk.client._query(returned.session_id, "custom-response", "queue") + low_level = sdk.client._query(returned.session_id, "custom-response") assert isinstance(low_level, CommandExecution) assert low_level.model_dump(by_alias=True, exclude_none=True) == execution assert_released(sdk) @@ -243,21 +245,15 @@ def test_run_preserves_ordinary_text_and_result(sdk: DeepSeekHarness, text: str) assert_released(sdk) -def test_run_accepts_steer_for_text(sdk: DeepSeekHarness) -> None: - result = sdk.start_session("main").run("next step", delivery="steer") - assert isinstance(result, RunResult) - assert result.final_response == "answer for next step" - - -@pytest.mark.parametrize("entry,text,delivery", [ - ("harness", "/plan Describe this image.", "queue"), - ("session", "/plan Describe this image.", "steer"), - ("harness", "Explain this image.", "queue"), - ("session", "/unknown-slash", "steer"), - ("session", "", "queue"), +@pytest.mark.parametrize("entry,text", [ + ("harness", "/plan Describe this image."), + ("session", "/plan Describe this image."), + ("harness", "Explain this image."), + ("session", "/unknown-slash"), + ("session", ""), ]) def test_run_forwards_content_blocks_with_the_routed_result_and_notifications( - sdk: DeepSeekHarness, tmp_path: Path, entry: str, text: str, delivery: str, + sdk: DeepSeekHarness, tmp_path: Path, entry: str, text: str, ) -> None: blocks = [ {"type": "text", "text": text}, @@ -265,9 +261,9 @@ def test_run_forwards_content_blocks_with_the_routed_result_and_notifications( ] notifications = [] result = ( - sdk.run(blocks, session_id="main", delivery=delivery, on_notification=notifications.append) + sdk.run(blocks, session_id="main", on_notification=notifications.append) if entry == "harness" else sdk.start_session("main").run( - blocks, delivery=delivery, on_notification=notifications.append, + blocks, on_notification=notifications.append, ) ) if text == "/plan Describe this image.": @@ -280,7 +276,7 @@ def test_run_forwards_content_blocks_with_the_routed_result_and_notifications( sent = [json.loads(line) for line in (tmp_path / "requests.jsonl").read_text(encoding="utf-8").splitlines()] assert sent[-1]["method"] == "session/query" assert sent[-1]["params"] == { - "sessionId": "main", "contentBlocks": blocks, "delivery": delivery, + "sessionId": "main", "contentBlocks": blocks, } assert_released(sdk) @@ -290,7 +286,7 @@ def test_run_normalizes_strings_without_changing_their_text(sdk: DeepSeekHarness assert isinstance(result, RunResult) sent = [json.loads(line) for line in (tmp_path / "requests.jsonl").read_text(encoding="utf-8").splitlines()] assert sent[-1]["params"] == { - "sessionId": "main", "contentBlocks": [{"type": "text", "text": " preserve whitespace "}], "delivery": "queue", + "sessionId": "main", "contentBlocks": [{"type": "text", "text": " preserve whitespace "}], } @@ -365,14 +361,6 @@ def test_command_timeout_keeps_runtime_responsive(sdk: DeepSeekHarness) -> None: assert isinstance(sdk.start_session("main").run("/compact"), RunResult) -def test_run_requires_supported_delivery(sdk: DeepSeekHarness) -> None: - session = sdk.start_session("main") - with pytest.raises(ValueError, match="delivery"): - session.run("ordinary", delivery="unknown") - with pytest.raises(ValueError, match="delivery"): - session.run([{"type": "text", "text": "ordinary"}], delivery="unknown") - - @pytest.mark.parametrize("response", [ None, [], {"kind": "unknown"}, {"kind": "prompt"}, {"kind": "prompt", "messageId": ""}, {"kind": "prompt", "messageId": 4}, @@ -427,3 +415,40 @@ def test_run_rejects_malformed_completion_and_releases_its_subscription( with pytest.raises(SdkProtocolError): sdk.run("custom-response") assert_released(sdk) + + +@pytest.mark.parametrize("execution", [ + {}, + {"commandId": "command-1"}, + {"commandId": "", "result": {"kind": "success"}}, + {"commandId": "command-1", "result": {"kind": "unknown"}}, + {"commandId": "command-1", "result": {"kind": "error"}}, + {"commandId": "command-1", "result": {"kind": "error", "text": ""}}, + {"commandId": "command-1", "result": {"kind": "error", "text": " \t\n"}}, + {"commandId": "command-1", "result": {"kind": "success", "text": None}}, + {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": None}}, + {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": "4"}}, + {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": True}}, + {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": -1}}, + {"commandId": "command-1", "result": {"kind": "success", "sourceEventSeq": 2**53}}, +]) +def test_run_rejects_malformed_native_results(peer: Path, tmp_path: Path, execution: dict) -> None: + with DeepSeekHarness( + cwd=str(tmp_path), dsh_home=str(tmp_path / "home"), + _launch_args=(sys.executable, str(peer)), + env={"REQUEST_LOG": str(tmp_path / "requests.jsonl"), "QUERY_RESPONSE": json.dumps({ + "kind": "command", "execution": execution, + })}, + ) as sdk: + with pytest.raises(SdkProtocolError) as raised: + sdk.run("custom-response") + assert isinstance(raised.value.__cause__, ValidationError) + assert_released(sdk) + + +def test_low_level_prompt_keeps_slash_text_as_an_ordinary_prompt(sdk: DeepSeekHarness, tmp_path: Path) -> None: + blocks = [{"type": "text", "text": "/compact"}] + assert sdk.client.session_prompt("main", blocks) == "literal-input" + sent = [json.loads(line) for line in (tmp_path / "requests.jsonl").read_text(encoding="utf-8").splitlines()] + assert sent[-1]["method"] == "session/prompt" + assert sent[-1]["params"] == {"sessionId": "main", "contentBlocks": blocks}