From b8080268599b33090c150786feb0b9438517f716 Mon Sep 17 00:00:00 2001
From: Tianyi Cui <53024+tianyicui@users.noreply.github.com>
Date: Mon, 20 Jul 2026 00:51:19 +0800
Subject: [PATCH] feat(workflow): add fresh-agent Ralph tool
---
docs/capability-seams.md | 7 +-
docs/config-catalog.md | 18 +
docs/core-data-structures/workflow.md | 8 +-
docs/glossary.md | 6 +
docs/module-graph.md | 8 +
docs/rfc/INDEX.md | 1 +
...-fresh-agent-ralph-workflow-tool.i18n.yaml | 6 +
...6-07-19-fresh-agent-ralph-workflow-tool.md | 67 +++
...7-19-fresh-agent-ralph-workflow-tool.zh.md | 67 +++
docs/tool-catalog.md | 30 ++
examples/acp-agent/composition.md | 3 +
examples/acp-agent/cordis.yml | 3 +
.../system-prompt.expected.md | 9 +
.../tool-schemas.expected.json | 20 +
.../both-mode-turn/system-prompt.expected.md | 9 +
.../both-mode-turn/tool-schemas.expected.json | 20 +
.../code-mode-turn/system-prompt.expected.md | 9 +
.../system-prompt.expected.md | 9 +
.../model-switching/system-prompt.expected.md | 4 +
.../tool-schemas.expected.json | 40 ++
.../system-prompt.expected.md | 4 +
.../tool-schemas.expected.json | 40 ++
.../skill-load/system-prompt.expected.md | 2 +
.../skill-load/tool-schemas.expected.json | 20 +
.../text-turn/system-prompt.expected.md | 2 +
.../text-turn/tool-schemas.expected.json | 20 +
.../system-prompt.expected.md | 2 +
.../tool-schemas.expected.json | 20 +
.../workspace-edit/system-prompt.expected.md | 2 +
.../workspace-edit/tool-schemas.expected.json | 20 +
examples/headless-agent/README.md | 2 +-
examples/headless-agent/composition.md | 3 +
examples/headless-agent/cordis.yml | 5 +
examples/package.json | 1 +
examples/repl-agent/README.md | 4 +-
examples/repl-agent/composition.md | 3 +
examples/repl-agent/cordis.yml | 3 +
examples/tui-agent/tests/tui.snapshot.ts | 2 +
packages/README.md | 2 +-
.../cordis/tool-cordis/src/api-catalog.ts | 2 +-
.../core/tools/tests/gen-tool-catalog.spec.ts | 2 +-
packages/workflow/README.md | 3 +-
packages/workflow/tool-ralph/README.md | 87 ++++
packages/workflow/tool-ralph/package.json | 53 +++
packages/workflow/tool-ralph/src/index.ts | 384 ++++++++++++++++++
.../tool-ralph/tests/integration.spec.ts | 92 +++++
.../tool-ralph/tests/tool-ralph.spec.ts | 319 +++++++++++++++
packages/workflow/tool-ralph/tsconfig.json | 39 ++
.../workflow/workflow-workerthread/README.md | 4 +-
.../workflow-workerthread/src/index.ts | 3 +-
.../tests/built-worker.e2e.ts | 22 +-
.../tests/workflow-workerthread.spec.ts | 20 +
packages/workflow/workflow/README.md | 2 +-
packages/workflow/workflow/src/types.ts | 6 +
pnpm-lock.yaml | 55 +++
scripts/gen-doc-graphs.ts | 8 +-
scripts/gen-tool-catalog.ts | 18 +-
tsconfig.json | 1 +
58 files changed, 1599 insertions(+), 22 deletions(-)
create mode 100644 docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml
create mode 100644 docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md
create mode 100644 docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md
create mode 100644 packages/workflow/tool-ralph/README.md
create mode 100644 packages/workflow/tool-ralph/package.json
create mode 100644 packages/workflow/tool-ralph/src/index.ts
create mode 100644 packages/workflow/tool-ralph/tests/integration.spec.ts
create mode 100644 packages/workflow/tool-ralph/tests/tool-ralph.spec.ts
create mode 100644 packages/workflow/tool-ralph/tsconfig.json
diff --git a/docs/capability-seams.md b/docs/capability-seams.md
index 50cb528951..c03469e83e 100644
--- a/docs/capability-seams.md
+++ b/docs/capability-seams.md
@@ -83,6 +83,7 @@ flowchart LR
pkg_subagent_spawn["subagent-spawn"]
pkg_subagent_fork["subagent-fork"]
pkg_subagent_acp["subagent-acp"]
+ pkg_tool_ralph["tool-ralph"]
pkg_tasks["tasks"]
svc_tasks["ctx.tasks
Background task registry"]
pkg_tool_tasks["tool-tasks"]
@@ -186,6 +187,7 @@ flowchart LR
svc_sessions --> pkg_subagent_inprocess
svc_skills --> pkg_tool_skill
svc_spillStore --> pkg_spill_policy
+ svc_subagents --> pkg_tool_ralph
svc_subagents --> pkg_tool_subagent
svc_systemPrompt --> pkg_agent_loop
svc_systemPrompt --> pkg_tool_fs
@@ -209,6 +211,7 @@ flowchart LR
svc_userInteraction --> pkg_stdio_demo
svc_userInteraction --> pkg_tool_ask_user
svc_web --> pkg_tool_web
+ svc_workflows --> pkg_tool_ralph
svc_workflows --> pkg_tool_workflow
svc_fs -. event gate .-> pkg_fs_policy
```
@@ -236,10 +239,10 @@ flowchart LR
| `ctx.codeRuntime` | `seam` | [`code-runtime`](../packages/code-runtime/code-runtime) | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | [`tools`](../packages/core/tools) | - | Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the tool registry consumes it for Code Mode). |
| `ctx.fs` | `seam` | [`fs`](../packages/fs/fs) | [`fs-local`](../packages/fs/fs-local) | [`tool-fs`](../packages/fs/tool-fs) | [`fs-policy`](../packages/fs/fs-policy) | tool-fs executes read/write/edit through ctx.fs; fs-policy contributes observed-state checks through the fs/* event gate. |
| `ctx.compact` | `seam` | [`compact`](../packages/compact/compact) | [`compact-basic`](../packages/compact/compact-basic) | [`compact-basic`](../packages/compact/compact-basic) | - | The basic backend consumes post-step pressure and request-error recovery events; a model-facing compact tool remains deferred. |
-| `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn`](../packages/subagent/subagent-spawn), [`subagent-fork`](../packages/subagent/subagent-fork), [`subagent-acp`](../packages/subagent/subagent-acp) | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name. |
+| `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn`](../packages/subagent/subagent-spawn), [`subagent-fork`](../packages/subagent/subagent-fork), [`subagent-acp`](../packages/subagent/subagent-acp) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-ralph`](../packages/workflow/tool-ralph) | - | Providers implement transports; tool-subagent exposes configured delegation while tool-ralph requires one fresh structured-output route. |
| `ctx.tasks` | `core` | [`tasks`](../packages/tasks/tasks) | - | [`tool-bash`](../packages/bash/tool-bash), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-tasks`](../packages/tasks/tool-tasks) | - | Producers (tool-bash background commands, tool-subagent background delegations) register running work; tool-tasks is the model-facing control surface that reads, lists, and kills it. |
| `ctx.web` | `seam` | [`web`](../packages/web/web) | [`web-search-exa`](../packages/web/web-search-exa), [`web-search-perplexity`](../packages/web/web-search-perplexity), [`web-search-deepseek`](../packages/web/web-search-deepseek), [`web-fetch-local`](../packages/web/web-fetch-local) | [`tool-web`](../packages/web/tool-web) | - | Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names. |
| `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill. |
-| `ctx.workflows` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | [`tool-workflow`](../packages/workflow/tool-workflow) | - | One engine per context (bash shape, no named-provider registry); the worker-thread engine fans agent() calls out through ctx.subagents. |
+| `ctx.workflows` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/workflow/tool-ralph) | - | One engine per context (bash shape, no named-provider registry); the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. |
Maintenance mode: hybrid: services are discovered from Cordis declarations; interface/implementation/consumer roles are classified in `scripts/gen-doc-graphs.ts` with a completeness guard.
diff --git a/docs/config-catalog.md b/docs/config-catalog.md
index 0cbe1854e1..dbf7ded411 100644
--- a/docs/config-catalog.md
+++ b/docs/config-catalog.md
@@ -1133,6 +1133,24 @@ export interface Config {
Source: [`packages/goal/tool-goal/src/index.ts:27`](../packages/goal/tool-goal/src/index.ts)
+## `@deepseek-ai/dsh-tool-ralph`
+
+Requires: `tools` · `workflows` · `subagents` · `systemPrompt`
+
+```ts config-catalog
+/** Deployment policy for the fixed Ralph workflow. */
+export interface Config {
+ /** Fresh structured-output provider used for every round (default `spawn`). */
+ subagentProvider?: string
+ /** Default and deployment ceiling for one call's round count (default 256). */
+ maxRounds?: number
+ /** Maximum serialized characters in one structured handoff (default 16384). */
+ maxHandoffChars?: number
+}
+```
+
+Source: [`packages/workflow/tool-ralph/src/index.ts:22`](../packages/workflow/tool-ralph/src/index.ts)
+
## `@deepseek-ai/dsh-tool-skill`
Requires: `tools` · `skills`
diff --git a/docs/core-data-structures/workflow.md b/docs/core-data-structures/workflow.md
index 40b17a3112..6991ecbd00 100644
--- a/docs/core-data-structures/workflow.md
+++ b/docs/core-data-structures/workflow.md
@@ -8,7 +8,7 @@ Source: [`packages/workflow/workflow/src/types.ts`](../../packages/workflow/work
## The start request
-What a caller asks for when starting a run. The tool layer builds this from the model's `{ script, meta, args }` call plus the calling agent; `meta` and `args` are plain JSON DATA (the engine shape-validates `meta` and rejects loud BEFORE anything runs — no script text is ever evaluated to obtain it). `parent` is REQUIRED — every child the script spawns is attributed to it (cwd, lineage, and depth flow through the [subagent seam](subagent.md)).
+What a caller asks for when starting a run. The ordinary workflow tool builds this from the model's `{ script, meta, args }` call plus the calling agent; specialized consumers may also select one engine-wide `subagentProvider` for the run, but the script cannot observe or replace it. `meta` and `args` are plain JSON DATA (the engine shape-validates `meta` and rejects loud BEFORE anything runs — no script text is ever evaluated to obtain it). `parent` is REQUIRED — every child the script spawns is attributed to it (cwd, lineage, and depth flow through the [subagent seam](subagent.md)).
```ts type-equiv
/**
@@ -26,6 +26,12 @@ interface WorkflowStartRequest {
meta: WorkflowMeta
/** Optional input exposed verbatim to the script as the `args` global. */
args?: unknown
+ /**
+ * Optional engine-wide child-provider override for this run. The workflow
+ * script cannot observe or replace it; omission uses the engine's configured
+ * provider.
+ */
+ subagentProvider?: string
/** The agent on whose behalf the run executes (parent of every child). */
parent: Agent
/** Cancels the run when aborted (the tool's `exec.signal`). */
diff --git a/docs/glossary.md b/docs/glossary.md
index 9a27ead799..945eb60ef1 100644
--- a/docs/glossary.md
+++ b/docs/glossary.md
@@ -34,3 +34,9 @@ FIXME(glossary-completeness): Expand this glossary before the first release so i
- **turn** — one drain of admitted input in a session, ending after the model and its tools stop or a terminal policy intervenes.
- **step** — one model request plus the tool executions caused by its response; a turn contains one or more steps.
- **round** — an outer policy iteration containing a turn, such as a [goal round](#goal-round) or one fresh-agent Ralph attempt. Round counters belong to that policy and do not count every turn in a session.
+
+## Ralph
+
+- **Ralph loop** — one foreground fresh-agent workflow run toward an immutable objective. It is a model-facing tool policy composed from workflow and subagent primitives, not a same-session goal, agent-loop mode, scheduler, or generic workflow-script feature.
+- **Ralph round** — one fresh child session in a [Ralph loop](#ralph-loop). The child receives no parent or prior-child conversation seed; the shared workspace and one bounded [Ralph handoff](#ralph-handoff) carry cross-round state.
+- **Ralph handoff** — the normalized bounded structured report passed from one continuing Ralph round to the next, containing status, summary, evidence, next steps, and blocker text. It supplements the shared workspace rather than replacing it as authority.
diff --git a/docs/module-graph.md b/docs/module-graph.md
index a9b4876334..95562bebca 100644
--- a/docs/module-graph.md
+++ b/docs/module-graph.md
@@ -154,6 +154,7 @@ flowchart TD
pkg_tool_tasks["tool-tasks"]
end
subgraph group_workflow["packages/workflow"]
+ pkg_tool_ralph["tool-ralph"]
pkg_tool_workflow["tool-workflow"]
pkg_workflow["workflow"]
pkg_workflow_workerthread["workflow-workerthread"]
@@ -434,6 +435,12 @@ flowchart TD
pkg_agent_spine_demo --> pkg_tool_tasks
pkg_agent_spine_demo --> pkg_tools
pkg_agent_spine_demo --> pkg_workspace_context
+ pkg_tool_ralph --> pkg_agent
+ pkg_tool_ralph --> pkg_llm
+ pkg_tool_ralph --> pkg_subagent
+ pkg_tool_ralph --> pkg_system_prompt
+ pkg_tool_ralph --> pkg_tools
+ pkg_tool_ralph --> pkg_workflow
pkg_workflow_workerthread --> pkg_agent
pkg_workflow_workerthread --> pkg_brand
pkg_workflow_workerthread --> pkg_llm
@@ -572,6 +579,7 @@ flowchart TD
| [`stdio`](../packages/ui/stdio) | `ui` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`user-interaction`](../packages/ui/user-interaction) |
| [`tui`](../packages/ui/tui) | `ui` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`commands`](../packages/ui/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) |
| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`home`](../packages/util/home), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) |
+| [`tool-ralph`](../packages/workflow/tool-ralph) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) |
| [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) |
| [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) |
| [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) |
diff --git a/docs/rfc/INDEX.md b/docs/rfc/INDEX.md
index 90e508da27..6bb0cc8202 100644
--- a/docs/rfc/INDEX.md
+++ b/docs/rfc/INDEX.md
@@ -90,6 +90,7 @@ Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand;
| [Optional time-context plugin](implemented/feature/2026-07-14-time-context-plugin.md) | 2026-07-14 |
| [Durable per-step time context](implemented/feature/2026-07-16-durable-per-step-time-context.md) | 2026-07-16 |
| [Dedicated full-screen TUI front door](implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md) | 2026-07-17 |
+| [Fresh-agent Ralph workflow tool](implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md) | 2026-07-19 |
| [Human `/goal` command](implemented/feature/2026-07-19-human-goal-command.md) | 2026-07-19 |
| [Model-facing same-session goal tools](implemented/feature/2026-07-19-model-facing-goal-tools.md) | 2026-07-19 |
| [Persisted same-session goal domain](implemented/feature/2026-07-19-persisted-same-session-goal-domain.md) | 2026-07-19 |
diff --git a/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml b/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml
new file mode 100644
index 0000000000..4b56f36113
--- /dev/null
+++ b/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.i18n.yaml
@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write
+2026-07-19-fresh-agent-ralph-workflow-tool.md: 71f83f25018fc930fd058777f6909ea94c5a77cb
+2026-07-19-fresh-agent-ralph-workflow-tool.zh.md: 0f3fc7910dc726436605f12e292f18bee84be0dd
diff --git a/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md b/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md
new file mode 100644
index 0000000000..71f83f2501
--- /dev/null
+++ b/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.md
@@ -0,0 +1,67 @@
+# RFC: Fresh-agent Ralph workflow tool
+
+Status: implemented
+
+English | [中文](2026-07-19-fresh-agent-ralph-workflow-tool.zh.md)
+
+## Problem
+
+Same-session goals preserve conversation and let one agent continue a durable objective, while the general workflow tool lets the model write a fan-out orchestration script. Neither is the Ralph pattern: repeatedly give the same objective to a completely fresh worker, use the shared workspace as long-term memory, and carry only a small explicit handoff until work completes or a limit is reached.
+
+Adding Ralph behavior to `dsh-agent-loop`, the goal driver, or the public model-written workflow language would couple one policy to unrelated execution machinery. Letting each child inherit the parent conversation would also defeat context reset and make replay depend on a growing implicit prefix. The feature needs a fixed, reviewable policy built from existing plugin primitives, with cancellation quiescence, bounded cross-round data, a generous configurable cap, and no novel human-facing goal state.
+
+## Decision
+
+Add `@deepseek-ai/dsh-tool-ralph` as a separate consumer package under `packages/workflow/`. It registers `ralph({ objective, maxRounds? })`, owns a fixed workflow script, and depends only on `ctx.tools`, `ctx.systemPrompt`, `ctx.workflows`, and `ctx.subagents`. A Ralph run is not a session goal, creates no goal state, and requires no branch in the concrete agent loop.
+
+The tool is foreground-only. The calling agent parents every child for cwd and lineage, the parent tool call waits for the complete run, and the parent step's abort signal cancels the workflow. `run.dispose()` is awaited on every path, so cancellation reaches the worker engine's bounded settlement and child quiescence before the call returns.
+
+### Per-run workflow provider route
+
+`WorkflowStartRequest` gains optional `subagentProvider`. The worker-thread engine resolves that explicit per-run value before falling back to its configured provider and uses the result for every `agent()` call in the run. The script cannot observe or replace this route. The ordinary `workflow` tool leaves the field unset and exposes no new model argument, so general workflow behavior and provider policy stay unchanged.
+
+The Ralph plugin's `subagentProvider` defaults to `spawn`. Immediately before a call it requires the named provider to exist, support structured output, and report `inheritsParentContext: false`; a fork-like or incapable provider fails loudly before workflow start. Provider lookup remains call-time because effect-scoped provider registration can change under HMR.
+
+### Ralph rounds and handoff
+
+The hierarchy is Ralph Run → Ralph Round → fresh child Turn → Step. One Ralph round creates exactly one child through the selected provider. Spawn gives that child a distinct session with no seed while preserving the parent's cwd, so the shared working tree is the durable authority and neither parent conversation nor prior child history enters the request.
+
+The fixed prompt passes only the immutable objective, current round and cap, a workspace-as-authority instruction, and the previous structured report. A `RalphRoundReport` contains `status: continue | complete | blocked`, `summary`, `evidence`, `nextSteps`, and `blocker`. Strings must be normalized; `continue` requires next steps and no blocker, `complete` requires evidence with no next steps or blocker, and `blocked` requires a concrete blocker. The script validates semantics and serialized size before the report can become the next handoff; the consumer validates the materialized terminal value again across the workflow seam.
+
+`maxRounds` defaults to `256` and is also the deployment ceiling for a call override. `maxHandoffChars` defaults to `16384`. Both are positive safe-integer config values, and oversized reports fail rather than being silently truncated. After a `continue` report at the last permitted round, the fixed script returns `budget-limited`; `complete` and `blocked` return immediately with the final report and number of rounds started.
+
+### Model and UI surface
+
+The model may supply only `objective` and optional `maxRounds`; provider selection, report schema, handoff cap, and script are deployment-owned. A fixed prompt section says to use `ralph` only when the direct human explicitly asks for Ralph or fresh-agent iteration, and distinguishes it from same-session goals, bounded delegation, and general fan-out workflows. This is guidance rather than a new goal UX state machine.
+
+ACP and terminal presentation use a generic `ralph` card whose raw input is the objective. The parent transcript retains the original tool call and one bounded terminal report, not intermediate child messages. Shipped headless, REPL/TUI, and ACP compositions load the plugin beside the existing workflow engine; JSON-RPC remains unchanged because its default composition does not expose workflows.
+
+## Testing
+
+Unit tests cover config and call-cap resolution, provider capability rejection, fixed start-request routing, all three terminal outcomes, malformed and oversized boundary values, abort timing, disposal, render intent, prompt lifecycle, and namespace-plugin shape at per-file 100% coverage. Worker-engine tests prove that a per-run provider override selects every child without changing the configured default, including the built `lib/worker.cjs` under plain Node.
+
+A keyless real-stack integration drives the fixed script through the actual worker-thread engine, spawn provider, structured-output runtime, and agent loop. It proves distinct child identities, absent `seedLength`, inherited cwd, no parent-history markers in either child request, exact previous-report handoff only in the following round, terminal completion, and disposal of both children. Tool tests pin generic call/result presentation, while ACP replay header snapshots pin the shipped schema and prompt-guidance transcript surface.
+
+## Alternatives considered
+
+- **Put Ralph in the same-session goal driver** — rejected because goal rounds intentionally preserve one conversation, while Ralph's defining property is a fresh context per round; combining them would make goal lifecycle and child orchestration inseparable.
+- **Expose a `fresh` or loop flag on the general workflow tool** — rejected because the model-written script surface should remain general and provider-neutral; Ralph's fixed report protocol and stop policy deserve one reviewable consumer.
+- **Use `subagent_fork` for replay convenience** — rejected because inherited completed turns are implicit, growing handoff state and violate the fresh-context contract. The workspace plus one structured report is replayable without inserting artificial cancellation records.
+- **Call the subagent seam directly from the tool** — rejected because the existing workflow engine already owns foreground orchestration, structured children, cancellation propagation, worker termination, events, and quiescent disposal. Reusing it demonstrates plugin composition instead of building a second loop runtime.
+- **Silently truncate a large report** — rejected because truncation can remove status evidence or next steps while still looking like an authoritative handoff. A producer must emit a valid report within the configured bound.
+
+## Consequences
+
+- Fresh-agent iteration is a first-class model tool implemented entirely as a removable plugin over existing seams.
+- Goal rounds and Ralph rounds stay different concepts: the former is one same-session continuation turn, while the latter is one fresh child inside a foreground workflow.
+- The workspace becomes authoritative cross-round memory, so workers must inspect and verify it rather than trusting a narrative handoff.
+- A generous round ceiling permits substantial autonomous work, while deployment config still bounds child count and every handoff remains size-limited.
+- Provider routing becomes an explicit workflow start concern without expanding the script or ordinary workflow tool surface.
+
+## Known limitations and deferred work
+
+- Completion and blocker status are worker self-declarations. An independent evaluator, evaluator-driven feedback round, completion certificate, or adversarial verifier is intentionally deferred.
+- Runs are foreground and process-local. Background collection, persistence/resume, scheduling, and restart recovery are absent.
+- Round count is the only aggregate budget. Token, currency, elapsed-time, and provider-usage budgets remain separate future policy.
+- One round creates one child. Within-round fan-out, evaluator/worker role separation, dynamic provider or model selection, and cross-run journals are deferred.
+- Prompt guidance asks models not to invoke Ralph recursively; a structural child-tool restriction would require a separately designed workflow child-policy surface.
diff --git a/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md b/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md
new file mode 100644
index 0000000000..0f3fc7910d
--- /dev/null
+++ b/docs/rfc/implemented/feature/2026-07-19-fresh-agent-ralph-workflow-tool.zh.md
@@ -0,0 +1,67 @@
+# RFC:全新 agent Ralph 工作流工具
+
+Status: implemented
+
+[English](2026-07-19-fresh-agent-ralph-workflow-tool.md) | 中文
+
+## 问题
+
+同会话目标会保留对话,让一个 agent 持续完成持久目标;通用工作流工具则让模型编写扇出编排脚本。两者都不是 Ralph 模式:把同一目标反复交给完全全新的工作者,以共享工作区作为长期记忆,并且在各轮之间只传递一份小型显式交接,直到工作完成或触及限制。
+
+如果把 Ralph 行为加入 `dsh-agent-loop`、目标驱动器或面向模型的公开工作流语言,就会让一项策略与无关的执行机制耦合。让每个子 agent 继承父对话也会破坏上下文重置,并让重放依赖不断增长的隐式前缀。此功能需要一项由现有插件原语组合而成的固定、可评审策略,同时具备取消静止性、有界跨轮数据、宽裕且可配置的上限,并且不引入新颖的面向人类目标状态。
+
+## 决策
+
+在 `packages/workflow/` 下新增独立消费者包 `@deepseek-ai/dsh-tool-ralph`。它注册 `ralph({ objective, maxRounds? })`,拥有固定工作流脚本,并且只依赖 `ctx.tools`、`ctx.systemPrompt`、`ctx.workflows` 和 `ctx.subagents`。Ralph 运行不是会话目标,不会创建目标状态,也不要求在具体 agent loop 中增加分支。
+
+该工具仅以前台方式运行。调用 agent 作为每个子 agent 的父级以提供 cwd 和谱系,父工具调用等待整次运行结束,父步骤的中止信号会取消工作流。每条路径都会等待 `run.dispose()`,因此调用返回前,取消会经过工作流引擎的有界收敛并达到子 agent 静止状态。
+
+### 每次运行的工作流 provider 路由
+
+`WorkflowStartRequest` 新增可选的 `subagentProvider`。工作线程引擎先解析这个显式的每次运行值,再回退到引擎配置的 provider,并把结果用于该运行中的每次 `agent()` 调用。脚本无法观察或替换此路由。普通 `workflow` 工具不设置该字段,也不暴露新的模型参数,因此通用工作流行为和 provider 策略保持不变。
+
+Ralph 插件的 `subagentProvider` 默认为 `spawn`。每次调用前,它要求具名 provider 已存在、支持结构化输出且报告 `inheritsParentContext: false`;类似 fork 或能力不足的 provider 会在工作流启动前响亮失败。provider 查找保留在调用期,因为效果作用域内的 provider 注册可能随 HMR 改变。
+
+### Ralph 轮次与交接
+
+层级为 Ralph 运行 → Ralph 轮次 → 全新子 agent 回合 → 步骤。每个 Ralph 轮次恰好通过所选 provider 创建一个子 agent。Spawn 给该子 agent 一个没有种子的独立会话,同时保留父级 cwd,因此共享工作树是持久权威,父对话和先前子 agent 历史都不会进入请求。
+
+固定提示只传递不可变目标、当前轮次与上限、以工作区为权威的指令,以及上一份结构化报告。`RalphRoundReport` 包含 `status: continue | complete | blocked`、`summary`、`evidence`、`nextSteps` 和 `blocker`。字符串必须规范化;`continue` 要求存在下一步且没有阻塞项,`complete` 要求存在证据且没有下一步或阻塞项,`blocked` 要求具体阻塞项。报告成为下一次交接前,脚本会验证语义与序列化大小;消费者还会跨工作流接缝再次验证实体化的终止值。
+
+`maxRounds` 默认为 `256`,同时也是调用覆盖值的部署上限。`maxHandoffChars` 默认为 `16384`。两者都是正安全整数配置值;过大的报告会失败,而不会被静默截断。最后一个允许轮次报告 `continue` 后,固定脚本返回 `budget-limited`;`complete` 和 `blocked` 会立即返回最终报告与已启动轮次数。
+
+### 模型与 UI 表面
+
+模型只能提供 `objective` 和可选的 `maxRounds`;provider 选择、报告 schema、交接上限和脚本都由部署拥有。固定提示区段说明,只有直接人类明确要求 Ralph 或全新 agent 迭代时才使用 `ralph`,并将其与同会话目标、有界委派和通用扇出工作流区分开。这是指导,而不是新的目标 UX 状态机。
+
+ACP 和终端展示使用通用 `ralph` 卡片,并把目标作为原始输入。父转录只保留原始工具调用和一份有界终止报告,不包含中间子 agent 消息。发布的无头、REPL/TUI 与 ACP 组合会在现有工作流引擎旁加载该插件;JSON-RPC 保持不变,因为其默认组合不暴露工作流。
+
+## 测试
+
+单元测试覆盖配置与调用上限解析、provider 能力拒绝、固定启动请求路由、三种终止结果、畸形及过大边界值、中止时序、处置、渲染意图、提示生命周期和命名空间插件形状,并达到逐文件 100% 覆盖率。工作流引擎测试证明,每次运行的 provider 覆盖会选择每个子 agent 且不改变配置默认值,其中包括普通 Node 下构建后的 `lib/worker.cjs`。
+
+一项无密钥真实栈集成测试通过实际工作线程引擎、spawn provider、结构化输出运行时和 agent loop 驱动固定脚本。它证明子 agent 标识不同、没有 `seedLength`、继承 cwd、两个子请求都不含父历史标记、上一份报告只精确出现在下一轮交接中、终止完成以及两个子 agent 都被处置。工具测试固定通用调用/结果展示,而 ACP 重放请求头快照固定发布的 schema 与提示指导转录表面。
+
+## 考虑过的替代方案
+
+- **把 Ralph 放进同会话目标驱动器** — 拒绝,因为目标轮次有意保留同一段对话,而 Ralph 的定义性属性是每轮使用全新上下文;合并两者会让目标生命周期与子 agent 编排无法分离。
+- **在通用工作流工具上暴露 `fresh` 或循环标志** — 拒绝,因为模型编写的脚本表面应保持通用且与 provider 无关;Ralph 的固定报告协议和停止策略值得拥有一个可评审消费者。
+- **为了方便重放而使用 `subagent_fork`** — 拒绝,因为继承的已完成回合是隐式、不断增长的交接状态,并违反全新上下文契约。工作区加一份结构化报告即可重放,无需插入人为取消记录。
+- **让工具直接调用 subagent 接缝** — 拒绝,因为现有工作流引擎已经拥有前台编排、结构化子 agent、取消传播、工作线程终止、事件和静止处置。复用它可以展示插件组合,而不是构建第二个循环运行时。
+- **静默截断大型报告** — 拒绝,因为截断可能删除状态证据或下一步,却仍看似权威交接。生产者必须在配置边界内发出有效报告。
+
+## 后果
+
+- 全新 agent 迭代成为一项一等模型工具,并完全以现有接缝之上的可移除插件实现。
+- 目标轮次与 Ralph 轮次保持不同概念:前者是一次同会话续行回合,后者是前台工作流中的一个全新子 agent。
+- 工作区成为权威跨轮记忆,因此工作者必须检查和验证工作区,而不能信任叙事性交接。
+- 宽裕的轮次上限允许大量自治工作,而部署配置仍会限制子 agent 数量,并且每次交接始终受大小约束。
+- provider 路由成为显式的工作流启动关注点,但不扩展脚本或普通工作流工具表面。
+
+## 已知限制与推迟工作
+
+- 完成与阻塞状态由工作者自行声明。独立 evaluator、evaluator 驱动的反馈轮次、完成证书或对抗式 verifier 被有意推迟。
+- 运行位于前台且只存在于进程内。后台收集、持久化/恢复、调度和重启恢复均不存在。
+- 轮次数是唯一聚合预算。token、货币、耗时和 provider 用量预算仍属于未来的独立策略。
+- 每轮创建一个子 agent。轮内扇出、evaluator/工作者角色分离、动态 provider 或模型选择,以及跨运行日志均被推迟。
+- 提示指导模型不要递归调用 Ralph;结构化的子 agent 工具限制需要另行设计工作流子策略表面。
diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md
index 64fd5e692d..8d73477bd5 100644
--- a/docs/tool-catalog.md
+++ b/docs/tool-catalog.md
@@ -22,6 +22,7 @@ This table connects model-visible tool names to the plugin package and service s
| `@deepseek-ai/dsh-tool-fs` | `edit`, `read`, `write` | `ctx.tools`, `ctx.fs`, `ctx.systemPrompt` | `tool/call`, `fs/write-intent or fs/edit-intent for mutations`, `fs/observed after successful file operations`, `tool/result` | - | The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. The tool schemas above are identical with or without the policy plugin. |
| `@deepseek-ai/dsh-tool-fs-search` | `glob`, `grep` | `ctx.tools`, `ctx.bash`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | glob and grep are bash-backed discovery tools: they run fixed ripgrep commands through ctx.bash as ordinary foreground calls (never background tasks). Capped results save the complete formatted list through the optional ctx.spillStore backend; returned locators are follow-up-readable/searchable when the backend exposes local paths in co-located deployments. |
| `@deepseek-ai/dsh-tool-goal` | `create_goal`, `get_goal`, `update_goal` | `ctx.tools`, `ctx.agents`, `ctx.goals`, `ctx.systemPrompt`, `a calling Agent in an authorized open turn` | `tool/call`, `context/message goal snapshot for mutations`, `tool/result` | - | create, edit, pause, and resume require direct-human root authority; complete and blocked also accept the exact current goal round. The default blocked lower bound is three admitted rounds. |
+| `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflows`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. |
| `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.tools`, `ctx.skills` | `tool/call`, `tool/result` | - | - |
| `@deepseek-ai/dsh-tool-subagent` | `subagent` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped example agents load this package once per subagent backend, so the model additionally sees `subagent_fork` (bound to the fork backend) with an identical schema — see `examples/repl-agent/cordis.yml` and `examples/acp-agent/cordis.yml`. |
| `@deepseek-ai/dsh-tool-tasks` | `task_kill`, `task_list`, `task_output` | `ctx.tools`, `ctx.tasks`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `context/message via agent.inject() for background completion notices` | - | The kind-agnostic background-task control surface: a background bash command and a background subagent are read, listed, and killed through the same three tools. Loading the plugin attaches the control surface that arms producers' `ctx.tasks.start()`. |
@@ -482,6 +483,35 @@ Source: [`packages/goal/tool-goal/src/index.ts`](../packages/goal/tool-goal/src/
create, edit, pause, and resume require direct-human root authority; complete and blocked also accept the exact current goal round. The default blocked lower bound is three admitted rounds.
+## `@deepseek-ai/dsh-tool-ralph`
+
+### `ralph`
+
+Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+}
+```
+
+Source: [`packages/workflow/tool-ralph/src/index.ts`](../packages/workflow/tool-ralph/src/index.ts)
+
+A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap.
+
## `@deepseek-ai/dsh-tool-skill`
### `skill`
diff --git a/examples/acp-agent/composition.md b/examples/acp-agent/composition.md
index 194ff3dee0..56074f9b99 100644
--- a/examples/acp-agent/composition.md
+++ b/examples/acp-agent/composition.md
@@ -41,6 +41,8 @@ flowchart LR
cfg --> plugin_acp_workflow_workerthread
plugin_acp_tool_workflow["tool-workflow
@deepseek-ai/dsh-tool-workflow"]
cfg --> plugin_acp_tool_workflow
+ plugin_acp_tool_ralph["tool-ralph
@deepseek-ai/dsh-tool-ralph"]
+ cfg --> plugin_acp_tool_ralph
plugin_acp_tool_todo["tool-todo
@deepseek-ai/dsh-tool-todo"]
cfg --> plugin_acp_tool_todo
plugin_acp_repeat_tool_guard["repeat-tool-guard
@deepseek-ai/dsh-repeat-tool-guard"]
@@ -66,6 +68,7 @@ flowchart LR
| `tool-subagent-fork` | `@deepseek-ai/dsh-tool-subagent` |
| `workflow-workerthread` | `@deepseek-ai/dsh-workflow-workerthread` |
| `tool-workflow` | `@deepseek-ai/dsh-tool-workflow` |
+| `tool-ralph` | `@deepseek-ai/dsh-tool-ralph` |
| `tool-todo` | `@deepseek-ai/dsh-tool-todo` |
| `repeat-tool-guard` | `@deepseek-ai/dsh-repeat-tool-guard` |
| `hooks-claude` | `@deepseek-ai/dsh-hooks-claude` |
diff --git a/examples/acp-agent/cordis.yml b/examples/acp-agent/cordis.yml
index cb8890dae7..5c70e5851b 100644
--- a/examples/acp-agent/cordis.yml
+++ b/examples/acp-agent/cordis.yml
@@ -86,6 +86,9 @@
- id: tool-workflow
name: '@deepseek-ai/dsh-tool-workflow'
+
+- id: tool-ralph
+ name: '@deepseek-ai/dsh-tool-ralph'
# `todo_write` replaces the logged whole list and surfaces an ACP `plan` update.
- id: tool-todo
name: '@deepseek-ai/dsh-tool-todo'
diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md
index 5ba28dca73..867bbcc7b7 100644
--- a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md
@@ -16,6 +16,8 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
+
## Writing code for run_code
Pass `run_code` the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:
@@ -72,6 +74,13 @@ declare const tools: {
}): Promise;
/** Read the current same-session goal, including its exact id/revision, durable phase, admitted round count, cap, and live process-local activation. Call this before updating a goal. */
get_goal(args: Record): Promise;
+ /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools. */
+ ralph(args: {
+ /** The immutable completion objective for every fresh Ralph round. */
+ objective: string;
+ /** Optional positive safe-integer round cap, bounded by the deployment ceiling. */
+ maxRounds?: number;
+ }): Promise;
/** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */
skill(args: {
/** The exact skill name from the available skills list. */
diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json
index c27f1788e7..bebf7b25df 100644
--- a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json
@@ -130,6 +130,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "run_code",
"description": "Execute a TypeScript program against the available tools. Write the BODY of an async function (erasable syntax only; top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back — curate it.",
diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md
index 9b14172e43..e974d937e7 100644
--- a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md
@@ -16,6 +16,8 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
+
## Writing code for run_code
Pass `run_code` the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:
@@ -55,6 +57,13 @@ declare const tools: {
}): Promise;
/** Read the current same-session goal, including its exact id/revision, durable phase, admitted round count, cap, and live process-local activation. Call this before updating a goal. */
get_goal(args: Record): Promise;
+ /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools. */
+ ralph(args: {
+ /** The immutable completion objective for every fresh Ralph round. */
+ objective: string;
+ /** Optional positive safe-integer round cap, bounded by the deployment ceiling. */
+ maxRounds?: number;
+ }): Promise;
/** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */
skill(args: {
/** The exact skill name from the available skills list. */
diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json
index 5112f55a25..2ffcf4f04a 100644
--- a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json
@@ -73,6 +73,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "run_code",
"description": "Execute a TypeScript program against the available tools. Write the BODY of an async function (erasable syntax only; top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back — curate it.",
diff --git a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md
index 9b14172e43..e974d937e7 100644
--- a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md
@@ -16,6 +16,8 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
+
## Writing code for run_code
Pass `run_code` the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:
@@ -55,6 +57,13 @@ declare const tools: {
}): Promise;
/** Read the current same-session goal, including its exact id/revision, durable phase, admitted round count, cap, and live process-local activation. Call this before updating a goal. */
get_goal(args: Record): Promise;
+ /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools. */
+ ralph(args: {
+ /** The immutable completion objective for every fresh Ralph round. */
+ objective: string;
+ /** Optional positive safe-integer round cap, bounded by the deployment ceiling. */
+ maxRounds?: number;
+ }): Promise;
/** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */
skill(args: {
/** The exact skill name from the available skills list. */
diff --git a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md
index ec0b4430e1..ec7e2758a8 100644
--- a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md
@@ -22,6 +22,8 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
+
## Writing code for run_code
Pass `run_code` the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:
@@ -72,6 +74,13 @@ declare const tools: {
}): Promise;
/** Read the current same-session goal, including its exact id/revision, durable phase, admitted round count, cap, and live process-local activation. Call this before updating a goal. */
get_goal(args: Record): Promise;
+ /** Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools. */
+ ralph(args: {
+ /** The immutable completion objective for every fresh Ralph round. */
+ objective: string;
+ /** Optional positive safe-integer round cap, bounded by the deployment ceiling. */
+ maxRounds?: number;
+ }): Promise;
/** Read a UTF-8 text file and return line-numbered content. */
read(args: {
/** Path to read, resolved by the filesystem backend. */
diff --git a/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md
index f81876701a..751040c92e 100644
--- a/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md
@@ -16,6 +16,8 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
+
You are an AI agent powered by the DeepSeek Harness SDK.
@@ -35,3 +37,5 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
diff --git a/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json
index bae7be5f6b..09b42a7ac1 100644
--- a/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json
@@ -73,6 +73,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "skill",
"description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
@@ -417,6 +437,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "skill",
"description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
diff --git a/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md
index 82335a7f1e..472db36968 100644
--- a/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md
@@ -15,6 +15,8 @@ Use goal tools for one long-running completion objective in the current session.
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
+
You are an AI agent powered by the DeepSeek Harness SDK.
@@ -34,3 +36,5 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
diff --git a/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json
index bae7be5f6b..09b42a7ac1 100644
--- a/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json
@@ -73,6 +73,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "skill",
"description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
@@ -417,6 +437,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "skill",
"description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
diff --git a/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md
index 87818d5b6d..6bc89dccd5 100644
--- a/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md
@@ -15,3 +15,5 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
diff --git a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json
index 0680b50e05..99c8f338a3 100644
--- a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json
@@ -73,6 +73,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "skill",
"description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
diff --git a/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md
index 87818d5b6d..6bc89dccd5 100644
--- a/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md
@@ -15,3 +15,5 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
diff --git a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json
index 0680b50e05..99c8f338a3 100644
--- a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json
@@ -73,6 +73,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "skill",
"description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
diff --git a/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md
index 6f49fcf1c2..cc8fc47873 100644
--- a/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md
@@ -21,3 +21,5 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
diff --git a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json
index 0ef5307126..0fcb95895c 100644
--- a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json
@@ -103,6 +103,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "read",
"description": "Read a UTF-8 text file and return line-numbered content.",
diff --git a/examples/acp-agent/tests/snapshots/workspace-edit/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/workspace-edit/system-prompt.expected.md
index 4af39f6b4b..dc934714b9 100644
--- a/examples/acp-agent/tests/snapshots/workspace-edit/system-prompt.expected.md
+++ b/examples/acp-agent/tests/snapshots/workspace-edit/system-prompt.expected.md
@@ -21,3 +21,5 @@ Approval prompts are disabled in this session: actions that require approval are
Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.
+
+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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.
diff --git a/examples/acp-agent/tests/snapshots/workspace-edit/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/workspace-edit/tool-schemas.expected.json
index 0ef5307126..0fcb95895c 100644
--- a/examples/acp-agent/tests/snapshots/workspace-edit/tool-schemas.expected.json
+++ b/examples/acp-agent/tests/snapshots/workspace-edit/tool-schemas.expected.json
@@ -103,6 +103,26 @@
"properties": {}
}
},
+ {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns on completion, a concrete blocker, or the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ }
+ },
{
"name": "read",
"description": "Read a UTF-8 text file and return line-numbered content.",
diff --git a/examples/headless-agent/README.md b/examples/headless-agent/README.md
index 285263146f..10667a6101 100644
--- a/examples/headless-agent/README.md
+++ b/examples/headless-agent/README.md
@@ -1,6 +1,6 @@
# headless-agent
-Headless one-shot agent wiring: DeepSeek V4 + local bash and filesystem tools + subagent delegation + workflows + `todo_write` + JSONL persistence, with [`@deepseek-ai/dsh-cli-demo`](../../packages/examples/cli-demo) as the app front door.
+Headless one-shot agent wiring: DeepSeek V4 + local bash and filesystem tools + subagent delegation + workflows and fresh-agent Ralph iteration + `todo_write` + JSONL persistence, with [`@deepseek-ai/dsh-cli-demo`](../../packages/examples/cli-demo) as the app front door.
## Run it
diff --git a/examples/headless-agent/composition.md b/examples/headless-agent/composition.md
index 9533af28d3..3e5876c2b6 100644
--- a/examples/headless-agent/composition.md
+++ b/examples/headless-agent/composition.md
@@ -37,6 +37,8 @@ flowchart LR
cfg --> plugin_headless_workflow_workerthread
plugin_headless_tool_workflow["tool-workflow
@deepseek-ai/dsh-tool-workflow"]
cfg --> plugin_headless_tool_workflow
+ plugin_headless_tool_ralph["tool-ralph
@deepseek-ai/dsh-tool-ralph"]
+ cfg --> plugin_headless_tool_ralph
plugin_headless_tool_todo["tool-todo
@deepseek-ai/dsh-tool-todo"]
cfg --> plugin_headless_tool_todo
plugin_headless_fs_local["fs-local
@deepseek-ai/dsh-fs-local"]
@@ -60,6 +62,7 @@ flowchart LR
| `tool-subagent-fork` | `@deepseek-ai/dsh-tool-subagent` |
| `workflow-workerthread` | `@deepseek-ai/dsh-workflow-workerthread` |
| `tool-workflow` | `@deepseek-ai/dsh-tool-workflow` |
+| `tool-ralph` | `@deepseek-ai/dsh-tool-ralph` |
| `tool-todo` | `@deepseek-ai/dsh-tool-todo` |
| `fs-local` | `@deepseek-ai/dsh-fs-local` |
| `fs-policy` | `@deepseek-ai/dsh-fs-policy` |
diff --git a/examples/headless-agent/cordis.yml b/examples/headless-agent/cordis.yml
index 7f48c529c4..766e8b7891 100644
--- a/examples/headless-agent/cordis.yml
+++ b/examples/headless-agent/cordis.yml
@@ -81,6 +81,11 @@
- id: tool-workflow
name: '@deepseek-ai/dsh-tool-workflow'
+# A separate fixed consumer demonstrates fresh-agent Ralph iteration without
+# changing the workflow tool or same-session goal behavior.
+- id: tool-ralph
+ name: '@deepseek-ai/dsh-tool-ralph'
+
# `todo_write` replaces the logged whole list.
- id: tool-todo
name: '@deepseek-ai/dsh-tool-todo'
diff --git a/examples/package.json b/examples/package.json
index f893ab6bc2..04931f2fc1 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -41,6 +41,7 @@
"@deepseek-ai/dsh-tool-fs": "workspace:*",
"@deepseek-ai/dsh-tool-fs-search": "workspace:*",
"@deepseek-ai/dsh-tool-goal": "workspace:*",
+ "@deepseek-ai/dsh-tool-ralph": "workspace:*",
"@deepseek-ai/dsh-tool-subagent": "workspace:*",
"@deepseek-ai/dsh-tool-todo": "workspace:*",
"@deepseek-ai/dsh-tool-workflow": "workspace:*",
diff --git a/examples/repl-agent/README.md b/examples/repl-agent/README.md
index 7145873e9a..d86b18dcb4 100644
--- a/examples/repl-agent/README.md
+++ b/examples/repl-agent/README.md
@@ -1,6 +1,6 @@
# repl-agent
-The repl-agent wiring: DeepSeek V4 + the `read`/`write`/`edit` filesystem tools + the bash tool suite + subagent delegation + workflows + `todo_write` + readline chat + JSONL persistence, loaded from `cordis.yml`. The sibling [`tui-agent`](../tui-agent/README.md) fixes the same agent composition to the full-screen terminal front door.
+The repl-agent wiring: DeepSeek V4 + the `read`/`write`/`edit` filesystem tools + the bash tool suite + subagent delegation + workflows and fresh-agent Ralph iteration + `todo_write` + readline chat + JSONL persistence, loaded from `cordis.yml`. The sibling [`tui-agent`](../tui-agent/README.md) fixes the same agent composition to the full-screen terminal front door.
## Run it
@@ -52,7 +52,7 @@ This example is a thin leaf `cordis.yml`: it picks the swappable backends, loads
| `stdio-agent` (`@deepseek-ai/dsh-stdio-demo`) | the app bundle: the agent-spine demo + JSONL persistence + the configured terminal channel + a pre-created `main` agent. This leaf fixes `ui.mode` to `readline`; `tui-agent` owns the corresponding TUI leaf |
| `subagent`, `subagent-spawn`, `subagent-fork` | the subagent provider registry plus the two in-process backends: a fresh child and a child seeded with the parent's completed-turn prefix |
| `tool-subagent`, `tool-subagent-fork` | two model-facing `dsh-tool-subagent` loads, each bound to a different provider and exposed under a distinct tool name (`subagent`, `subagent_fork`) |
-| `workflow-workerthread`, `tool-workflow` | the worker-thread workflow engine and its model-facing `workflow` tool, with child calls routed through the spawn backend |
+| `workflow-workerthread`, `tool-workflow`, `tool-ralph` | the worker-thread engine, general model-written `workflow` tool, and separate fixed fresh-agent `ralph` consumer, with children routed through spawn |
| `tool-todo` | the model-facing `todo_write` tool; writes the whole task list to the session log and renders as a persistent TUI plan or readline checklist |
| `fs-local`, `fs-policy`, `tool-fs` | the filesystem stack: the local `ctx.fs` provider, the read-before-write/edit policy gate (on the `fs/*` event gate), and the model-facing `read`/`write`/`edit` tools. Relative paths resolve against the session workspace |
diff --git a/examples/repl-agent/composition.md b/examples/repl-agent/composition.md
index af3f810585..faa5825d9f 100644
--- a/examples/repl-agent/composition.md
+++ b/examples/repl-agent/composition.md
@@ -41,6 +41,8 @@ flowchart LR
cfg --> plugin_repl_workflow_workerthread
plugin_repl_tool_workflow["tool-workflow
@deepseek-ai/dsh-tool-workflow"]
cfg --> plugin_repl_tool_workflow
+ plugin_repl_tool_ralph["tool-ralph
@deepseek-ai/dsh-tool-ralph"]
+ cfg --> plugin_repl_tool_ralph
plugin_repl_tool_todo["tool-todo
@deepseek-ai/dsh-tool-todo"]
cfg --> plugin_repl_tool_todo
plugin_repl_fs_local["fs-local
@deepseek-ai/dsh-fs-local"]
@@ -74,6 +76,7 @@ flowchart LR
| `tool-subagent-fork` | `@deepseek-ai/dsh-tool-subagent` |
| `workflow-workerthread` | `@deepseek-ai/dsh-workflow-workerthread` |
| `tool-workflow` | `@deepseek-ai/dsh-tool-workflow` |
+| `tool-ralph` | `@deepseek-ai/dsh-tool-ralph` |
| `tool-todo` | `@deepseek-ai/dsh-tool-todo` |
| `fs-local` | `@deepseek-ai/dsh-fs-local` |
| `fs-policy` | `@deepseek-ai/dsh-fs-policy` |
diff --git a/examples/repl-agent/cordis.yml b/examples/repl-agent/cordis.yml
index 4428d5f3a8..5a7ca0f62f 100644
--- a/examples/repl-agent/cordis.yml
+++ b/examples/repl-agent/cordis.yml
@@ -94,6 +94,9 @@
- id: tool-workflow
name: '@deepseek-ai/dsh-tool-workflow'
+
+- id: tool-ralph
+ name: '@deepseek-ai/dsh-tool-ralph'
# `todo_write` replaces the logged whole list and renders as a stdio checklist or ACP plan.
- id: tool-todo
name: '@deepseek-ai/dsh-tool-todo'
diff --git a/examples/tui-agent/tests/tui.snapshot.ts b/examples/tui-agent/tests/tui.snapshot.ts
index 2c62ba25e6..a9f937f883 100644
--- a/examples/tui-agent/tests/tui.snapshot.ts
+++ b/examples/tui-agent/tests/tui.snapshot.ts
@@ -22,6 +22,7 @@ import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn'
import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
+import * as ToolRalph from '@deepseek-ai/dsh-tool-ralph'
import * as ToolWorkflow from '@deepseek-ai/dsh-tool-workflow'
import { createTuiChat } from '@deepseek-ai/dsh-tui'
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
@@ -180,6 +181,7 @@ async function mountScenarioContext(
await ctx.plugin(ToolSubagent, { provider: 'spawn', toolName: 'subagent', enableRunInBackground: false })
await ctx.plugin(WorkerWorkflowEngine, { provider: 'spawn' })
await ctx.plugin(ToolWorkflow)
+ await ctx.plugin(ToolRalph)
await ctx.plugin(CommandService)
if (scenario.composition === 'code' || scenario.composition === 'advanced') {
await ctx.plugin(WorkerCodeRuntime, {})
diff --git a/packages/README.md b/packages/README.md
index f2298a47fa..d9b11a1f3b 100644
--- a/packages/README.md
+++ b/packages/README.md
@@ -20,7 +20,7 @@ Packages live at `packages///`; groups are containers, while names r
| [`context/`](context/README.md) | Model-visible request context, including workspace instructions and time context | Product — stable surface |
| [`subagent/`](subagent/README.md) | Subagent capability family: the provider-registry seam and the model-facing delegation tool | Product — stable surface |
| [`tasks/`](tasks/README.md) | Generic background-task runtime and model-facing `task_*` control tools | Product — stable surface |
-| [`workflow/`](workflow/README.md) | Workflow capability family: the script-engine seam, the worker-thread engine, and the model-facing `workflow` tool | Product — stable surface |
+| [`workflow/`](workflow/README.md) | Workflow capability family: the script-engine seam, worker-thread engine, and model-facing `workflow` and fresh-agent `ralph` tools | Product — stable surface |
| [`web/`](web/README.md) | Web capability family: the abstract seam, search/fetch provider impls, and the model-facing web tools | Product — stable surface |
| [`spill/`](spill/README.md) | Spill capability family: the storage seam, a local impl, and the tool-result spill policy | Product — stable surface |
| [`todo/`](todo/README.md) | Todo/planning family: the model-facing `todo_write` tool | Product — stable surface |
diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts
index d2e88e0707..0becd20a65 100644
--- a/packages/cordis/tool-cordis/src/api-catalog.ts
+++ b/packages/cordis/tool-cordis/src/api-catalog.ts
@@ -1791,7 +1791,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'WorkflowStartRequest',
- declaration: 'export interface WorkflowStartRequest {\n script: string;\n meta: WorkflowMeta;\n args?: unknown;\n parent: Agent;\n signal?: AbortSignal;\n}',
+ declaration: 'export interface WorkflowStartRequest {\n script: string;\n meta: WorkflowMeta;\n args?: unknown;\n subagentProvider?: string;\n parent: Agent;\n signal?: AbortSignal;\n}',
},
{
name: 'WorkflowStopReason',
diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts
index c6b7f9a804..3c99ecbd4d 100644
--- a/packages/core/tools/tests/gen-tool-catalog.spec.ts
+++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts
@@ -23,7 +23,7 @@ describe('gen-tool-catalog collectToolCatalog', () => {
it('boots every shipped tool package and harvests its model-facing schemas', async () => {
const catalog = await collectToolCatalog()
const names = catalog.flatMap(entry => entry.schemas.map(s => s.name)).sort()
- expect(names).toEqual(['ask_user_question', 'bash', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'read', 'run_code', 'skill', 'subagent', 'task_kill', 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'write'])
+ expect(names).toEqual(['ask_user_question', 'bash', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'ralph', 'read', 'run_code', 'skill', 'subagent', 'task_kill', 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'write'])
// Every tool carries a JSON-Schema `parameters` object (what the model sees).
for (const entry of catalog) {
for (const schema of entry.schemas) {
diff --git a/packages/workflow/README.md b/packages/workflow/README.md
index 98fa3cfe04..7c503b1aaf 100644
--- a/packages/workflow/README.md
+++ b/packages/workflow/README.md
@@ -7,7 +7,8 @@ The workflow seam: a model-written JavaScript orchestration script that fans out
| `workflow/` | Abstract workflow seam: service base class + run vocabulary + `workflow/*` events | `ctx.workflows` |
| `workflow-workerthread/` | `node:worker_threads` engine: one worker per run; the script's vm context lives inside the worker, `agent()` bridges to `ctx.subagents` over the message port | (provides `ctx.workflows`) |
| `tool-workflow/` | Model-facing `workflow` tool over `ctx.workflows` | (registers on `ctx.tools`) |
+| `tool-ralph/` | Fixed fresh-agent Ralph policy over `ctx.workflows` and a fresh structured-output subagent provider | (registers on `ctx.tools`) |
The interface lives at `workflow/workflow/`. The engine's `agent()` hook rides the [subagent seam](../subagent/README.md) (any registered provider; the shipped examples use `spawn`), and `agent({ schema })` rides the structured-output support the in-process backends implement. The worker thread isolates the SCRIPT — the host never blocks on it, and a cancelled run's post-grace termination is real — but it is NOT a security boundary; an isolated-vm/separate-process engine (actual sandboxing) swaps in behind the same interface if that ever matters.
-The proposal, decisions, and deferred work: [docs/rfc/implemented/feature/2026-07-05-dynamic-workflows.md](../../docs/rfc/implemented/feature/2026-07-05-dynamic-workflows.md).
+The general script engine's proposal, decisions, and deferred work: [docs/rfc/implemented/feature/2026-07-05-dynamic-workflows.md](../../docs/rfc/implemented/feature/2026-07-05-dynamic-workflows.md). The separate Ralph consumer fixes the script and fresh-provider policy rather than adding another engine or an agent-loop mode.
diff --git a/packages/workflow/tool-ralph/README.md b/packages/workflow/tool-ralph/README.md
new file mode 100644
index 0000000000..4b42da7cf5
--- /dev/null
+++ b/packages/workflow/tool-ralph/README.md
@@ -0,0 +1,87 @@
+# @deepseek-ai/dsh-tool-ralph
+
+The model-facing `ralph` tool runs a fixed foreground workflow that gives one immutable objective to a sequence of fresh child agents. It demonstrates a specialized orchestration policy as an ordinary plugin over [`ctx.workflows`](../workflow/README.md) and [`ctx.subagents`](../../subagent/subagent/README.md): no Ralph mode or fresh-agent loop is added to `agent-loop`, and the same-session [goal domain](../../goal/goal/README.md) remains independent.
+
+## Contract
+
+`ralph({ objective, maxRounds? })` waits for the entire run. The deployment config's `maxRounds` is both the default and a ceiling on a call override. Every Ralph round starts one child through `subagentProvider`; that provider must exist, support structured output, and report `inheritsParentContext: false`. 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.
+
+Each child receives only the immutable objective, its current Ralph round and cap, a shared-workspace-as-authority instruction, and the previous structured handoff. The workspace is long-term memory; parent conversation and prior child sessions are not seeded. Reports have `status: continue | complete | blocked`, a non-empty summary, evidence, next steps, and blocker text. Status-specific semantics and the serialized `maxHandoffChars` ceiling are validated inside the fixed workflow and again at the consumer boundary. Invalid, missing, or oversized reports fail the workflow instead of being truncated or mistaken for cap exhaustion.
+
+The terminal tool result is `complete`, `blocked`, or `budget-limited`, with the last bounded report and number of rounds started. Child self-declaration determines completion in this cut. A workflow failure or cancellation is an error result; partial output is never success.
+
+## 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 the engine's bounded termination and child quiescence before returning.
+
+## Render intent
+
+The pending call is a `generic` card titled `ralph`; the immutable objective is its `rawInput`. The result keeps the generic card. Both presentation functions depend only on tool arguments and the settled tool envelope.
+
+## Config
+
+| Key | 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. |
+
+All config values are normalized and validated when the plugin applies, including direct application outside Loader schema normalization. Provider capabilities are resolved immediately before each call because provider registration can change under plugin lifecycle and HMR.
+
+## 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
+
+```markdown
+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. 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](../../../docs/tool-catalog.md#deepseek-aidsh-tool-ralph) 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 surface.
+
+#### 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 status, round count, and pretty-printed final report; intermediate child messages and reports do not enter the parent conversation.
+
+#### Token effect
+
+Every round pays for a fresh child context. The parent result is bounded indirectly by `maxHandoffChars`; 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
+
+- **Completion is worker self-declaration** — there is no independent evaluator or verifier deciding whether the objective is actually complete; evaluator policy and evaluator-driven continuation are deferred.
+- **Foreground only** — there is no task 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/provider switching, fork context, or model-call-selected provider.
+- **Only round count bounds aggregate effort** — token, price, and elapsed-time budgets are deferred.
diff --git a/packages/workflow/tool-ralph/package.json b/packages/workflow/tool-ralph/package.json
new file mode 100644
index 0000000000..31c368b6f4
--- /dev/null
+++ b/packages/workflow/tool-ralph/package.json
@@ -0,0 +1,53 @@
+{
+ "name": "@deepseek-ai/dsh-tool-ralph",
+ "description": "Model-facing fresh-agent Ralph loop over the workflow and subagent seams",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "main": "lib/index.js",
+ "types": "lib/types/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./lib/types/index.d.ts",
+ "default": "./lib/index.js"
+ },
+ "./src/*": "./src/*",
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "lib/index.js",
+ "lib/types/**/*.d.ts",
+ "lib/types/**/*.d.ts.map",
+ "src"
+ ],
+ "license": "BSD-3-Clause",
+ "peerDependencies": {
+ "@deepseek-ai/dsh-agent": "^0.0.1",
+ "@deepseek-ai/dsh-llm": "^0.0.1",
+ "@deepseek-ai/dsh-subagent": "^0.0.1",
+ "@deepseek-ai/dsh-system-prompt": "^0.0.1",
+ "@deepseek-ai/dsh-tools": "^0.0.1",
+ "@deepseek-ai/dsh-workflow": "^0.0.1",
+ "cordis": "^4.0.0-rc.7"
+ },
+ "dependencies": {
+ "schemastery": "^3.18.0"
+ },
+ "devDependencies": {
+ "@cordisjs/plugin-loader": "workspace:^",
+ "@deepseek-ai/dsh-agent": "workspace:^",
+ "@deepseek-ai/dsh-agent-loop": "workspace:^",
+ "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^",
+ "@deepseek-ai/dsh-invariants": "workspace:^",
+ "@deepseek-ai/dsh-llm": "workspace:^",
+ "@deepseek-ai/dsh-session": "workspace:^",
+ "@deepseek-ai/dsh-subagent": "workspace:^",
+ "@deepseek-ai/dsh-subagent-inprocess": "workspace:^",
+ "@deepseek-ai/dsh-subagent-spawn": "workspace:^",
+ "@deepseek-ai/dsh-system-prompt": "workspace:^",
+ "@deepseek-ai/dsh-tools": "workspace:^",
+ "@deepseek-ai/dsh-workflow": "workspace:^",
+ "@deepseek-ai/dsh-workflow-workerthread": "workspace:^",
+ "cordis": "^4.0.0-rc.7"
+ }
+}
diff --git a/packages/workflow/tool-ralph/src/index.ts b/packages/workflow/tool-ralph/src/index.ts
new file mode 100644
index 0000000000..83da19b119
--- /dev/null
+++ b/packages/workflow/tool-ralph/src/index.ts
@@ -0,0 +1,384 @@
+/**
+ * Model-facing foreground Ralph loop over the workflow and subagent seams. A
+ * fixed script starts one fresh structured-output child per round, carrying
+ * only the immutable objective and the previous bounded handoff between them.
+ * @module @deepseek-ai/dsh-tool-ralph
+ */
+
+import type { Context } from 'cordis'
+import z from 'schemastery'
+import type { ContentBlock } from '@deepseek-ai/dsh-llm'
+import type { SubagentProvider } from '@deepseek-ai/dsh-subagent'
+import { defineTool } from '@deepseek-ai/dsh-tools'
+import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
+import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow'
+// Declaration merge only: makes ctx.systemPrompt visible for section registration.
+import type {} from '@deepseek-ai/dsh-system-prompt'
+
+export const name = 'tool-ralph'
+export const inject = ['tools', 'workflows', 'subagents', 'systemPrompt']
+
+/** Deployment policy for the fixed Ralph workflow. */
+export interface Config {
+ /** Fresh structured-output provider used for every round (default `spawn`). */
+ subagentProvider?: string
+ /** Default and deployment ceiling for one call's round count (default 256). */
+ maxRounds?: number
+ /** Maximum serialized characters in one structured handoff (default 16384). */
+ maxHandoffChars?: number
+}
+
+/** Schemastery configuration for the Ralph tool. */
+export const Config: z = z.object({
+ subagentProvider: z.string().default('spawn'),
+ maxRounds: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(256),
+ maxHandoffChars: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(16_384),
+})
+
+interface ResolvedConfig {
+ readonly subagentProvider: string
+ readonly maxRounds: number
+ readonly maxHandoffChars: number
+}
+
+type RalphRoundStatus = 'continue' | 'complete' | 'blocked'
+
+interface RalphRoundReport {
+ readonly status: RalphRoundStatus
+ readonly summary: string
+ readonly evidence: string[]
+ readonly nextSteps: string[]
+ readonly blocker: string
+}
+
+type RalphRunStatus = 'complete' | 'blocked' | 'budget-limited'
+
+interface RalphRunResult {
+ readonly status: RalphRunStatus
+ readonly roundsStarted: number
+ readonly report: RalphRoundReport
+}
+
+interface RalphCallArgs {
+ objective: string
+ maxRounds?: number
+}
+
+const RALPH_META = {
+ name: 'ralph-loop',
+ description: 'Iterate toward one objective with a fresh child and bounded structured handoff per round.',
+ phases: [{ title: 'Fresh-agent rounds', detail: 'One clean child context per Ralph round.' }],
+}
+
+/**
+ * Fixed, deployment-owned orchestration. The model supplies data only; it
+ * cannot alter the loop, provider route, schema, or handoff validation.
+ */
+const RALPH_SCRIPT = String.raw`
+const reportSchema = {
+ type: 'object',
+ properties: {
+ status: { type: 'string', enum: ['continue', 'complete', 'blocked'] },
+ summary: { type: 'string' },
+ evidence: { type: 'array', items: { type: 'string' } },
+ nextSteps: { type: 'array', items: { type: 'string' } },
+ blocker: { type: 'string' },
+ },
+ required: ['status', 'summary', 'evidence', 'nextSteps', 'blocker'],
+ additionalProperties: false,
+}
+
+function normalizedText(value) {
+ return typeof value === 'string' && value.length > 0 && value === value.trim()
+}
+
+function normalizedList(value) {
+ return Array.isArray(value) && value.every(normalizedText)
+}
+
+function validateReport(report) {
+ if (report === null || typeof report !== 'object' || Array.isArray(report)) {
+ throw new Error('Ralph child returned no structured round report')
+ }
+ if (!normalizedText(report.summary)) {
+ throw new Error('Ralph round report summary must be non-empty and normalized')
+ }
+ if (!normalizedList(report.evidence) || !normalizedList(report.nextSteps)) {
+ throw new Error('Ralph round report evidence and nextSteps must contain only non-empty normalized strings')
+ }
+ if (typeof report.blocker !== 'string' || report.blocker !== report.blocker.trim()) {
+ throw new Error('Ralph round report blocker must be a normalized string')
+ }
+ switch (report.status) {
+ case 'continue':
+ if (report.nextSteps.length === 0 || report.blocker !== '') {
+ throw new Error('a continuing Ralph report needs nextSteps and an empty blocker')
+ }
+ break
+ case 'complete':
+ if (report.evidence.length === 0 || report.nextSteps.length !== 0 || report.blocker !== '') {
+ throw new Error('a complete Ralph report needs evidence, no nextSteps, and an empty blocker')
+ }
+ break
+ case 'blocked':
+ if (!normalizedText(report.blocker)) {
+ throw new Error('a blocked Ralph report needs a concrete blocker')
+ }
+ break
+ default:
+ throw new Error('Ralph round report status is invalid')
+ }
+ const serialized = JSON.stringify(report)
+ if (serialized.length > args.maxHandoffChars) {
+ throw new Error('Ralph round report exceeds maxHandoffChars (' + serialized.length + ' > ' + args.maxHandoffChars + ')')
+ }
+ return report
+}
+
+let previous
+for (let round = 1; round <= args.maxRounds; round += 1) {
+ phase('Fresh-agent rounds')
+ const prior = previous === undefined ? '(none — this is the first round)' : JSON.stringify(previous)
+ const prompt = [
+ 'You are one fresh worker in a foreground Ralph loop. You receive no parent conversation and no prior child session. Do not call the ralph tool: this round already is its worker.',
+ 'Immutable objective:\n' + args.objective,
+ 'Ralph round: ' + round + ' of ' + args.maxRounds + '.',
+ 'The shared workspace and its current working tree are the long-term memory and source of truth. Inspect them before acting, preserve existing work, perform concrete in-scope work, and verify what you change. Treat the previous report only as a bounded handoff; confirm it against the workspace.',
+ 'Previous structured handoff:\n' + prior,
+ 'Return one report with exact normalized strings. Use status continue with at least one nextSteps entry while useful work remains; complete only with concrete evidence and no nextSteps; blocked only when no meaningful progress is possible without human input or an external-state change. blocker must be empty unless blocked.',
+ ].join('\n\n')
+ const report = validateReport(await agent(prompt, {
+ label: 'Ralph round ' + round,
+ phase: 'Fresh-agent rounds',
+ schema: reportSchema,
+ }))
+ if (report.status === 'complete') return { status: 'complete', roundsStarted: round, report }
+ if (report.status === 'blocked') return { status: 'blocked', roundsStarted: round, report }
+ previous = report
+}
+return { status: 'budget-limited', roundsStarted: args.maxRounds, report: previous }
+`
+
+const DESCRIPTION = 'Run a foreground fresh-agent Ralph loop toward one immutable objective. '
+ + 'Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round '
+ + 'opens a new child with no parent conversation or prior child session; the shared workspace is '
+ + 'long-term memory, and only a bounded structured report crosses rounds. The call returns on '
+ + 'completion, a concrete blocker, or the round limit. Ordinary long-running same-session work '
+ + 'belongs to goal tools.'
+
+/** Validate defaults even when a caller invokes apply() without Loader normalization. */
+function resolveConfig(config: Config): ResolvedConfig {
+ const subagentProvider = config.subagentProvider ?? 'spawn'
+ const maxRounds = config.maxRounds ?? 256
+ const maxHandoffChars = config.maxHandoffChars ?? 16_384
+ if (subagentProvider.length === 0 || subagentProvider !== subagentProvider.trim()) {
+ throw new TypeError('subagentProvider must be a non-empty normalized string')
+ }
+ if (!Number.isSafeInteger(maxRounds) || maxRounds < 1) {
+ throw new TypeError('maxRounds must be a positive safe integer')
+ }
+ if (!Number.isSafeInteger(maxHandoffChars) || maxHandoffChars < 1) {
+ throw new TypeError('maxHandoffChars must be a positive safe integer')
+ }
+ return { subagentProvider, maxRounds, maxHandoffChars }
+}
+
+/** Resolve one model-selected cap against the deployment ceiling. */
+function resolveMaxRounds(requested: number | undefined, ceiling: number): number {
+ const value = requested ?? ceiling
+ if (!Number.isSafeInteger(value) || value < 1) {
+ throw new TypeError('Ralph maxRounds must be a positive safe integer')
+ }
+ if (value > ceiling) {
+ throw new TypeError(`Ralph maxRounds ${value} exceeds the deployment ceiling ${ceiling}`)
+ }
+ return value
+}
+
+/** Require the configured route to mean a genuinely fresh structured child. */
+function requireFreshProvider(ctx: Context, name: string): SubagentProvider {
+ const provider = ctx.subagents.getProvider(name)
+ if (provider === undefined) {
+ throw new Error(`Ralph subagent provider "${name}" is not registered`)
+ }
+ if (!provider.capabilities.outputSchema) {
+ throw new Error(`Ralph subagent provider "${name}" does not support structured output`)
+ }
+ if (provider.inheritsParentContext) {
+ throw new Error(`Ralph subagent provider "${name}" inherits parent context; Ralph requires a fresh provider`)
+ }
+ return provider
+}
+
+function isRecord(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function normalizedText(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value === value.trim()
+}
+
+function normalizedList(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every(normalizedText)
+}
+
+/** Defensively decode the fixed script's report across an implementation seam. */
+function readReport(value: unknown, expectedStatus: RalphRoundStatus, maxChars: number): RalphRoundReport {
+ if (!isRecord(value)
+ || Object.keys(value).sort().join(',') !== 'blocker,evidence,nextSteps,status,summary'
+ || value['status'] !== expectedStatus
+ || !normalizedText(value['summary'])
+ || !normalizedList(value['evidence'])
+ || !normalizedList(value['nextSteps'])
+ || typeof value['blocker'] !== 'string'
+ || value['blocker'] !== value['blocker'].trim()) {
+ throw new Error('Ralph workflow returned a malformed round report')
+ }
+ const report: RalphRoundReport = {
+ status: expectedStatus,
+ summary: value['summary'],
+ evidence: value['evidence'],
+ nextSteps: value['nextSteps'],
+ blocker: value['blocker'],
+ }
+ if (expectedStatus === 'continue' && (report.nextSteps.length === 0 || report.blocker !== '')) {
+ throw new Error('Ralph workflow returned an invalid continuing report')
+ }
+ if (expectedStatus === 'complete'
+ && (report.evidence.length === 0 || report.nextSteps.length !== 0 || report.blocker !== '')) {
+ throw new Error('Ralph workflow returned an invalid completion report')
+ }
+ if (expectedStatus === 'blocked' && !normalizedText(report.blocker)) {
+ throw new Error('Ralph workflow returned an invalid blocked report')
+ }
+ const chars = JSON.stringify(report).length
+ if (chars > maxChars) {
+ throw new Error(`Ralph workflow returned an oversized handoff (${chars} > ${maxChars})`)
+ }
+ return report
+}
+
+/** Defensively decode the fixed script's terminal value. */
+function readRunResult(value: unknown, maxRounds: number, maxHandoffChars: number): RalphRunResult {
+ if (!isRecord(value)
+ || Object.keys(value).sort().join(',') !== 'report,roundsStarted,status'
+ || typeof value['roundsStarted'] !== 'number'
+ || !Number.isSafeInteger(value['roundsStarted'])
+ || value['roundsStarted'] < 1
+ || value['roundsStarted'] > maxRounds) {
+ throw new Error('Ralph workflow returned a malformed terminal result')
+ }
+ const roundsStarted = value['roundsStarted']
+ switch (value['status']) {
+ case 'complete':
+ return { status: 'complete', roundsStarted, report: readReport(value['report'], 'complete', maxHandoffChars) }
+ case 'blocked':
+ return { status: 'blocked', roundsStarted, report: readReport(value['report'], 'blocked', maxHandoffChars) }
+ case 'budget-limited':
+ if (roundsStarted !== maxRounds) {
+ throw new Error('Ralph workflow returned budget-limited before the round limit')
+ }
+ return { status: 'budget-limited', roundsStarted, report: readReport(value['report'], 'continue', maxHandoffChars) }
+ default:
+ throw new Error('Ralph workflow returned an unknown terminal status')
+ }
+}
+
+/** A non-clean workflow finish is an error, never a partial Ralph success. */
+function stopReasonError(result: WorkflowResult): string | undefined {
+ switch (result.stopReason) {
+ case 'completed':
+ return undefined
+ case 'cancelled':
+ return `Ralph workflow was cancelled${result.error === undefined ? '' : ` (${result.error})`}`
+ case 'error':
+ return `Ralph workflow failed: ${result.error ?? 'unknown error'}`
+ /* v8 ignore start -- WorkflowStopReason is closed; a future variant must fail loud here. */
+ default:
+ return `Ralph workflow ended abnormally (${String(result.stopReason satisfies never)})`
+ /* v8 ignore stop */
+ }
+}
+
+/** Render the fixed terminal envelope without dropping the bounded report. */
+function renderResult(result: RalphRunResult): string {
+ const rounds = `${result.roundsStarted} round${result.roundsStarted === 1 ? '' : 's'}`
+ switch (result.status) {
+ case 'complete':
+ return `Ralph completed after ${rounds}.\nFinal report:\n${JSON.stringify(result.report, null, 2)}`
+ case 'blocked':
+ return `Ralph blocked after ${rounds}.\nFinal report:\n${JSON.stringify(result.report, null, 2)}`
+ case 'budget-limited':
+ return `Ralph reached its ${rounds} limit with work remaining.\nFinal report:\n${JSON.stringify(result.report, null, 2)}`
+ }
+}
+
+function presentCall(args: RalphCallArgs): ToolCallView {
+ return { card: 'generic', title: 'ralph', rawInput: args.objective }
+}
+
+function presentResult(args: RalphCallArgs, result: { content: ContentBlock[]; isError: boolean }): ToolResultView {
+ void args
+ void result
+ return { card: 'generic' }
+}
+
+/** Register the fixed Ralph tool and its explicit-ask usage policy. */
+export function apply(ctx: Context, config: Config): void {
+ const resolved = resolveConfig(config)
+ ctx.systemPrompt.section({
+ name: 'tool:ralph',
+ order: 116,
+ text: '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. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.',
+ })
+ ctx.tools.register(defineTool({
+ name: 'ralph',
+ description: DESCRIPTION,
+ parameters: {
+ objective: {
+ type: 'string',
+ required: true,
+ description: 'The immutable completion objective for every fresh Ralph round.',
+ },
+ maxRounds: {
+ type: 'number',
+ description: 'Optional positive safe-integer round cap, bounded by the deployment ceiling.',
+ },
+ },
+ async execute(args, exec): Promise {
+ const parent = exec.agent
+ if (parent === undefined) {
+ throw new Error('Ralph tool requires a calling agent (exec.agent was undefined)')
+ }
+ const objective = args.objective.trim()
+ if (objective.length === 0) throw new Error('Ralph objective must be a non-empty string')
+ const maxRounds = resolveMaxRounds(args.maxRounds, resolved.maxRounds)
+ void requireFreshProvider(ctx, resolved.subagentProvider)
+
+ const run: WorkflowRun = ctx.workflows.start({
+ script: RALPH_SCRIPT,
+ meta: RALPH_META,
+ args: { objective, maxRounds, maxHandoffChars: resolved.maxHandoffChars },
+ subagentProvider: resolved.subagentProvider,
+ parent,
+ ...exec.signal === undefined ? {} : { signal: exec.signal },
+ })
+ const onAbort = (): void => { run.cancel('parent step aborted') }
+ exec.signal?.addEventListener('abort', onAbort, { once: true })
+ if (exec.signal?.aborted) run.cancel('parent step aborted')
+
+ try {
+ const settled = await run.result
+ const error = stopReasonError(settled)
+ if (error !== undefined) throw new Error(error)
+ const value = readRunResult(settled.value, maxRounds, resolved.maxHandoffChars)
+ return [{ type: 'text', text: renderResult(value) }]
+ } finally {
+ exec.signal?.removeEventListener('abort', onAbort)
+ await run.dispose()
+ }
+ },
+ presentCall,
+ presentResult,
+ }))
+}
diff --git a/packages/workflow/tool-ralph/tests/integration.spec.ts b/packages/workflow/tool-ralph/tests/integration.spec.ts
new file mode 100644
index 0000000000..f984e67d22
--- /dev/null
+++ b/packages/workflow/tool-ralph/tests/integration.spec.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from 'vitest'
+import { Context } from 'cordis'
+import type { Agent } from '@deepseek-ai/dsh-agent'
+import AgentLoop from '@deepseek-ai/dsh-agent-loop'
+import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
+import * as Invariants from '@deepseek-ai/dsh-invariants'
+import { CallId } from '@deepseek-ai/dsh-llm'
+import { SessionId } from '@deepseek-ai/dsh-session'
+import SubagentService from '@deepseek-ai/dsh-subagent'
+import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-inprocess'
+import * as spawn from '@deepseek-ai/dsh-subagent-spawn'
+import WorkerWorkflowEngine from '@deepseek-ai/dsh-workflow-workerthread'
+import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
+import * as toolRalph from '../src/index.ts'
+
+describe('dsh-tool-ralph over the real spawn and worker-thread stack', () => {
+ it('uses distinct empty-seed children, shared cwd, and only the prior bounded handoff', async () => {
+ const firstReport = {
+ status: 'continue',
+ summary: 'ROUND_ONE_HANDOFF',
+ evidence: ['Created migration-a.ts.'],
+ nextSteps: ['Finish migration-b.ts.'],
+ blocker: '',
+ }
+ const finalReport = {
+ status: 'complete',
+ summary: 'Both migration slices are complete.',
+ evidence: ['Focused migration tests pass.'],
+ nextSteps: [],
+ blocker: '',
+ }
+ const ctx = new Context()
+ const adapter = new MockAdapter([
+ textResponse('PARENT_HISTORY_MARKER'),
+ toolCallResponse('round-1', STRUCTURED_OUTPUT_TOOL, firstReport),
+ toolCallResponse('round-2', STRUCTURED_OUTPUT_TOOL, finalReport),
+ ])
+ await mountAgentLoopTestDependencies(ctx)
+ await ctx.plugin(Invariants)
+ await ctx.plugin(AgentLoop, { agents: [] })
+ await ctx.plugin(SubagentService)
+ await ctx.plugin(spawn, { providerName: 'spawn' })
+ await ctx.plugin(WorkerWorkflowEngine, {})
+ await ctx.plugin(toolRalph, { maxRounds: 2 })
+ ctx.llm.registerAdapter(['mock'], adapter)
+
+ const parentHandle = await ctx.agents.create({
+ sessionId: SessionId('ralph-parent'),
+ meta: { cwd: '/tmp/ralph-shared-workspace' },
+ agentOptions: { provider: 'mock', model: 'mock' },
+ })
+ const parent = parentHandle.agent
+ parent.send([{ type: 'text', text: 'PARENT_PROMPT_MARKER' }])
+ await parent.whenIdle()
+
+ const children: Agent[] = []
+ ctx.on('workflow/agent-start', (_run, child) => {
+ const agent = ctx.agents.get(child.childId)
+ expect(agent).toBeDefined()
+ children.push(agent!)
+ })
+ const result = await ctx.tools.execute({
+ callId: CallId('ralph-integration'),
+ name: 'ralph',
+ arguments: { objective: 'Complete both migration slices.', maxRounds: 2 },
+ agent: parent,
+ })
+
+ expect(result.isError).toBe(false)
+ expect((result.content[0] as { text: string }).text).toContain('Ralph completed after 2 rounds.')
+ expect(children).toHaveLength(2)
+ expect(new Set(children.map(child => child.id)).size).toBe(2)
+ for (const child of children) {
+ expect(child.session.header.cwd).toBe('/tmp/ralph-shared-workspace')
+ expect(child.session.header.parentSession).toBe(parent.session.header.id)
+ expect(child.session.header.seedLength).toBeUndefined()
+ expect(ctx.agents.get(child.id)).toBeUndefined()
+ }
+
+ expect(adapter.requests).toHaveLength(3)
+ const firstChildRequest = JSON.stringify(adapter.requests[1]!.messages)
+ const secondChildRequest = JSON.stringify(adapter.requests[2]!.messages)
+ expect(firstChildRequest).not.toContain('PARENT_PROMPT_MARKER')
+ expect(firstChildRequest).not.toContain('PARENT_HISTORY_MARKER')
+ expect(firstChildRequest).not.toContain('ROUND_ONE_HANDOFF')
+ expect(secondChildRequest).not.toContain('PARENT_PROMPT_MARKER')
+ expect(secondChildRequest).not.toContain('PARENT_HISTORY_MARKER')
+ expect(secondChildRequest).toContain('ROUND_ONE_HANDOFF')
+
+ await parentHandle.dispose()
+ })
+})
diff --git a/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts b/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts
new file mode 100644
index 0000000000..b7a70fd7d7
--- /dev/null
+++ b/packages/workflow/tool-ralph/tests/tool-ralph.spec.ts
@@ -0,0 +1,319 @@
+import { describe, expect, it, vi } from 'vitest'
+import { Context } from 'cordis'
+import Loader from '@cordisjs/plugin-loader'
+import type { Agent } from '@deepseek-ai/dsh-agent'
+import { CallId } from '@deepseek-ai/dsh-llm'
+import { SessionId } from '@deepseek-ai/dsh-session'
+import SubagentService from '@deepseek-ai/dsh-subagent'
+import type { SubagentCapabilities, SubagentProvider, SubagentRun, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
+import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
+import ToolRegistry from '@deepseek-ai/dsh-tools'
+import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools'
+import { WorkflowRunId, WorkflowService } from '@deepseek-ai/dsh-workflow'
+import type { WorkflowResult, WorkflowRun, WorkflowStartRequest } from '@deepseek-ai/dsh-workflow'
+import * as toolRalph from '../src/index.ts'
+
+class StubEngine extends WorkflowService {
+ requests: WorkflowStartRequest[] = []
+ cancels: string[] = []
+ disposed = 0
+ settle!: (result: WorkflowResult) => void
+ startError: Error | undefined
+
+ start(request: WorkflowStartRequest): WorkflowRun {
+ if (this.startError !== undefined) throw this.startError
+ this.requests.push(request)
+ const result = new Promise((resolve) => { this.settle = resolve })
+ return {
+ id: WorkflowRunId(`ralph-${this.requests.length}`),
+ meta: request.meta,
+ result,
+ cancel: (reason?: string) => {
+ this.cancels.push(reason ?? 'cancelled')
+ this.settle({
+ value: null,
+ stopReason: 'cancelled',
+ ...reason === undefined ? {} : { error: reason },
+ agentsStarted: 0,
+ })
+ },
+ dispose: () => {
+ this.disposed += 1
+ return Promise.resolve()
+ },
+ }
+ }
+}
+
+class StubProvider implements SubagentProvider {
+ readonly name = 'fresh'
+ readonly capabilities: SubagentCapabilities
+ readonly inheritsParentContext: boolean
+
+ constructor(options?: { outputSchema?: boolean; inheritsParentContext?: boolean }) {
+ this.capabilities = {
+ outputSchema: options?.outputSchema ?? true,
+ depthLimit: true,
+ toolFilter: true,
+ persona: true,
+ }
+ this.inheritsParentContext = options?.inheritsParentContext ?? false
+ }
+
+ start(_request: SubagentStartRequest): Promise {
+ return Promise.reject(new Error('StubProvider.start must not be reached behind StubEngine'))
+ }
+}
+
+interface SetupOptions {
+ config?: toolRalph.Config
+ provider?: StubProvider | false
+}
+
+async function setup(options?: SetupOptions) {
+ const ctx = new Context()
+ await ctx.plugin(SystemPrompt)
+ await ctx.plugin(ToolRegistry)
+ await ctx.plugin(SubagentService)
+ const provider = options?.provider === false ? undefined : options?.provider ?? new StubProvider()
+ if (provider !== undefined) ctx.subagents.registerProvider(provider)
+ await ctx.plugin(StubEngine)
+ const config: toolRalph.Config = { subagentProvider: 'fresh' }
+ if (options?.config?.subagentProvider !== undefined) config.subagentProvider = options.config.subagentProvider
+ if (options?.config?.maxRounds !== undefined) config.maxRounds = options.config.maxRounds
+ if (options?.config?.maxHandoffChars !== undefined) config.maxHandoffChars = options.config.maxHandoffChars
+ const fiber = await ctx.plugin(toolRalph, config)
+ const parent = { id: SessionId('caller'), options: {} } as unknown as Agent
+ return { ctx, engine: ctx.workflows as StubEngine, parent, fiber }
+}
+
+function execute(
+ ctx: Context,
+ args: unknown,
+ extra?: { agent?: Agent; signal?: AbortSignal },
+): Promise {
+ return ctx.tools.execute({
+ callId: CallId('ralph-call'),
+ name: 'ralph',
+ arguments: args,
+ ...extra?.agent === undefined ? {} : { agent: extra.agent },
+ ...extra?.signal === undefined ? {} : { signal: extra.signal },
+ })
+}
+
+const CONTINUE = {
+ status: 'continue',
+ summary: 'Implemented the first slice.',
+ evidence: ['Focused tests pass.'],
+ nextSteps: ['Implement the second slice.'],
+ blocker: '',
+}
+
+const COMPLETE = {
+ status: 'complete',
+ summary: 'The objective is complete.',
+ evidence: ['All required gates pass.'],
+ nextSteps: [],
+ blocker: '',
+}
+
+const BLOCKED = {
+ status: 'blocked',
+ summary: 'No local work can progress.',
+ evidence: ['The required remote service is unavailable.'],
+ nextSteps: ['Retry after service recovery.'],
+ blocker: 'The required remote service is unavailable.',
+}
+
+async function settleCompleted(
+ engine: StubEngine,
+ pending: Promise,
+ value: unknown,
+ agentsStarted = 1,
+): Promise {
+ await vi.waitFor(() => { expect(engine.requests.length).toBeGreaterThan(0) })
+ engine.settle({ value, stopReason: 'completed', agentsStarted })
+ return pending
+}
+
+describe('dsh-tool-ralph', () => {
+ it('starts the fixed workflow through the configured fresh provider and renders completion', async () => {
+ const { ctx, engine, parent } = await setup({ config: { maxRounds: 9, maxHandoffChars: 9000 } })
+ const pending = execute(ctx, { objective: ' Finish the migration. ', maxRounds: 4 }, { agent: parent })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
+ expect(engine.requests[0]).toMatchObject({
+ meta: { name: 'ralph-loop' },
+ args: { objective: 'Finish the migration.', maxRounds: 4, maxHandoffChars: 9000 },
+ subagentProvider: 'fresh',
+ parent,
+ })
+ expect(engine.requests[0]!.script).toContain("status: 'budget-limited'")
+ const result = await settleCompleted(engine, pending, {
+ status: 'complete',
+ roundsStarted: 1,
+ report: COMPLETE,
+ })
+ expect(result.isError).toBe(false)
+ expect((result.content[0] as { text: string }).text).toContain('Ralph completed after 1 round.')
+ expect((result.content[0] as { text: string }).text).toContain('All required gates pass.')
+ expect(engine.disposed).toBe(1)
+ })
+
+ it('renders blocked and budget-limited terminal outcomes as bounded successful results', async () => {
+ const { ctx, engine, parent } = await setup({ config: { maxRounds: 2 } })
+ const blocked = execute(ctx, { objective: 'Ship it.' }, { agent: parent })
+ const blockedResult = await settleCompleted(engine, blocked, {
+ status: 'blocked',
+ roundsStarted: 2,
+ report: BLOCKED,
+ }, 2)
+ expect((blockedResult.content[0] as { text: string }).text).toContain('Ralph blocked after 2 rounds.')
+
+ const limited = execute(ctx, { objective: 'Ship it.' }, { agent: parent })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) })
+ const limitedResult = await settleCompleted(engine, limited, {
+ status: 'budget-limited',
+ roundsStarted: 2,
+ report: CONTINUE,
+ }, 2)
+ expect((limitedResult.content[0] as { text: string }).text)
+ .toContain('Ralph reached its 2 rounds limit with work remaining.')
+ })
+
+ it('maps workflow error and cancellation reasons to tool errors and always disposes', async () => {
+ const { ctx, engine, parent } = await setup()
+ const failed = execute(ctx, { objective: 'Work.' }, { agent: parent })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
+ engine.settle({ value: null, stopReason: 'error', error: 'child report malformed', agentsStarted: 1 })
+ expect(((await failed).content[0] as { text: string }).text)
+ .toContain('Ralph workflow failed: child report malformed')
+
+ const unknown = execute(ctx, { objective: 'Work.' }, { agent: parent })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) })
+ engine.settle({ value: null, stopReason: 'error', agentsStarted: 0 })
+ expect(((await unknown).content[0] as { text: string }).text).toContain('unknown error')
+
+ const cancelled = execute(ctx, { objective: 'Work.' }, { agent: parent })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(3) })
+ engine.settle({ value: null, stopReason: 'cancelled', error: 'user stopped', agentsStarted: 0 })
+ expect(((await cancelled).content[0] as { text: string }).text).toContain('cancelled (user stopped)')
+
+ const bare = execute(ctx, { objective: 'Work.' }, { agent: parent })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(4) })
+ engine.settle({ value: null, stopReason: 'cancelled', agentsStarted: 0 })
+ expect(((await bare).content[0] as { text: string }).text).toMatch(/cancelled$/)
+ expect(engine.disposed).toBe(4)
+ })
+
+ it('bridges mid-flight and already-aborted parent signals to cancellation', async () => {
+ const { ctx, engine, parent } = await setup()
+ const controller = new AbortController()
+ const pending = execute(ctx, { objective: 'Work.' }, { agent: parent, signal: controller.signal })
+ await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
+ controller.abort()
+ expect((await pending).isError).toBe(true)
+
+ const already = new AbortController()
+ already.abort()
+ expect((await execute(ctx, { objective: 'Work.' }, { agent: parent, signal: already.signal })).isError).toBe(true)
+ expect(engine.cancels).toEqual(['parent step aborted', 'parent step aborted'])
+ expect(engine.disposed).toBe(2)
+ })
+
+ it('rejects absent authority, empty objectives, bad round caps, and schema-invalid calls before start', async () => {
+ const { ctx, engine, parent } = await setup({ config: { maxRounds: 3 } })
+ expect((await execute(ctx, { objective: 'Work.' })).isError).toBe(true)
+ expect((await execute(ctx, { objective: ' ' }, { agent: parent })).isError).toBe(true)
+ for (const maxRounds of [0, 1.5, Number.NaN, 4]) {
+ expect((await execute(ctx, { objective: 'Work.', maxRounds }, { agent: parent })).isError).toBe(true)
+ }
+ const missing = await execute(ctx, {}, { agent: parent })
+ expect(missing.error?.code).toBe('INVALID_ARGS')
+ expect(engine.requests).toHaveLength(0)
+ })
+
+ it('rejects missing, unstructured, and parent-context-inheriting provider routes', async () => {
+ const missing = await setup({ provider: false })
+ expect(((await execute(missing.ctx, { objective: 'Work.' }, { agent: missing.parent })).content[0] as { text: string }).text)
+ .toContain('is not registered')
+ expect(missing.engine.requests).toHaveLength(0)
+
+ const unstructured = await setup({ provider: new StubProvider({ outputSchema: false }) })
+ expect(((await execute(unstructured.ctx, { objective: 'Work.' }, { agent: unstructured.parent })).content[0] as { text: string }).text)
+ .toContain('does not support structured output')
+
+ const inherited = await setup({ provider: new StubProvider({ inheritsParentContext: true }) })
+ expect(((await execute(inherited.ctx, { objective: 'Work.' }, { agent: inherited.parent })).content[0] as { text: string }).text)
+ .toContain('inherits parent context')
+ })
+
+ it('rejects invalid direct-apply config before touching injected services', () => {
+ expect(() => { toolRalph.apply(new Context(), { subagentProvider: ' ' }) }).toThrow('non-empty normalized')
+ expect(() => { toolRalph.apply(new Context(), { maxRounds: 0 }) }).toThrow('positive safe integer')
+ expect(() => { toolRalph.apply(new Context(), { maxHandoffChars: 1.5 }) }).toThrow('positive safe integer')
+ })
+
+ it('turns malformed fixed-workflow terminal values and reports into errors', async () => {
+ const cases: { value: unknown; message: string; config?: toolRalph.Config }[] = [
+ { value: null, message: 'malformed terminal result' },
+ { value: { status: 'complete', roundsStarted: 0, report: COMPLETE }, message: 'malformed terminal result' },
+ { value: { status: 'complete', roundsStarted: 3, report: COMPLETE }, message: 'malformed terminal result', config: { maxRounds: 2 } },
+ { value: { status: 'mystery', roundsStarted: 1, report: COMPLETE }, message: 'unknown terminal status' },
+ { value: { status: 'budget-limited', roundsStarted: 1, report: CONTINUE }, message: 'before the round limit', config: { maxRounds: 2 } },
+ { value: { status: 'complete', roundsStarted: 1, report: null }, message: 'malformed round report' },
+ { value: { status: 'complete', roundsStarted: 1, report: { ...COMPLETE, status: 'continue' } }, message: 'malformed round report' },
+ { value: { status: 'budget-limited', roundsStarted: 1, report: { ...CONTINUE, nextSteps: [] } }, message: 'invalid continuing report', config: { maxRounds: 1 } },
+ { value: { status: 'complete', roundsStarted: 1, report: { ...COMPLETE, evidence: [] } }, message: 'invalid completion report' },
+ { value: { status: 'blocked', roundsStarted: 1, report: { ...BLOCKED, blocker: '' } }, message: 'invalid blocked report' },
+ { value: { status: 'complete', roundsStarted: 1, report: { ...COMPLETE, summary: 'x'.repeat(500) } }, message: 'oversized handoff', config: { maxHandoffChars: 100 } },
+ ]
+ for (const testCase of cases) {
+ const { ctx, engine, parent } = await setup(
+ testCase.config === undefined ? undefined : { config: testCase.config },
+ )
+ const result = await settleCompleted(
+ engine,
+ execute(ctx, { objective: 'Work.', ...testCase.config?.maxRounds === undefined ? {} : { maxRounds: testCase.config.maxRounds } }, { agent: parent }),
+ testCase.value,
+ )
+ expect(result.isError).toBe(true)
+ expect((result.content[0] as { text: string }).text).toContain(testCase.message)
+ }
+ })
+
+ it('surfaces a synchronous engine start failure without inventing a run', async () => {
+ const { ctx, engine, parent } = await setup()
+ engine.startError = new Error('engine refused fixed script')
+ const result = await execute(ctx, { objective: 'Work.' }, { agent: parent })
+ expect(result.isError).toBe(true)
+ expect((result.content[0] as { text: string }).text).toContain('engine refused fixed script')
+ expect(engine.disposed).toBe(0)
+ })
+
+ it('registers scoped guidance and pure replay-safe generic presentation', async () => {
+ const { ctx, fiber } = await setup()
+ const section = (await ctx.systemPrompt.assemble()).sections.find(candidate => candidate.name === 'tool:ralph')
+ expect(section?.text).toContain('ONLY when the direct human explicitly asks')
+ const tool = ctx.tools.get('ralph')!
+ expect(tool.presentCall!({ objective: 'Finish it.' })).toEqual({
+ card: 'generic',
+ title: 'ralph',
+ rawInput: 'Finish it.',
+ })
+ expect(tool.presentResult!({ objective: 'Finish it.' }, { content: [], isError: false })).toEqual({ card: 'generic' })
+ expect(tool.presentCall!({ nope: true })).toBeUndefined()
+ await fiber.dispose()
+ expect(ctx.tools.get('ralph')).toBeUndefined()
+ expect((await ctx.systemPrompt.assemble()).sections.some(candidate => candidate.name === 'tool:ralph')).toBe(false)
+ })
+
+ it('has the namespace-plugin export shape', () => {
+ expect('default' in toolRalph).toBe(false)
+ expect(toolRalph.name).toBe('tool-ralph')
+ expect(toolRalph.inject).toEqual(['tools', 'workflows', 'subagents', 'systemPrompt'])
+ const loader = Object.create(Loader.prototype) as Loader
+ const unwrapped = loader.unwrapExports(toolRalph) as Record
+ expect(unwrapped).toBe(toolRalph)
+ expect(typeof unwrapped.apply).toBe('function')
+ })
+})
diff --git a/packages/workflow/tool-ralph/tsconfig.json b/packages/workflow/tool-ralph/tsconfig.json
new file mode 100644
index 0000000000..294a851a5b
--- /dev/null
+++ b/packages/workflow/tool-ralph/tsconfig.json
@@ -0,0 +1,39 @@
+{
+ "extends": "../../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "include": [
+ "src"
+ ],
+ "references": [
+ {
+ "path": "../../../vendor/cosmokit"
+ },
+ {
+ "path": "../../../vendor/cordis"
+ },
+ {
+ "path": "../../../vendor/schemastery"
+ },
+ {
+ "path": "../../core/agent"
+ },
+ {
+ "path": "../../llm/llm"
+ },
+ {
+ "path": "../../subagent/subagent"
+ },
+ {
+ "path": "../../core/system-prompt"
+ },
+ {
+ "path": "../../core/tools"
+ },
+ {
+ "path": "../workflow"
+ }
+ ]
+}
diff --git a/packages/workflow/workflow-workerthread/README.md b/packages/workflow/workflow-workerthread/README.md
index f7fcd6e6d2..23fa849888 100644
--- a/packages/workflow/workflow-workerthread/README.md
+++ b/packages/workflow/workflow-workerthread/README.md
@@ -39,7 +39,7 @@ Unknown options, malformed arguments, unsupported schemas, tripped caps, provide
For each `agent()` call:
1. The worker sends `child-start` with a plain-data prompt and options.
-2. The host calls the configured provider through async `SubagentService.start`, passing the workflow's parent and one canonical per-run abort signal.
+2. The host calls the start request's provider override, or otherwise the configured provider, through async `SubagentService.start`, passing the workflow's parent and one canonical per-run abort signal. Provider choice applies to every child in that run and is not visible to the script.
3. If start rejects, the host sends `child-start-error`; provider startup has already reached quiescence and no child lifecycle event is emitted.
4. If start fulfills while the workflow still admits work, the host records the run, observes `result`, then sends `child-started`. Even an already-settled result is forwarded afterward, preserving start-before-result order.
5. The worker emits paired `workflow/agent-start` and `workflow/agent-end` narration and requests child disposal after collection.
@@ -81,6 +81,8 @@ The host keeps a ledger of forwarded child starts. A graceful worker supplies th
| `syncTimeoutMs` | `5000` | VM timeout for the script's initial synchronous slice. |
| `disposeGraceMs` | `5000` | Bound before force-settlement/termination and for public disposal. |
+An owning consumer may set `WorkflowStartRequest.subagentProvider` for one run. This is an engine-level route, not a script hook or a model-facing option; the ordinary `workflow` tool leaves it unset.
+
## Model Experience
### Child-agent requests
diff --git a/packages/workflow/workflow-workerthread/src/index.ts b/packages/workflow/workflow-workerthread/src/index.ts
index 9fed7d3450..604d8ba754 100644
--- a/packages/workflow/workflow-workerthread/src/index.ts
+++ b/packages/workflow/workflow-workerthread/src/index.ts
@@ -137,6 +137,7 @@ class WorkerWorkflowEngine extends WorkflowService {
// the now-inactive engine fiber and break the seam's holder-owned lifetime.
const runCtx = this.ctx
const subagents = runCtx.subagents
+ const subagentProvider = request.subagentProvider ?? this.config.provider
const workerRun = new WorkerRun(
runCtx,
subagents,
@@ -144,7 +145,7 @@ class WorkerWorkflowEngine extends WorkflowService {
meta,
request.parent,
init,
- this.config.provider,
+ subagentProvider,
this.config.disposeGraceMs,
{
phase: (title) => { this.emitWorkflowEvent('workflow/phase', info, title) },
diff --git a/packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts b/packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts
index e9d9a9b4e1..e330b3ee83 100644
--- a/packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts
+++ b/packages/workflow/workflow-workerthread/tests/built-worker.e2e.ts
@@ -27,16 +27,30 @@ import WorkerWorkflowEngine from '@deepseek-ai/dsh-workflow-workerthread'
const ctx = new Context()
await ctx.plugin(SubagentService)
-await ctx.plugin(WorkerWorkflowEngine, {})
+let selectedStarts = 0
+ctx.subagents.registerProvider({
+ name: 'built-selected',
+ capabilities: { outputSchema: true, depthLimit: false, toolFilter: false, persona: false },
+ inheritsParentContext: false,
+ async start() {
+ selectedStarts += 1
+ return {
+ id: 'built-child',
+ result: Promise.resolve({ output: [], structured: { answer: 42 }, stopReason: 'completed' }),
+ dispose: () => Promise.resolve(),
+ }
+ },
+})
+await ctx.plugin(WorkerWorkflowEngine, { provider: 'must-not-be-used' })
const run = ctx.workflows.start({
- script: 'return 6 * 7',
+ script: "const value = await agent('answer', { schema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] } }); return value.answer",
meta: { name: 'built-smoke', description: 'built worker smoke' },
- // A zero-agent script never touches the provider.
+ subagentProvider: 'built-selected',
parent: { id: 'built-smoke-parent', options: {} },
})
const result = await run.result
await run.dispose()
-if (result.stopReason !== 'completed' || result.value !== 42) {
+if (result.stopReason !== 'completed' || result.value !== 42 || selectedStarts !== 1) {
console.error('unexpected result: ' + JSON.stringify(result))
process.exit(1)
}
diff --git a/packages/workflow/workflow-workerthread/tests/workflow-workerthread.spec.ts b/packages/workflow/workflow-workerthread/tests/workflow-workerthread.spec.ts
index 2f52cd7b6b..e2cc227704 100644
--- a/packages/workflow/workflow-workerthread/tests/workflow-workerthread.spec.ts
+++ b/packages/workflow/workflow-workerthread/tests/workflow-workerthread.spec.ts
@@ -232,6 +232,26 @@ describe('dsh-workflow-workerthread', () => {
expect(provider.runs[0]!.request.agentOptions).toEqual({ provider: 'openai' })
})
+ it('a start-request provider override selects every child without changing the engine default', async () => {
+ const { ctx, parent, provider } = await setup()
+ const selected = new StubProvider('selected', () => text('selected reply'))
+ ctx.subagents.registerProvider(selected)
+
+ const overridden = ctx.workflows.start({
+ ...scripted("return await agent('route this run')"),
+ parent,
+ subagentProvider: 'selected',
+ })
+ expect((await overridden.result).value).toBe('selected reply')
+ await overridden.dispose()
+ expect(selected.runs).toHaveLength(1)
+ expect(provider.runs).toHaveLength(0)
+
+ const ordinary = await run(ctx, parent, scripted("return await agent('use the default')"))
+ expect(ordinary.value).toBe('stub reply')
+ expect(provider.runs).toHaveLength(1)
+ })
+
it('a fatal hook error inside the worker kills the script and reports the error', async () => {
const { ctx, parent } = await setup()
const result = await run(ctx, parent, scripted("return await parallel([() => agent('x', { isolation: 'worktree' })])"))
diff --git a/packages/workflow/workflow/README.md b/packages/workflow/workflow/README.md
index 9f2b557811..e21ebcd701 100644
--- a/packages/workflow/workflow/README.md
+++ b/packages/workflow/workflow/README.md
@@ -10,7 +10,7 @@ The workflow seam (`ctx.workflows`) executes a model-written orchestration scrip
A run is holder-owned. Engine-plugin unload prevents new starts but does not revoke accepted runs. The holder must call `dispose()` on every path; disposal cancels remaining work and reaches or abandons quiescence within the documented bound.
-`WorkflowStartRequest` contains `{ meta, script, args?, parent, signal? }`. `parent` attributes every child agent to the invoking agent. `meta` and `args` are plain data, not script fragments.
+`WorkflowStartRequest` contains `{ meta, script, args?, subagentProvider?, parent, signal? }`. `parent` attributes every child agent to the invoking agent. `subagentProvider` optionally routes every child in that run without exposing provider choice to the script; omission uses the engine's configured provider. `meta` and `args` are plain data, not script fragments.
`WorkflowRun` exposes `{ id, meta, result, cancel(reason?), dispose() }`. `WorkflowResult` contains `{ value, stopReason, error?, agentsStarted }`; `value` is plain JSON data or `null`.
diff --git a/packages/workflow/workflow/src/types.ts b/packages/workflow/workflow/src/types.ts
index faef18aeb0..de6af8f838 100644
--- a/packages/workflow/workflow/src/types.ts
+++ b/packages/workflow/workflow/src/types.ts
@@ -70,6 +70,12 @@ export interface WorkflowStartRequest {
meta: WorkflowMeta
/** Optional input exposed verbatim to the script as the `args` global. */
args?: unknown
+ /**
+ * Optional engine-wide child-provider override for this run. The workflow
+ * script cannot observe or replace it; omission uses the engine's configured
+ * provider.
+ */
+ subagentProvider?: string
/** The agent on whose behalf the run executes (parent of every child). */
parent: Agent
/** Cancels the run when aborted (the tool's `exec.signal`). */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1a45c8b505..2ecae79efe 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -200,6 +200,9 @@ importers:
'@deepseek-ai/dsh-tool-goal':
specifier: workspace:*
version: link:../packages/goal/tool-goal
+ '@deepseek-ai/dsh-tool-ralph':
+ specifier: workspace:*
+ version: link:../packages/workflow/tool-ralph
'@deepseek-ai/dsh-tool-subagent':
specifier: workspace:*
version: link:../packages/subagent/tool-subagent
@@ -2514,6 +2517,58 @@ importers:
specifier: ^4.0.0-rc.7
version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5)
+ packages/workflow/tool-ralph:
+ dependencies:
+ schemastery:
+ specifier: ^3.18.0
+ version: 3.18.0
+ devDependencies:
+ '@cordisjs/plugin-loader':
+ specifier: workspace:^
+ version: link:../../../vendor/loader
+ '@deepseek-ai/dsh-agent':
+ specifier: workspace:^
+ version: link:../../core/agent
+ '@deepseek-ai/dsh-agent-loop':
+ specifier: workspace:^
+ version: link:../../core/agent-loop
+ '@deepseek-ai/dsh-agent-loop-testkit':
+ specifier: workspace:^
+ version: link:../../support/agent-loop-testkit
+ '@deepseek-ai/dsh-invariants':
+ specifier: workspace:^
+ version: link:../../support/invariants
+ '@deepseek-ai/dsh-llm':
+ specifier: workspace:^
+ version: link:../../llm/llm
+ '@deepseek-ai/dsh-session':
+ specifier: workspace:^
+ version: link:../../core/session
+ '@deepseek-ai/dsh-subagent':
+ specifier: workspace:^
+ version: link:../../subagent/subagent
+ '@deepseek-ai/dsh-subagent-inprocess':
+ specifier: workspace:^
+ version: link:../../subagent/subagent-inprocess
+ '@deepseek-ai/dsh-subagent-spawn':
+ specifier: workspace:^
+ version: link:../../subagent/subagent-spawn
+ '@deepseek-ai/dsh-system-prompt':
+ specifier: workspace:^
+ version: link:../../core/system-prompt
+ '@deepseek-ai/dsh-tools':
+ specifier: workspace:^
+ version: link:../../core/tools
+ '@deepseek-ai/dsh-workflow':
+ specifier: workspace:^
+ version: link:../workflow
+ '@deepseek-ai/dsh-workflow-workerthread':
+ specifier: workspace:^
+ version: link:../workflow-workerthread
+ cordis:
+ specifier: ^4.0.0-rc.7
+ version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader)
+
packages/workflow/tool-workflow:
dependencies:
schemastery:
diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts
index bec93c790a..d271192516 100644
--- a/scripts/gen-doc-graphs.ts
+++ b/scripts/gen-doc-graphs.ts
@@ -262,8 +262,8 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'Subagent provider registry',
mode: 'seam',
implementations: ['subagent-spawn', 'subagent-fork', 'subagent-acp'],
- consumers: ['tool-subagent'],
- note: 'Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name.',
+ consumers: ['tool-subagent', 'tool-ralph'],
+ note: 'Providers implement transports; tool-subagent exposes configured delegation while tool-ralph requires one fresh structured-output route.',
},
{
key: 'tasks',
@@ -297,8 +297,8 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'Workflow script engine',
mode: 'seam',
implementations: ['workflow-workerthread'],
- consumers: ['tool-workflow'],
- note: 'One engine per context (bash shape, no named-provider registry); the worker-thread engine fans agent() calls out through ctx.subagents.',
+ consumers: ['tool-workflow', 'tool-ralph'],
+ note: 'One engine per context (bash shape, no named-provider registry); the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents.',
},
]
diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts
index 1921dbf27c..c1fe87eb04 100644
--- a/scripts/gen-tool-catalog.ts
+++ b/scripts/gen-tool-catalog.ts
@@ -37,6 +37,7 @@ import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
import VmWorkflowEngine from '@deepseek-ai/dsh-workflow-workerthread'
+import * as ToolRalph from '@deepseek-ai/dsh-tool-ralph'
import * as ToolWorkflow from '@deepseek-ai/dsh-tool-workflow'
const root = resolve(import.meta.dirname, '..')
@@ -46,7 +47,7 @@ const OUT = 'docs/tool-catalog.md'
function registerCatalogSubagentProvider(ctx: Context, name: string): void {
const provider: SubagentProvider = {
name,
- capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
+ capabilities: { outputSchema: true, depthLimit: false, toolFilter: false, persona: false },
inheritsParentContext: false,
start: () => Promise.reject(new Error('tool-catalog provider cannot start a child')),
}
@@ -195,6 +196,21 @@ const TOOL_PACKAGES: ToolPackage[] = [
note:
'create, edit, pause, and resume require direct-human root authority; complete and blocked also accept the exact current goal round. The default blocked lower bound is three admitted rounds.',
},
+ {
+ pkg: '@deepseek-ai/dsh-tool-ralph',
+ dir: 'tool-ralph',
+ source: 'packages/workflow/tool-ralph/src/index.ts',
+ requires: ['ctx.tools', 'ctx.workflows', 'ctx.subagents', 'ctx.systemPrompt', 'a calling Agent (exec.agent parents every fresh round)'],
+ writes: ['tool/call', 'tool/result', 'workflow and child session events during execution'],
+ async mount(ctx) {
+ await ctx.plugin(SubagentService)
+ registerCatalogSubagentProvider(ctx, 'mock')
+ await ctx.plugin(VmWorkflowEngine, { provider: 'mock' })
+ await ctx.plugin(ToolRalph, { subagentProvider: 'mock' })
+ },
+ note:
+ 'A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap.',
+ },
{
pkg: '@deepseek-ai/dsh-tool-skill',
dir: 'tool-skill',
diff --git a/tsconfig.json b/tsconfig.json
index 085c533130..cfda7192e7 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -106,6 +106,7 @@
{ "path": "./packages/workflow/workflow" },
{ "path": "./packages/workflow/workflow-workerthread" },
{ "path": "./packages/workflow/tool-workflow" },
+ { "path": "./packages/workflow/tool-ralph" },
{ "path": "./packages/todo/tool-todo" },
{ "path": "./packages/guard/repeat-tool-guard" },
{ "path": "./packages/cordis/tool-cordis" },