refactor(python-sdk): accept options when resuming sessions
This commit is contained in:
1 parent
145d2d8a49
commit
78e5ecce15
10 files changed
+33
-25
No files matched your search
@@ -9,8 +9,8 @@
|
||||
en: ddf4dabea526cef1
|
||||
zh: 6e31cab10d2f3ed8
|
||||
/deepseek-harness-python-sdk/start-a-runtime:
|
||||
en: d5725382c12d9806
|
||||
zh: 03fca3306e740a80
|
||||
en: b30e665f9fd2149b
|
||||
zh: ebaf35a8a34ad31e
|
||||
/deepseek-harness-python-sdk/run-text-and-commands:
|
||||
en: b2c847c1452e137d
|
||||
zh: c595c5e82151d0cb
|
||||
|
||||
@@ -52,7 +52,7 @@ 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.
|
||||
|
||||
Pass `permission_mode="danger-full-access"` to replace the saved permission preset before resumed execution. Omission preserves saved permissions. 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.
|
||||
Call `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` to replace the saved permission preset before resumed execution. Omission preserves saved permissions. 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:
|
||||
|
||||
@@ -52,7 +52,7 @@ print(result.final_response)
|
||||
|
||||
`harness.resume_session(saved_session_id)` 恢复持久化历史,并返回可调用 `run()` 的 `Session`。请保存原会话 id,并沿用其 `dsh_home` 和工作区。恢复会保留存储的目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时会抛出异常,不创建替代会话。`start_session(id)` 只打开惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。
|
||||
|
||||
传入 `permission_mode="danger-full-access"` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。所选预设同时更新 sandbox 和审批策略,并持久化供后续恢复使用;该预设必须存在于 profile 的权限服务中。标准 `sdk` profile 提供 `read-only`、`workspace-write` 和 `danger-full-access`。缺少该服务的 profile(如 `sdk-minimal`)会拒绝显式覆盖。已被提醒任务恢复的会话也会拒绝覆盖;请对该运行中会话使用 `/permission`。
|
||||
调用 `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。所选预设同时更新 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:
|
||||
|
||||
@@ -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,15 +176,15 @@ class DeepSeekHarness:
|
||||
self.start()
|
||||
return Session(self, session_id or f"session-{uuid.uuid4().hex}")
|
||||
|
||||
def resume_session(self, session_id: str, *, permission_mode: str | None = None) -> "Session":
|
||||
def resume_session(self, session_id: str, options: ResumeSessionOptions | None = None) -> "Session":
|
||||
"""Restore persisted history without sending input.
|
||||
|
||||
Omit permission_mode to retain saved permissions, or name a configured permission preset
|
||||
Omit options to retain saved permissions, or set options["permission_mode"] to a configured preset
|
||||
to persist before resumed execution. 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, permission_mode=permission_mode)
|
||||
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,11 @@ class HarnessClient:
|
||||
)
|
||||
return response.messageId
|
||||
|
||||
def resume_session(self, session_id: str, *, permission_mode: str | None = None) -> None:
|
||||
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 permission_mode is not None:
|
||||
params["permissionMode"] = permission_mode
|
||||
if options is not None and "permission_mode" in options:
|
||||
params["permissionMode"] = options["permission_mode"]
|
||||
self.request(
|
||||
"session/resume",
|
||||
params,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -683,7 +683,7 @@ def test_resume_permission_override_applies_before_tools_and_survives_restart(tm
|
||||
]
|
||||
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",
|
||||
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.")
|
||||
|
||||
@@ -6,13 +6,18 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from deepseek_harness import DeepSeekHarness
|
||||
from deepseek_harness import DeepSeekHarness, ResumeSessionOptions
|
||||
from deepseek_harness.errors import JsonRpcError
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outcome,permission_mode", [("restored", None), ("restored", "danger-full-access"), ("missing", 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, permission_mode: str | None,
|
||||
tmp_path: Path, outcome: str, options: ResumeSessionOptions | None, expected_params: dict[str, str],
|
||||
) -> None:
|
||||
script = tmp_path / "runtime.py"
|
||||
requests = tmp_path / "requests.jsonl"
|
||||
@@ -49,8 +54,7 @@ for line in sys.stdin:
|
||||
env={"OUTCOME": outcome, "REQUESTS": str(requests)},
|
||||
) as harness:
|
||||
if outcome == "restored":
|
||||
session = (harness.resume_session("saved") if permission_mode is None
|
||||
else harness.resume_session("saved", permission_mode=permission_mode))
|
||||
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:
|
||||
@@ -58,7 +62,4 @@ 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"]
|
||||
expected = {"sessionId": "saved"}
|
||||
if permission_mode is not None:
|
||||
expected["permissionMode"] = permission_mode
|
||||
assert frames[1]["params"] == expected
|
||||
assert frames[1]["params"] == expected_params
|
||||
Reference in new issue
Block a user