Merge branch 'feat/session-workspace-root' into feat/session-workspace-root-consumers
Brings master (23c1d884226) through the parent branch. The SDK client README keeps master's resume-permission paragraph and this branch's statement that `setWorkingDirectory` moves the `workspace-write` boundary.
This commit is contained in:
commit
cb0ebcc032
54 files changed
+1103
-155
No files matched your search
@@ -9,8 +9,8 @@
|
||||
en: ddf4dabea526cef1
|
||||
zh: 6e31cab10d2f3ed8
|
||||
/deepseek-harness-python-sdk/start-a-runtime:
|
||||
en: ac793c588b13ce87
|
||||
zh: 502015cda46de3ac
|
||||
en: 05298d7872586fcf
|
||||
zh: 9262ee9b2a8dee7d
|
||||
/deepseek-harness-python-sdk/run-text-and-commands:
|
||||
en: b2c847c1452e137d
|
||||
zh: c595c5e82151d0cb
|
||||
|
||||
@@ -52,6 +52,8 @@ print(result.final_response)
|
||||
|
||||
`harness.resume_session(saved_session_id)` restores persisted history and returns a `Session` ready for `run()`. Save the original session id and reuse its `dsh_home` and workspace. Restoration preserves the stored directory, repairs an interrupted final turn, and sends no new input. Missing, unreadable, incompatible, or occupied sessions raise without creating a replacement. `start_session(id)` only opens a lazy handle; it does not request persisted restoration. This API does not restore shell, browser, or other external processes.
|
||||
|
||||
Call `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` to replace the saved permission preset before resumed execution. Omitting options or passing an empty dict preserves saved permissions. Unknown keys and options other than a dict or `None` raise `TypeError` before the resume request is sent. The selected preset updates both sandbox and approval policy and persists for later resumes; it must exist in the profile’s permission service. The standard `sdk` profile offers `read-only`, `workspace-write`, and `danger-full-access`. Profiles without that service, such as `sdk-minimal`, reject explicit overrides. A session already restored by a reminder also rejects overrides; use `/permission` for that live session.
|
||||
|
||||
```py
|
||||
with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness:
|
||||
session = harness.resume_session(saved_session_id)
|
||||
|
||||
@@ -52,6 +52,8 @@ print(result.final_response)
|
||||
|
||||
`harness.resume_session(saved_session_id)` 恢复持久化历史,并返回可调用 `run()` 的 `Session`。请保存原会话 id,并沿用其 `dsh_home` 和工作区。恢复会保留存储的目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时会抛出异常,不创建替代会话。`start_session(id)` 只打开惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。
|
||||
|
||||
调用 `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` 可在恢复后的执行开始前覆盖已保存的权限预设;省略选项或传入空字典时保留历史权限。若选项含未知键,或传入的选项既非字典也非 `None`,SDK 会在发送恢复请求前抛出 `TypeError`。所选预设同时更新 sandbox 和审批策略,并持久化供后续恢复使用;该预设必须存在于 profile 的权限服务中。标准 `sdk` profile 提供 `read-only`、`workspace-write` 和 `danger-full-access`。缺少该服务的 profile(如 `sdk-minimal`)会拒绝显式覆盖。已被提醒任务恢复的会话也会拒绝覆盖;请对该运行中会话使用 `/permission`。
|
||||
|
||||
```py
|
||||
with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness:
|
||||
session = harness.resume_session(saved_session_id)
|
||||
|
||||
@@ -3,7 +3,7 @@ from .client import HarnessClient, HarnessConfig, UserQuestionHandler
|
||||
from .errors import SdkProtocolError
|
||||
from .models import (
|
||||
ApprovalRequestParams, ApprovalRequestResult, IncomingRequest, InitializeResponse,
|
||||
JsonObject, Notification, ServerInfo, UserQuestionAnswer, UserQuestionAnswerItem, UserQuestionRequest,
|
||||
JsonObject, Notification, ResumeSessionOptions, ServerInfo, UserQuestionAnswer, UserQuestionAnswerItem, UserQuestionRequest,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -11,6 +11,7 @@ __all__ = [
|
||||
"DeepSeekHarnessConfig",
|
||||
"Session",
|
||||
"RunResult",
|
||||
"ResumeSessionOptions",
|
||||
"HarnessClient",
|
||||
"HarnessConfig",
|
||||
"UserQuestionHandler",
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Callable, Literal
|
||||
|
||||
from .client import HarnessClient, HarnessConfig, UserQuestionHandler
|
||||
from .errors import SdkProtocolError
|
||||
from .models import CommandExecution, JsonObject, Notification
|
||||
from .models import CommandExecution, JsonObject, Notification, ResumeSessionOptions
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -176,13 +176,15 @@ class DeepSeekHarness:
|
||||
self.start()
|
||||
return Session(self, session_id or f"session-{uuid.uuid4().hex}")
|
||||
|
||||
def resume_session(self, session_id: str) -> "Session":
|
||||
"""Restore persisted history from the configured Harness home without sending input.
|
||||
def resume_session(self, session_id: str, options: ResumeSessionOptions | None = None) -> "Session":
|
||||
"""Restore persisted history without sending input.
|
||||
|
||||
Omit options to retain saved permissions, or set options["permission_mode"] to a configured preset
|
||||
to persist before resumed execution. Invalid option keys raise TypeError. Unsupported presets or profiles raise.
|
||||
Missing, unreadable, incompatible, or occupied sessions raise instead of creating a new session.
|
||||
"""
|
||||
self.start()
|
||||
self._client.resume_session(session_id)
|
||||
self._client.resume_session(session_id, options)
|
||||
return Session(self, session_id)
|
||||
|
||||
def run(
|
||||
|
||||
@@ -15,7 +15,7 @@ from typing import Callable, TypeAlias, TypeVar
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from .errors import JsonRpcError, SdkProtocolError, TransportClosedError
|
||||
from .models import CommandExecution, IncomingRequest, InitializeResponse, JsonObject, JsonValue, Notification, UserQuestionAnswer, UserQuestionRequest
|
||||
from .models import CommandExecution, IncomingRequest, InitializeResponse, JsonObject, JsonValue, Notification, ResumeSessionOptions, UserQuestionAnswer, UserQuestionRequest
|
||||
|
||||
ModelT = TypeVar("ModelT", bound=BaseModel)
|
||||
NotificationFilter: TypeAlias = Callable[[Notification], bool]
|
||||
@@ -217,11 +217,20 @@ class HarnessClient:
|
||||
)
|
||||
return response.messageId
|
||||
|
||||
def resume_session(self, session_id: str) -> None:
|
||||
"""Restore a persisted session without sending a prompt; propagate restoration failures."""
|
||||
def resume_session(self, session_id: str, options: ResumeSessionOptions | None = None) -> None:
|
||||
"""Restore history; an explicit permission preset replaces saved permissions before execution."""
|
||||
params: JsonObject = {"sessionId": session_id}
|
||||
if options is not None:
|
||||
if not isinstance(options, dict):
|
||||
raise TypeError("resume_session options must be a dict or None")
|
||||
for key in options:
|
||||
if key != "permission_mode":
|
||||
raise TypeError(f"unknown resume_session option {key!r}; expected 'permission_mode'")
|
||||
if "permission_mode" in options:
|
||||
params["permissionMode"] = options["permission_mode"]
|
||||
self.request(
|
||||
"session/resume",
|
||||
{"sessionId": session_id},
|
||||
params,
|
||||
response_model=_EmptyResponse,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
from typing import Annotated, Literal, TypeAlias, TypedDict
|
||||
|
||||
from pydantic import BaseModel, Field, JsonValue as PydanticJsonValue, field_validator
|
||||
|
||||
@@ -10,6 +10,12 @@ JsonValue: TypeAlias = JsonScalar | dict[str, "JsonValue"] | list["JsonValue"]
|
||||
JsonObject: TypeAlias = dict[str, JsonValue]
|
||||
|
||||
|
||||
class ResumeSessionOptions(TypedDict, total=False):
|
||||
"""Options applied before a restored session resumes execution."""
|
||||
|
||||
permission_mode: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Notification:
|
||||
method: str
|
||||
|
||||
@@ -90,12 +90,26 @@ class _ModelServer:
|
||||
self.request.settimeout(_WAIT_SECONDS)
|
||||
super().setup()
|
||||
|
||||
def handle_one_request(self) -> None:
|
||||
self.raw_requestline = b""
|
||||
try:
|
||||
super().handle_one_request()
|
||||
except (ConnectionAbortedError, ConnectionResetError):
|
||||
if self.raw_requestline:
|
||||
raise
|
||||
# A cancelled upload can close a newly opened socket before sending a request.
|
||||
self.close_connection = True
|
||||
|
||||
def do_POST(self) -> None:
|
||||
payload = self.rfile.read(int(self.headers["Content-Length"]))
|
||||
if self.path == "/v1/files":
|
||||
# The model fixture accepts inline images through the provider's Files fallback.
|
||||
self.send_error(404, "Images are accepted inline")
|
||||
# The first 404 selects inline images and cancels concurrent file uploads.
|
||||
try:
|
||||
self.rfile.read(int(self.headers["Content-Length"]))
|
||||
self.send_error(404, "Images are accepted inline")
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
|
||||
self.close_connection = True
|
||||
return
|
||||
payload = self.rfile.read(int(self.headers["Content-Length"]))
|
||||
assert self.path == "/v1/messages", f"unexpected model endpoint: {self.path}"
|
||||
body = json.loads(payload)
|
||||
assert isinstance(body, dict) and isinstance(body.get("model"), str)
|
||||
@@ -199,6 +213,20 @@ def test_model_server_only_allows_expected_connection_aborts(
|
||||
assert not model.thread.is_alive()
|
||||
|
||||
|
||||
def test_model_server_accepts_cancelled_file_upload(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
model = _ModelServer([])
|
||||
|
||||
def reset(_handler: BaseHTTPRequestHandler) -> None:
|
||||
raise ConnectionResetError("sibling upload selected inline fallback")
|
||||
|
||||
monkeypatch.setattr(model.server.RequestHandlerClass, "end_headers", reset)
|
||||
with model, closing(HTTPConnection(*model.server.server_address, timeout=_WAIT_SECONDS)) as connection:
|
||||
connection.request("POST", "/v1/files", body=b"image")
|
||||
with pytest.raises(RemoteDisconnected):
|
||||
connection.getresponse()
|
||||
assert model.captured() == []
|
||||
|
||||
|
||||
def _dsh_bin() -> str | None:
|
||||
mode = os.environ.get("DSH_COMMANDS_TEST_RUNTIME", "built")
|
||||
if mode == "installed":
|
||||
@@ -669,3 +697,38 @@ def test_resumed_permission_survives_different_launch_defaults(tmp_path: Path) -
|
||||
_assert_request_permission(request, "read-only", "ask")
|
||||
assert resumed.harness.config.env["DSH_PERMISSION_MODE"] == "danger-full-access"
|
||||
assert _permission_facts(_read_events(resumed.logs)) == saved
|
||||
|
||||
|
||||
def test_resume_permission_override_applies_before_tools_and_survives_restart(tmp_path: Path) -> None:
|
||||
with _runtime(tmp_path, [], initial_permission="workspace-write") as original:
|
||||
session = original.harness.start_session(_SESSION_ID)
|
||||
assert _permission_command(original, session, "workspace-write").result.kind == "success"
|
||||
saved = _permission_facts(_read_events(original.logs))
|
||||
target = tmp_path / "resumed-write.txt"
|
||||
completions = [
|
||||
_Completion("", tool_call=("write", {"file_path": str(target), "content": "resumed with full access"})),
|
||||
_Completion("OVERRIDE_APPLIED"),
|
||||
]
|
||||
with _runtime(tmp_path, completions, initial_permission="workspace-write") as resumed:
|
||||
session = resumed.call(
|
||||
resumed.harness.resume_session, _SESSION_ID, {"permission_mode": "danger-full-access"},
|
||||
)
|
||||
assert resumed.model.captured() == [], "resume must not send new model input"
|
||||
result = resumed.call(session.run, "Write the marker, then finish.")
|
||||
assert result.final_response == "OVERRIDE_APPLIED"
|
||||
assert target.read_text(encoding="utf-8") == "resumed with full access"
|
||||
for request in resumed.model.captured():
|
||||
_assert_request_permission(request, "danger-full-access", "never")
|
||||
assert resumed.harness.config.env["DSH_PERMISSION_MODE"] == "workspace-write"
|
||||
facts = _permission_facts(_read_events(resumed.logs))
|
||||
assert facts[:len(saved)] == saved
|
||||
assert facts[len(saved):] == [
|
||||
{"type": "permission/preset", "data": {"preset": "danger-full-access"}},
|
||||
{"type": "sandbox/mode", "data": {"mode": "danger-full-access"}},
|
||||
{"type": "approval/policy", "data": {"policy": "never"}},
|
||||
]
|
||||
with _runtime(tmp_path, [_Completion("STILL_FULL")], initial_permission="workspace-write") as again:
|
||||
session = again.call(again.harness.resume_session, _SESSION_ID)
|
||||
assert again.call(session.run, "Continue without tools.").final_response == "STILL_FULL"
|
||||
_assert_request_permission(again.model.captured()[0], "danger-full-access", "never")
|
||||
assert _permission_facts(_read_events(again.logs)) == facts
|
||||
@@ -3,15 +3,23 @@ from __future__ import annotations
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from deepseek_harness import DeepSeekHarness
|
||||
from deepseek_harness import DeepSeekHarness, HarnessClient, ResumeSessionOptions
|
||||
from deepseek_harness.errors import JsonRpcError
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outcome", ["restored", "missing"])
|
||||
def test_resume_preserves_identity_and_propagates_failure(tmp_path: Path, outcome: str) -> None:
|
||||
@pytest.mark.parametrize(("outcome", "options", "expected_params"), [
|
||||
("restored", None, {"sessionId": "saved"}),
|
||||
("restored", {}, {"sessionId": "saved"}),
|
||||
("restored", {"permission_mode": "danger-full-access"}, {"sessionId": "saved", "permissionMode": "danger-full-access"}),
|
||||
("missing", None, {"sessionId": "saved"}),
|
||||
])
|
||||
def test_resume_preserves_identity_and_propagates_failure(
|
||||
tmp_path: Path, outcome: str, options: ResumeSessionOptions | None, expected_params: dict[str, str],
|
||||
) -> None:
|
||||
script = tmp_path / "runtime.py"
|
||||
requests = tmp_path / "requests.jsonl"
|
||||
script.write_text(
|
||||
@@ -47,7 +55,7 @@ for line in sys.stdin:
|
||||
env={"OUTCOME": outcome, "REQUESTS": str(requests)},
|
||||
) as harness:
|
||||
if outcome == "restored":
|
||||
session = harness.resume_session("saved")
|
||||
session = harness.resume_session("saved") if options is None else harness.resume_session("saved", options)
|
||||
assert session.id == "saved"
|
||||
assert session.harness is harness
|
||||
else:
|
||||
@@ -55,4 +63,17 @@ for line in sys.stdin:
|
||||
harness.resume_session("saved")
|
||||
frames = [json.loads(line) for line in requests.read_text(encoding="utf-8").splitlines()]
|
||||
assert [frame["method"] for frame in frames] == ["initialize", "session/resume", "shutdown"]
|
||||
assert frames[1]["params"] == {"sessionId": "saved"}
|
||||
assert frames[1]["params"] == expected_params
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("options", "error"), [
|
||||
({"permissionMode": "read-only"}, "permissionMode"),
|
||||
({"permission_mode": "read-only", "permision_mode": "read-only"}, "permision_mode"),
|
||||
("read-only", "dict"),
|
||||
])
|
||||
def test_invalid_resume_options_do_not_send_a_request(options: object, error: str) -> None:
|
||||
client = HarnessClient()
|
||||
with patch.object(client, "request") as request:
|
||||
with pytest.raises(TypeError, match=error):
|
||||
client.resume_session("saved", options)
|
||||
request.assert_not_called()
|
||||
Reference in new issue
Block a user