deepseek-harness/packages/compaction/command-compact/tests/loader-composition.spec.ts

186 lines
5.9 KiB
TypeScript
Raw Normal View History

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'
build(vendor): rescope the vendored Cordis packages into @deepseek-ai Machine-produced by `pnpm run rescope-vendor --apply` plus the regeneration it prints: `pnpm install` for the lockfile, `pnpm run gen-third-party-notices`, `verify-translation-pairing --write` for the touched bilingual pairs, `gen-doc-graphs`, and one typert snapshot whose ids embed character offsets. `pnpm run rescope-vendor --check` verifies the result. Renames nine vendored packages (cordis, cosmokit, schemastery and the six @cordisjs plugins) and every reference that resolves them: manifest names and dependency keys, module specifiers including declare-module merges, cordis.yml plugin names, tsconfig paths, every Markdown fence, and `docs/` prose. Directory names, upstream versions, and dependency ranges are unchanged, so vendor/README.md still reads as an upstream snapshot; its manifest table gains an upstream-name column so THIRD_PARTY_NOTICES keeps MIT attribution pointed at each fork's origin. The tutorial tier follows the rename end to end: its yaml fences named plugins the Loader can no longer resolve, its `ts ignore-check` fences disagreed with the compiled fences beside them, and its prose quoted both. The contracts that told readers to keep upstream names — the root convention and the vendoring cookbook's tree comment and manifest invariant — now say to rescope instead. Two rules read `@deepseek-ai/` as "another workspace plugin": the client bundle purity gate now names the vendored libraries a browser bundle inlines, and the files where a bare `cordis` is an agent-preset id keep that product data.
2026-08-10 22:04:06 +08:00
import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import Include from '@deepseek-ai/cordis-plugin-include'
import type { Agent } from '@deepseek-ai/dsh-agent'
import CommandRuntime from '@deepseek-ai/dsh-commands'
import {
CompactionId,
CompactionEngine,
type CompactionAgentContext,
type CompactionResult,
type CompactionTrigger,
type ManualCompactAgentContext,
} from '@deepseek-ai/dsh-compaction'
import * as commandCompact from '@deepseek-ai/dsh-command-compact'
import { Session, SessionId } from '@deepseek-ai/dsh-session'
const COMPACTION_ID = CompactionId('loader-command-compact-test')
const RESULT: CompactionResult = {
compactionId: COMPACTION_ID,
startSeq: 1,
summarySeq: 2,
endSeq: 3,
summary: [{ type: 'text', text: 'loader summary' }],
shadowedRange: { start: 3, end: 8 },
shadowedSeqs: [3, 5, 8],
shadowedTokenCount: 99,
}
class LoaderCompactionEngine extends CompactionEngine {
override compactIfNeeded(
_agent: CompactionAgentContext,
_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,
sourceCommandId?: Parameters<CompactionEngine['compactNow']>[2],
): Promise<CompactionResult | null> {
const provenance = {
compactionId: RESULT.compactionId,
...sourceCommandId === undefined ? {} : { sourceCommandId },
}
agent.session.append('compaction/start', { ...provenance, turn: null })
agent.session.append('compaction/summary', {
...provenance,
summary: RESULT.summary,
shadowedRange: RESULT.shadowedRange,
shadowedSeqs: RESULT.shadowedSeqs,
shadowedTokenCount: RESULT.shadowedTokenCount,
provider: 'loader-test',
model: 'loader-test',
})
agent.session.append('compaction/end', { ...provenance, turn: null })
return Promise.resolve({ ...RESULT, ...provenance })
}
}
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', CommandRuntime],
['@test/compact-backend', LoaderCompactionEngine],
['@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 = Session.create(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',
})
feat(commands): route composer image attachments through slash commands A claimed slash command consumed only the text half of the composer submission: /goal with reference images executed, cleared the draft, and silently stranded the images in the rail. Model-visible attachment intent had no route through the command plane. The submission envelope is now modeled end to end. CommandDefinition input.images declares acceptance; the declaration rides the descriptor to every client, onto the minted CommandClaim, and into the input machine's claim snapshot. commands.execute carries the submission's base64 images and enforces the declaration in the executor: non-declaring commands, a missing attachment store, and exceeded batch limits settle as logged error results before the handler runs. Admission reuses the attachment package's new admitEncodedImages, extracted from api-proxy's prompt path so both wire endpoints share one limits/validation/commit sequence. Producers own model visibility: /goal submits one user followup (image blocks + a fixed reference line) after a successful create/edit so goal rounds read the images from session history; /plan folds them into its steered message. Grammar misfits (/goal pause, bare /plan, /plan off) return direct errors and the composer keeps the images. On the client, enter adjudication carries a SubmitEnvelope and every command route that cannot consume images throws a localized refusal that renders as one composer notice with draft and images retained; the claimed pre-gate applies the same copy. An accepting claim serializes the draft images, forwards them to commands.execute, and clears plus releases them only on a success outcome. The assembled web test roster gains the ui-input-trigger and ui-commands plugins, mirroring the shipped composition, so slash submissions exercise the command plane; a new keyless snapshot pins the refusal banner and the accepting /goal flow over the built client graph.
2026-08-17 18:57:55 +08:00
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).',
sourceEventSeq: RESULT.summarySeq,
})
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: 'compaction/start',
data: {
compactionId: COMPACTION_ID,
sourceCommandId: execution.commandId,
turn: null,
},
},
{
type: 'compaction/summary',
data: {
compactionId: COMPACTION_ID,
sourceCommandId: execution.commandId,
summary: RESULT.summary,
shadowedRange: RESULT.shadowedRange,
shadowedSeqs: RESULT.shadowedSeqs,
shadowedTokenCount: RESULT.shadowedTokenCount,
provider: 'loader-test',
model: 'loader-test',
},
},
{
type: 'compaction/end',
data: {
compactionId: COMPACTION_ID,
sourceCommandId: execution.commandId,
turn: null,
},
},
{
type: 'command/done',
data: {
commandId: execution.commandId,
kind: 'success',
text: 'Compacted 3 history items (~99 tokens).',
sourceEventSeq: RESULT.summarySeq,
},
},
])
expect(session.surface.nodes).toEqual([])
expect(session.deriveMessages()).toEqual([])
})
})