mirror of
https://github.com/deepseek-ai/deepseek-harness
synced 2026-08-15 21:04:50 +00:00
round 1: implement bracket-first manual compaction
This commit is contained in:
6
packages/compact/command-compact/README.i18n.yaml
Normal file
6
packages/compact/command-compact/README.i18n.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/compact/command-compact/README.md
|
||||
README.md: 314b259025a2b7a13faf27f9d3935cca370224fe
|
||||
README.zh.md: 9fb30c6720c3c3d69ed64242e995d953ec8a008f
|
||||
66
packages/compact/command-compact/README.md
Normal file
66
packages/compact/command-compact/README.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# @deepseek-ai/dsh-command-compact
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Human-facing `/compact` control over [`ctx.compact`](../compact/README.md). The plugin registers one global command through [`ctx.commands`](../../ui/commands/README.md), so every composed command adapter discovers it; the shipped TUI executes it without a model turn. The [queued manual compaction Agent Note](../../../.agents/notes/implemented/feature/2026-07-30-queued-manual-compaction.md) owns the admission, lock, and durability decisions.
|
||||
|
||||
## Command contract
|
||||
|
||||
| Input | Result |
|
||||
|---|---|
|
||||
| `/compact` | Summarize one useful balanced older span even below automatic pressure, then report the replaced history-item count and estimated tokens after the standalone bracket is flushed. |
|
||||
| `/compact` with no compactable history | `No compactable history yet.` — no marker or surface mutation is written. |
|
||||
| `/compact <anything>` | `Usage: /compact (no arguments)` — the command takes no arguments and calls no compaction backend. |
|
||||
|
||||
The command is backend-independent: it depends only on `compactNow(agent, signal)`. The invoking agent is the exact target, and the dispatching UI's cancellation signal is forwarded through the seam. Every resolved invocation records the executor-owned log-only pair `command/run` / `command/done`; neither event joins model history.
|
||||
|
||||
Expected `ManualCompactionError` codes become stable direct errors:
|
||||
|
||||
| Code | Direct result |
|
||||
|---|---|
|
||||
| `busy` | `Compaction is unavailable because this process has an active compaction, or the agent is not idle.` |
|
||||
| `changed` | `The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.` |
|
||||
| `summary` | `Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.` |
|
||||
| `commit` | `Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.` |
|
||||
| `persistence` | `Compaction finished, but the session could not be saved.` |
|
||||
|
||||
The busy result is intentionally process-scoped: a live unmatched marker blocks, while a marker older than the newest `session/end-seed` is stale and does not. Unexpected implementation failures reject dispatch. Cancellation remains authoritative; the backend completes its required close/flush cleanup, and the command settles internally as `Compaction cancelled.` while the command executor stops waiting with its cancellation error.
|
||||
|
||||
Prompts submitted while compaction runs remain accepted in the agent's ordinary FIFO with the same identity and wakeup facts. They start only after the compaction's explicit durability checkpoint and admission release. Idle injected context is not held: it may be logged between `compact/start` and `compact/end`, and positional replacement leaves it visible after the checkpoint.
|
||||
|
||||
## Composition
|
||||
|
||||
The producer injects `commands` and `compact`. Mount the command registry, one backend, and this plugin:
|
||||
|
||||
```yaml
|
||||
- id: commands
|
||||
name: '@deepseek-ai/dsh-commands'
|
||||
- id: compact-basic
|
||||
name: '@deepseek-ai/dsh-compact-basic'
|
||||
- id: command-compact
|
||||
name: '@deepseek-ai/dsh-command-compact'
|
||||
```
|
||||
|
||||
The TUI example and CLI host mount it beside `compact-basic`. Automation surfaces that compose no command registry keep automatic compaction only.
|
||||
|
||||
## Model Experience
|
||||
|
||||
### Human `/compact` control
|
||||
|
||||
#### What the model sees
|
||||
|
||||
The slash input and direct result never enter a model request. An accepted compaction separately replaces an older span with the backend's user-role checkpoint inside a standalone `compact/* { turn: null }` bracket.
|
||||
|
||||
#### Token effect
|
||||
|
||||
The command lifecycle adds no model tokens. A successful compaction reduces later requests by replacing the selected span with one framed summary; summarization itself is one auxiliary request.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
Discovery and command bookkeeping do not affect the cache. The accepted surface replacement invalidates reuse from the first shadowed history token.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Idle-only** — `/compact` reports `busy` when a turn or already accepted waking prompt has right of way; the command itself is not queued.
|
||||
- **No range or policy arguments** — the argument-free form keeps behavior stable across command adapters. Explicit ranges remain the programmatic `compactRegion()` path.
|
||||
- **Command adapters only** — surfaces without `ctx.commands` cannot invoke it and rely on automatic pressure compaction.
|
||||
66
packages/compact/command-compact/README.zh.md
Normal file
66
packages/compact/command-compact/README.zh.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# @deepseek-ai/dsh-command-compact
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
通过 [`ctx.compact`](../compact/README.md) 提供面向用户的 `/compact` 压缩(compaction)控制。该插件通过 [`ctx.commands`](../../ui/commands/README.md) 注册一个全局命令,因此组合中的每个命令适配器都能发现它;随附 TUI 无需模型轮次即可执行该命令。[排队手动压缩 Agent Note(agent 决策记录)](../../../.agents/notes/implemented/feature/2026-07-30-queued-manual-compaction.md)拥有接纳、锁与持久性决策。
|
||||
|
||||
## 命令契约
|
||||
|
||||
| 输入 | 结果 |
|
||||
|---|---|
|
||||
| `/compact` | 即使未达到自动压力,也摘要一段有效、平衡的较早范围;独立标记对 flush 后,报告被替换的历史项数量与估算 token 数。 |
|
||||
| `/compact`,但没有可压缩历史 | `No compactable history yet.`:不会写入标记,也不会变更 surface。 |
|
||||
| `/compact <anything>` | `Usage: /compact (no arguments)`:该命令不接受参数,也不会调用压缩后端。 |
|
||||
|
||||
该命令与后端无关,只依赖 `compactNow(agent, signal)`。调用该命令的 agent(智能体)就是操作的确切目标,发起分发的 UI 会通过 seam 转发取消信号。每次完成的调用都会记录执行器所属的纯日志事件对 `command/run` / `command/done`;两者都不进入模型历史。
|
||||
|
||||
预期的 `ManualCompactionError` 代码会成为稳定的直接错误:
|
||||
|
||||
| 代码 | 直接结果 |
|
||||
|---|---|
|
||||
| `busy` | `Compaction is unavailable because this process has an active compaction, or the agent is not idle.` |
|
||||
| `changed` | `The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.` |
|
||||
| `summary` | `Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.` |
|
||||
| `commit` | `Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.` |
|
||||
| `persistence` | `Compaction finished, but the session could not be saved.` |
|
||||
|
||||
busy 结果有意限定在进程范围内:活动的未匹配标记会阻塞,而早于最新 `session/end-seed` 的标记已陈旧,不会阻塞。意外实现故障会拒绝分发。取消仍具有最终决定权;后端会完成必需的闭合/flush 清理,命令内部以 `Compaction cancelled.` 结算,而命令执行器会因取消错误停止等待。
|
||||
|
||||
压缩运行期间提交的提示词仍会按 agent 的普通 FIFO 获得接纳,保留相同的身份与唤醒信息。它们仅在压缩的显式持久性检查点和接纳预留释放后启动。空闲注入的上下文不受阻塞:它可以记录在 `compact/start` 与 `compact/end` 之间,位置替换会使其在检查点之后保持可见。
|
||||
|
||||
## 组合
|
||||
|
||||
生产方注入 `commands` 和 `compact`。挂载命令注册表、一个后端与本插件:
|
||||
|
||||
```yaml
|
||||
- id: commands
|
||||
name: '@deepseek-ai/dsh-commands'
|
||||
- id: compact-basic
|
||||
name: '@deepseek-ai/dsh-compact-basic'
|
||||
- id: command-compact
|
||||
name: '@deepseek-ai/dsh-command-compact'
|
||||
```
|
||||
|
||||
TUI 示例与 CLI host 将它挂载在 `compact-basic` 旁。未组合命令注册表的自动化接口只保留自动压缩。
|
||||
|
||||
## 模型体验
|
||||
|
||||
### 用户 `/compact` 控制
|
||||
|
||||
#### 模型看到什么
|
||||
|
||||
斜杠输入与直接结果绝不会进入模型请求。已获接纳的压缩会另外在独立的 `compact/* { turn: null }` 标记对内,用后端的 user 角色检查点替换一段较早范围。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
命令生命周期不会增加模型 token。成功压缩会用一份带框架的摘要替换所选范围,从而减少后续请求;摘要生成本身需要一次辅助请求。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
命令发现与簿记不会影响缓存。已获接纳的 surface 替换会从第一个被遮蔽的历史 token 起使复用失效。
|
||||
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- **仅限空闲状态**:当一个轮次或已获接纳的唤醒提示词拥有优先权时,`/compact` 会报告 `busy`;命令本身不会排队。
|
||||
- **不接受范围或策略参数**:无参数形式使各命令适配器的行为保持稳定。显式范围仍由编程接口 `compactRegion()` 处理。
|
||||
- **仅限命令适配器**:没有 `ctx.commands` 的接口无法调用该命令,只能依赖自动压力压缩。
|
||||
46
packages/compact/command-compact/package.json
Normal file
46
packages/compact/command-compact/package.json
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-command-compact",
|
||||
"description": "Human-facing slash command for explicit session compaction",
|
||||
"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"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-commands": "^0.0.1",
|
||||
"@deepseek-ai/dsh-compact": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cordisjs/plugin-include": "workspace:^",
|
||||
"@cordisjs/plugin-loader": "workspace:^",
|
||||
"@deepseek-ai/dsh-agent": "workspace:^",
|
||||
"@deepseek-ai/dsh-commands": "workspace:^",
|
||||
"@deepseek-ai/dsh-compact": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
}
|
||||
}
|
||||
87
packages/compact/command-compact/src/index.ts
Normal file
87
packages/compact/command-compact/src/index.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Human-facing `/compact` command over the backend-independent compaction seam.
|
||||
* @module @deepseek-ai/dsh-command-compact
|
||||
*/
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import { ManualCompactionError } from '@deepseek-ai/dsh-compact'
|
||||
import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands'
|
||||
|
||||
export const name = 'command-compact'
|
||||
export const inject = ['commands', 'compact']
|
||||
|
||||
const USAGE = 'Usage: /compact (no arguments)'
|
||||
|
||||
/** Fail loudly if a locally closed union gains an unhandled member. */
|
||||
/* v8 ignore start -- closed-union backstop is unreachable without violating the TypeScript contract */
|
||||
function assertNever(value: never): never {
|
||||
throw new TypeError(`unknown manual compaction error code: ${String(value)}`)
|
||||
}
|
||||
/* v8 ignore stop */
|
||||
|
||||
/** Convert expected capability failures into concise human-only outcomes. */
|
||||
function expectedFailure(error: ManualCompactionError): CommandResult {
|
||||
switch (error.code) {
|
||||
case 'busy':
|
||||
return {
|
||||
kind: 'error',
|
||||
text: 'Compaction is unavailable because this process has an active compaction, or the agent is not idle.',
|
||||
}
|
||||
case 'changed':
|
||||
return {
|
||||
kind: 'error',
|
||||
text: 'The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.',
|
||||
}
|
||||
case 'summary':
|
||||
return {
|
||||
kind: 'error',
|
||||
text: 'Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.',
|
||||
}
|
||||
case 'commit':
|
||||
return {
|
||||
kind: 'error',
|
||||
text: 'Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.',
|
||||
}
|
||||
case 'persistence':
|
||||
return {
|
||||
kind: 'error',
|
||||
text: 'Compaction finished, but the session could not be saved.',
|
||||
}
|
||||
/* v8 ignore next 2 -- ManualCompactionErrorCode is closed and every member is handled above */
|
||||
default: return assertNever(error.code)
|
||||
}
|
||||
}
|
||||
|
||||
/** Execute one argument-free manual compaction request. */
|
||||
async function executeCompact(
|
||||
ctx: Context,
|
||||
invocation: CommandInvocation,
|
||||
): Promise<CommandResult> {
|
||||
if (invocation.rawInput.trim().length > 0) {
|
||||
return { kind: 'error', text: USAGE }
|
||||
}
|
||||
try {
|
||||
const result = await ctx.compact.compactNow(invocation.agent, invocation.signal)
|
||||
if (result === null) return { kind: 'success', text: 'No compactable history yet.' }
|
||||
return {
|
||||
kind: 'success',
|
||||
text: `Compacted ${result.shadowedSeqs.length} history items (~${result.shadowedTokenCount} tokens).`,
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (invocation.signal.aborted) return { kind: 'error', text: 'Compaction cancelled.' }
|
||||
if (error instanceof ManualCompactionError) return expectedFailure(error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register `/compact` for every composed human-command adapter.
|
||||
* @param ctx - context carrying the command registry and the compaction seam.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.commands.register({
|
||||
name: 'compact',
|
||||
description: 'Compact older conversation history',
|
||||
handler: invocation => executeCompact(ctx, invocation),
|
||||
})
|
||||
}
|
||||
30
packages/compact/command-compact/src/invariant.ts
Normal file
30
packages/compact/command-compact/src/invariant.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-command-compact`.
|
||||
* @module @deepseek-ai/dsh-command-compact/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-command-compact'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'command-compact-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this command adapter owns no state or event stream; the compaction seam owns
|
||||
* the balanced durable transaction and the command registry owns registration and dispatch lifecycle.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
/* jscpd:ignore-end */
|
||||
207
packages/compact/command-compact/tests/command-compact.spec.ts
Normal file
207
packages/compact/command-compact/tests/command-compact.spec.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import Loader from '@cordisjs/plugin-loader'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import CommandService from '@deepseek-ai/dsh-commands'
|
||||
import {
|
||||
CompactService,
|
||||
ManualCompactionError,
|
||||
type CompactAgentContext,
|
||||
type CompactionResult,
|
||||
type CompactionTrigger,
|
||||
type ManualCompactAgentContext,
|
||||
} from '@deepseek-ai/dsh-compact'
|
||||
import { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import * as commandCompact from '@deepseek-ai/dsh-command-compact'
|
||||
|
||||
const RESULT: CompactionResult = {
|
||||
startSeq: 10,
|
||||
summarySeq: 11,
|
||||
endSeq: 13,
|
||||
summary: [{ type: 'text', text: 'summary' }],
|
||||
shadowedRange: { start: 1, end: 7 },
|
||||
shadowedSeqs: [1, 3, 7],
|
||||
shadowedTokenCount: 42,
|
||||
}
|
||||
|
||||
class StubCompactService extends CompactService {
|
||||
result: CompactionResult | null = RESULT
|
||||
failure: unknown
|
||||
operation: (() => Promise<CompactionResult | null>) | undefined
|
||||
calls: { agent: ManualCompactAgentContext; signal: AbortSignal }[] = []
|
||||
|
||||
override compactIfNeeded(
|
||||
_agent: CompactAgentContext,
|
||||
_trigger: CompactionTrigger,
|
||||
_signal: AbortSignal,
|
||||
): Promise<CompactionResult | null> {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
|
||||
override compactRegion(): Promise<CompactionResult> {
|
||||
return Promise.resolve(RESULT)
|
||||
}
|
||||
|
||||
override compactNow(
|
||||
agent: ManualCompactAgentContext,
|
||||
signal: AbortSignal,
|
||||
): Promise<CompactionResult | null> {
|
||||
this.calls.push({ agent, signal })
|
||||
if (this.operation !== undefined) return this.operation()
|
||||
return this.failure === undefined
|
||||
? Promise.resolve(this.result)
|
||||
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise arbitrary backend rejection values.
|
||||
: Promise.reject(this.failure)
|
||||
}
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
readonly ctx: Context
|
||||
readonly compact: StubCompactService
|
||||
readonly agent: Agent
|
||||
readonly plugin: Awaited<ReturnType<Context['plugin']>>
|
||||
}
|
||||
|
||||
async function harness(): Promise<Harness> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(CommandService)
|
||||
const compact = new StubCompactService(ctx)
|
||||
const plugin = await ctx.plugin(commandCompact)
|
||||
const session = new Session(SessionId('command-compact'))
|
||||
const agent = {
|
||||
session,
|
||||
status: 'idle',
|
||||
options: {},
|
||||
reserveTurnAdmission: () => () => undefined,
|
||||
} as unknown as Agent
|
||||
return { ctx, compact, agent, plugin }
|
||||
}
|
||||
|
||||
async function run(
|
||||
test: Harness,
|
||||
suffix = '',
|
||||
controller = new AbortController(),
|
||||
): Promise<NonNullable<Awaited<ReturnType<CommandService['execute']>>>> {
|
||||
const execution = await test.ctx.commands.execute(test.agent, `/compact${suffix}`, controller.signal)
|
||||
if (execution === undefined) throw new Error('compact command was not registered')
|
||||
return execution
|
||||
}
|
||||
|
||||
/** Assert the executor-owned lifecycle pair and absence from model history. */
|
||||
function expectLastLifecycle(
|
||||
test: Harness,
|
||||
args: string,
|
||||
outcome: { readonly kind: 'success' | 'error'; readonly text?: string },
|
||||
): string {
|
||||
const lifecycle = test.agent.session.events.slice(-2)
|
||||
const runEvent = lifecycle[0]
|
||||
const doneEvent = lifecycle[1]
|
||||
if (runEvent?.type !== 'command/run' || doneEvent?.type !== 'command/done') {
|
||||
throw new Error(`expected command lifecycle pair, got ${lifecycle.map(event => event.type).join(',')}`)
|
||||
}
|
||||
expect(lifecycle.map(event => ({ type: event.type, data: event.data }))).toEqual([
|
||||
{
|
||||
type: 'command/run',
|
||||
data: {
|
||||
commandId: runEvent.data.commandId,
|
||||
name: 'compact',
|
||||
args,
|
||||
source: { kind: 'user' },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'command/done',
|
||||
data: {
|
||||
commandId: runEvent.data.commandId,
|
||||
...outcome,
|
||||
},
|
||||
},
|
||||
])
|
||||
expect(doneEvent.data.commandId).toBe(runEvent.data.commandId)
|
||||
expect(test.agent.session.surface.nodes).toEqual([])
|
||||
expect(test.agent.session.deriveMessages()).toEqual([])
|
||||
return runEvent.data.commandId
|
||||
}
|
||||
|
||||
describe('@deepseek-ai/dsh-command-compact registration', () => {
|
||||
it('registers one argument-free command with Loader-safe exports and disposes it', async () => {
|
||||
const test = await harness()
|
||||
expect(commandCompact.name).toBe('command-compact')
|
||||
expect(commandCompact.inject).toEqual(['commands', 'compact'])
|
||||
expect('default' in commandCompact).toBe(false)
|
||||
const loader = Object.create(Loader.prototype) as Loader
|
||||
expect(loader.unwrapExports(commandCompact)).toBe(commandCompact)
|
||||
expect(test.ctx.commands.list(test.agent)).toContainEqual({
|
||||
name: 'compact',
|
||||
description: 'Compact older conversation history',
|
||||
})
|
||||
|
||||
await test.plugin.dispose()
|
||||
expect(test.ctx.commands.find(test.agent, 'compact')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('/compact human command', () => {
|
||||
it('reports success with useful accounting and forwards the exact target and signal', async () => {
|
||||
const test = await harness()
|
||||
const controller = new AbortController()
|
||||
const execution = await run(test, '', controller)
|
||||
expect(execution.result).toEqual({
|
||||
kind: 'success',
|
||||
text: 'Compacted 3 history items (~42 tokens).',
|
||||
})
|
||||
expect(execution.commandId).toBe(expectLastLifecycle(test, '', execution.result))
|
||||
expect(test.compact.calls).toEqual([{ agent: test.agent, signal: controller.signal }])
|
||||
})
|
||||
|
||||
it('returns direct no-history and argument-rejection results', async () => {
|
||||
const test = await harness()
|
||||
test.compact.result = null
|
||||
const empty = await run(test)
|
||||
expect(empty.result).toEqual({
|
||||
kind: 'success',
|
||||
text: 'No compactable history yet.',
|
||||
})
|
||||
expect(empty.commandId).toBe(expectLastLifecycle(test, '', empty.result))
|
||||
|
||||
const rejected = await run(test, ' now')
|
||||
expect(rejected.result).toEqual({
|
||||
kind: 'error',
|
||||
text: 'Usage: /compact (no arguments)',
|
||||
})
|
||||
expect(rejected.commandId).toBe(expectLastLifecycle(test, ' now', rejected.result))
|
||||
expect(test.compact.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['busy', 'Compaction is unavailable because this process has an active compaction, or the agent is not idle.'],
|
||||
['changed', 'The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.'],
|
||||
['summary', 'Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.'],
|
||||
['commit', 'Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.'],
|
||||
['persistence', 'Compaction finished, but the session could not be saved.'],
|
||||
] as const)('maps expected %s failures to direct errors', async (code, text) => {
|
||||
const test = await harness()
|
||||
test.compact.failure = new ManualCompactionError(code, 'backend detail')
|
||||
const execution = await run(test)
|
||||
expect(execution.result).toEqual({ kind: 'error', text })
|
||||
expect(execution.commandId).toBe(expectLastLifecycle(test, '', execution.result))
|
||||
})
|
||||
|
||||
it('preserves cancellation and unexpected implementation failures', async () => {
|
||||
const cancelled = await harness()
|
||||
const controller = new AbortController()
|
||||
const abort = new Error('operator cancelled')
|
||||
cancelled.compact.operation = () => {
|
||||
controller.abort(abort)
|
||||
return Promise.reject(new ManualCompactionError('summary', 'late failure'))
|
||||
}
|
||||
await expect(run(cancelled, '', controller)).rejects.toBe(abort)
|
||||
expectLastLifecycle(cancelled, '', { kind: 'error', text: abort.message })
|
||||
|
||||
const unexpected = await harness()
|
||||
const bug = new Error('unexpected backend bug')
|
||||
unexpected.compact.failure = bug
|
||||
await expect(run(unexpected)).rejects.toBe(bug)
|
||||
expectLastLifecycle(unexpected, '', { kind: 'error', text: bug.message })
|
||||
})
|
||||
})
|
||||
18
packages/compact/command-compact/tests/invariant.spec.ts
Normal file
18
packages/compact/command-compact/tests/invariant.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import * as invariant from '@deepseek-ai/dsh-command-compact/invariant'
|
||||
|
||||
describe('command-compact invariant companion', () => {
|
||||
it('registers the package-owned no-op installer', async () => {
|
||||
const register = vi.fn().mockReturnValue(() => {})
|
||||
const ctx = { invariants: { register } } as never
|
||||
const dispose = await invariant.apply(ctx)
|
||||
expect(invariant.name).toBe('command-compact-invariant')
|
||||
expect(invariant.inject).toEqual(['invariants'])
|
||||
expect(register).toHaveBeenCalledWith('@deepseek-ai/dsh-command-compact', expect.any(Function))
|
||||
expect(() => {
|
||||
const install = register.mock.calls[0]![1] as () => void
|
||||
install()
|
||||
}).not.toThrow()
|
||||
expect(dispose).toBeTypeOf('function')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import Loader from '@cordisjs/plugin-loader'
|
||||
import Include from '@cordisjs/plugin-include'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import CommandService from '@deepseek-ai/dsh-commands'
|
||||
import {
|
||||
CompactService,
|
||||
type CompactAgentContext,
|
||||
type CompactionResult,
|
||||
type CompactionTrigger,
|
||||
type ManualCompactAgentContext,
|
||||
} from '@deepseek-ai/dsh-compact'
|
||||
import * as commandCompact from '@deepseek-ai/dsh-command-compact'
|
||||
import { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
|
||||
const RESULT: CompactionResult = {
|
||||
startSeq: 1,
|
||||
summarySeq: 2,
|
||||
endSeq: 4,
|
||||
summary: [{ type: 'text', text: 'loader summary' }],
|
||||
shadowedRange: { start: 3, end: 8 },
|
||||
shadowedSeqs: [3, 5, 8],
|
||||
shadowedTokenCount: 99,
|
||||
}
|
||||
|
||||
class LoaderCompactService extends CompactService {
|
||||
override compactIfNeeded(
|
||||
_agent: CompactAgentContext,
|
||||
_trigger: CompactionTrigger,
|
||||
_signal: AbortSignal,
|
||||
): Promise<CompactionResult | null> {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
|
||||
override compactRegion(): Promise<CompactionResult> {
|
||||
return Promise.resolve(RESULT)
|
||||
}
|
||||
|
||||
override compactNow(
|
||||
_agent: ManualCompactAgentContext,
|
||||
_signal: AbortSignal,
|
||||
): Promise<CompactionResult | null> {
|
||||
return Promise.resolve(RESULT)
|
||||
}
|
||||
}
|
||||
|
||||
let root: string | undefined
|
||||
let context: Context | undefined
|
||||
|
||||
afterEach(async () => {
|
||||
await context?.fiber.dispose()
|
||||
context = undefined
|
||||
if (root !== undefined) await rm(root, { recursive: true, force: true })
|
||||
root = undefined
|
||||
})
|
||||
|
||||
describe('command-compact real Loader composition', () => {
|
||||
it('discovers and executes /compact through the assembled command plane', async () => {
|
||||
root = await mkdtemp(join(tmpdir(), 'dsh-command-compact-loader-'))
|
||||
const configPath = join(root, 'cordis.yml')
|
||||
await writeFile(configPath, [
|
||||
"- name: '@deepseek-ai/dsh-commands'",
|
||||
"- name: '@test/compact-backend'",
|
||||
"- name: '@deepseek-ai/dsh-command-compact'",
|
||||
'',
|
||||
].join('\n'))
|
||||
|
||||
context = new Context()
|
||||
context.baseUrl = pathToFileURL(root).href + '/'
|
||||
await context.plugin(Loader)
|
||||
context.loader.builtins.include = Include
|
||||
const modules = new Map<string, unknown>([
|
||||
['@deepseek-ai/dsh-commands', CommandService],
|
||||
['@test/compact-backend', LoaderCompactService],
|
||||
['@deepseek-ai/dsh-command-compact', commandCompact],
|
||||
])
|
||||
context.loader.internal = {
|
||||
version: 'v2',
|
||||
async import(specifier: string) {
|
||||
if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
|
||||
return modules.get(specifier)
|
||||
},
|
||||
} as unknown as NonNullable<typeof context.loader.internal>
|
||||
await context.loader.create({
|
||||
name: 'cordis:include',
|
||||
config: { path: pathToFileURL(configPath).href },
|
||||
})
|
||||
await context.loader.await()
|
||||
|
||||
const session = new Session(SessionId('loader-command-compact'))
|
||||
const agent = {
|
||||
session,
|
||||
status: 'idle',
|
||||
options: {},
|
||||
reserveTurnAdmission: () => () => undefined,
|
||||
} as unknown as Agent
|
||||
expect(context.commands.list(agent)).toContainEqual({
|
||||
name: 'compact',
|
||||
description: 'Compact older conversation history',
|
||||
})
|
||||
const execution = await context.commands.execute(agent, '/compact', new AbortController().signal)
|
||||
if (execution === undefined) throw new Error('Loader composition did not resolve /compact')
|
||||
expect(execution.result).toEqual({
|
||||
kind: 'success',
|
||||
text: 'Compacted 3 history items (~99 tokens).',
|
||||
})
|
||||
expect(session.events.map(event => ({ type: event.type, data: event.data }))).toEqual([
|
||||
{
|
||||
type: 'command/run',
|
||||
data: {
|
||||
commandId: execution.commandId,
|
||||
name: 'compact',
|
||||
args: '',
|
||||
source: { kind: 'user' },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'command/done',
|
||||
data: {
|
||||
commandId: execution.commandId,
|
||||
kind: 'success',
|
||||
text: 'Compacted 3 history items (~99 tokens).',
|
||||
},
|
||||
},
|
||||
])
|
||||
expect(session.surface.nodes).toEqual([])
|
||||
expect(session.deriveMessages()).toEqual([])
|
||||
})
|
||||
})
|
||||
27
packages/compact/command-compact/tsconfig.json
Normal file
27
packages/compact/command-compact/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cosmokit"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../ui/commands"
|
||||
},
|
||||
{
|
||||
"path": "../compact"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user