Files
deepseek-harness/packages/experimental/tool-ralph
涂轶翔 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
..

description, kind
description kind
The model-facing ralph tool: a fixed foreground fresh-agent loop toward one immutable objective, for users and maintainers choosing or configuring fresh-agent iteration. package-reference

@deepseek-ai/dsh-tool-ralph

English | 中文

Summary

ralph runs a foreground sequence of fresh child agents against one immutable objective, with each round receiving only the previous bounded report and shared workspace state. It returns when a worker reports completion or a concrete blocker, or when the configured round limit is reached; those reports are not independently verified. Parent conversation and prior child sessions are never copied into a new round. Use it only when the direct human explicitly requests Ralph-style fresh-agent iteration; use goal tools for ordinary long-running work and subagents or workflows for bounded delegation.

Table of Contents


Use this package

The ralph tool runs a fixed foreground loop: one fresh child per round works on the immutable objective in the shared workspace, and only a bounded structured report crosses rounds. Use it only when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. For ordinary long-running same-session work, use goal tools; for bounded delegation and fan-out, use plain subagents or the workflow tool.

Calling the tool

The model submits { objective, maxRounds? } and the call blocks until the whole run settles. The deployment config's maxRounds is both the default and a ceiling on a call override. The terminal result is complete, blocked, or budget-limited, carrying the last bounded report and the number of rounds started; an ordinary child failure returns an error naming the failed round and retaining the last successful handoff when one exists. Failures carry RalphError with a closed code: RALPH_ROUND_FAILED for a child round that ends without a structured report, RALPH_WORKFLOW_FAILED for a workflow that errors or is cancelled by something other than the caller, including a child report that fails validation inside the workflow because the workflow returns its errors only as text, RALPH_INVALID_RESULT for a malformed workflow value, and RALPH_PROVIDER_UNAVAILABLE or RALPH_PROVIDER_UNSUPPORTED for a provider route violation. An empty objective or an out-of-range maxRounds is a ToolArgsError, and caller cancellation is an AbortError.

What each round sees

Each child receives only the immutable objective, its current round and cap, a shared-workspace-as-authority instruction, and the previous structured handoff; parent conversation and prior child sessions are never seeded. The workspace is the long-term memory across rounds. Reports carry a status (continue, complete, or blocked), a non-empty summary, evidence, next steps, and blocker text; invalid or oversized reports fail the workflow instead of being truncated or mistaken for cap exhaustion.

Config

Field Default Meaning
subagentProvider spawn Fresh structured-output provider used for every round.
maxRounds 256 Default and deployment ceiling for one Ralph run.
maxHandoffChars 16384 Maximum serialized characters in one round report.
maxResultChars 16384 Maximum characters in the complete successful parent result.

The generated configuration catalog is the exhaustive source for every accepted field. The configured provider must exist, support structured output, and report inheritsParentContext: false; a call against a provider that violates this fails loudly before any round starts.


Understand the implementation

Implementation internals — click to expand

This section explains the fixed-script design and the validation and lifecycle mechanics; observable behavior is fully covered in Use this package.

Design concept

The loop is a deployment-owned fixed script: the model supplies data only and cannot alter the loop, provider route, schema, or handoff validation. The tool is an ordinary plugin over ctx.workflowEngine and ctx.subagents — no Ralph mode or fresh-agent loop is added to agent-loop, and the same-session goal domain stays independent.

Fixed script and routing

The configured provider is carried as WorkflowStartRequest.subagentProvider, so the fixed script cannot inspect or change routing and the ordinary model-written workflow tool gains no provider selector. The resolved round cap is carried as WorkflowStartRequest.maxTotalAgents, coordinating the fixed loop with the engine's total-child backstop; the engine rejects a cap above its deployment ceiling before publishing a run.

Report validation

Status-specific semantics and the serialized maxHandoffChars ceiling are validated inside the fixed workflow and again at the consumer boundary: a continuing report needs next steps and an empty blocker, a completion report needs evidence and no next steps, and a blocked report needs a concrete blocker. Invalid, missing, or oversized reports fail the workflow.

Lifecycle and cancellation

The caller's agent is the parent of every fresh child, preserving cwd and lineage without copying its conversation. exec.signal enters the workflow engine and is also bridged to run.cancel() for implementation independence. The tool awaits run.result and calls run.dispose() in finally, so a cancelled parent step waits for process and child cleanup before returning. The PTC engine sets no overall workflow elapsed deadline; caller cancellation still applies.

Render intent

The pending call is a generic card titled ralph with the immutable objective as its rawInput; the result keeps the generic card. Both presentation functions depend only on tool arguments and the settled tool envelope, and the completion and blocker labels state that a worker reported the outcome, not independent certification.

Source map

File Role
src/index.ts Plugin entry: fixed script, provider routing, report validation, tool registration

Further Exploration

Read these pages when the tool-level contract is not enough. They move from the shared workflow model to the engine, the subagent seam, and the adjacent goal domain.


Model Experience

System prompt

What the model sees

Every parent request in this plugin's registration scope receives the fixed routing guidance below.

Ralph guidance
Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.

Token effect

Small fixed guidance cost per request while the plugin is active.

KV Cache effect

Prefix-stable while the plugin scope and guidance text are unchanged. Activation or disposal may invalidate reuse from this prompt section.

Tool schema

What the model sees

The generated ralph schema exposes one required objective string and one optional maxRounds number. Provider choice, handoff size, report schema, workflow script, and orchestration behavior are deployment-owned and absent from the call schema.

Token effect

Small fixed schema cost on each request where the tool is visible.

KV Cache effect

Prefix-stable while the definition and visibility are unchanged.

Child requests and parent result

What the model sees

Each child sees the standalone fixed round prompt plus the structured-output capture contract. The parent sees only the original call and one terminal result containing a worker-reported status, round count, and pretty-printed final report; intermediate child messages and reports do not enter the parent conversation. A failed ordinary child instead yields an error with its round number and, after round one, the last successful handoff.

Token effect

Every round pays for a fresh child context. maxHandoffChars bounds cross-round state and maxResultChars independently bounds the complete successful parent text; child work remains outside the parent context.

KV Cache effect

Each fresh child has an independent request cache. The parent result appends after the reusable request prefix.

Known Limitations and Deferred Work

These limits define what the tool does not yet support. They are current constraints, not a task backlog.

  • Completion is worker self-declaration — there is no independent evaluator or verifier deciding whether the objective is complete; evaluator policy and evaluator-driven continuation are deferred. An evaluator needs separately defined inputs, tool access, deterministic checks, provider choice, isolation, and authority before it can certify completion or drive continuation.
  • Foreground only — there is no job id, background collection, process-resume checkpoint, scheduler, or wall-clock start policy.
  • The workspace is the only cross-round long-term memory — one bounded report is the explicit handoff, and uncommitted conversational reasoning disappears with each child.
  • One round is one fresh child — there is no within-round fan-out, model or provider switching, fork context, or model-call-selected provider.
  • No enforced recursive-Ralph denial — structural denial is not implemented; prompt guidance does not enforce a recursion ban.
  • Ordinary child failure is terminal for the run — the fixed script reports the failed round and last successful handoff but does not retry; fatal workflow infrastructure failures can end before that state is returned.
  • Only round count bounds aggregate effort — token, price, and elapsed-time budgets are deferred.

Dev Note

Working context for maintainers — click to expand

This Dev Note is working context for maintainers: open directions that are not decided. It is explicitly non-authoritative — shipped behavior, limits, and accepted rationale live in the sections above, the package code, and the linked Agent Notes.

Open directions: an independent evaluator with evaluator-driven continuation; within-round fan-out and provider selection; and token, price, and elapsed-time budgets beyond the round cap.