fix: fold session fork into session store
This commit is contained in:
@@ -30,7 +30,6 @@ The default distribution is a composition, not a hierarchy. `packages/core/` is
|
||||
| `ctx.web` | [`web/`](../packages/web/README.md) | search/fetch provider registries |
|
||||
| `ctx.compact` | [`compact/`](../packages/compact/README.md) | session-surface compaction |
|
||||
| `ctx.subagents` | [`subagent/`](../packages/subagent/README.md) | named delegation providers |
|
||||
| `ctx.sessionFork` | [`session-fork/`](../packages/session-fork/README.md) | live-session fork boundary validation and seed snapshots |
|
||||
| `ctx.sessionPersistence` | [`session-persistence/`](../packages/session-persistence/README.md) | durable storage for session logs |
|
||||
|
||||
## Event Surface
|
||||
@@ -109,7 +108,7 @@ Every session event is turn-enclosed. Reloading a crashed session preserves the
|
||||
|
||||
The session log is the source of truth. `deriveMessages()` projects session events into the `Message[]` sent to the model; raw `assistant/chunk` events stay in the log for replay and UI fidelity. Replay, fork, resume, transcript rendering, telemetry, and persistence all derive from the same event stream.
|
||||
|
||||
The low-level fork primitive is `ctx.sessions.create(id, { seed, meta })`. The optional `ctx.sessionFork` service owns live-session fork policy: it validates that a source session is empty or at a turn boundary, snapshots the seed, and creates child metadata without changing the core log.
|
||||
The low-level fork primitive is `ctx.sessions.create(id, { seed, meta })`. The session store also exposes `ctx.sessions.snapshot(source)` and `ctx.sessions.fork({ source, sessionId? })` for ordinary live-session forks: they validate that a source session is empty or at a turn boundary, snapshot the seed, and create child metadata without changing the core log.
|
||||
|
||||
Durability is a plugin concern. Persistence backends buffer synchronous `session/event` notifications and the loop awaits a turn-end checkpoint before moving on. The `SessionPersistence` seam stores `SessionEvent` directly, with metadata in `SessionHeader`; JSONL and SQLite share one contract suite.
|
||||
|
||||
@@ -125,7 +124,7 @@ Streaming is a raw chunk protocol (`block-start` through `finish`) with `BlockAs
|
||||
|
||||
A swappable capability usually splits into **interface / implementation / consumer**: the interface owns the `ctx` key and vocabulary; an implementation registers a backend; a consumer exposes model-facing behavior through `ctx.tools` or prompt assembly. The bash trio is the reference shape, and the [capability seam graph](capability-seams.md) shows the current package families.
|
||||
|
||||
Some seams bend the template deliberately. LLM keeps interface and consumer vocabulary together because adapters are the implementations. Filesystem adds policy as event gates around provider primitives. Web is one service with search and fetch provider registries, so provider swaps do not rename model tools. Session-fork keeps its interface and implementation together because it delegates durable work to the existing session store. Subagents use a named provider registry because multiple delegation backends can coexist; `spawn` starts fresh, `fork` seeds from the parent's completed-turn prefix, and ACP can drive an out-of-process child ([subagent.md](core-data-structures/subagent.md)).
|
||||
Some seams bend the template deliberately. LLM keeps interface and consumer vocabulary together because adapters are the implementations. Filesystem adds policy as event gates around provider primitives. Web is one service with search and fetch provider registries, so provider swaps do not rename model tools. Subagents use a named provider registry because multiple delegation backends can coexist; `spawn` starts fresh, `fork` seeds from the parent's completed-turn prefix, and ACP can drive an out-of-process child ([subagent.md](core-data-structures/subagent.md)).
|
||||
|
||||
### Bundles And Apps
|
||||
|
||||
@@ -144,6 +143,6 @@ New behavior should attach to a documented seam; changing the shipped loop requi
|
||||
| Intercept prompts, requests, tool use, or continuation | listen on the relevant `agent/*` or `tools/*` waterfall |
|
||||
| Add UI or editor integration | drive `ctx.agents` and render from `session/event` |
|
||||
| Add durable session state | add a `SessionEventMap` member and render/replay from the log |
|
||||
| Fork a live session | use `ctx.sessionFork` to validate the boundary and create a seeded child session |
|
||||
| Fork a live session | use `ctx.sessions.snapshot()` for reusable seed metadata or `ctx.sessions.fork()` to create a seeded child session |
|
||||
|
||||
The [extension cookbook](cookbook/extension-cookbook.md) carries plugin skeletons and the feature-to-seam map; step-by-step guides cover [packages](cookbook/adding-a-package.md), [tools](cookbook/adding-a-tool.md), [LLM adapters](cookbook/adding-an-llm-adapter.md), and [vendored packages](cookbook/adding-a-vendored-package.md).
|
||||
|
||||
@@ -126,17 +126,6 @@ Types: [GenerateOptions](../core-data-structures/core.md) · [StreamChunk](../co
|
||||
|
||||
Source: [`packages/llm/llm/src/index.ts:78`](../../packages/llm/llm/src/index.ts)
|
||||
|
||||
## `ctx.sessionFork` — `SessionForkService`
|
||||
|
||||
`ctx.sessionFork`: validates live session fork boundaries and creates seeded child sessions using the existing `ctx.sessions.create({ seed })` primitive.
|
||||
|
||||
```ts cordis-catalog
|
||||
snapshot(source: SessionForkSource): SessionForkSeed
|
||||
fork(options: ForkSessionOptions): Session
|
||||
```
|
||||
|
||||
Source: [`packages/session-fork/session-fork/src/index.ts:65`](../../packages/session-fork/session-fork/src/index.ts)
|
||||
|
||||
## `ctx.sessionPersistence` — `SessionPersistence` (abstract seam)
|
||||
|
||||
Abstract durable session-persistence service. Subclass, implement the abstract methods, and load the subclass as a plugin — it registers as `ctx.sessionPersistence` (one implementation per context; loading a second throws, cordis' standard duplicate-service behavior).
|
||||
@@ -172,9 +161,11 @@ enter(session: Session): () => void
|
||||
announce(session: Session): void
|
||||
get(id: SessionId): Session | undefined
|
||||
list(): Session[]
|
||||
snapshot(source: SessionForkSource): SessionForkSeed
|
||||
fork(options: ForkSessionOptions): Session
|
||||
```
|
||||
|
||||
Source: [`packages/core/session/src/index.ts:327`](../../packages/core/session/src/index.ts)
|
||||
Source: [`packages/core/session/src/index.ts:369`](../../packages/core/session/src/index.ts)
|
||||
|
||||
## `ctx.subagents` — `SubagentService`
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ Everything else is documented on a **sub-page**, not here. The rule that draws t
|
||||
| [filesystem.md](filesystem.md) | the filesystem seam: `FsTarget`, read/write/edit outcomes, observed-file state, `FsErrorCode` |
|
||||
| [compaction.md](compaction.md) | the compaction seam: the `compact/*` session events, `CompactionResult`, the `CompactService` interface |
|
||||
| [subagent.md](subagent.md) | the subagent seam: the named-provider registry, `SubagentStartRequest`/`Result`/`Run`, the start-time-vs-runtime capability split |
|
||||
| [session-fork.md](session-fork.md) | the session fork seam: live-session boundary validation, seed snapshot metadata, and child-session creation |
|
||||
| [web.md](web.md) | the web access seam: `WebSearchRequest`/`Result`, `WebFetchRequest`/`Result`, `WebFetchBody`, provider/capability status, `WebError` |
|
||||
|
||||
> Type definitions on this page are pasted **verbatim** from source and drift-checked by `pnpm run verify-type-equiv` (see [development.md](../development.md#documenting-types-verbatim-ts-type-equiv)). Inline JSDoc is omitted for readability; follow the source link for the full contracts.
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
# Session Fork
|
||||
|
||||
The session fork service is an optional capability over the core session store. It does not add new log events or persisted record shapes; it packages the existing seed primitive into a safe service with a turn-boundary policy.
|
||||
|
||||
Package: [`@deepseek-ai/dsh-session-fork`](../../packages/session-fork/session-fork) (`ctx.sessionFork`). The decision and rationale are recorded in [the session fork service RFC](../rfc/implemented/feature/2026-06-30-session-fork-service.md).
|
||||
|
||||
## Service Shape
|
||||
|
||||
`SessionForkService.snapshot(source)` accepts a live `Session` object or live `SessionId`, validates the source log is empty or ends at `turn/end`, then returns the resolved source, a deep-cloned `SessionEvent[]` seed, and child metadata: `parentSession`, `seedLength`, and optional inherited `cwd`.
|
||||
|
||||
`SessionForkService.fork({ source, sessionId? })` is a convenience wrapper around `ctx.sessions.create(sessionId, { seed, meta })`. Consumers that create agents can use `snapshot()` directly and pass the returned seed/meta through the agent factory instead of creating a detached session first.
|
||||
|
||||
## Boundary Policy
|
||||
|
||||
The boundary rule is structural: every `turn/end` reason is forkable, and every non-empty log whose last event is not `turn/end` is rejected. This is intentionally stricter than the subagent fork backend, which clips to the parent's last completed-turn prefix because it is usually invoked from inside the parent's active tool turn.
|
||||
|
||||
## Persistence
|
||||
|
||||
No persistence method is added. A forked child is just a normal live session with seed events already present at creation time, so existing persistence backends persist the inherited prefix and header metadata through `session/created` and `session/flush`.
|
||||
@@ -159,6 +159,15 @@ export interface SurfaceNode {
|
||||
|
||||
Everything else (`turn/*`, `step/*`) is structural and does not project into a message. Token usage is observed on `assistant/message.usage` (the step that produced it); an operational error's step number is on `turn/end.reason` for `kind: 'error'`.
|
||||
|
||||
## Live-session fork helpers
|
||||
|
||||
`ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` adds two policy helpers:
|
||||
|
||||
- `snapshot(source)` accepts a live `Session` object or live `SessionId`, validates the source log is empty or ends at `turn/end`, then returns a deep-cloned `SessionEvent[]` seed plus child metadata (`parentSession`, `seedLength`, and inherited `cwd`).
|
||||
- `fork({ source, sessionId? })` calls `snapshot(source)` and immediately creates the live child via `ctx.sessions.create(sessionId, { seed, meta })`.
|
||||
|
||||
The split is intentional: `snapshot()` is the reusable seed/metadata computation for callers that create an agent or defer session creation; `fork()` is the convenience path when a caller only needs a child `Session`. Both reject open-turn sources instead of clipping to an older prefix. `dsh-subagent-fork` keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should not silently drop the parent turn tail.
|
||||
|
||||
## What started a turn: `TurnTriggerMap`
|
||||
|
||||
```ts type-equiv
|
||||
|
||||
@@ -78,9 +78,6 @@ flowchart TD
|
||||
pkg_app_boot["app-boot"]
|
||||
pkg_stdio_agent["stdio-agent"]
|
||||
end
|
||||
subgraph group_session_fork["packages/session-fork"]
|
||||
pkg_session_fork["session-fork"]
|
||||
end
|
||||
pkg_llm --> pkg_brand
|
||||
pkg_bash --> pkg_brand
|
||||
pkg_llm_deepseek --> pkg_llm
|
||||
@@ -109,7 +106,6 @@ flowchart TD
|
||||
pkg_session_persistence --> pkg_session
|
||||
pkg_llm_replay --> pkg_llm
|
||||
pkg_llm_replay --> pkg_session
|
||||
pkg_session_fork --> pkg_session
|
||||
pkg_tools --> pkg_agent
|
||||
pkg_tools --> pkg_llm
|
||||
pkg_tools --> pkg_system_prompt
|
||||
@@ -230,7 +226,6 @@ flowchart TD
|
||||
| [`hook-protocol`](../packages/hooks/hook-protocol) | `hooks` | [`bash`](../packages/bash/bash), [`session`](../packages/core/session) |
|
||||
| [`session-persistence`](../packages/session-persistence/session-persistence) | `session-persistence` | [`session`](../packages/core/session) |
|
||||
| [`llm-replay`](../packages/support/llm-replay) | `support` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
|
||||
| [`session-fork`](../packages/session-fork/session-fork) | `session-fork` | [`session`](../packages/core/session) |
|
||||
| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt) |
|
||||
| [`compact-basic`](../packages/compact/compact-basic) | `compact` | [`agent`](../packages/core/agent), [`compact`](../packages/compact/compact), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
|
||||
| [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl) | `session-persistence` | [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence) |
|
||||
|
||||
@@ -58,7 +58,7 @@ Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand;
|
||||
| [dsh-hooks-claude + dsh-hooks-codex — the Claude Code / Codex hook bridges](implemented/feature/2026-06-30-hook-bridges.md) | 2026-06-30 |
|
||||
| [dsh-hook-protocol — the shared Claude Code / Codex hook wire-protocol core](implemented/feature/2026-06-30-hook-protocol-lib.md) | 2026-06-30 |
|
||||
| [Interception seams — the typed-Decision surface a hook programs against](implemented/feature/2026-06-30-interception-seams.md) | 2026-06-30 |
|
||||
| [Session fork service](implemented/feature/2026-06-30-session-fork-service.md) | 2026-06-30 |
|
||||
| [SessionStore fork helpers](implemented/feature/2026-06-30-session-store-fork-helpers.md) | 2026-06-30 |
|
||||
| [Subagent lifecycle enrichment — lastAssistantMessage (observe-only)](implemented/feature/2026-06-30-subagent-observe-enrich.md) | 2026-06-30 |
|
||||
|
||||
### Simplification
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
# RFC: Session fork service
|
||||
|
||||
Status: implemented (proposed 2026-06-30, accepted 2026-06-30)
|
||||
|
||||
## Context
|
||||
|
||||
The event-sourced session log already has the primitive a fork needs: create a new session with a seed event prefix, then derive model history from that seeded log exactly as replay does. That primitive is intentionally low-level. It lives on `dsh-session` as `ctx.sessions.create(id, { seed })`, while durable metadata such as `parentSession` and `seedLength` is stored on the out-of-log `SessionHeader` introduced by [session persistence](../../implemented/architecture/2026-06-14-session-persistence.md). The same mechanics already support in-process subagent fork children and replay routing for forked child logs.
|
||||
|
||||
What is missing is a reusable product service for ordinary session forking. Putting that directly on `dsh-session` would make a derived workflow part of the core log API, even though the core session package should stay focused on append-only storage, derived history, and lifecycle events. The harness architecture prefers optional capability plugins over widening the core spine; [event-sourced sessions](../../implemented/architecture/2026-06-11-event-sourced-sessions.md) provide the log semantics, and [capability seams](../../implemented/architecture/2026-06-13-capability-seams.md) provide the extension pattern.
|
||||
|
||||
The main semantic hazard is the fork boundary. A session event log is only a valid seed when it is contiguous and balanced. Forking inside an active turn would copy an open `turn/start`, possibly an open `step/start`, and possibly dangling tool calls. That violates the turn-enclosure and provider-transcript invariants, and it creates a misleading child history that appears to have participated in an unfinished parent turn. The existing [subagent seam](../../implemented/feature/2026-06-21-subagent-capability-seam.md) deliberately solves a different problem: a tool-triggered subagent fork usually happens while the parent turn is open, so `dsh-subagent-fork` clips the seed to the parent's last completed-turn prefix. A general session fork should not silently clip; it should reject attempts made away from a boundary.
|
||||
|
||||
## Decision
|
||||
|
||||
The shipped design adds an optional product package, `@deepseek-ai/dsh-session-fork`, under `packages/session-fork/session-fork`. It registers `ctx.sessionFork` and depends only on `cordis` plus the `dsh-session` vocabulary/service. No new session event types, persistence methods, ACP methods, agent-loop hooks, or subagent behavior are added in the first cut.
|
||||
|
||||
The service exposes two operations:
|
||||
|
||||
```ts ignore-check
|
||||
type SessionForkSource = Session | SessionId
|
||||
|
||||
interface SessionForkSeed {
|
||||
source: Session
|
||||
seed: SessionEvent[]
|
||||
meta: {
|
||||
parentSession: SessionId
|
||||
seedLength: number
|
||||
cwd?: string
|
||||
}
|
||||
}
|
||||
|
||||
interface ForkSessionOptions {
|
||||
source: SessionForkSource
|
||||
sessionId?: SessionId
|
||||
}
|
||||
|
||||
class SessionForkService extends Service {
|
||||
snapshot(source: SessionForkSource): SessionForkSeed
|
||||
fork(options: ForkSessionOptions): Session
|
||||
}
|
||||
```
|
||||
|
||||
`snapshot()` is the reusable half. It resolves only live sessions from `ctx.sessions`; v1 does not load unloaded persisted sessions by id. It validates the source is at a turn boundary, deep-clones the source events, and returns the seed plus metadata a caller can pass to a later session or agent creation path. This shape keeps the fork computation reusable for future ACP or agent-facing consumers without coupling this service to `ctx.agents`.
|
||||
|
||||
`fork()` is the convenience half. It calls `snapshot()`, then creates a live child session via `ctx.sessions.create(sessionId, { seed, meta })`. The child inherits the source session's `cwd`, stamps `parentSession` to the source id, and sets `seedLength` to the seeded prefix length. When `sessionId` is omitted, `SessionStore` generates one using its existing id policy.
|
||||
|
||||
The boundary rule is structural: an empty source log is forkable, and any source whose last event is `turn/end` is forkable regardless of the turn-end reason (`completed`, `aborted`, `error`, `disposed`, `max-tokens`, `interrupted`, or a future merge-extensible reason). Any non-empty source whose last event is not `turn/end` is inside a turn or otherwise not at the boundary and is rejected with a typed `SessionForkError` code. The service also classifies non-live source ids (`SESSION_NOT_FOUND`), stale `Session` object references whose id is live on a different instance (`SESSION_NOT_LIVE`), and duplicate requested child ids (`SESSION_ALREADY_EXISTS`) instead of leaking raw store errors. This is intentionally stricter than `dsh-subagent-fork`, whose completed-prefix clipping remains unchanged because it serves tool-time delegation rather than user/session branching.
|
||||
|
||||
## Consequences
|
||||
|
||||
The feature is a small capability seam rather than a change to `dsh-session`: the core log keeps its low-level seed primitive, while `dsh-session-fork` owns policy, error taxonomy, and convenience creation. Persistence continues to work through existing `session/created` and `session/flush` behavior: a forked child starts life with seeded events, so existing backends persist that seed once and preserve `parentSession` / `seedLength` in the header.
|
||||
|
||||
The v1 scope deliberately excludes ACP `session/fork`, unloaded persisted-session forking, model-facing tools, and subagent refactors. Those can consume `snapshot()` later. If a future ACP method is added, it should advertise the capability only after it has transcript/snapshot coverage; this RFC adds no editor-facing updates, so no ACP snapshot is required now. Fork-child replay remains covered by the existing [seed-boundary testing RFC](../../implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md), while this service gets focused unit tests plus one persistence integration test.
|
||||
@@ -0,0 +1,59 @@
|
||||
# RFC: SessionStore fork helpers
|
||||
|
||||
Status: implemented
|
||||
|
||||
## Problem
|
||||
|
||||
The event-sourced session log already has the primitive a fork needs: create a new session with a seed event prefix, then derive model history from that seeded log exactly as replay does. That primitive is intentionally low-level: `ctx.sessions.create(id, { seed, meta })` accepts any valid seed, but ordinary live-session branching needs policy around where the seed may be taken, which metadata is stamped on the child, and how errors are classified.
|
||||
|
||||
The semantic hazard is the fork boundary. A session event log is only a valid user-visible fork seed when it is contiguous and balanced. Forking inside an active turn would copy an open `turn/start`, possibly an open `step/start`, and possibly dangling tool calls. That violates the turn-enclosure and provider-transcript invariants, and it creates a misleading child history that appears to have participated in an unfinished parent turn. The existing [subagent seam](../../implemented/feature/2026-06-21-subagent-capability-seam.md) deliberately solves a different problem: a tool-triggered subagent fork usually happens while the parent turn is open, so `dsh-subagent-fork` clips the seed to the parent's last completed-turn prefix. A general session fork should not silently clip; it should reject attempts made away from a boundary.
|
||||
|
||||
## Decision
|
||||
|
||||
`dsh-session` owns ordinary live-session fork helpers directly on `ctx.sessions`. There is no separate `dsh-session-fork` package or `ctx.sessionFork` service: the helpers have no independent backend, event vocabulary, lifecycle, or persistence behavior, and all durable work delegates to the existing session store and persistence backends.
|
||||
|
||||
The store exposes two operations:
|
||||
|
||||
```ts ignore-check
|
||||
type SessionForkSource = Session | SessionId
|
||||
|
||||
interface SessionForkSeed {
|
||||
source: Session
|
||||
seed: SessionEvent[]
|
||||
meta: {
|
||||
parentSession: SessionId
|
||||
seedLength: number
|
||||
cwd?: string
|
||||
}
|
||||
}
|
||||
|
||||
interface ForkSessionOptions {
|
||||
source: SessionForkSource
|
||||
sessionId?: SessionId
|
||||
}
|
||||
|
||||
class SessionStore extends Service {
|
||||
snapshot(source: SessionForkSource): SessionForkSeed
|
||||
fork(options: ForkSessionOptions): Session
|
||||
}
|
||||
```
|
||||
|
||||
`snapshot()` is the reusable half. It resolves only live sessions from `ctx.sessions`; v1 does not load unloaded persisted sessions by id. It validates the source is at a turn boundary, deep-clones the source events, and returns the seed plus metadata a caller can pass to a later session or agent creation path. This keeps the fork computation reusable for future ACP or agent-facing consumers without coupling `dsh-session` to `ctx.agents`.
|
||||
|
||||
`fork()` is the convenience half. It calls `snapshot()`, then creates a live child session via `ctx.sessions.create(sessionId, { seed, meta })`. The child inherits the source session's `cwd`, stamps `parentSession` to the source id, and sets `seedLength` to the seeded prefix length. When `sessionId` is omitted, `SessionStore` generates one using its existing id policy.
|
||||
|
||||
The boundary rule is structural: an empty source log is forkable, and any source whose last event is `turn/end` is forkable regardless of the turn-end reason (`completed`, `aborted`, `error`, `disposed`, `max-tokens`, `interrupted`, or a future merge-extensible reason). Any non-empty source whose last event is not `turn/end` is inside a turn or otherwise not at the boundary and is rejected with a typed `SessionForkError` code. The helpers also classify non-live source ids (`SESSION_NOT_FOUND`), stale `Session` object references whose id is live on a different instance (`SESSION_NOT_LIVE`), and duplicate requested child ids (`SESSION_ALREADY_EXISTS`) instead of leaking lower-level store errors.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Separate `ctx.sessionFork` service.** This was the first implementation, but review showed it overfit the capability-seam pattern. The code had no swappable backend, no extra event surface, no independent ownership lifecycle, and no durable behavior beyond `ctx.sessions.create({ seed, meta })`. Keeping a separate package would make callers discover and install a second service just to perform policy around a session-store primitive.
|
||||
|
||||
**Only expose `fork()`.** A one-function API is simpler for immediate child-session creation, but it forces callers that need a seed for another creation path to create a detached child session just to get the seed. `snapshot()` keeps the seed/metadata computation reusable without importing `ctx.agents` into `dsh-session`; `fork()` remains the simple one-call convenience.
|
||||
|
||||
**Silently clip open turns to the last completed boundary.** That is correct for `dsh-subagent-fork`, where delegation often starts while the parent turn is open and the child should inherit only the completed prefix. It is wrong for ordinary user/session branching because it hides that the requested fork point was not actually a valid boundary and silently drops the parent turn tail.
|
||||
|
||||
## Consequences
|
||||
|
||||
The public surface stays small and discoverable: live session branching is part of `ctx.sessions`, next to `create({ seed })`, rather than a standalone service. Persistence continues to work through existing `session/created` and `session/flush` behavior: a forked child starts life with seeded events, so existing backends persist that seed once and preserve `parentSession` / `seedLength` in the header.
|
||||
|
||||
The v1 scope still excludes ACP `session/fork`, unloaded persisted-session forking, model-facing tools, and subagent refactors. Those can consume `snapshot()` later. If a future ACP method is added, it should advertise the capability only after it has transcript/snapshot coverage; this RFC adds no editor-facing updates, so no ACP snapshot is required now. Fork-child replay remains covered by the existing [seed-boundary testing RFC](../../implemented/testing/2026-06-22-fork-child-replay-seed-boundary.md), while these helpers get focused `dsh-session` unit tests plus JSONL persistence coverage.
|
||||
@@ -16,7 +16,6 @@ Packages are grouped by modular role at `packages/<group>/<pkg>/`. The group dir
|
||||
| [`subagent/`](subagent/README.md) | Subagent capability family: the provider-registry seam and the model-facing delegation tool | 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 |
|
||||
| [`todo/`](todo/README.md) | Todo/planning family: the model-facing `todo_write` tool (whole-list task tracking on the session log) | Product — stable surface |
|
||||
| [`session-fork/`](session-fork/README.md) | Session fork capability family: live-session fork snapshots and child session creation | Product — stable surface |
|
||||
| [`hooks/`](hooks/README.md) | Hook bridges + the shared Claude Code / Codex wire-protocol library | Product — stable surface |
|
||||
| [`session-persistence/`](session-persistence/README.md) | Persistence capability family: the seam + JSONL/SQLite backends | Product — stable surface |
|
||||
| [`ui/`](ui/README.md) | Editor/client integration surfaces (the ACP bridge) + the app packages | Product — stable surface |
|
||||
|
||||
@@ -9,6 +9,8 @@ Creates and holds event-sourced `Session` instances. Persistence is intentionall
|
||||
### Public API
|
||||
|
||||
- `ctx.sessions.create(id?: SessionId, options?: { seed?: SessionEvent[]; meta?: { cwd?: string; parentSession?: SessionId; createdAt?: number; seedLength?: number } }): Session` — Create a session. `options.seed` replays/forks an existing event log; `options.meta` attaches creation metadata (validated absolute `cwd`, `parentSession` lineage, seed boundary) as the immutable `SessionHeader`. The store fills `version`/`id` and defaults `createdAt` to now; a caller reconstructing a persisted session passes the original `createdAt` and persisted `seedLength` to preserve them. Disposed with the calling fiber.
|
||||
- `ctx.sessions.snapshot(source: Session | SessionId): SessionForkSeed` — Resolve a live session object or id, reject non-boundary logs, and return a deep-cloned seed plus `parentSession` / `seedLength` metadata. Use this when the caller will pass the seed/meta into another creation path instead of creating a detached session immediately.
|
||||
- `ctx.sessions.fork({ source, sessionId? }): Session` — Convenience wrapper around `snapshot(source)` + `create(sessionId, { seed, meta })`; creates a live child session with lineage metadata.
|
||||
- `ctx.sessions.get(id: SessionId): Session | undefined`
|
||||
- `ctx.sessions.list(): Session[]`
|
||||
|
||||
@@ -67,9 +69,9 @@ Every `SessionEvent` carries two optional top-level fields (structural metadata)
|
||||
### Extension points
|
||||
|
||||
- Persistence plugins: subscribe to `session/event` (write-behind) and drain on `session/flush` (awaited) and fiber dispose. A durable backend reads the log and reloads it into a live session; the metadata seam (`SessionHeader`, `session.header`) is what such a backend stores beside the log.
|
||||
- Replay/fork: `ctx.sessions.create(id, { seed })` seeds a new session with an existing event log. The surface rebuilds deterministically from `surfaceOp` markers in the seeded events. The seed is validated to the SAME invariants `append` enforces — including that every surface-eligible event (`SurfaceEventType`) carries a `surfaceOp` marker — so a marker-less message event is rejected at construction rather than silently vanishing from `deriveMessages()` (the surface is the sole derivation path) on resume.
|
||||
- Replay/fork: `ctx.sessions.create(id, { seed })` seeds a new session with an existing event log. The surface rebuilds deterministically from `surfaceOp` markers in the seeded events. The seed is validated to the SAME invariants `append` enforces — including that every surface-eligible event (`SurfaceEventType`) carries a `surfaceOp` marker — so a marker-less message event is rejected at construction rather than silently vanishing from `deriveMessages()` (the surface is the sole derivation path) on resume. Ordinary live-session forks use `ctx.sessions.snapshot()` to validate an empty or `turn/end` boundary and build reusable seed metadata, or `ctx.sessions.fork()` to create the child session immediately.
|
||||
- Compaction: the `dsh-compact-basic` plugin appends a `user/message` with `surfaceOp: { op: 'replace', start, end }` to shadow old surface nodes behind a summary checkpoint.
|
||||
|
||||
### What is NOT here (TODO)
|
||||
|
||||
- **Session branching/tree** (pi-style entry tree) — deferred unless needed beyond seed-based forking.
|
||||
- **Session branching/tree** (pi-style entry tree) — deferred unless needed beyond turn-boundary `snapshot()` / `fork()`.
|
||||
|
||||
@@ -318,6 +318,48 @@ export class Session {
|
||||
}
|
||||
}
|
||||
|
||||
/** A fork source: either the live session object or its live store id. */
|
||||
export type SessionForkSource = Session | SessionId
|
||||
|
||||
/** Metadata and seed events that can create a forked child session or agent. */
|
||||
export interface SessionForkSeed {
|
||||
/** The resolved live source session. */
|
||||
source: Session
|
||||
/** Deep-cloned seed events copied from the source session at a turn boundary. */
|
||||
seed: SessionEvent[]
|
||||
/** Session creation metadata for the forked child. */
|
||||
meta: {
|
||||
/** The source session id. */
|
||||
parentSession: SessionId
|
||||
/** How many leading child events were inherited rather than produced. */
|
||||
seedLength: number
|
||||
/** The source session workspace, inherited by the child when present. */
|
||||
cwd?: string
|
||||
}
|
||||
}
|
||||
|
||||
/** Inputs for the convenience session-creation path. */
|
||||
export interface ForkSessionOptions {
|
||||
/** Live source session object or id. */
|
||||
source: SessionForkSource
|
||||
/** Optional child session id; omitted delegates to SessionStore's id policy. */
|
||||
sessionId?: SessionId
|
||||
}
|
||||
|
||||
export type SessionForkErrorCode =
|
||||
| 'SESSION_NOT_FOUND'
|
||||
| 'SESSION_NOT_LIVE'
|
||||
| 'SESSION_ALREADY_EXISTS'
|
||||
| 'OPEN_TURN'
|
||||
|
||||
/** Typed error for session fork rejections. */
|
||||
export class SessionForkError extends Error {
|
||||
constructor(message: string, public readonly code: SessionForkErrorCode) {
|
||||
super(message)
|
||||
this.name = 'SessionForkError'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory session store (`ctx.sessions`).
|
||||
*
|
||||
@@ -452,6 +494,73 @@ export class SessionStore extends Service {
|
||||
list(): Session[] {
|
||||
return [...this.store.values()]
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and validate a live source session, then return a reusable deep-
|
||||
* cloned fork seed. A non-empty source must end exactly at `turn/end`; this
|
||||
* rejects open turns rather than clipping to an older boundary.
|
||||
*
|
||||
* @param source Live session object or live store id to snapshot.
|
||||
* @returns Deep-cloned seed events plus child session metadata.
|
||||
*/
|
||||
snapshot(source: SessionForkSource): SessionForkSeed {
|
||||
const session = this._resolveForkSource(source)
|
||||
this._assertForkBoundary(session)
|
||||
const seed = session.events.map(event => structuredClone(event))
|
||||
return {
|
||||
source: session,
|
||||
seed,
|
||||
meta: {
|
||||
...session.header.cwd !== undefined ? { cwd: session.header.cwd } : {},
|
||||
parentSession: session.id,
|
||||
seedLength: seed.length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience path: create a live child session from a fork snapshot. Callers
|
||||
* that create agents can use {@link snapshot} and pass its seed/meta through
|
||||
* `ctx.agents.create` instead.
|
||||
*
|
||||
* @param options Source and optional child session id for the fork.
|
||||
* @returns The created live child session.
|
||||
*/
|
||||
fork(options: ForkSessionOptions): Session {
|
||||
if (options.sessionId !== undefined && this.get(options.sessionId) !== undefined) {
|
||||
throw new SessionForkError(`session "${options.sessionId}" already exists`, 'SESSION_ALREADY_EXISTS')
|
||||
}
|
||||
const snapshot = this.snapshot(options.source)
|
||||
return this.create(options.sessionId, {
|
||||
seed: snapshot.seed,
|
||||
meta: snapshot.meta,
|
||||
})
|
||||
}
|
||||
|
||||
private _resolveForkSource(source: SessionForkSource): Session {
|
||||
if (typeof source === 'string') {
|
||||
const session = this.get(source)
|
||||
if (session === undefined) throw new SessionForkError(`session "${source}" not found`, 'SESSION_NOT_FOUND')
|
||||
return session
|
||||
}
|
||||
|
||||
const live = this.get(source.id)
|
||||
if (live === undefined) {
|
||||
throw new SessionForkError(`session "${source.id}" not found`, 'SESSION_NOT_FOUND')
|
||||
}
|
||||
if (live !== source) throw new SessionForkError(`session "${source.id}" is not the live store instance`, 'SESSION_NOT_LIVE')
|
||||
return source
|
||||
}
|
||||
|
||||
private _assertForkBoundary(session: Session): void {
|
||||
const last = session.events.at(-1)
|
||||
if (last !== undefined && last.type !== 'turn/end') {
|
||||
throw new SessionForkError(
|
||||
`cannot fork session "${session.id}" inside an open turn (last event: ${last.type})`,
|
||||
'OPEN_TURN',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SessionStore
|
||||
|
||||
@@ -1,31 +1,13 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { CallId } from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import SessionStore, { Session, SessionForkError, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, TurnEndReason } from '@deepseek-ai/dsh-session'
|
||||
import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import SessionForkService, { SessionForkError } from '../src/index.ts'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const dir of tempDirs.splice(0)) await rm(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function tempRoot(): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'dsh-session-fork-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
async function setup(): Promise<{ ctx: Context; fork: SessionForkService }> {
|
||||
async function setup(): Promise<{ ctx: Context; sessions: SessionStore }> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionForkService)
|
||||
return { ctx, fork: ctx.sessionFork }
|
||||
return { ctx, sessions: ctx.sessions }
|
||||
}
|
||||
|
||||
function appendClosedTurn(session: Session, reason: TurnEndReason = { kind: 'completed' }): void {
|
||||
@@ -43,23 +25,12 @@ function firstUserMessage(events: readonly SessionEvent[]): SessionEvent<'user/m
|
||||
return event
|
||||
}
|
||||
|
||||
describe('SessionForkService', () => {
|
||||
it('registers as ctx.sessionFork and unregisters on fiber disposal', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
const fiber = await ctx.plugin(SessionForkService)
|
||||
expect(ctx.sessionFork).toBeInstanceOf(SessionForkService)
|
||||
|
||||
await fiber.dispose()
|
||||
|
||||
expect(ctx.sessionFork).toBeUndefined()
|
||||
})
|
||||
|
||||
describe('SessionStore fork helpers', () => {
|
||||
it('snapshots an empty live session as an empty seed with lineage metadata', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const source = ctx.sessions.create(SessionId('empty-parent'), { meta: { cwd: '/workspace' } })
|
||||
|
||||
const snapshot = fork.snapshot(source)
|
||||
const snapshot = sessions.snapshot(source)
|
||||
|
||||
expect(snapshot.source).toBe(source)
|
||||
expect(snapshot.seed).toEqual([])
|
||||
@@ -71,11 +42,11 @@ describe('SessionForkService', () => {
|
||||
})
|
||||
|
||||
it('snapshots a completed boundary by live session id and deep-clones seed events', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })
|
||||
appendClosedTurn(source)
|
||||
|
||||
const snapshot = fork.snapshot(SessionId('parent'))
|
||||
const snapshot = sessions.snapshot(SessionId('parent'))
|
||||
|
||||
expect(snapshot.source).toBe(source)
|
||||
expect(snapshot.seed).toEqual(source.events)
|
||||
@@ -91,7 +62,7 @@ describe('SessionForkService', () => {
|
||||
})
|
||||
|
||||
it('accepts every turn/end reason as a fork boundary', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const reasons: TurnEndReason[] = [
|
||||
{ kind: 'completed' },
|
||||
{ kind: 'aborted', reason: 'cancelled by user' },
|
||||
@@ -105,7 +76,7 @@ describe('SessionForkService', () => {
|
||||
const source = ctx.sessions.create(SessionId(`parent-${reason.kind}`))
|
||||
appendClosedTurn(source, reason)
|
||||
|
||||
const snapshot = fork.snapshot(source)
|
||||
const snapshot = sessions.snapshot(source)
|
||||
|
||||
expect(snapshot.seed.at(-1)?.type).toBe('turn/end')
|
||||
expect(snapshot.meta.seedLength).toBe(source.events.length)
|
||||
@@ -113,31 +84,31 @@ describe('SessionForkService', () => {
|
||||
})
|
||||
|
||||
it('rejects an unknown live session id', async () => {
|
||||
const { fork } = await setup()
|
||||
const { sessions } = await setup()
|
||||
|
||||
expect(() => fork.snapshot(SessionId('missing')))
|
||||
expect(() => sessions.snapshot(SessionId('missing')))
|
||||
.toThrow(new SessionForkError('session "missing" not found', 'SESSION_NOT_FOUND'))
|
||||
})
|
||||
|
||||
it('rejects a detached Session object that is not live in ctx.sessions', async () => {
|
||||
const { fork } = await setup()
|
||||
const { sessions } = await setup()
|
||||
const detached = new Session(SessionId('detached'))
|
||||
|
||||
expect(() => fork.snapshot(detached))
|
||||
expect(() => sessions.snapshot(detached))
|
||||
.toThrow(new SessionForkError('session "detached" not found', 'SESSION_NOT_FOUND'))
|
||||
})
|
||||
|
||||
it('rejects a stale Session object whose id is live on a different instance', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
ctx.sessions.create(SessionId('same-id'))
|
||||
const stale = new Session(SessionId('same-id'))
|
||||
|
||||
expect(() => fork.snapshot(stale))
|
||||
expect(() => sessions.snapshot(stale))
|
||||
.toThrow(new SessionForkError('session "same-id" is not the live store instance', 'SESSION_NOT_LIVE'))
|
||||
})
|
||||
|
||||
it('rejects non-empty logs whose last event is not turn/end', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const cases: [string, (session: Session) => void][] = [
|
||||
['turn/start', (session) => {
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
@@ -172,17 +143,17 @@ describe('SessionForkService', () => {
|
||||
const source = ctx.sessions.create(SessionId(`open-${lastType}`))
|
||||
build(source)
|
||||
|
||||
expect(() => fork.snapshot(source))
|
||||
expect(() => sessions.snapshot(source))
|
||||
.toThrow(new SessionForkError(`cannot fork session "open-${lastType}" inside an open turn (last event: ${lastType})`, 'OPEN_TURN'))
|
||||
}
|
||||
})
|
||||
|
||||
it('creates a forked child session with the seed and lineage metadata', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })
|
||||
appendClosedTurn(source)
|
||||
|
||||
const child = fork.fork({ source, sessionId: SessionId('child') })
|
||||
const child = sessions.fork({ source, sessionId: SessionId('child') })
|
||||
|
||||
expect(child.id).toBe(SessionId('child'))
|
||||
expect(child.events).toEqual(source.events)
|
||||
@@ -194,45 +165,22 @@ describe('SessionForkService', () => {
|
||||
})
|
||||
|
||||
it('rejects a child session id that is already live with a typed fork error', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const source = ctx.sessions.create(SessionId('parent'))
|
||||
appendClosedTurn(source)
|
||||
ctx.sessions.create(SessionId('child'))
|
||||
|
||||
expect(() => fork.fork({ source, sessionId: SessionId('child') }))
|
||||
expect(() => sessions.fork({ source, sessionId: SessionId('child') }))
|
||||
.toThrow(new SessionForkError('session "child" already exists', 'SESSION_ALREADY_EXISTS'))
|
||||
})
|
||||
|
||||
it('rejects a duplicate child session id before validating the source boundary', async () => {
|
||||
const { ctx, fork } = await setup()
|
||||
const { ctx, sessions } = await setup()
|
||||
const source = ctx.sessions.create(SessionId('open-parent'))
|
||||
source.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
ctx.sessions.create(SessionId('child'))
|
||||
|
||||
expect(() => fork.fork({ source, sessionId: SessionId('child') }))
|
||||
expect(() => sessions.fork({ source, sessionId: SessionId('child') }))
|
||||
.toThrow(new SessionForkError('session "child" already exists', 'SESSION_ALREADY_EXISTS'))
|
||||
})
|
||||
|
||||
it('persists a forked child seed through the existing session write path', async () => {
|
||||
const root = await tempRoot()
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionForkService)
|
||||
await ctx.plugin(SessionPersistenceJsonl, { root })
|
||||
const source = ctx.sessions.create(SessionId('persist-parent'), { meta: { cwd: '/workspace' } })
|
||||
appendClosedTurn(source)
|
||||
|
||||
const child = ctx.sessionFork.fork({ source, sessionId: SessionId('persist-child') })
|
||||
await ctx.parallel('session/flush', child)
|
||||
const loaded = await ctx.sessionPersistence.load(child.id)
|
||||
|
||||
expect(loaded.events).toEqual(source.events)
|
||||
expect(loaded.meta).toMatchObject({
|
||||
id: SessionId('persist-child'),
|
||||
cwd: '/workspace',
|
||||
parentSession: SessionId('persist-parent'),
|
||||
seedLength: source.events.length,
|
||||
})
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
})
|
||||
@@ -1,9 +0,0 @@
|
||||
# session-fork/ — session fork capability family
|
||||
|
||||
The session fork capability: a small optional service that validates a live session is at a turn boundary, snapshots its event log as a seed, and creates forked child sessions through the existing `dsh-session` seed primitive. All **product** packages.
|
||||
|
||||
| Package | Role | ctx key |
|
||||
|---|---|---|
|
||||
| `session-fork/` | Session fork service: reusable seed snapshot + forked live-session creation | `ctx.sessionFork` |
|
||||
|
||||
The interface and implementation live together at `session-fork/session-fork/` because v1 has no swappable backend: all durable behavior is delegated to the existing session store and persistence backends. The decision is recorded in [the session fork service RFC](../../docs/rfc/implemented/feature/2026-06-30-session-fork-service.md).
|
||||
@@ -1,31 +0,0 @@
|
||||
# @deepseek-ai/dsh-session-fork
|
||||
|
||||
Session fork service (`ctx.sessionFork`) for creating seeded child sessions from a live source session at a turn boundary.
|
||||
|
||||
## Service: `SessionForkService`
|
||||
|
||||
`SessionForkService` is an optional plugin over `dsh-session`; it does not add session events or persistence methods. It owns fork policy, while `ctx.sessions.create(id, { seed, meta })` remains the low-level replay/fork primitive.
|
||||
|
||||
| Method | Purpose |
|
||||
|---|---|
|
||||
| `snapshot(source)` | Resolve a live `Session \| SessionId`, reject non-boundary logs, and return a deep-cloned seed plus `parentSession` / `seedLength` metadata. |
|
||||
| `fork({ source, sessionId? })` | Create a live child session from `snapshot(source)`, using the caller-supplied child id or the session store's generated id. |
|
||||
|
||||
## Boundary Rule
|
||||
|
||||
A source is forkable only when its log is empty or its last event is `turn/end`. The service accepts any turn-end reason, including `aborted`, `error`, `disposed`, `max-tokens`, and crash-repaired `interrupted`; the boundary is structural, not a statement that the prior turn was successful.
|
||||
|
||||
Forking inside a turn is rejected with `SessionForkError` code `OPEN_TURN`. The service intentionally does not clip to an older completed prefix; that behavior is specific to `dsh-subagent-fork`, where tool-time delegation normally happens while the parent turn is open.
|
||||
|
||||
## Errors
|
||||
|
||||
| Code | Meaning |
|
||||
|---|---|
|
||||
| `SESSION_NOT_FOUND` | A source id is not live in `ctx.sessions`, or a passed `Session` object's id is not live in the store. |
|
||||
| `SESSION_NOT_LIVE` | A passed `Session` object has a live id in the store, but it is not that live store instance. |
|
||||
| `SESSION_ALREADY_EXISTS` | The requested child `sessionId` is already live in `ctx.sessions`. |
|
||||
| `OPEN_TURN` | The source log is non-empty and does not end at `turn/end`. |
|
||||
|
||||
## Persistence
|
||||
|
||||
Forked sessions use existing session metadata: `parentSession` points to the source session id, `seedLength` is the number of inherited events, and `cwd` is inherited when present. Persistence backends observe the forked child through their existing `session/created` and `session/flush` write path, so no backend-specific fork API is needed.
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-session-fork",
|
||||
"description": "Session fork service for creating seeded child sessions at turn boundaries",
|
||||
"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-session": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.6"
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
/**
|
||||
* Session forking as an optional service. The core session store exposes the
|
||||
* low-level seed primitive; this plugin owns the policy for when a live session
|
||||
* may be forked and the metadata stamped on the child.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-session-fork
|
||||
*/
|
||||
|
||||
import { Context, Service } from 'cordis'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
|
||||
declare module 'cordis' {
|
||||
interface Context {
|
||||
sessionFork: SessionForkService
|
||||
}
|
||||
}
|
||||
|
||||
/** A fork source: either the live session object or its live store id. */
|
||||
export type SessionForkSource = Session | SessionId
|
||||
|
||||
/** Metadata and seed events that can create a forked child session or agent. */
|
||||
export interface SessionForkSeed {
|
||||
/** The resolved live source session. */
|
||||
source: Session
|
||||
/** Deep-cloned seed events copied from the source session at a turn boundary. */
|
||||
seed: SessionEvent[]
|
||||
/** Session creation metadata for the forked child. */
|
||||
meta: {
|
||||
/** The source session id. */
|
||||
parentSession: SessionId
|
||||
/** How many leading child events were inherited rather than produced. */
|
||||
seedLength: number
|
||||
/** The source session workspace, inherited by the child when present. */
|
||||
cwd?: string
|
||||
}
|
||||
}
|
||||
|
||||
/** Inputs for the convenience session-creation path. */
|
||||
export interface ForkSessionOptions {
|
||||
/** Live source session object or id. */
|
||||
source: SessionForkSource
|
||||
/** Optional child session id; omitted delegates to SessionStore's id policy. */
|
||||
sessionId?: SessionId
|
||||
}
|
||||
|
||||
export type SessionForkErrorCode =
|
||||
| 'SESSION_NOT_FOUND'
|
||||
| 'SESSION_NOT_LIVE'
|
||||
| 'SESSION_ALREADY_EXISTS'
|
||||
| 'OPEN_TURN'
|
||||
|
||||
/** Typed error for service-level fork rejections. */
|
||||
export class SessionForkError extends Error {
|
||||
constructor(message: string, public readonly code: SessionForkErrorCode) {
|
||||
super(message)
|
||||
this.name = 'SessionForkError'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `ctx.sessionFork`: validates live session fork boundaries and creates seeded
|
||||
* child sessions using the existing `ctx.sessions.create({ seed })` primitive.
|
||||
*/
|
||||
export class SessionForkService extends Service {
|
||||
static inject = ['sessions']
|
||||
|
||||
constructor(ctx: Context) {
|
||||
super(ctx, 'sessionFork')
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and validate a live source session, then return a reusable deep-
|
||||
* cloned fork seed. A non-empty source must end exactly at `turn/end`; this
|
||||
* service rejects open turns rather than clipping to an older boundary.
|
||||
*
|
||||
* @param source Live session object or live store id to snapshot.
|
||||
* @returns Deep-cloned seed events plus child session metadata.
|
||||
*/
|
||||
snapshot(source: SessionForkSource): SessionForkSeed {
|
||||
const session = this._resolve(source)
|
||||
this._assertTurnBoundary(session)
|
||||
const seed = session.events.map(event => structuredClone(event))
|
||||
return {
|
||||
source: session,
|
||||
seed,
|
||||
meta: {
|
||||
...session.header.cwd !== undefined ? { cwd: session.header.cwd } : {},
|
||||
parentSession: session.id,
|
||||
seedLength: seed.length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience path: create a live child session from a fork snapshot. Callers
|
||||
* that create agents can use {@link snapshot} and pass its seed/meta through
|
||||
* `ctx.agents.create` instead.
|
||||
*
|
||||
* @param options Source and optional child session id for the fork.
|
||||
* @returns The created live child session.
|
||||
*/
|
||||
fork(options: ForkSessionOptions): Session {
|
||||
if (options.sessionId !== undefined && this.ctx.sessions.get(options.sessionId) !== undefined) {
|
||||
throw new SessionForkError(`session "${options.sessionId}" already exists`, 'SESSION_ALREADY_EXISTS')
|
||||
}
|
||||
const snapshot = this.snapshot(options.source)
|
||||
return this.ctx.sessions.create(options.sessionId, {
|
||||
seed: snapshot.seed,
|
||||
meta: snapshot.meta,
|
||||
})
|
||||
}
|
||||
|
||||
private _resolve(source: SessionForkSource): Session {
|
||||
if (typeof source === 'string') {
|
||||
const session = this.ctx.sessions.get(source)
|
||||
if (session === undefined) throw new SessionForkError(`session "${source}" not found`, 'SESSION_NOT_FOUND')
|
||||
return session
|
||||
}
|
||||
|
||||
const live = this.ctx.sessions.get(source.id)
|
||||
if (live === undefined) {
|
||||
throw new SessionForkError(`session "${source.id}" not found`, 'SESSION_NOT_FOUND')
|
||||
}
|
||||
if (live !== source) throw new SessionForkError(`session "${source.id}" is not the live store instance`, 'SESSION_NOT_LIVE')
|
||||
return source
|
||||
}
|
||||
|
||||
private _assertTurnBoundary(session: Session): void {
|
||||
const last = session.events.at(-1)
|
||||
if (last !== undefined && last.type !== 'turn/end') {
|
||||
throw new SessionForkError(
|
||||
`cannot fork session "${session.id}" inside an open turn (last event: ${last.type})`,
|
||||
'OPEN_TURN',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SessionForkService
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cosmokit"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../core/session"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -23,6 +23,15 @@ afterEach(async () => {
|
||||
for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function appendClosedTurn(session: Session): void {
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('user/message', {
|
||||
content: [{ type: 'text', text: 'hello' }],
|
||||
source: { kind: 'user' },
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
}
|
||||
|
||||
// Run the shared backend contract against the real JSONL backend.
|
||||
runPersistenceContract('jsonl', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'dsh-jsonl-'))
|
||||
@@ -131,6 +140,23 @@ describe('SessionPersistenceJsonl: durability and crash semantics', () => {
|
||||
expect(loaded.events).toEqual(log) // chunks preserved, contiguous seqs
|
||||
})
|
||||
|
||||
it('persists a forked child seed through the existing session write path', async () => {
|
||||
const source = ctx.sessions.create(SessionId('persist-parent'), { meta: { cwd: '/workspace' } })
|
||||
appendClosedTurn(source)
|
||||
|
||||
const child = ctx.sessions.fork({ source, sessionId: SessionId('persist-child') })
|
||||
await ctx.parallel('session/flush', child)
|
||||
const loaded = await ctx.sessionPersistence.load(child.id)
|
||||
|
||||
expect(loaded.events).toEqual(source.events)
|
||||
expect(loaded.meta).toMatchObject({
|
||||
id: SessionId('persist-child'),
|
||||
cwd: '/workspace',
|
||||
parentSession: SessionId('persist-parent'),
|
||||
seedLength: source.events.length,
|
||||
})
|
||||
})
|
||||
|
||||
it('crash recovery: load preserves the interrupted turn and closes it with a synthetic turn/end {interrupted}', async () => {
|
||||
const m = meta('crash', '/proj')
|
||||
await ctx.sessionPersistence.create(m)
|
||||
|
||||
30
pnpm-lock.yaml
generated
30
pnpm-lock.yaml
generated
@@ -511,21 +511,6 @@ importers:
|
||||
specifier: ^4.0.0-rc.6
|
||||
version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4)
|
||||
|
||||
packages/session-fork/session-fork:
|
||||
devDependencies:
|
||||
'@deepseek-ai/dsh-llm':
|
||||
specifier: workspace:^
|
||||
version: link:../../llm/llm
|
||||
'@deepseek-ai/dsh-session':
|
||||
specifier: workspace:^
|
||||
version: link:../../core/session
|
||||
'@deepseek-ai/dsh-session-persistence-jsonl':
|
||||
specifier: workspace:^
|
||||
version: link:../../session-persistence/session-persistence-jsonl
|
||||
cordis:
|
||||
specifier: ^4.0.0-rc.6
|
||||
version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4)
|
||||
|
||||
packages/session-persistence/session-persistence:
|
||||
devDependencies:
|
||||
'@deepseek-ai/dsh-session':
|
||||
@@ -2375,9 +2360,6 @@ packages:
|
||||
'@types/tough-cookie@4.0.5':
|
||||
resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||
|
||||
'@types/unist@3.0.3':
|
||||
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
|
||||
|
||||
@@ -5108,9 +5090,6 @@ snapshots:
|
||||
|
||||
'@types/tough-cookie@4.0.5': {}
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
optional: true
|
||||
|
||||
'@types/unist@3.0.3': {}
|
||||
|
||||
'@typescript-eslint/eslint-plugin@8.61.0(@typescript-eslint/parser@8.61.0(eslint@10.5.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.5.0(jiti@2.7.0))(typescript@6.0.3)':
|
||||
@@ -5204,10 +5183,7 @@ snapshots:
|
||||
'@typescript-eslint/types': 8.61.0
|
||||
eslint-visitor-keys: 5.0.1
|
||||
|
||||
'@upsetjs/venn.js@2.0.0':
|
||||
optionalDependencies:
|
||||
d3-selection: 3.0.0
|
||||
d3-transition: 3.0.1(d3-selection@3.0.0)
|
||||
'@upsetjs/venn.js@2.0.0': {}
|
||||
|
||||
'@vitest/coverage-v8@4.1.8(vitest@4.1.8)':
|
||||
dependencies:
|
||||
@@ -5597,9 +5573,7 @@ snapshots:
|
||||
|
||||
diff@9.0.0: {}
|
||||
|
||||
dompurify@3.4.11:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
dompurify@3.4.11: {}
|
||||
|
||||
dts-resolver@3.0.0(oxc-resolver@11.20.0):
|
||||
optionalDependencies:
|
||||
|
||||
@@ -46,7 +46,6 @@
|
||||
"./packages/fs/*/src",
|
||||
"./packages/compact/*/src",
|
||||
"./packages/subagent/*/src",
|
||||
"./packages/session-fork/*/src",
|
||||
"./packages/web/*/src",
|
||||
"./packages/todo/*/src",
|
||||
"./packages/hooks/*/src",
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
{ "path": "./packages/core/agent-core" },
|
||||
{ "path": "./packages/bash/bash" },
|
||||
{ "path": "./packages/compact/compact" },
|
||||
{ "path": "./packages/session-fork/session-fork" },
|
||||
{ "path": "./packages/compact/compact-basic" },
|
||||
{ "path": "./packages/llm/llm-deepseek" },
|
||||
{ "path": "./packages/llm/llm-pi-ai" },
|
||||
|
||||
@@ -42,7 +42,6 @@
|
||||
{ "path": "./packages/fs/fs-policy" },
|
||||
{ "path": "./packages/fs/tool-fs" },
|
||||
{ "path": "./packages/compact/compact" },
|
||||
{ "path": "./packages/session-fork/session-fork" },
|
||||
{ "path": "./packages/compact/compact-basic" },
|
||||
{ "path": "./packages/web/web" },
|
||||
{ "path": "./packages/web/web-search-exa" },
|
||||
|
||||
Reference in New Issue
Block a user