Jaylor-Wang/dsh-agent-loop-experiment ↗★ 1

dsh-agent-loop-experiment

Isolated convergence-policy experiments around the unchanged official DSH agent loop.

Package
dsh-agent-loop-experiment
Compatibility
Unverified
Harness peer range
0.2.2-rc.1
Cordis peer range
~4.1.0
Version
0.2.2-rc.1
License
MIT
Last updated
Nov 5, 2026

Install

$npx -p @deepseek-ai/dsh dsh plugin --profile web add github:Jaylor-Wang/dsh-agent-loop-experiment

dsh-agent-loop-experiment

Controllable Convergence Policy & Agent Loop Replacement for DeepSeek Harness (DSH)
Isolated convergence policies (runtime fingerprinting, finite recovery, file mutation guards, soft tool requirements) around the unchanged official DSH agent loop.

License: MIT GitHub release DeepSeek Harness Compatibility Tests TypeScript

English | 中文

This package is an isolated convergence-policy experiment and drop-in replacement bundle for @deepseek-ai/dsh-agent-loop. See EXPERIMENT.md for setup, runtime convergence policies, and A/B commands. The official loop implementation remains byte-identical; upstream documentation follows below.

Summary

dsh-agent-loop creates fresh agents or resumes persisted sessions, then drives each turn through model requests, streamed responses, tool execution, and durable session history. Mount it for standard agent compositions; declarative entries start agents at boot, while the public ctx.agents API supports programmatic creation and resume. The selected tool executor owns dispatch, concurrency, cancellation, and tool logging. Cancellation preserves streamed text already delivered to the user. Choose a custom Agent implementation only when the standard "call model, run tools, repeat" lifecycle is insufficient.

Table of Contents


Use this package

Mount dsh-agent-loop in any composition that should run agents. It supplies the driver behind ctx.agents and starts any agents you declare in its config; both dsh-base and dsh-sdk-minimal mount it as an explicit row.

Configure declarative agents

Agents declared in config start automatically when the plugin loads. Each entry needs an id label; a model step also needs both provider and model in the Session selection or initial options before prompt assembly.

- name: '@deepseek-ai/dsh-agent-loop'
  config:
    agents:
      - id: 'main'
        provider: deepseek
        model: deepseek-chat
        reasoningEffort: high
        cwd: /workspace
FieldDefaultMeaning
agents[].idrequiredStable label; a fresh session mints ${id}-session- unless sessionId is set
agents[].provider / agents[].model—Model route; both required before step preparation
agents[].reasoningEffort—Non-empty initial reasoning effort; later choices are recorded in the Session
agents[].maxTokens—Positive per-request output-token cap
agents[].cwd—Workspace directory for a fresh session
agents[].sessionId—Exact identity: first use creates, a remount resumes materialized history
agents[].resumeSessionId—Load this persisted session instead of creating one; mutually exclusive with sessionId

The generated configuration catalog lists every accepted field. maxParallelToolCalls remains a volatile positive-integer Config field with default 10; 1 selects serial execution. The loop passes its current value to each batch's execute() call, taking precedence over executor configuration. Live edits apply to the next batch; agents remains startup configuration.

A configured resume records the declared route as the Session selection before publication. Programmatic resume preserves the Session choice unless its setup explicitly records another route; initial agentOptions alone do not override saved history.

Create or resume agents programmatically

Plugins and hosts create agents through ctx.agents.create() and resume persisted sessions through ctx.agents.resume(); both return an AgentHandle whose dispose() owns exact teardown. The loop runs each created agent to completion — the handle is only needed when the caller must tear the agent down itself.

const handle = await ctx.agents.create({
  sessionId,
  agentOptions: { provider: 'deepseek', model: 'deepseek-chat' },
  setup: (agentCtx, agent) => { /* scoped registrations plus explicit unpublished Agent */ },
})

Every inbox mutation commits one normalized agent/inbox/spliced event. The projection registry folds that event synchronously, so the live projection reflects the splice when Session.append() returns. Insertions, edits, removals, claiming, and cancellation replay through the same standard splice coordinates. Ordinary removals carry outcome: 'canceled' and emit agent/inbox/discarded { message }; claiming uses pure deletions with no outcome and emits agent/inbox/claimed. Every insertion emits agent/inbox/inserted { message }. MessageId stays unique across both pending lists. Consumers that need a removed message use the claimed or discarded notification instead of depending on a pre-splice session/event view.

What a step does

Each step sends the session's derived history — with the latest non-empty system/message node as the effective prompt, or no system messages when the rendered prompt is empty — and its visible tool schemas; the model's tool calls run through the guarded tool pipeline and every accepted fact is appended to the session log before the next step derives from it. The loop passes the complete raw call batch to ctx.tools.execute(); built-in executors preserve model-order results and exclusive barriers. Cancellation is cooperative: agent.cancel() aborts the current activity and, unless keepInbox is set, clears pending work; a cancelled stream finalizes the text already delivered to the user.


Understand the implementation

Implementation internals — click to expand

This section explains how the package realizes the behavior above; the observable contract is covered in Use this package.

Design concept

The package is the one concrete implementation of the public Agent contract. It registers itself as the AgentFactory on ctx.agents, so consumers never import this package; ownership of each created agent lives with the caller fiber and the loop provider, converging on one memoized quiescence boundary. Every observable effect happens through session events and the agent/* taxonomy — package internals are never part of the public surface.

Request headers and adapter defaults

Before prompt assembly, the loop calls agent.model.current() and captures provider, model, and optional explicit reasoning effort for the step and its retries. AssembleContext.modelSelection and agent/pre-step.modelSelection carry that selection; prompt variables use its route, and omitted effort uses adapter defaults. The deprecated agent/request hook remains available to existing listeners and may replace other controls such as sampling. Changing provider or model, or adding, changing, or clearing reasoning effort rejects the step before input is committed. A later recorded choice applies to the next step, including a tool continuation in the same turn.

After agent/request, ctx.llm.prepareCall() validates adapter-owned fields and resolves reasoning-effort and output-token defaults under the active turn signal. The loop retains that exact adapter through resolution, request/header logging, and dispatch. It writes a full header for the first request, a changed envelope (config or tools — the prompt is not part of the header), an explicit message-series start, a request after a surface replacement or image-offload decision, and resume; unchanged steps, retries, and ordinary later turns in the same series inherit the latest header, and an in-history prompt append is not a replacement, so the request that follows it inherits the header too. Beside the header, the loop logs request/context — provider, model, contextWindow, and the route's systemPromptUpdate mode from prepareCall() — only when one of those differs from the latest snapshot. Before the next waterfall, the loop removes adapter-default fields so the current route resolves them again, while explicit settings persist. An unhandled route still fails with NO_ADAPTER.

The loop deep-freezes each derived message identity on its first request and reuses that proof only within the same agent. Restored messages keep their identity; request construction does not freeze their containing event wrappers. Each request freezes its local canonical header, fresh message array, and envelope while leaving the cancellation signal live. The archived request-freeze decision explains ownership and measurement.

Source map

FileRole
src/index.tsPlugin entry: AgentLoop service, config schema, declarative agent startup, factory registration
src/agent.tsThe concrete ReactLoopAgent driver: inbox, turn/step machine, cancellation
src/inbox.tsPackage-internal ReactLoopInbox: durable projection, structural commands, and loop-only claim state
src/runtime-context.tsPer-step runtime-context snapshot handling

Creation and teardown

Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete session/created; await optional setup and its commit; enter the AgentRegistry; await serial agent/created listeners; then release queued input. A caller creating a runtime child sets options.parentAgent; the caller Context separately owns the transaction and live handle. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits session/disposed, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement.

The loop awaits its required registrations before publishing its factory. It calls readerFor(session) on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown.

Persistence integration

The loop is the production acquisition point for session write handles. When ctx.sessionPersistence is mounted, create/createAgent call persistence.create(header) — storing the durable identity and taking write ownership before publication — and append the constructor seed through the handle; resume calls persistence.open(id, 'write') first (excluding a concurrent resume of the same id), reads the physically valid log through the handle, and appends interruptedTurnClosers for a log crashed mid-turn as an ordinary batch — semantic crash repair is the agent layer's job, not a storage entry point. Before store entry, appendUnstoredSuffix stores constructor history, including seed markers. Setup then appends through the live event feed. From store entry onward, the mounted backend routes the session's session/event batches, session/flush barriers, and session/disposed retirement into the active write handle by session id; the loop touches storage only through the handle it owns. With the backend still mounted, teardown closes the handle after the driver commits its closing events; close drains the routed buffer and releases write ownership. Without a backend, sessions are memory-only and nothing else changes.

Turn and step flow

The driver owns one agent for its lifetime and runs inside ctx.agents.withInitiator(agent, ...). AgentLoop registers the standard inbox projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. It also owns modelSelection and constructs an AgentModel for each Agent, with the public Model API. Its package-internal ReactLoopInbox uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver assembles the prompt and tools and runs agent/pre-step; the fallback projects runtime context after listeners run. A rejected decision or empty first batch opens no step. On the first attempt after acceptance, step/start precedes the agent/request waterfall and prepareCall(); neither async phase sees the pending system prompt or accepted users committed to history, and cancellation during either commits neither. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving system/message nodes using the prepared call capability, refreshes registered runtime facts without reassembling the bound prompt or tools, appends the accepted user/message batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the same rendered assembly without repeating assembly, agent/pre-step, or user admission. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is header.config, deriveMessages(), and header.tools; it carries no system field. Each model attempt emits one process-local start, emits every chunk only after the matching durable assistant-frame settlement, and emits exactly one terminal end; final assembly or message-append failure settles it as aborted, while committed follows the durable assistant/message. Each successful model call appends one message anchor, and a cancelled stream appends an interrupted: true anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars)