Files
deepseek-harness/python/sdk
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00
..

DeepSeek Harness Python SDK

English | 中文

Python subprocess SDK for driving DeepSeek Harness over newline-delimited JSON-RPC on stdio. Install deepseek-harness-sdk; it installs the exact same-version deepseek-harness-runtime-bin wheel for the current platform.

python -m pip install deepseek-harness-sdk

Optional Office operations

Download the Office runtime explicitly, then call the local API without an agent, Session, model request, API key, or Harness home:

from deepseek_harness_runtime import download_office
from deepseek_harness.office import convert, recalculate, render_images

download_office()
pdf = convert("report.docx", "report.pdf")
workbook = recalculate("forecast.xlsx", "calculated.xlsx")
preview = render_images("report.docx", "report-preview", pages=[1])

The output file or image directory must not exist. Successful outputs belong to the caller; Kit removes failed outputs. OfficeOptions supplies operation limits and font preferences. Results expose typed paths, missing fonts, and image metadata. OfficeError retains CLI failure codes; malformed results raise SdkProtocolError. Recalculation does not verify business logic or Excel fidelity. Ctrl+C waits for CLI cleanup; a second interrupt forces termination and may leave partial output. Windows requires an absolute SystemRoot and a shared console for Ctrl+C delivery.

The authoring environment is independently optional through deepseek_harness_runtime.download_primary_runtime(). See the runtime reference for cache selection, resource activation, and download behavior. SDK startup and Office operations never acquire missing resources automatically.

Start a runtime

The Python SDK has no separate application entrypoint. It launches the bundled dsh CLI with --profile sdk; the selected profile owns the JSON-RPC server, agent composition, credentials, persistence, tools, and shutdown behavior.

Every launch requires an explicit Harness home. Pass dsh_home or provide a non-empty DSH_HOME in the child environment. The SDK deliberately never discovers ~/.dsh.

from deepseek_harness import DeepSeekHarness

with DeepSeekHarness(
    dsh_home="/absolute/path/to/isolated-dsh-home",
    cwd="/absolute/path/to/workspace",
    provider="deepseek-official",
    model="deepseek-v4-flash",
    reasoning_effort="max",
    max_tokens=49_152,
) as harness:
    result = harness.run("Say hi.", session_id="example-001")

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.

with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness:
    session = harness.resume_session(saved_session_id)
    result = session.run("Continue the task.")

Run text and commands

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; 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.

Content-block arrays use the same command routing as strings. Both session.run([{"type": "text", "text": "/compact"}]) and session.run("/compact") invoke native compaction and return RunResult. To bypass native command routing, call the low-level client.session_prompt(session_id, blocks) and manage subsequent activity; runtime skill recognition still applies.

Pass the user's zone as time_zone, for example session.run("When is noon tomorrow?", time_zone="Asia/Shanghai"); harness.run() and client.session_prompt() accept the same keyword and send it as the timeZone wire field. The value is UTC or an IANA Area/Location name; the runtime rejects any other value with JsonRpcError before running input. Without it, the runtime samples its own process zone for each prompt. Native commands record no zone.

Select a model that supports image input. Submit a command and image in the existing content-block array, for example session.run([{"type": "text", "text": "/plan Analyze this image."}, {"type": "image", "data": image_base64, "mimeType": "image/png"}]); harness.run() accepts the same input. Plan input and goal creation or editing accept images; /plan off, goal controls, compact, and permission commands reject them through the native attachment rules. Native command input supports encoded raster images, not general file uploads or client-supplied attachment references.

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. See the compaction example.

/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.

/plan enters plan mode, /plan off leaves, and /plan <message> enters then submits the trimmed message through native steer. run() waits for submitted model activity, including native review and approved continuation; no separate subscription or session/wait call is required. Keep on_user_question available for review, as in the plan example. Plans submitted through exit_plan_mode arrive in the review question's detail; final_response contains the final assistant text. Plan mode does not change permission settings.

/goal shows the current goal. Creation and resume through run() wait across automatic rounds until the goal stops and its closing activity finishes. Completion returns completed, pause or clear returns aborted, and blocking or lost activation reports failure. State-only controls return without waiting for unrelated activity. A restored active goal stays disarmed until explicit resume. See the goal example.

Client approvals

For an interactive full-profile example that explicitly prepares Node/pnpm and answers permission requests while a turn runs, see examples/manage_plugins.py. It uses the existing stdio approval protocol, asks before each operation, and closes the runtime before joining its request worker. Plugin configuration takes effect after runtime restart.

This low-level example receives one approval and rejects it. Use a dedicated request-handling thread or loop for a full run: next_request() blocks, and the request handler must run concurrently with session/wait or a high-level run(). Set approval_requests=True on HarnessClient.initialize() or DeepSeekHarnessConfig only when that handler is ready. Omission preserves the runtime's answerer chain. Decisions are one-shot; invalid responses and lost connections fail closed, and cancellation discards late replies. ApprovalRequestResult validates response values when constructing decisions.

from deepseek_harness import ApprovalRequestParams, HarnessClient, HarnessConfig

with HarnessClient(HarnessConfig(dsh_home="/absolute/path/to/dsh-home")) as client:
    client.initialize(cwd="/absolute/path/to/workspace", provider="deepseek-official",
                      model="deepseek-v4-flash", approval_requests=True)
    client.session_prompt("main", [{"type": "text", "text": "Run the operation requiring approval."}])
    request = client.next_request()
    if request.method == "approval/request":
        question = ApprovalRequestParams.model_validate(request.payload)
        print(question.toolName, question.reason)
        client.respond(request.id, {"outcome": "rejected"})
    else:
        client.respond_error(request.id, code=-32601, message="Unsupported client request")

Customize plugins

Persistent customization belongs to a dsh profile. Initialize the shipped SDK profile and install an external bundle with the runtime wheel's dsh command:

export DSH_HOME=/absolute/path/to/isolated-dsh-home
dsh --profile sdk --dump-default-config >/dev/null
dsh plugin --profile sdk add file:/absolute/path/to/my-plugin-bundle

The file: form installs the local bundle into the profile package tree, where its peer imports reach the bundled installation fallback. The profile manifest records installed dependencies and ordered bundle layers; its $DSH_HOME/profiles/sdk/cordis.patch.yml is the persistent user patch. dsh plugin needs pnpm only when managing external packages. Running the SDK does not require system Node.js.

For an invocation-specific change, pass one or more patch files. They become absolute and are forwarded in order after the profile and home patch layers:

with DeepSeekHarness(
    dsh_home="/absolute/path/to/isolated-dsh-home",
    profile="sdk",
    patches=("/absolute/path/to/first.patch.yml", "/absolute/path/to/last.patch.yml"),
) as harness:
    result = harness.run("Make the requested code change.")

profile may select another existing profile, but that composition must retain @deepseek-ai/dsh-sdk-app or another @deepseek-ai/dsh-sdk-jsonrpc-server row. Misconfiguration fails during CLI boot or SDK initialization; there is no complete-config fallback. dsh_bin may select another dsh executable while preserving the same profile grammar. Arbitrary argv replacement remains an internal fake-runtime test adapter, not public API.

provider selects a provider route registered by the chosen Cordis composition; model is the model id resolved by that adapter. reasoning_effort is an optional non-empty adapter-owned identifier for that exact route; omission preserves the model's own default. max_tokens is an optional positive per-request output-token cap for the root agent and its in-process descendants; omission leaves the provider default in control. Initialization rejects a missing adapter, unavailable model, or unsupported effort before a prompt runs. Compaction summaries keep the separate limit configured by their compaction plugin. The bundled default composition registers deepseek-official. A custom composition can mount llm-pi-ai, configure provider-specific credentials/endpoints there, and select any provider/model present in pi-ai's installed catalog.

The shipped sdk-minimal profile is a standalone explicit tree rather than an overlay on dsh-base. Select it with profile="sdk-minimal"; the ordinary model argument is the sole runtime model selection, including for model ids outside the adapter's advisory catalog. It provides a platform-selected persistent shell, read_image, local execution, JSONL sessions, and automatic compaction. Text file tools, settings, managed credentials, telemetry, Web tools, and the full default tool roster remain available through the separate full sdk and web profiles. The sdk-minimal profile leaves unsupported slash input on the ordinary prompt path.

Native user questions

Pass on_user_question to DeepSeekHarnessConfig, DeepSeekHarness, or HarnessConfig to answer the built-in ask_user_question tool through the native SDK protocol. The callback receives a UserQuestionRequest (request_id, session_id, and the original questions) and a threading.Event signalling cancellation. Return UserQuestionAnswer or a JSON object shaped as {"answers": [{"id": "question-id", "selected": ["option label"], "custom": "optional free text"}]}. Each original question id must appear exactly once. Return { "cancelled": true } to dismiss instead of answering; this preserves the native plan-review dismissal, which ends the turn while keeping plan mode active. The application supplies its UI or simulated-user policy; the SDK does not choose answers.

Callbacks run on separate threads so the reader can process cancellation and other requests. They may run concurrently and may make further client requests. Release callback-owned work when the cancellation Event is set. Closing the client signals outstanding callbacks and gives their workers a shared 0.5-second join window; callbacks that ignore cancellation may continue, but their late answers cannot reach the runtime or a later process. A callback exception becomes a protocol error, and an absent callback retains existing native answerers or reports NO_PROVIDER.

Results and notifications

For ordinary prompts, Session.run() owns an activity interval from its prompt's durable inbox receipt through the next whole-agent idle and returns RunResult(session_id, final_response, finish_reason, events, notifications). final_response is the last committed root-session assistant text in the interval. finish_reason is the kind of the last root-session turn/end, such as completed, max-tokens, or error, and is None when no turn ended. A turn/end without a string data.reason.kind violates the protocol and raises SdkProtocolError.

NotificationSubscription.next(timeout_seconds=...) bounds one local notification wait and raises TimeoutError on expiry. Omitting the argument waits indefinitely. A timeout neither cancels runtime work nor closes the subscription; a later call can receive subsequent notifications.

HarnessClient retains discovered subagent ancestry for the runtime process lifetime. During Session.run(), RunResult.notifications and on_notification receive the root session and known descendants in wire order. RunResult.events contains root-session events only, so descendant output cannot replace the root response. The low-level session_prompt() returns the queued message id immediately; callers that bypass Session.run() own the later activity boundary.

The selected home stores profiles, plugins, and every profile-owned durable resource. The full sdk profile uses its credentials, settings, and session stores; sdk-minimal uses JSONL session storage and stores images under $DSH_HOME/attachments/v1, with request-image cache under $DSH_HOME/cache/attachments. Use a fresh home when those resources must be isolated, and a fresh session id for independent work. Reusing both a harness and session id continues the durable conversation and session-owned resources.

See the Python tutorial, runnable example, and runtime wheel reference.

Session.get_working_directory() reads the effective working directory; set_working_directory(path) changes it and returns the validated absolute path. Both create an unknown Session without running a model turn. Relative paths use that Session's current directory. Origin metadata and existing processes remain unchanged; the workspace-write boundary moves to the new directory. The low-level client provides the same methods with a leading session_id argument.