npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jayyuen66/dsh-session-rescue

v0.1.19

Published

Session rescue for dsh web: auto-resume on transient model failures, max-tokens continuation and unclosed-todo catch-up (host), plus edit-resend / retry / queue-withdraw / stop-and-reask / settings card (client).

Downloads

3,967

Readme

A dsh plugin: three automatic user-role injections when a turn ends badly (transient failure / max-tokens truncation / an open todo list), a request-level last-resort rate-limit retry, and a client dock with manual recovery actions and a settings card. Zero model tools, zero HTTP routes of its own.

Contents

What it does

  • Three automatic injections when a turn ends badly, each with its own delay / cooldown / quota gates (lib/resume-scheduler.ts, cooldowns tracked per kind):
    • resume — agent/error whose failure classifyFailure (lib/failure-classify.ts) judges transient; the message lands after resumeDelayMs.
    • continue — the turn ended with reason.kind === "max-tokens"; "continue from the truncation" lands after continueDelayMs.
    • unfinished — the turn ended completed, but the todo list that turn itself wrote still holds open items (lib/turn-review.ts, a purely structural signal, no text guessing); the catch-up message lands after unfinishedDelayMs.
    • Every injection is a role: "user" message with source: { kind: "plugin:session-rescue" } sent through agent.followup() — the model keeps running, so tokens and quota keep being spent.
  • A request-level last-resort rate-limit retry: it listens on agent/request-error (waterfall) and asks downstream first, taking over only when nobody answers (the same shape as the official llm-retry's always mode). A retry decision coming back from downstream — failures the official policy is willing to retry — is adopted verbatim; only when downstream passes (failure code outside the policy's code table — the default table excludes QUOTA — retries exhausted, Retry-After above the policy ceiling) does this plugin return { kind: "retry" }, so the host re-sends that request inside the same turn. On a profile without dsh-llm-retry mounted, this ladder is the only request-level recovery for rate limiting.
    • Fixed backoff ladder (defaults 2 s / 5 s / 10 s / 20 s / 30 s, at most requestRetryMax retries per turn cycle — deployment values); a provider Retry-After wins over the ladder, and anything above the cap (default 30 s) is not waited out — the request settles terminally. The counter resets when the turn closes.
    • "Did the host resolve a retryPolicy" cannot be the dividing line: the llm registry backstops unconfigured providers with a default policy, so that condition is always true. The real division of labor is the downstream waterfall decision itself.
  • Two manual recovery surfaces: a per-turn action row on conversation.chat.turnTail (the same stack as first-party deliverables / plan / schedule) carries edit-resend (this session) / fork-resend (new branch) / manual retry / send-continue, plus a manual-only "resume interrupted turn" button where the host's crash repair appended an interrupted closer to an orphaned turn; the dock above the input box keeps only the session-level trio — the countdown banner / stop-and-reask / a per-session switch. Stop-and-reask prefers the host-side reask Remote method: after cancel(keepInbox) it uses agent.inbox.prepend to put the re-ask at the front of next-turn, then wakes the driver with a wake-only message that is removed immediately — strict priority, without the client prompt's queue/steer limitation. When the host read surface is unavailable it falls back to the client path: cancel first, then queue (the reverse order leaves the message parked), wait for the session to reach idle (2 s cap), use steer when idle and queue on timeout. Both paths still queue the re-ask when the cancel is rejected and show a neutral "stopping the turn failed" notice in the dock; a requestId is reused across retries after an ambiguous failure, deduplicated on both the client and the host. You can edit the re-ask text first (prefilled with your last message); while the host's built-in retry is in progress the retry button is hidden entirely — the composer primary button is already "Continue generating" at that moment.
  • Rescue-exhausted escalation: quota exhaustion is no longer log-only — a frame-wide floating toast names the exhausted kind once, and clears itself once a turn completes normally (or the todo list closes for catch-up); a later exhaustion reports again.
  • Optional steer continuation (off by default): when enabled on the settings card, a turn about to close while the todo list it wrote itself still has open items is continued in the same turn via agent.steer instead of being closed and re-run; it shares the maxUnfinished quota with catch-up, so the anti-runaway semantics are one track.
  • Connection-aware: an injection whose send failed (transport trouble) is suspended instead of dropped, shown as a reconnecting banner, and re-armed with its remaining delay once the connection returns.
  • /state polling is a self-scheduling two-tier loop: 1 s while a pending exists (the banner counts down by the second), 5 s otherwise; the next hop is armed only after the current one lands, so an in-flight request neither overlaps nor strands the loop. After three consecutive unreadable polls the cached snapshot is discarded — the banner and the per-session switch fall back to their neutral state instead of counting down from a value nobody confirmed — and polling backs off by doubling up to 30 s.
  • A settings card with the recovery knobs in this package's session-rescue namespace, plus per-provider retry presets and a custom code editor written into the official llm-pi-ai dictionary or the provider row's own namespace; preset selection saves in a batch, while "Save codes" replaces only that provider's retryableCodes (mode/count/backoff stay as they are).
  • Host read surface: agent/error, agent/status, agent/request-error, agent/disposed (cleanup). Turn facts (turn/start, turn/end, user/message, tool/call, todo/write) fold incrementally through ctx.sessionProjections; on profiles without that registry, or on shapes the fold cannot vouch for, it falls back to sessionQuery.observeSession(sessionId, { projectionMode: "none" }) for one immutable event snapshot with identical verdicts.

How a decision is made

  • Classification (classifyFailure) is a fixed ladder. Permanent failure codes veto first (CONTEXT_WINDOW_EXCEEDED / AUTH / INVALID_CREDENTIAL / MISSING_CREDENTIAL / INVALID_REQUEST / INVALID_ARGS / NO_ADAPTER / INVALID_MODEL_CONTEXT / INVALID_PREPARED_CALL). The QUOTA code is then split by evidence: HTTP 429, Retry-After or rate-limit wording means transient; balance-exhausted wording means permanent. HTTP 401/403 and billing status 402 are permanent; the explicit transient codes (RATE_LIMIT / SERVER / TIMEOUT / TRANSPORT / EMPTY_RESPONSE / INVALID_TOOL_ARGUMENTS), HTTP 408/425/429/5xx and rate-limit wording are transient; PI_AI_ERROR with an unrecognized finish_reason or empty-response wording is transient. Everything unrecognized is permanent — conservative by design.
    • An error without a .failure face counts the same as permanent; the classifier unwraps host-wrapped AggregateError before giving up.
    • Classification is built-in safety logic; the card deliberately exposes no way to change it.
  • Standing down: non-root (subagent) sessions; providerExcludes hits resume only; the last turn/end says aborted (a user/parent/hook cancel — you stopped it, nothing is injected, no quota spent) or interrupted (a closing marker the host's crash repair writes for an orphaned turn, appended by the agent-loop resume path and never emitted live — state after a crash is unknown, so nothing is auto-injected either); the turn called ask_user_question (no catch-up); the turn was opened by the official Schedule reminder (all three kinds stand down).
    • A "goal" turn is decided at fire time from the official goal service, not unconditionally: active + armed (the driver is still driving) → stand down; active + disarmed (the driver gave up — by its own design it never auto-retries) → this plugin takes the round over; paused / blocked / complete are human or lifecycle decisions and are never overridden; an unreadable goal state stands down too.
  • Pre-fire check (preFireCheck): the agent is gone, the status is not idle, the inbox holds queued messages, or a newer turn already started → the pending injection is silently voided, without counting or entering cooldown.
  • Quota is consecutive: one completed turn zeroes resume / continue; unfinished only refills once the todo list closes (otherwise inject → still open → inject again would self-oscillate).

Install

dsh plugin --profile web add @jayyuen66/dsh-session-rescue

Remove with dsh plugin --profile web remove @jayyuen66/dsh-session-rescue. The package is on the public npm registry, so installation needs no credentials and no scoped-registry line.

  • Requires Node.js ^24.22.3 || >=26.13.1. This is an ESM-only package; engines.node follows the host floor, so an installer rejects a Node the host itself will not start on.
  • Requires host dsh at the 0.2.3-alpha.3 line or later. The requirement the host reads is engines.dsh (^0.2.3-alpha.3), and it decides alone: once that branch answers, peerDependencies is not consulted. Prereleases take part in the range comparison (the host calls it with includePrerelease: true). The @deepseek-ai/dsh-* peers carry the same window; the exact devDependencies pins are the compile-time discipline, not an install gate. The support window rolls: this package is verified against every released host version inside the window at publish time and re-verified once the window moves, so the version number in this bullet is not a standing promise.
  • No @deepseek-ai/* under dependencies, by contract (test/publish-manifest.test.ts enforces it). Consumer profiles install with nodeLinker: hoisted and autoInstallPeers: false, so a host package under dependencies is materialized as a real directory next to the copy the running host already loaded — native tool calls then throw while build, typecheck and coverage stay green. The host packages host.js imports for value (@deepseek-ai/dsh-brand, @deepseek-ai/dsh-typert-protocol, @deepseek-ai/schemastery) are required peers repeated under devDependencies at the same pin, so the bundler externalizes them instead of inlining official function bodies.
  • What ships: the prepare-rebuilt host.js and client.js, cordis.patch.yml, plus README*, LICENSE, CHANGELOG.md and icon.svg. Artifacts are not committed. The client bundle is minified; externalization is asserted structurally from the chunk's module list, not from readable function names.
  • Install fails with 404: that version was never published (check dist-tags.latest). It usually means the sibling library package @jayyuen66/dsh-plugin-shared is not on the registry yet — host.js value-imports its internal/tool/* modules (errors, instance-lock, lesson-bus, locale, record, remote-marker and session-projection), and client.js value-imports client, so a missing one surfaces as ERR_MODULE_NOT_FOUND.

Shared version floor

If your profile pins @jayyuen66/dsh-plugin-shared with a pnpm overrides entry, that pin must be at least the version this package declares. A lower pin installs a copy without the names imported at runtime, and the host then reports N entries did not activate together with does not provide an export named ... at boot — the package installs fine and never loads, and no per-repository CI run can see it.

Bundle order decides it too: from alpha.3 on, when several bundles insert the same dsh-plugin-shared row, the first bundle in dsh.profile.bundles that declares the dependency decides which copy loads. Keep that copy at or above the version this package declares, and upgrade mixed old/new plugin sets together. From this release on, the client stylesheets (meta.stylesheets) and ProgressBar require shared 0.3.2 or later; the ^0.3.1 range only keeps older plugins compatible, so treat 0.3.2 as the effective floor for releases and single-repository CI.

Verify it is live

  1. Mounted: dsh --profile web --dump-config shows this package's layer.
    • That command is the only accepted "it is in the layer stack" signal, and it is not read-only — it rewrites the profile's root assembly file. Read layer lines from stdout and check stderr separately: an unmatched patch target appears only on stderr, so the exit code alone proves nothing.
    • A layer line may read # == <layer> or # == <layer>, patched by <path>; accept both forms.
  2. Both surfaces render: with a session open, the recovery dock sits above the input box — the per-session switch row and stop-and-reask while a turn is running; the latest completed turn (failed / truncated / crash-interrupted) carries the action row at its tail — edit-resend / fork-resend / retry / send-continue.
  3. The settings card renders live data: the plugin page lists the session-rescue card, and its provider retry section loads your configurable providers (llm-pi-ai dictionary and alpha.3 provider rows; name, retry mode, quota coverage, current code list); the code list can be edited and saved separately. A permanently "unavailable" readout means the layer is mounted but the Remote namespace did not reach the browser.
  4. A live rescue: make the model call fail transiently mid-turn (for example by cutting the network); the banner appears and counts down by the second, and the log carries [session-rescue] lines naming the kind and the gate. Counter-check: a turn you stop yourself (aborted) injects nothing, by design — "no injection" there is not a broken install.

What it does not provide

  • It registers no model tools. The surface is host events plus the Remote namespace; there is no session_rescue tool for the model to call.
  • It opens no HTTP route of its own. The data plane is the official Typert Remote namespace sessionRescue, reached through the host /api gateway; authentication, Host / DNS-rebinding / Origin checks and body limits are all the gateway's.
  • It adds no CLI subcommand.
  • It renders no queued-message UI of its own: the official conversation package already docks the queue with per-item edit / delete / interject, and this package does not duplicate it.
  • The host half writes no file and makes no outbound request (see Data and privacy).
  • What it does consume optionally: the lessonLoop bus (facts and passes), sessionProjections (fast turn facts) and the goal service (fire-time takeover verdict). A profile without them keeps rescuing — it just falls back to the full log scan, and goal turns are left alone.

Enabling it in dsh

  • Bundle form: dsh.bundle.patch in package.json points at cordis.patch.yml, a list of operations whose insert: block carries a - id: dsh-plugin-shared supplier row (keep it enabled; disabling it removes the cards' shared component supply) plus the - id: session-rescue entry with name: "@jayyuen66/dsh-session-rescue" — the host scans dsh.client on bare-name entries only. The card components come from the shared client row, externalized as @jayyuen66/dsh-plugin-shared/client; the host module table provides react, zod and that shared row. dsh plugin add/remove maintains the assembly layer.
  • The host half hard-depends on timer and settings (inject: ["timer", "settings"]); the read surface is registered through an injected child fiber into the host remote gateway. It does not depend on webServer, so a host without that service (TUI) keeps auto-recovery working and only loses the settings card's data plane.
  • The settings card lives in plugins.bundle.config on the plugin page, keyed by the bundle package name; configForms.get() and the settings namespace stay the bare entry id session-rescue. Edits are staged, Save writes them into settings, Revert discards.
  • Without UI, deployment defaults go on the registration line's config:; precedence = card runtime value > line config > schema .default(), and an invalid config fails the plugin load loudly.

The three automatic actions

| Kind | Trigger | Default delay / cooldown / quota | |---|---|---| | resume | agent/error, failure classified transient (lib/failure-classify.ts) | 10 s / 120 s / 3 | | continue | Turn ended max-tokens (output truncated) | 3 s / 60 s / 3 | | unfinished | Turn ended completed, its own todo list still open (lib/turn-review.ts) | 5 s / 120 s / 2 |

  • resumeOnOpenTodos is the catch-up kind's own switch; providerExcludes gates resume only and touches neither of the other kinds nor the request-level 429 retry.
  • A resume-opened turn that fails again transiently bypasses the cooldown and re-schedules at chainResumeDelayMs (default 60 s): resumeDelayMs plus failure time always sits inside the 120 s cooldown, so without this exception a failing chain would be silently swallowed.
  • The injected text comes from the fixed bilingual templates in lib/messages.ts and follows the official locale preference (Chinese when that entry is not projected); no session content is interpolated.

Settings

Settings live on the session-rescue card. Namespace session-rescue is the entry id (implicit registration); the form and line config share one Config schema. The card shows seconds and stores milliseconds. Its thirteen hinted fields are the reference for ranges and effects; this README does not keep a second field list.

enabled is the one visible field without an inline hint. It defaults to on; turning it off stops all three injections and the request-level 429 retry while keeping the manual dock. Default gates are resume 10 s / 120 s / 3, continue 3 s / 60 s / 3, and unfinished 5 s / 120 s / 2. chainResumeDelayMs defaults to 60 s, resumeOnOpenTodos is on, unfinishedSteerMode is off, and providerExcludes is empty. Card values are read per decision, so saving them needs no restart.

providerExcludes matches provider strings exactly and case-sensitively, and gates resume only. The provider retry section's selectors have section-level help; custom retry-code fields have their own hints. Presets are default / enhanced / always / off / custom; preset changes save in a batch, while Save codes replaces only retryableCodes. Request-level retry asks downstream first and takes only what downstream passes. Failure classification remains fixed and conservative, quotas remain consecutive, and the stand-down and pre-fire vetoes described above still apply.

The three requestRetry* rows are deployment values, not .volatile() card controls. Set plain values in the registration line's config: block; they apply on restart.

| Field | Type / range | Default | Purpose | |---|---|---|---| | requestRetryMax | 0–20 | 5 | Request-level 429 retry cap | | requestRetryBackoffMs | non-empty number[] | [2000, 5000, 10000, 20000, 30000] | Backoff ladder; the configured array replaces the default as a whole | | requestRetryBackoffCapMs | ≥ 1000 ms | 30000 | Longest wait this plugin will take; a longer Retry-After settles terminally |

Public interface

Seven methods on the official Typert Remote namespace sessionRescue. Parameters go through strict codecs; results use src-json.

| Method | Input | Reply | |---|---|---| | state | — | ok plus a per-session snapshot: pending kind, remaining-ms countdown, chained / suspended flags, fire counters, the per-session switch | | cancel | { sessionId } | Cancels that session's pending injection, suspended ones included | | toggle | { sessionId } | Flips the per-session switch; switching off also cancels pendings. 409 when the toggle ledger is full with no dead session to evict | | resume | — | Restores suspended injections after a reconnect; ok plus the restored count | | reask | { sessionId, text, requestId } | Host-side stop-and-reask: cancel(keepInbox), prepend the re-ask to the front of next-turn, then wake the driver; retries carrying the same requestId answer duplicate without re-queuing | | retryProviders | — | Configurable providers with retry mode / count / quota coverage / current code list — the official llm-pi-ai dictionary plus alpha.3 provider rows; 503 when neither settings surface is readable | | retryPolicy | { provider, preset, retryableCodes? } | Writes providers.<name>.retryPolicy for a dictionary provider, or the row's root retryPolicy for a provider row (presets default / enhanced / always / off / custom) via settings.mutate; enhanced keeps the current code list, custom replaces only retryableCodes; a revision conflict answers 409 |

  • A refusal's status is a retained semantic code, not an HTTP status of a route of this package — there are no routes.
  • Model-visible artifacts: the automatic continuation, one role: "user" message through agent.followup() (id like session-rescue-<timestamp>-<seq>, text from the fixed templates), plus the user message you submit through stop-and-reask. This package keeps no second retry configuration of its own.
  • Optional lessonLoop bus: when present it receives the transient-failure, unclassified-failure, max-tokens and unfinished-turn facts, and one pass once the same provider genuinely finishes a completed turn. An absent or throwing bus only warns; the main path never depends on it.

Data and privacy

| Aspect | Content | |---|---| | Nothing written, nothing fetched | The host half uses no node:fs and makes no network calls; apart from the exit path below, the only output surfaces are console.* lines and the injected message | | In memory, bounded | At most 200 session records in the scheduler, 64 suspended pendings and 64 pending-pass entries; those three trim the oldest first. The per-session toggle ledger also holds 200 entries, but when full it evicts only sessions with no live agent, and toggle returns 409 if none can be evicted — a live session's off-switch is never dropped, which would silently re-enable its recovery. Timers are released on agent/disposed and on plugin unload | | Persisted, exactly two places, both through official settings | This namespace session-rescue and the llm-pi-ai retry presets, stored under the dsh data directory and surviving restarts | | Per-session switch | Process memory only; a restart falls back to the global enabled | | Language | The injected text follows the official locale preference; Chinese when that entry is not projected | | The only exit path | Content leaves only towards lesson-loop, and only when it is installed: it receives the failure code / status / message verbatim, the session id and the session's cwd, and lesson-loop alone decides where that is written. Without it nothing is recorded |

Known boundaries

  • Unknown failure shapes are permanent, by design. Everything the classifier cannot recognize is left alone; the card exposes no override. A mis-guessed "transient" would re-open turns that can never succeed.
  • providerExcludes gates resume only — continue, unfinished and the request-level 429 retry do not consult it.
  • Subagent sessions are never touched — only root sessions are rescued.
  • The catch-up kind has a structural precondition: the turn must have written a todo/write list that still holds pending or in_progress items. Sessions that never use the todo tool cannot trigger it.
  • The request-level ladder is the "last resort", not a "no-policy-provider" tool: the llm registry backstops unconfigured providers with a default policy, so dividing by "has a policy" would delegate forever. The current contract asks downstream first — failures the official llm-retry accepts (inside the code table, retries left) belong to it, and this plugin takes only what it passes (outside the table such as QUOTA, retries exhausted, Retry-After over the ceiling).
  • The official llm-retry is not always downstream: while its abort signal is fired or its entry is disposed it returns without delegating — in those windows this plugin's adoption step simply observes that it declined to participate; in always mode it asks downstream before retrying, so the two decisions do not collide.
  • While the read surface stays unreachable the dock degrades instead of pretending: the banner and the per-session switch fall back to neutral and polling backs off. The turn-relative actions keep working — they read live session state, not the read surface.

FAQ

| Question | Answer | |---|---| | Does it silently spend money? | Yes. The injections are user-role messages, so the model continues and keeps consuming tokens and quota. | | I want one switch off. | The card's master switch (enabled = false) stops all three injections and the request-level 429 retry while keeping the manual UI. | | Narrower exits? | The dock's per-session switch, resumeOnOpenTodos (catch-up only), providerExcludes (resume on one provider only). | | The model stopped but nothing resumed. | Look for [session-rescue] <sid>: auto-<kind> skipped (pending/cooldown/max-resumes) or vetoed at fire time (<reason>) in the log. Quota is consecutive — one finished turn refills it. | | Will it interrupt a question aimed at me? | No. Nothing is injected after ask_user_question, and a goal round is only taken over once the official driver has disarmed for it. | | The catch-up never fires. | It requires that turn to have written a todo list that still holds open items — sessions that never use the todo tool structurally cannot trigger it. | | The banner counts down but nothing happens. | The pre-fire check voided it (agent gone, status not idle, queued inbox messages, or a newer turn) — check the vetoed at fire time log line. |

Development

pnpm install
pnpm run check   # typecheck → lint → client build → host build → types → tests → integration → property → format
  • Unit tests (hand-written host stubs) drive the pure chains: failure classification, scheduler gates, turn-facts fold, dock payload parse.
  • test/integration/ drives the real thing: the published artifact booted through the real cordis loader; a real AgentLoop with the official testkit; a real goal round with the official goal-round-driver and a scripted failing mock LLM; abort semantics (a turn you stopped consumes no quota).
  • test/property/ (fast-check) covers the classification order, the turn-facts fold, the /state payload parse, and the scheduler's state-machine invariants under random command sequences — each property carries a reach guard, so a criterion that was never exercised turns red instead of green.
  • Coverage thresholds are 100% across four metrics, so a new branch needs a case that reaches it.
  • test/publish-manifest.test.ts guards the published shape: entry targets shipped, no source entry, no @deepseek-ai/* under dependencies, dsh-* devDependencies pinned exactly and all on one version, @deepseek-ai/dsh* peers carrying the same support-window range as engines.dsh, and no dates or machine paths in comments or docs. test/dist-size.test.ts holds a size budget over the artifacts.

Feedback

Issues and pull requests are welcome: https://github.com/JayYuen666/dsh-session-rescue/issues.

If a plugin fails to boot, include the dsh host version, the profile install shape, and the browser console line. The missed the module table line is especially useful: it tells us whether the shared client row was materialized.

License

MIT. Source at github.com/JayYuen666/dsh-session-rescue. Issues go to that repository's tracker.