Document the codebase thoroughly and tighten type safety

Docs: per-folder README.md for packages/ (family overview + one per
package: service, events, API, extension points, TODOs), examples/,
and examples/echo-agent/; folder-level AGENTS.md (+ CLAUDE.md
symlinks) for packages/ and vendor/; module-level doc comments in
every packages/*/src file; richer JSDoc on all exported API
(event side effects, disposal contracts, error behavior). Root
AGENTS.md gains a "Type Safety and Documentation" policy section:
the codebase aims to be very type-safe and well documented; type
gymnastics are acceptable in core packages when they improve
plugin-author DX; verbose docs are fine as long as they stay strictly
in sync with the code.

Type safety: removed the upstream-inherited "noImplicitAny": false
from tsconfig.base.json — packages/* now compile under full strict
mode; vendor/loader and vendor/include set it locally (vendor/cordis
already did). Eliminated every `: any` / `as any` from packages and
examples (catch clauses use unknown + a CodedError narrowing type;
event data access uses discriminated-union narrowing).

Typed tool schemas: new @deepseek-ai/dsh-tools schema DSL —
SchemaSpec with per-property `required: true` booleans, type-level
InferArgs<S>, a runtime SchemaSpec → JSON Schema converter, and
defineTool() so first-party tools get typed execute(args) with zero
casts (raw JSON Schema still accepted for MCP interop; chosen over
schemastery because it targets JSON Schema generation directly).
echo-tool and all test tools migrated; +7 tests.
This commit is contained in:
Tianyi Cui
2026-06-11 12:39:27 +08:00
parent 217b8ec0e2
commit 7f024a1a9d
35 changed files with 1274 additions and 101 deletions

View File

@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import LlmService, { StreamChunk } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionEventType } from '@deepseek-ai/dsh-session'
import LlmService, { StreamChunk, ToolResultBlock } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionEventType, TurnEndReason } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import AgentLoop, { LoopAgent } from '@deepseek-ai/dsh-agent-loop'
import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
@@ -76,14 +76,14 @@ describe('agent loop', () => {
textResponse('done'),
])
const ctx = await harness(adapter)
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'echo',
description: 'echo back',
parameters: { type: 'object' },
async execute(args: any) {
parameters: { text: { type: 'string' } },
async execute(args) {
return [{ type: 'text', text: `echo: ${args.text}` }]
},
})
}))
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
send(agent, 'use the tool')
@@ -99,7 +99,7 @@ describe('agent loop', () => {
expect(toolResultMessage).toBeDefined()
const block = toolResultMessage!.content.find(b => b.type === 'tool-result')!
expect(block).toMatchObject({ toolCallId: 'c1', isError: false })
expect((block as any).content).toEqual([{ type: 'text', text: 'echo: ping' }])
expect((block as ToolResultBlock).content).toEqual([{ type: 'text', text: 'echo: ping' }])
// session log records call + result
const types = agent.session.events.map(e => e.type)
@@ -111,14 +111,14 @@ describe('agent loop', () => {
const adapter = new MockAdapter([textResponse('ok')])
const ctx = await harness(adapter)
ctx.systemPrompt.section({ name: 'persona', order: 0, text: 'You are a test agent.' })
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'noop',
description: 'does nothing',
parameters: { type: 'object' },
parameters: {},
async execute() {
return []
},
})
}))
const agent = ctx.agentLoop.create('a1', { model: 'mock', systemPrompt: 'Agent-specific suffix.' })
send(agent, 'hi')
@@ -146,9 +146,9 @@ describe('agent loop', () => {
expect(streamed).toHaveLength(7)
// replay: chunk events alone re-assemble to the recorded assistant message
const deltaText = chunkEvents
.map(e => (e.data as any).chunk)
.filter((c: StreamChunk) => c.type === 'text-delta')
.map((c: any) => c.text)
.flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
.filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
.map(c => c.text)
.join('')
expect(deltaText).toBe('abc')
})
@@ -161,16 +161,16 @@ describe('agent loop', () => {
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'slow',
description: '',
parameters: { type: 'object' },
parameters: {},
async execute() {
// steer while the turn is running (during tool execution)
agent.steer([{ type: 'text', text: 'change of plans' }])
return [{ type: 'text', text: 'tool done' }]
},
})
}))
send(agent, 'start')
await waitForIdle(ctx, agent)
@@ -243,14 +243,14 @@ describe('agent loop', () => {
it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
const ctx = await harness(adapter)
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'echo',
description: '',
parameters: { type: 'object' },
async execute(args: any) {
parameters: { text: { type: 'string' } },
async execute(args) {
return [{ type: 'text', text: String(args.text) }]
},
})
}))
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
ctx.on('agent/turn-continuation', async () => false as const)
@@ -284,7 +284,7 @@ describe('agent loop', () => {
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
const reasons: any[] = []
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
send(agent, 'go')
@@ -348,7 +348,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
const errors: Error[] = []
const reasons: any[] = []
const reasons: TurnEndReason[] = []
ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
@@ -389,14 +389,14 @@ describe('agent loop', () => {
textResponse('done'),
])
const ctx = await harness(adapter)
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'echo',
description: '',
parameters: { type: 'object' },
async execute(args: any) {
parameters: { text: { type: 'string' } },
async execute(args) {
return [{ type: 'text', text: String(args.text) }]
},
})
}))
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
send(agent, 'run')
await waitForIdle(ctx, agent)

View File

@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import LlmService, { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm'
import SessionStore, { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import LlmService, { ContentBlock, MessageSource, StreamChunk } from '@deepseek-ai/dsh-llm'
import SessionStore, { Session, SessionEvent, TurnEndReason } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import AgentLoop, { LoopAgent } from '@deepseek-ai/dsh-agent-loop'
import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
@@ -45,15 +45,15 @@ describe('HIGH: session log records what agent/step-result actually produced', (
const adapter = new MockAdapter([textResponse('original'), textResponse('done')])
const ctx = await harness(adapter)
const executed: string[] = []
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'injected-tool',
description: '',
parameters: { type: 'object' },
parameters: {},
async execute() {
executed.push('injected-tool')
return [{ type: 'text', text: 'ran' }]
},
})
}))
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
// Plugin rewrites the message: replaces the text AND adds a tool call.
@@ -81,7 +81,8 @@ describe('HIGH: session log records what agent/step-result actually produced', (
expect(JSON.stringify(recorded.data)).not.toContain('original')
// tool/call + tool/result correlate with the injected call id
const callEvent = agent.session.events.find(e => e.type === 'tool/call')!
expect((callEvent.data as any).callId).toBe('c-injected')
if (callEvent.type !== 'tool/call') throw new Error('wrong event type')
expect(callEvent.data.callId).toBe('c-injected')
// derived history shows the rewritten message (replay-correct)
const derived = agent.session.deriveMessages()
expect(JSON.stringify(derived)).toContain('rewritten')
@@ -105,27 +106,27 @@ describe('HIGH: abort during tool execution ends the turn', () => {
const ctx = await harness(adapter)
const executed: string[] = []
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'aborter',
description: '',
parameters: { type: 'object' },
parameters: {},
async execute() {
executed.push('aborter')
agent.abort('user interrupt')
return [{ type: 'text', text: 'done' }]
},
})
ctx.tools.register({
}))
ctx.tools.register(defineTool({
name: 'second',
description: '',
parameters: { type: 'object' },
parameters: {},
async execute() {
executed.push('second')
return [{ type: 'text', text: 'done' }]
},
})
}))
const reasons: any[] = []
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
send(agent, 'go')
@@ -144,14 +145,14 @@ describe('HIGH: steering from late extension points is never stranded', () => {
textResponse('after steering'),
])
const ctx = await harness(adapter)
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'echo',
description: '',
parameters: { type: 'object' },
async execute(args: any) {
parameters: { text: { type: 'string' } },
async execute(args) {
return [{ type: 'text', text: String(args.text) }]
},
})
}))
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
let steeredOnce = false
@@ -301,7 +302,7 @@ describe('MEDIUM: disposed status is part of the agent/status contract', () => {
}, { inject: ['agentLoop'] }))
const statuses: string[] = []
const reasons: any[] = []
const reasons: TurnEndReason[] = []
ctx.on('agent/status', (_agent, status) => void statuses.push(status))
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
@@ -384,18 +385,18 @@ describe('MEDIUM: misc registry and config fixes', () => {
const adapter = new MockAdapter([toolCallResponse('c1', 'noop', {}), textResponse('done')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create('a1', { model: 'mock' })
ctx.tools.register({
ctx.tools.register(defineTool({
name: 'noop',
description: '',
parameters: { type: 'object' },
parameters: {},
async execute() {
agent.steer([{ type: 'text', text: 's' }], { source: { kind: 'plugin', plugin: 'goal' } })
return []
},
})
}))
const queuedSources: any[] = []
const steeringSources: any[] = []
const queuedSources: { source: MessageSource; steering: boolean }[] = []
const steeringSources: MessageSource[] = []
ctx.on('agent/queued', (_agent, _content, info) => void queuedSources.push(info))
ctx.on('agent/steering', (_agent, _turn, _content, source) => void steeringSources.push(source))