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

@@ -0,0 +1,83 @@
# dsh-agent-loop
THE concrete agent plugin: `LoopAgent` and the loop driver. Implements the
`Agent` interface and drives the session/turn/step lifecycle.
This is the only package in the harness that contains concrete loop logic.
Everything else is an abstract service or a plugin against extension seams —
new behavior goes into plugins, not here.
## Service: `AgentLoop` (ctx key: `agentLoop`)
### Public API
- `ctx.agentLoop.create(id: string, options?: AgentOptions): LoopAgent`
Create an agent, start its loop, and register it in `ctx.agents`. Disposed
with the calling fiber.
### Injected services
`agents`, `sessions`, `llm`, `tools`, `systemPrompt` — all five interface
services.
### Configuration (schemastery)
```ts
Config: {
agents: Array<{
id: string // required
model?: string
systemPrompt?: string
}>
}
```
Agents listed in config are auto-created at startup.
### Classes
- `LoopAgent` — the concrete `Agent` implementation. Owns the inbox (`Inbox`),
the per-step `AbortController`, and the loop driver. Everything observable
happens through session events and the `agent/*` event taxonomy.
- `Inbox` — per-agent queued + steering FIFOs (`enqueue`, `steer`, `drainQueued`,
`drainSteering`, `waitForQueued`).
### Loop lifecycle (`loop.ts`)
One invocation of `runLoop()` drives one agent for its whole lifetime:
```
forever:
wait for queued messages (idle)
TURN (error-contained):
drain queued → session('user/message') → 'turn/start'
STEP loop:
drain steering
assembly = systemPrompt.assemble()
request = waterfall agent/request
stream llm.stream(request) → session('assistant/chunk')
message = waterfall agent/step-result
session('assistant/message')
each tool-call: session('tool/call') → tools.execute() → session('tool/result')
drain steering → session('steering/message')
cont = waterfall agent/turn-continuation
if !cont: break
session('turn/end')
await session/flush
re-enqueue leftover steering as queued
idle unless more queued
```
Error containment: a throwing plugin ends the **turn**, never the loop. Dispose
mid-turn emits `agent/status('disposed')` and ends with reason `disposed`.
### What is NOT here
Everything that goes beyond "call the model, run the tools, repeat" belongs to
plugins listening on the event taxonomy:
- Hooks: `agent/request`, `agent/step-result`, `tools/execute`, `agent/turn-continuation`
- Compaction: `agent/request`
- Sandbox, permission, plan mode: `tools/execute`
- Sub-agents: TODO seam on `AgentLoop.create()`
- Persistence: `session/event` + `session/flush`
- UI: `agent/stream-chunk` + `agent/*` events

View File

@@ -1,3 +1,11 @@
/**
* The concrete Agent implementation: LoopAgent plus its inbox. Everything
* observable happens through session events and the agent/* event taxonomy —
* plugins never need this class.
*
* @module dsh-agent-loop/agent
*/
import type { Context } from 'cordis'
import type { AgentOptions, AgentStatus, SendOptions } from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
@@ -72,7 +80,12 @@ export class LoopAgent implements Agent {
this.currentAbort?.abort(reason ?? 'aborted')
}
/** Start the driver loop. Returns a disposer that stops it. */
/**
* Start the driver loop. Returns a disposer: calling it sets status to
* `disposed`, emits `agent/status('disposed')`, resolves the disposed
* promise (unblocking the idle wait), and aborts the current request if
* any. The returned `agent.done` promise resolves once the loop exits.
*/
start(): () => void {
this.done = runLoop(this.ctx, this, {
setStatus: status => this.setStatus(status),

View File

@@ -1,3 +1,11 @@
/**
* Per-agent message inbox: queued and steering FIFOs. Purely an in-memory
* mechanism of the loop driver — the public surface is `Agent.send()` and
* `Agent.steer()`.
*
* @module dsh-agent-loop/inbox
*/
import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
/** One message waiting in an agent's inbox. */

View File

@@ -1,3 +1,12 @@
/**
* THE concrete agent plugin: creates LoopAgents, runs their loops, and
* registers them in ctx.agents. Deliberately thin — every behavior beyond
* "call the model, run the tools, repeat" belongs to plugins on the event
* taxonomy.
*
* @module @deepseek-ai/dsh-agent-loop
*/
import { Context, Service } from 'cordis'
import z from 'schemastery'
import type { AgentOptions } from '@deepseek-ai/dsh-agent'

View File

@@ -1,3 +1,12 @@
/**
* The agent loop driver: one `runLoop()` invocation drives one agent for its
* whole lifetime. Error-contained at the turn level — a throwing plugin ends
* the turn, never kills the loop. See the JSDoc on `runLoop()` for the full
* lifecycle pseudo-code.
*
* @module dsh-agent-loop/loop
*/
import type { Context } from 'cordis'
import type { GenerateOptions, Message } from '@deepseek-ai/dsh-llm'
import { BlockAssembler } from '@deepseek-ai/dsh-llm'
@@ -6,6 +15,14 @@ import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import type {} from '@deepseek-ai/dsh-tools'
import type { LoopAgent } from './agent.ts'
/** An Error with an optional machine-readable code (e.g., from LlmError or a throwing plugin). */
type CodedError = Error & { code?: string }
/**
* Ambient handles the loop driver receives from the agent. Decouples the
* pure function `runLoop` from the mutable LoopAgent fields, making the
* loop testable without a real agent.
*/
export interface LoopHandle {
setStatus(status: 'idle' | 'running'): void
setAbort(controller: AbortController | undefined): void
@@ -58,12 +75,12 @@ export async function runLoop(ctx: Context, agent: LoopAgent, handle: LoopHandle
turn += 1
try {
await runTurn(ctx, agent, handle, turn)
} catch (error: any) {
} catch (error: unknown) {
// Backstop: a throwing emit listener (turn boundaries) or a broken
// finalizer must not kill the driver. Record what we can and move on.
try {
const err = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step: 0, message: err.message, code: (err as any).code })
const err: CodedError = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step: 0, message: err.message, code: err.code })
ctx.emit('agent/error', agent, turn, 0, err)
} catch { /* the error path itself is broken; nothing left to do */ }
}
@@ -110,7 +127,7 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
let stepOutcome: { hadToolCalls: boolean } | { error: Error }
try {
stepOutcome = await runStep(ctx, agent, turn, step, abort.signal)
} catch (error: any) {
} catch (error: unknown) {
stepOutcome = { error: error instanceof Error ? error : new Error(String(error)) }
} finally {
handle.setAbort(undefined)
@@ -128,9 +145,10 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
} else if (abort.signal.aborted) {
reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
} else {
session.append('error', { turn, step, message: error.message, code: (error as any).code })
const coded = error as CodedError
session.append('error', { turn, step, message: coded.message, code: coded.code })
ctx.emit('agent/error', agent, turn, step, error)
reason = { kind: 'error', message: error.message, code: (error as any).code }
reason = { kind: 'error', message: coded.message, code: coded.code }
}
break
}
@@ -148,12 +166,12 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
'agent/turn-continuation', agent, turn, defaultDecision,
async () => defaultDecision,
)
} catch (error: any) {
} catch (error: unknown) {
// A broken continuation plugin ends the turn, not the loop.
const err = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step, message: err.message, code: (err as any).code })
const err: CodedError = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step, message: err.message, code: err.code })
ctx.emit('agent/error', agent, turn, step, err)
reason = { kind: 'error', message: err.message, code: (err as any).code }
reason = { kind: 'error', message: err.message, code: err.code }
break
}
@@ -175,9 +193,9 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
// A failing persistence plugin is reported but doesn't kill the agent.
try {
await ctx.parallel('session/flush', session)
} catch (error: any) {
const err = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step, message: err.message, code: (err as any).code })
} catch (error: unknown) {
const err: CodedError = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step, message: err.message, code: err.code })
ctx.emit('agent/error', agent, turn, step, err)
}
}

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))