forked from cflmy/deepseek-harness
refactor(sdk): simplify slash command input APIs
This commit is contained in:
1 parent
c68c2aa96c
commit
74ff76d1ff
42 files changed
+267
-613
No files matched your search
@@ -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
|
||||
|
||||
@@ -61,7 +61,7 @@ with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness:
|
||||
<a id="run-text-and-commands"></a>
|
||||
## 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 <preset>` 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).
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness:
|
||||
<a id="run-text-and-commands"></a>
|
||||
## 运行文本与命令
|
||||
|
||||
`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 <preset>` 只修改接收命令的 Session。未知 preset 返回命令错误,不改变策略。后续输入与恢复保留成功的修改,其他 Session 和调用方的 `DeepSeekHarnessConfig` 保留自己的值。运行中的审批策略变化可以注入通知并触发下一模型步骤。见[权限示例](examples/README.zh.md#change-session-permissions)。
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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"}]}
|
||||
@@ -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 "<compacted-summary>" in checkpoint_text and "</compacted-summary>" 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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}
|
||||
Reference in new issue
Block a user