mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-29 00:30:04 +08:00
424 lines
17 KiB
Python
424 lines
17 KiB
Python
from __future__ import annotations
|
|
|
|
import uuid
|
|
import threading
|
|
from collections import deque
|
|
from collections.abc import Iterator
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Callable, Literal
|
|
|
|
from .client import HarnessClient, HarnessConfig, NotificationSubscription, UserQuestionHandler, _PendingRequest
|
|
from .errors import SdkProtocolError, TransportClosedError
|
|
from .models import CommandExecution, JsonObject, Notification
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class DeepSeekHarnessConfig:
|
|
"""Configuration for launching the local DeepSeek Harness SDK runtime.
|
|
|
|
The runtime inherits the caller's environment by default, so existing
|
|
DEEPSEEK_API_KEY and DEEPSEEK_BASE_URL settings keep working. Use ``env`` to
|
|
intentionally override or inject variables for a subprocess.
|
|
These values are startup input, not a live Session state mirror; Session
|
|
commands do not rewrite this object.
|
|
"""
|
|
|
|
provider: str = "deepseek-official"
|
|
model: str = "deepseek-v4-flash"
|
|
reasoning_effort: str | None = None
|
|
max_tokens: int | None = None
|
|
cwd: str | None = None
|
|
runtime_cwd: str | None = None
|
|
dsh_bin: str | None = None
|
|
profile: str = "sdk"
|
|
patches: tuple[str, ...] = ()
|
|
dsh_home: str | None = None
|
|
env: dict[str, str] = field(default_factory=dict)
|
|
initialize_timeout_seconds: float = 30.0
|
|
request_timeout_seconds: float | None = None
|
|
shutdown_timeout_seconds: float | None = 1.0
|
|
base_url: str | None = None
|
|
api_key: str | None = None
|
|
on_user_question: UserQuestionHandler | None = None
|
|
approval_requests: bool = False
|
|
|
|
|
|
@dataclass(slots=True)
|
|
class RunResult:
|
|
session_id: str
|
|
final_response: str
|
|
finish_reason: str | None
|
|
events: list[JsonObject]
|
|
notifications: list[Notification]
|
|
|
|
|
|
class _PromptActivity:
|
|
"""Collect an ordinary prompt's notifications from its inbox receipt through idle."""
|
|
|
|
def __init__(self, session_id: str, message_id: str) -> None:
|
|
self.session_id = session_id
|
|
self.message_id = message_id
|
|
self.received = False
|
|
self.events: list[JsonObject] = []
|
|
self.notifications: list[Notification] = []
|
|
|
|
def record(self, notification: Notification, on_notification: Callable[[Notification], None] | None = None) -> bool:
|
|
if not self.received:
|
|
if not _is_inbox_receipt(notification, self.session_id, self.message_id):
|
|
return False
|
|
self.received = True
|
|
self.notifications.append(notification)
|
|
if on_notification is not None:
|
|
on_notification(notification)
|
|
if notification.method == "session.event" and notification.payload.get("sessionId") == self.session_id:
|
|
event = notification.payload.get("event")
|
|
if isinstance(event, dict):
|
|
self.events.append(event)
|
|
return True
|
|
|
|
def result(self) -> RunResult:
|
|
return RunResult(
|
|
session_id=self.session_id, final_response=final_response(self.events),
|
|
finish_reason=finish_reason(self.events), events=self.events, notifications=self.notifications,
|
|
)
|
|
|
|
|
|
class _QueryResponseIterator(Iterator[Notification | RunResult | CommandExecution]):
|
|
def __init__(
|
|
self, client: HarnessClient, session_id: str, request: _PendingRequest,
|
|
subscription: NotificationSubscription,
|
|
) -> None:
|
|
self._client = client
|
|
self._session_id = session_id
|
|
self._request = request
|
|
self._subscription = subscription
|
|
self._lock = threading.Lock()
|
|
self._closed = False
|
|
self._released = False
|
|
self._routed = False
|
|
self._activity: _PromptActivity | None = None
|
|
self._buffer: deque[Notification] = deque()
|
|
self._terminal: RunResult | CommandExecution | None = None
|
|
|
|
def _release(self, error: BaseException | None = None) -> None:
|
|
with self._lock:
|
|
if self._released:
|
|
return
|
|
self._released = True
|
|
self._client._discard_request(self._request, error)
|
|
if error is None:
|
|
self._subscription.close()
|
|
else:
|
|
self._subscription._cancel(error)
|
|
|
|
def close(self) -> None:
|
|
"""Stop observing this query; the runtime operation is not cancelled."""
|
|
with self._lock:
|
|
if self._closed:
|
|
return
|
|
self._closed = True
|
|
self._release(TransportClosedError("query response iterator closed"))
|
|
|
|
def _ensure_open(self) -> None:
|
|
if self._closed:
|
|
raise StopIteration
|
|
|
|
def __next__(self) -> Notification | RunResult | CommandExecution:
|
|
try:
|
|
self._ensure_open()
|
|
if not self._routed:
|
|
response = self._client._wait_request(self._request)
|
|
self._ensure_open()
|
|
self._routed = True
|
|
if not isinstance(response, dict):
|
|
raise SdkProtocolError("session/query response must be a JSON object")
|
|
if response.get("kind") == "command":
|
|
self._terminal = CommandExecution.model_validate(response.get("execution"))
|
|
self._release()
|
|
while True:
|
|
try:
|
|
notification = self._subscription._next_queued()
|
|
except TransportClosedError:
|
|
break
|
|
if notification is None:
|
|
break
|
|
self._buffer.append(notification)
|
|
if _is_command_done(notification, self._session_id, self._terminal.command_id):
|
|
break
|
|
elif response.get("kind") == "prompt" and isinstance(response.get("messageId"), str) and response["messageId"]:
|
|
self._activity = _PromptActivity(self._session_id, response["messageId"])
|
|
else:
|
|
raise SdkProtocolError("session/query requires a prompt messageId or command execution result")
|
|
self._ensure_open()
|
|
if self._buffer:
|
|
return self._buffer.popleft()
|
|
if self._terminal is not None:
|
|
terminal = self._terminal
|
|
self._terminal = None
|
|
self._release()
|
|
self._closed = True
|
|
return terminal
|
|
assert self._activity is not None
|
|
while True:
|
|
notification = self._subscription.next()
|
|
self._ensure_open()
|
|
if not self._activity.record(notification):
|
|
continue
|
|
if (notification.method == "session.status"
|
|
and notification.payload.get("sessionId") == self._session_id
|
|
and notification.payload.get("status") == "idle"):
|
|
self._terminal = self._activity.result()
|
|
self._release()
|
|
return notification
|
|
except BaseException as error:
|
|
locally_closed = self._closed
|
|
self.close()
|
|
if locally_closed and isinstance(error, (TransportClosedError, StopIteration)):
|
|
raise StopIteration
|
|
raise
|
|
|
|
|
|
class DeepSeekHarness:
|
|
"""Reusable synchronous SDK for running DeepSeek Harness agent turns.
|
|
|
|
The runtime subprocess starts lazily and remains owned by this instance
|
|
across calls to :meth:`run`. Use the instance as a context manager, or call
|
|
:meth:`close` explicitly when finished, so the subprocess is always reaped.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
config: DeepSeekHarnessConfig | None = None,
|
|
*,
|
|
_launch_args: tuple[str, ...] | None = None,
|
|
**kwargs: object,
|
|
) -> None:
|
|
if config is not None and kwargs:
|
|
raise TypeError("pass either DeepSeekHarnessConfig or keyword options, not both")
|
|
self.config = config or DeepSeekHarnessConfig(**kwargs)
|
|
cwd = str(Path(self.config.cwd or Path.cwd()).resolve())
|
|
runtime_cwd = str(Path(self.config.runtime_cwd).resolve()) if self.config.runtime_cwd is not None else cwd
|
|
self._cwd = cwd
|
|
env = dict(self.config.env)
|
|
if self.config.base_url is not None:
|
|
env["DEEPSEEK_BASE_URL"] = self.config.base_url
|
|
if self.config.api_key is not None:
|
|
env["DEEPSEEK_API_KEY"] = self.config.api_key
|
|
|
|
self._client = HarnessClient(
|
|
HarnessConfig(
|
|
dsh_bin=self.config.dsh_bin,
|
|
profile=self.config.profile,
|
|
patches=self.config.patches,
|
|
dsh_home=self.config.dsh_home,
|
|
cwd=runtime_cwd,
|
|
env=env,
|
|
initialize_timeout_seconds=self.config.initialize_timeout_seconds,
|
|
request_timeout_seconds=self.config.request_timeout_seconds,
|
|
shutdown_timeout_seconds=self.config.shutdown_timeout_seconds,
|
|
on_user_question=self.config.on_user_question,
|
|
),
|
|
_launch_args=_launch_args,
|
|
)
|
|
self._initialized = False
|
|
|
|
def __enter__(self) -> "DeepSeekHarness":
|
|
self.start()
|
|
return self
|
|
|
|
def __exit__(self, _exc_type, _exc, _tb) -> None:
|
|
self.close()
|
|
|
|
@property
|
|
def client(self) -> HarnessClient:
|
|
return self._client
|
|
|
|
def start(self) -> None:
|
|
if self._initialized:
|
|
return
|
|
self._client.start()
|
|
self._client.initialize(
|
|
cwd=self._cwd,
|
|
provider=self.config.provider,
|
|
model=self.config.model,
|
|
reasoning_effort=self.config.reasoning_effort,
|
|
max_tokens=self.config.max_tokens,
|
|
approval_requests=self.config.approval_requests,
|
|
)
|
|
self._initialized = True
|
|
|
|
def close(self) -> None:
|
|
self._client.close()
|
|
self._initialized = False
|
|
|
|
def start_session(self, session_id: str | None = None) -> "Session":
|
|
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.
|
|
|
|
Missing, unreadable, incompatible, or occupied sessions raise instead of creating a new session.
|
|
"""
|
|
self.start()
|
|
self._client.resume_session(session_id)
|
|
return Session(self, session_id)
|
|
|
|
def run(
|
|
self,
|
|
input: str | list[JsonObject],
|
|
*,
|
|
session_id: str | None = None,
|
|
on_notification: Callable[[Notification], None] | None = None,
|
|
) -> RunResult:
|
|
return self.start_session(session_id).run(input, on_notification=on_notification)
|
|
|
|
|
|
class Session:
|
|
def __init__(self, harness: DeepSeekHarness, session_id: str) -> None:
|
|
self.harness = harness
|
|
self.id = session_id
|
|
self._queries: deque[_QueryResponseIterator] = deque()
|
|
self._query_lock = threading.Lock()
|
|
|
|
def query(self, text: str, *, delivery: Literal["queue", "steer"] = "queue") -> None:
|
|
"""Send text for runtime prompt or command routing without waiting for the response.
|
|
|
|
Pair each call with receive_response(). Delivery selects where ordinary
|
|
prompts enter the inbox; commands retain their native execution timing.
|
|
"""
|
|
if not isinstance(text, str):
|
|
raise TypeError("query text must be a string")
|
|
if delivery not in ("queue", "steer"):
|
|
raise ValueError("query delivery must be queue or steer")
|
|
self.harness.start()
|
|
client = self.harness.client
|
|
with self._query_lock:
|
|
subscription = client.subscribe_session_notifications(self.id)
|
|
try:
|
|
request = client._begin_request("session/query", {"sessionId": self.id, "text": text, "delivery": delivery})
|
|
except BaseException:
|
|
subscription.close()
|
|
raise
|
|
self._queries.append(_QueryResponseIterator(client, self.id, request, subscription))
|
|
|
|
def receive_response(self) -> _QueryResponseIterator:
|
|
"""Claim the next query in send order and iterate its notifications and terminal result.
|
|
|
|
Prompts collect the inbox-receipt-to-idle interval used by run(); commands
|
|
finish on their RPC result. Close an unfinished iterator to release its
|
|
local observation resources without cancelling the runtime operation.
|
|
"""
|
|
with self._query_lock:
|
|
if not self._queries:
|
|
raise RuntimeError("receive_response requires a preceding query")
|
|
return self._queries.popleft()
|
|
|
|
def get_working_directory(self) -> str:
|
|
"""Read the effective directory, recovering a missing directory to the Session origin."""
|
|
self.harness.start()
|
|
return self.harness.client.get_working_directory(self.id)
|
|
|
|
def set_working_directory(self, path: str) -> str:
|
|
"""Change the effective directory while existing processes retain their own directories."""
|
|
self.harness.start()
|
|
return self.harness.client.set_working_directory(self.id, path)
|
|
|
|
def run(
|
|
self,
|
|
input: str | list[JsonObject],
|
|
*,
|
|
on_notification: Callable[[Notification], None] | None = None,
|
|
) -> RunResult:
|
|
content_blocks = normalize_input(input)
|
|
with self.harness.client.subscribe_session_notifications(self.id) as subscription:
|
|
message_id = self.harness.client.session_prompt(
|
|
self.id,
|
|
content_blocks,
|
|
notification_subscription=subscription,
|
|
)
|
|
|
|
activity = _PromptActivity(self.id, message_id)
|
|
while True:
|
|
notification = subscription.next()
|
|
if not activity.record(notification, on_notification):
|
|
continue
|
|
if (
|
|
notification.method == "session.status"
|
|
and notification.payload.get("sessionId") == self.id
|
|
and notification.payload.get("status") == "idle"
|
|
):
|
|
break
|
|
|
|
return activity.result()
|
|
|
|
|
|
def _is_inbox_receipt(notification: Notification, session_id: str, message_id: str) -> bool:
|
|
if notification.method != "session.event" or notification.payload.get("sessionId") != session_id:
|
|
return False
|
|
event = notification.payload.get("event")
|
|
if not isinstance(event, dict) or event.get("type") != "agent/inbox/spliced":
|
|
return False
|
|
data = event.get("data")
|
|
inserted = data.get("inserted") if isinstance(data, dict) else None
|
|
return isinstance(inserted, list) and any(
|
|
isinstance(message, dict) and message.get("id") == message_id for message in inserted
|
|
)
|
|
|
|
|
|
def _is_command_done(notification: Notification, session_id: str, command_id: str) -> bool:
|
|
if notification.method != "session.event" or notification.payload.get("sessionId") != session_id:
|
|
return False
|
|
event = notification.payload.get("event")
|
|
if not isinstance(event, dict) or event.get("type") != "command/done":
|
|
return False
|
|
data = event.get("data")
|
|
return isinstance(data, dict) and data.get("commandId") == command_id
|
|
|
|
|
|
def normalize_input(input: str | list[JsonObject]) -> list[JsonObject]:
|
|
if isinstance(input, str):
|
|
return [{"type": "text", "text": input}]
|
|
return input
|
|
|
|
|
|
def final_response(events: list[JsonObject]) -> str:
|
|
for event in reversed(events):
|
|
if event.get("type") != "assistant/message":
|
|
continue
|
|
data = event.get("data")
|
|
if not isinstance(data, dict):
|
|
continue
|
|
message = data.get("message")
|
|
content_owner = message if isinstance(message, dict) else data
|
|
content = content_owner.get("content")
|
|
if not isinstance(content, list):
|
|
continue
|
|
parts: list[str] = []
|
|
for block in content:
|
|
if isinstance(block, dict) and block.get("type") == "text":
|
|
parts.append(str(block.get("text") or ""))
|
|
return "".join(parts)
|
|
return ""
|
|
|
|
|
|
def finish_reason(events: list[JsonObject]) -> str | None:
|
|
"""Return the last turn-ending kind.
|
|
|
|
The input must contain root-session events from one owned run interval.
|
|
|
|
Raises:
|
|
SdkProtocolError: The last ``turn/end`` has no string reason kind.
|
|
"""
|
|
for event in reversed(events):
|
|
if event.get("type") != "turn/end":
|
|
continue
|
|
data = event.get("data")
|
|
reason = data.get("reason") if isinstance(data, dict) else None
|
|
kind = reason.get("kind") if isinstance(reason, dict) else None
|
|
if not isinstance(kind, str):
|
|
raise SdkProtocolError("turn/end event requires a string data.reason.kind")
|
|
return kind
|
|
return None
|