feat(sdk): report why a session agent was disposed (#8738)
* feat(sdk): report why a session agent was disposed A request for a session whose agent left the registry now states whether the whole runtime is shutting down, the SDK server is shutting down, or only the agent loop was unloaded. During runtime shutdown it names the last process event observed before teardown; for an agent-loop unload it gives the time and the plugin whose unload began first. The liveness check reads the registry as optional, so both stages of root disposal report the same failure. Refs #8737 * fix(sdk): keep the runtime observation out of the plugin entry exports The static gates reject a new read of the Cordis root context, a value export from a function plugin entry, and new assertions to unknown. The plugin entry now passes the server an observation built from the root fiber it already holds, the helper lives in the internal process-events module, and the new tests complete the handshake instead of casting the server. Refs #8737 * fix(sdk): keep the process-event record from throwing and state the unload origin as an observation A rejection value without a string form made the failure text throw inside a prepended listener, which would end the dispatch before the listener that owns the event. The text now falls back to a fixed marker. The plugin named for an agent-loop unload is the first one unloading at that time, which overlapping unloads can make unrelated, so the message and README say that. Refs #8737 * feat(python-sdk): log the runtime's stderr lines as they arrive The runtime writes its fatal report, including the stack of an unhandled rejection that ends the process, to its own stderr. The SDK kept those lines in memory and attached them only to initialization, timeout, and transport failures, so a host saw none of it for an ordinary JSON-RPC error. Each line now also goes to the Python logger deepseek_harness.runtime at INFO. Refs #8737
This commit is contained in:
1 parent
6fcc447c7f
commit
0750436cb4
19 files changed
+629
-16
No files matched your search
@@ -9,8 +9,8 @@
|
||||
en: ddf4dabea526cef1
|
||||
zh: 6e31cab10d2f3ed8
|
||||
/deepseek-harness-python-sdk/start-a-runtime:
|
||||
en: 05298d7872586fcf
|
||||
zh: 9262ee9b2a8dee7d
|
||||
en: 130fcf823217a00b
|
||||
zh: 59013ce608934404
|
||||
/deepseek-harness-python-sdk/run-text-and-commands:
|
||||
en: 6dec2d510bce71bd
|
||||
zh: 742ca999aaacd137
|
||||
|
||||
@@ -50,6 +50,8 @@ print(result.final_response)
|
||||
|
||||
`DeepSeekHarness` starts lazily and reuses its runtime until `close()` or context-manager exit. The initial profile handshake has an independent 30-second default bound through `initialize_timeout_seconds`; ordinary activity remains unbounded after its protocol response, whose wait can be limited with `request_timeout_seconds`. A timeout names the selected profile and includes retained runtime diagnostics. `cwd` is the agent workspace; `runtime_cwd` independently selects the subprocess working directory. Both become absolute before launch. `provider`, `model`, optional `reasoning_effort`, and optional positive `max_tokens` are sent during JSON-RPC initialization. `base_url` and `api_key` explicitly override `DEEPSEEK_BASE_URL` and `DEEPSEEK_API_KEY` in the child environment.
|
||||
|
||||
The SDK logs every line the runtime writes to stderr, as it arrives, to the Python logger `deepseek_harness.runtime` at `INFO`, prefixed with `dsh runtime[<pid>] stderr:`. That stream carries the runtime's fatal reports, including the stack of an uncaught exception or unhandled rejection that ends the process. A host that configures logging at `INFO`, for example with `logging.basicConfig(level=logging.INFO)`, receives these lines in its own log; without logging configuration Python shows nothing below `WARNING`. Set that logger's level to silence it.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -50,6 +50,8 @@ print(result.final_response)
|
||||
|
||||
`DeepSeekHarness` 延迟启动运行时,并在调用 `close()` 或退出上下文管理器前复用该进程。首次 profile 握手通过 `initialize_timeout_seconds` 使用独立的 30 秒默认上限;普通活动在协议响应后仍不设时限;`request_timeout_seconds` 可以限制协议响应的等待。超时诊断会指明所选 profile,并包含保留的运行时诊断。`cwd` 是 agent workspace;`runtime_cwd` 独立选择子进程工作目录。两者都会在启动前转成绝对路径。`provider`、`model`、可选的 `reasoning_effort` 和可选的正整数 `max_tokens` 通过 JSON-RPC 初始化发送。`base_url` 与 `api_key` 会显式覆盖子进程环境中的 `DEEPSEEK_BASE_URL` 与 `DEEPSEEK_API_KEY`。
|
||||
|
||||
SDK 把运行时写到 stderr 的每一行实时记录到 Python logger `deepseek_harness.runtime`,级别为 `INFO`,前缀为 `dsh runtime[<pid>] stderr:`。该输出包含运行时的致命错误报告,包括导致进程结束的未捕获异常或未处理拒绝的堆栈。宿主把日志配置为 `INFO`(例如 `logging.basicConfig(level=logging.INFO)`)后,这些行会进入宿主自己的日志;未配置日志时,Python 不显示低于 `WARNING` 的记录。调整该 logger 的级别即可关闭。
|
||||
|
||||
`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`。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
import subprocess
|
||||
@@ -18,6 +19,8 @@ from .errors import JsonRpcError, SdkProtocolError, TransportClosedError
|
||||
from .models import CommandExecution, IncomingRequest, InitializeResponse, JsonObject, JsonValue, Notification, ResumeSessionOptions, UserQuestionAnswer, UserQuestionRequest
|
||||
|
||||
ModelT = TypeVar("ModelT", bound=BaseModel)
|
||||
# Every line the runtime writes to stderr, as it arrives. The host's logging configuration decides whether it is shown.
|
||||
_runtime_logger = logging.getLogger("deepseek_harness.runtime")
|
||||
NotificationFilter: TypeAlias = Callable[[Notification], bool]
|
||||
UserQuestionHandler: TypeAlias = Callable[[UserQuestionRequest, threading.Event], UserQuestionAnswer | JsonObject]
|
||||
|
||||
@@ -459,7 +462,9 @@ class HarnessClient:
|
||||
if proc is None or proc.stderr is None:
|
||||
return
|
||||
for line in proc.stderr:
|
||||
self._stderr_lines.append(line.rstrip())
|
||||
text = line.rstrip()
|
||||
self._stderr_lines.append(text)
|
||||
_runtime_logger.info("dsh runtime[%d] stderr: %s", proc.pid, text)
|
||||
|
||||
def _handle_message(self, message: object) -> None:
|
||||
if not isinstance(message, dict):
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import inspect
|
||||
import sys
|
||||
import threading
|
||||
@@ -20,6 +21,7 @@ def test_high_level_sdk_runs_turn_and_preserves_auto_review_errors(tmp_path: Pat
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -226,6 +228,7 @@ def test_session_run_invokes_notification_callback_before_returning(tmp_path: Pa
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -265,6 +268,7 @@ def test_high_level_sdk_rejects_turn_end_without_reason_kind(tmp_path: Path) ->
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -303,6 +307,7 @@ def test_relative_cwd_is_absolute_in_process_environment_and_wire(
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -339,6 +344,7 @@ def test_session_run_includes_subagent_finished_for_parent_session(tmp_path: Pat
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -381,6 +387,7 @@ def test_session_run_collects_nested_subagent_tree_without_polluting_root_events
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -441,6 +448,7 @@ def test_session_run_ignores_notifications_for_other_sessions(tmp_path: Path) ->
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -478,6 +486,7 @@ def test_high_level_session_run_does_not_accumulate_global_notifications(tmp_pat
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -508,6 +517,7 @@ def test_session_run_waits_for_late_idle_without_replaying_stale_notifications(t
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
@@ -552,6 +562,7 @@ def test_client_starts_subprocess_sends_requests_and_routes_notifications(tmp_pa
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -721,6 +732,7 @@ def test_client_contains_notification_filter_failure_to_its_subscription(tmp_pat
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -763,6 +775,7 @@ def test_client_rejects_unaccepted_session_prompt_response(tmp_path: Path) -> No
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -789,6 +802,7 @@ def test_client_routes_bridge_requests_and_sends_responses(tmp_path: Path) -> No
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -824,6 +838,7 @@ def test_client_ignores_non_json_stdout_lines(tmp_path: Path) -> None:
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
print("node warning: experimental loader", flush=True)
|
||||
@@ -877,6 +892,7 @@ def test_client_close_times_out_when_shutdown_does_not_respond(tmp_path: Path) -
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
@@ -915,6 +931,7 @@ def test_client_close_allows_eof_quiescence_after_shutdown_response(tmp_path: Pa
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
@@ -951,6 +968,7 @@ def test_initialize_failure_reaps_started_runtime(tmp_path: Path) -> None:
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -1017,6 +1035,7 @@ def test_client_close_is_idempotent_before_and_after_start(tmp_path: Path) -> No
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
for line in sys.stdin:
|
||||
@@ -1063,6 +1082,7 @@ def test_client_serializes_concurrent_writes(tmp_path: Path) -> None:
|
||||
script.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -1107,6 +1127,7 @@ def _install_fake_bundled_dsh(
|
||||
runtime.write_text(
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -1201,3 +1222,31 @@ def test_client_reports_missing_bundled_runtime_dependency(monkeypatch: pytest.M
|
||||
|
||||
with pytest.raises(FileNotFoundError, match="Install deepseek-harness-runtime-bin"):
|
||||
HarnessClient(HarnessConfig(dsh_home="/explicit/home")).start()
|
||||
|
||||
|
||||
def test_runtime_stderr_lines_reach_the_runtime_logger(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
script = tmp_path / "failing_runtime.py"
|
||||
script.write_text(
|
||||
"""
|
||||
import sys
|
||||
|
||||
print("dsh: fatal load failure: TypeError: boom", file=sys.stderr, flush=True)
|
||||
print(" at node:internal/deps/undici/undici:6933:28", file=sys.stderr, flush=True)
|
||||
sys.exit(1)
|
||||
""".strip()
|
||||
)
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="deepseek_harness.runtime"):
|
||||
with HarnessClient(HarnessConfig(request_timeout_seconds=2), _launch_args=(sys.executable, str(script))) as client:
|
||||
pid = client._proc.pid
|
||||
with pytest.raises(Exception, match="fatal load failure"):
|
||||
client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
|
||||
# The reader thread ends at the runtime's stderr EOF, after it has logged every line.
|
||||
client._stderr_thread.join(timeout=5)
|
||||
assert not client._stderr_thread.is_alive()
|
||||
|
||||
records = [record for record in caplog.records if record.name == "deepseek_harness.runtime"]
|
||||
assert [(record.levelno, record.getMessage()) for record in records] == [
|
||||
(logging.INFO, f"dsh runtime[{pid}] stderr: dsh: fatal load failure: TypeError: boom"),
|
||||
(logging.INFO, f"dsh runtime[{pid}] stderr: at node:internal/deps/undici/undici:6933:28"),
|
||||
]
|
||||
Reference in new issue
Block a user