Reorganize packages into a modular hierarchy

Move the 18 flat packages/<name> packages into role-grouped dirs:
core/, llm/, bash/, session-persistence/, ui/, support/. Group dirs are
pure containers; each package keeps its @deepseek-ai/dsh-* name.

Collapse the per-package tsconfig paths maps (base + typecheck) into one
@deepseek-ai/dsh-* wildcard with a candidate per group, and derive the
publint list from the hierarchy. Update all depth-coupled globs/configs
(workspace, tsdown, vitest, eslint, knip, tsconfig includes/refs,
per-package tsconfigs, generators, doc-script scopes, type-equiv manifest)
and the cross-package/script relative imports in tests.

Fix doc-typecheck's workspacePaths() to parse tsconfig JSONC via the
TypeScript API instead of a regex comment-strip, which corrupted the
new wildcard `/*/` path candidates.

WIP: doc cross-links and package/RFC docs still to update.
This commit is contained in:
Tianyi Cui
2026-06-20 22:55:20 +08:00
parent 906705e353
commit d02e9f1bd6
191 changed files with 822 additions and 624 deletions
+376
View File
@@ -0,0 +1,376 @@
/**
* Tool registry and execution waterfall. Plugins register tools; the registry
* feeds schemas into the system prompt, and `execute()` dispatches each call
* through the `tools/execute` waterfall for sandbox, permission, and hook
* plugins to wrap or veto.
*
* @module @deepseek-ai/dsh-tools
*/
import { Context, Service } from 'cordis'
import type { CallId, ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm'
import { HarnessError } from '@deepseek-ai/dsh-llm'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-system-prompt'
export {
defineTool,
schemaSpecToJsonSchema,
validateArgs,
ToolArgsError,
type SchemaSpec,
type SchemaProp,
type SchemaType,
type InferArgs,
type DefineToolOptions,
type JsonSchemaObject,
} from './schema.ts'
declare module 'cordis' {
interface Context {
tools: ToolRegistry
}
interface Events {
/**
* Waterfall around every tool execution — the single seam where sandbox,
* permission, hook, and plan-mode plugins wrap or veto a call. Listeners
* receive `(exec, next)`: call `next()` to proceed (possibly around your
* own logic), or return a {@link ToolExecutionResult} without calling
* `next()` to short-circuit (veto).
* @mode waterfall
*/
'tools/execute'(this: ToolRegistry, exec: ToolExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult>
/**
* A tool was registered or unregistered (the available tool set changed).
* @mode emit
*/
'tools/change'(): void
}
}
// TODO(review): revisit these shapes when the first real tools and
// sandbox/permission plugins land (e.g. a concurrency-safety hint for
// parallel execution — Claude Code partitions read-only tools; phase 1
// executes sequentially).
/**
* Category of a tool call, used by a UI to pick an icon / treatment. A neutral
* vocabulary owned here (NOT an ACP type) so tools describe themselves without
* depending on any client protocol; a UI bridge maps it to its own enum. The
* member set mirrors the common ACP `ToolKind` values; `other` is the default.
*/
export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other'
// FIXME(tool-presentation): the ToolCallPresentation / ToolResultPresentation /
// ToolTerminal shapes need a rethink. They grew incrementally (title/kind/
// rawInput, then a `content` block, then a `terminal` sub-shape carrying cwd/
// output/exit) and the split of responsibility is now muddy: the call vs result
// terminal fields overlap, the bridge has to reconcile a `content` block AND a
// `terminal` block AND `rawInput` per call, and the "pending vs completed"
// boundary doesn't cleanly map to how editors actually render (terminal card,
// diff, generic card). Before more tools/UIs depend on this, redesign the type
// so a tool declares its render INTENT once (e.g. a tagged union over card
// kinds) rather than a bag of optional fields the bridge stitches together.
// Pin the design in an RFC and migrate dsh-tool-bash + the ACP bridge together.
/**
* How a tool wants ONE of its calls shown in a UI (an editor's tool-call card,
* a CLI log line) BEFORE the result is known — the *pending* state. Provider-
* neutral: a tool returns this from {@link ToolDefinition.presentCall} and a UI
* plugin (e.g. the ACP bridge) maps it to its own wire shape. The tool owns its
* own presentation — the UI must not special-case tool names.
*/
export interface ToolCallPresentation {
/**
* Human-readable, always-visible label describing what THIS call does (e.g.
* the model-written one-line summary of a bash command). Keep it short — a UI
* shows it as a card header / log line. Required: a presentation must have a
* title (a UI falls back to the tool name only when `presentCall` is absent).
*/
title: string
/** Category for icon/treatment; defaults to `other` when omitted. */
kind?: ToolCallKind
/**
* The salient input to surface in a detail/expanded view — e.g. the bash
* COMMAND itself (as a string), so the title can stay a readable summary
* while the exact command is still visible. Omit to show nothing; a string is
* rendered as-is, an object as pretty JSON. NOT the full raw args object
* unless that is genuinely what a reader wants.
*/
rawInput?: unknown
/**
* UI-facing content to show on the PENDING call alongside the title/card —
* harness {@link ContentBlock}s, in render order. A terminal tool uses this to
* surface its human-readable `description` as a text block ABOVE the terminal
* card (the card itself is requested via {@link terminal} and labelled by the
* command in `title`), since the card has no description slot. Omit to show no
* extra content. A UI maps these to its own content blocks and renders a
* {@link terminal} block (if any) as a terminal card.
*/
content?: ContentBlock[]
/**
* Ask a capable UI to render this call as a TERMINAL (a command running in a
* working directory), not a generic tool card — set by a tool whose call IS a
* shell command (e.g. `bash`). Provider-neutral; a UI bridge maps it to its
* own terminal affordance and a UI that can't falls back to the normal card.
* Pair with {@link ToolResultPresentation.terminal} for the output/exit.
*/
terminal?: ToolTerminal
}
/**
* A request to render a tool call as a terminal. The pending presentation
* supplies the working directory; the result presentation (see
* {@link ToolResultPresentation.terminal}) supplies the captured output and exit
* status. Provider-neutral — no client-protocol types. A UI that supports
* terminals shows a cwd-headed terminal card with the command, its output, and
* an exit-status pill; a UI that does not ignores this and renders the ordinary
* card/content.
*/
export interface ToolTerminal {
/**
* Working directory the command ran in, shown as the terminal header. An
* ABSOLUTE path is used as-is; a RELATIVE path is resolved by the UI bridge
* against the session workspace (the pure tool presenter can't see the
* session cwd). Omit entirely to let the bridge use the session workspace.
*/
cwd?: string
/** Captured command output (stdout+stderr as the tool chooses to combine them). Result-state only. */
output?: string
/**
* Process exit code, when the run ended by exiting (not a signal). Result-state
* only; lets a capable UI show an exit-status pill on the terminal card. Omit
* when the command was killed by a signal or the exit code is unknown.
*/
exitCode?: number
/**
* Signal name that killed the process (e.g. `SIGTERM`), when it died by signal
* rather than exiting. Result-state only; mutually exclusive with `exitCode`.
*/
signal?: string
}
/**
* How a tool wants the COMPLETED call shown — the *result* state, after
* `execute` returns. Lets the tool reformat its result for a UI distinctly from
* the model-facing text it returned from `execute` (e.g. wrap command output in
* a fenced ```console block for monospace rendering, which the model-facing
* result must NOT carry). All fields optional: a UI keeps the pending-state
* title and renders the raw result content for anything left unset.
*/
export interface ToolResultPresentation {
/** Replacement title for the completed call (e.g. append an exit status). Omit to keep the pending-state title. */
title?: string
/**
* UI-facing result content (harness {@link ContentBlock}s), reformatted from
* the model-facing result. Omit to let the UI render the raw result content.
* Stays in harness vocabulary; the UI maps these to its own content blocks.
*/
content?: ContentBlock[]
/**
* Terminal output/exit for a call the pending presentation marked as a
* terminal (see {@link ToolCallPresentation.terminal}). A capable UI renders
* `output` in the terminal card and shows the exit status; an incapable UI
* uses `content` (the tool should supply a text fallback there too).
*/
terminal?: ToolTerminal
}
/** A registered tool: its schema plus the execution function. */
export interface ToolDefinition extends ToolSchema {
execute(args: unknown, exec: ToolExecution): Promise<ContentBlock[]>
/**
* Optional: how to present the PENDING state of one call in a UI, derived
* from the call's `args` (parsed arguments, `unknown` — the tool validates/
* narrows its own input). Returning `undefined` (or omitting the method) tells
* a UI to fall back to a generic presentation (title = tool name, raw args as
* input). Pure and side-effect-free: a UI may call it during live streaming
* AND a session-log replay, so it must depend only on `args`.
*/
presentCall?(args: unknown): ToolCallPresentation | undefined
/**
* Optional: how to present the COMPLETED state, given the same `args` and the
* `result` (`execute`'s content + whether it errored). Returning `undefined`
* (or omitting the method) tells a UI to keep the pending title and render the
* raw result content. Pure and side-effect-free for the same replay reason.
*/
presentResult?(args: unknown, result: ToolResult): ToolResultPresentation | undefined
}
/** The completed outcome handed to {@link ToolDefinition.presentResult}. */
export interface ToolResult {
/** The model-facing content `execute` returned (or the error text on failure). */
content: ContentBlock[]
/** Whether the call failed. */
isError: boolean
}
/** One pending tool call, as it flows through the execution waterfall. */
export interface ToolExecution {
callId: CallId
name: string
/** Parsed JSON arguments (unknown — tools validate their own input). */
arguments: unknown
/** The agent on whose behalf the call runs (set by the agent loop). */
agent?: Agent
signal?: AbortSignal
}
/** Structured error metadata for a failed tool call (alongside the model-facing text). */
export interface ToolErrorInfo {
name: string
code: string
}
/**
* Thrown (internally) when the model requests a tool that isn't registered.
* Extends {@link HarnessError} (`code: 'UNKNOWN_TOOL'`) so an unknown-tool
* failure is as routable as a tool-thrown one — retry/sandbox/replay code can
* distinguish it from a tool body's own error.
*/
export class ToolNotFoundError extends HarnessError {
constructor(public readonly toolName: string) {
super(`unknown tool "${toolName}"`, 'UNKNOWN_TOOL')
this.name = 'ToolNotFoundError'
}
}
/** The outcome of one tool call. */
export interface ToolExecutionResult {
callId: CallId
content: ContentBlock[]
isError: boolean
/**
* Set when the call failed with a {@link HarnessError}: machine-routable
* `{ name, code }` for retry/sandbox plugins and replay. The model-facing
* text in `content` is always present; this is extra structure for code.
*/
error?: ToolErrorInfo
}
/**
* Best-effort human-readable message from an arbitrary thrown value: Error
* instances use `.message`; non-Error objects with a string `message`
* property (e.g. `throw { message: 'denied' }`) use it too; everything else
* is stringified.
*/
function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message
if (typeof error === 'object' && error !== null
&& 'message' in error && typeof error.message === 'string') {
return error.message
}
return String(error)
}
/** Structured `{ name, code }` for a thrown HarnessError, else undefined. */
function errorInfo(error: unknown): ToolErrorInfo | undefined {
return error instanceof HarnessError ? { name: error.name, code: error.code } : undefined
}
/**
* Tool registry (`ctx.tools`): tool plugins register definitions; the agent
* loop executes calls through the `tools/execute` waterfall. The registry
* contributes its schemas into the system-prompt assembly.
*/
export class ToolRegistry extends Service {
static inject = ['systemPrompt']
private store = new Map<string, ToolDefinition>()
constructor(ctx: Context) {
super(ctx, 'tools')
ctx.systemPrompt.tools(() => this.schemas())
}
/**
* Register a tool. Throws if a tool with the same name is already
* registered. The tool's schema (minus the `execute` function) is
* automatically contributed to the system-prompt assembly. Disposed
* with the calling fiber. Emits `tools/change` on register/unregister.
*/
register(definition: ToolDefinition): () => void {
const dispose = this.ctx.effect(function* (this: ToolRegistry) {
if (this.store.has(definition.name)) {
throw new Error(`tool "${definition.name}" is already registered`)
}
this.store.set(definition.name, definition)
// Yield the rollback BEFORE emitting `tools/change`: a generator effect
// collects each yielded disposer before the next step runs, so a throwing
// `tools/change` listener removes the tool instead of leaking it (a leak
// would wedge the duplicate-name check until restart). The duplicate
// throw above fires before any mutation — it leaks nothing.
yield () => {
this.store.delete(definition.name)
this.ctx.emit('tools/change')
}
this.ctx.emit('tools/change')
}.bind(this), 'tools.register()')
// ctx.effect's disposer returns Promise<void>; our disposer API is
// synchronous fire-and-forget — discard the (always-resolved) promise.
return () => void dispose()
}
get(name: string): ToolDefinition | undefined {
return this.store.get(name)
}
/**
* Return all registered tool schemas — exactly the model-facing fields
* (`name`, `description`, `parameters`, and `strict` when set), as sent to the
* model via the system-prompt assembly. Constructed EXPLICITLY rather than by
* stripping known non-schema members: a `ToolDefinition` also carries
* `execute` and the optional `presentCall`/`presentResult` UI callbacks, and
* those (especially the functions) must never leak into a model request. An
* allowlist can't drift when a new non-schema member is added to the
* definition; a denylist (rest-destructure) would silently leak it.
*/
schemas(): ToolSchema[] {
return [...this.store.values()].map(({ name, description, parameters, strict }): ToolSchema => ({
name,
description,
parameters: structuredClone(parameters),
...strict !== undefined ? { strict } : {},
}))
}
/**
* Execute one tool call through the `tools/execute` waterfall. If the tool is
* not registered, the result is an `isError` carrying a `UNKNOWN_TOOL`
* structured error. If the tool or a waterfall listener throws, the error is
* caught and returned as an `isError` result so the loop records a failed tool
* call instead of failing the whole turn; a thrown {@link HarnessError}
* surfaces its `{ name, code }` on the result.
*/
async execute(exec: ToolExecution): Promise<ToolExecutionResult> {
try {
return await this.ctx.waterfall(this, 'tools/execute', exec, async (): Promise<ToolExecutionResult> => {
try {
const tool = this.store.get(exec.name)
// Unknown tool routes through the same catch as a tool-thrown error, so
// both failure classes get structured `{ name, code }` from one path.
if (!tool) throw new ToolNotFoundError(exec.name)
const content = await tool.execute(exec.arguments, exec)
return { callId: exec.callId, content, isError: false }
} catch (error: unknown) {
return toolErrorResult(exec.callId, error)
}
})
} catch (error: unknown) {
return toolErrorResult(exec.callId, error)
}
}
}
function toolErrorResult(callId: ToolExecution['callId'], error: unknown): ToolExecutionResult {
const info = errorInfo(error)
return {
callId,
content: [{ type: 'text', text: `Error: ${errorMessage(error)}` }],
isError: true,
...info ? { error: info } : {},
}
}
export default ToolRegistry
+384
View File
@@ -0,0 +1,384 @@
/**
* Typed tool-parameter schema DSL.
*
* Plugin authors write per-property specs with `required: true` as a boolean
* (the `SchemaSpec` type). A type-level helper (`InferArgs`) maps a SchemaSpec
* to the TS argument type. At runtime, `schemaSpecToJsonSchema()` converts a
* SchemaSpec to standard JSON Schema (`type: 'object'`, `properties`,
* `required` array) for the wire format sent to the model.
*
* # Why a custom DSL and not schemastery?
*
* Schemastery is a validation/transformation library (StandardSchema v1) used
* for plugin Config. Tool parameters need JSON Schema specifically (the LLM
* wire format), not validation. A lightweight DSL focused on JSON Schema
* generation, with type inference for the tool's `execute` args, gives plugin
* authors the best DX with the smallest surface area. Schemastery would add
* unnecessary indirection and wouldn't cleanly produce JSON Schema.
*
* @module dsh-tools/schema
*/
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { assertNever, HarnessError } from '@deepseek-ai/dsh-llm'
import type { ToolCallPresentation, ToolDefinition, ToolExecution, ToolResult, ToolResultPresentation } from './index.ts'
// ---------------------------------------------------------------------------
// SchemaSpec — the author-facing per-property type
// ---------------------------------------------------------------------------
/** Valid JSON Schema primitive types for tool parameters. */
export type SchemaType = 'string' | 'number' | 'boolean' | 'object' | 'array'
/** One schema-spec property entry. */
export interface SchemaProp {
type: SchemaType
/** Per-property required flag (NOT the JSON Schema top-level required array). */
required?: true
/** Human-readable description, surfaced in the JSON Schema as well. */
description?: string
/** Enum of allowed values (strings only). */
enum?: string[]
/**
* Default value, emitted into the JSON Schema only (validation never applies
* it — see the validator note below).
*
* XXX(unused-default): no tool definition in the repo sets `default`; it rides
* into the wire schema for a model that no tool surfaces it to. Drop the field
* and its converter line unless a real tool needs a model-visible default.
*/
default?: unknown
/** Nested properties for type: 'object'. */
properties?: SchemaSpec
/** Items schema for type: 'array'. */
items?: SchemaProp
}
/**
* The author-facing parameter schema: a shallow map of property name to
* {@link SchemaProp}. Required-ness is a per-property boolean (`required:
* true`), not a separate array.
*/
export type SchemaSpec = Record<string, SchemaProp>
// ---------------------------------------------------------------------------
// InferArgs — type-level mapping from SchemaSpec to TS argument type
// ---------------------------------------------------------------------------
/** Map a {@link SchemaType} to its TS primitive type. */
type TypeOf<T extends SchemaType> =
T extends 'string' ? string :
T extends 'number' ? number :
T extends 'boolean' ? boolean :
T extends 'object' ? Record<string, unknown> :
T extends 'array' ? unknown[] :
never
/** Flatten an intersection into one object type for readable hovers. */
type Simplify<T> = { [K in keyof T]: T[K] } & {}
/** Keys of `S` whose prop is marked `required: true`. */
type RequiredKeys<S extends SchemaSpec> =
{ [K in keyof S]: S[K] extends { required: true } ? K : never }[keyof S]
/**
* The VALUE type of one {@link SchemaProp} — optionality is handled at the
* key level by {@link InferArgs}, never here.
* - `properties` on 'object' → recurse into the nested SchemaSpec
* - `items` on 'array' → recurse into the item prop (arrays of objects work)
* - otherwise → the primitive for `type`
*/
type InferPropValue<P extends SchemaProp> =
P extends { type: 'object'; properties: infer Sub extends SchemaSpec } ? InferArgs<Sub> :
P extends { type: 'array'; items: infer Item extends SchemaProp } ? InferPropValue<Item>[] :
TypeOf<P['type']>
/**
* Infer the TS argument type for a complete {@link SchemaSpec}.
*
* Properties marked `required: true` are required keys; all others are
* genuinely optional keys (`?`), so callers may omit them entirely.
*
* Example:
* ```ts
* type Args = InferArgs<{ path: { type: 'string'; required: true }; limit: { type: 'number' } }>
* // → { path: string; limit?: number }
* ```
*/
export type InferArgs<S extends SchemaSpec> = Simplify<
& { [K in RequiredKeys<S>]: InferPropValue<S[K]> }
& { [K in Exclude<keyof S, RequiredKeys<S>>]?: InferPropValue<S[K]> }
>
// ---------------------------------------------------------------------------
// Runtime conversion: SchemaSpec → JSON Schema
// ---------------------------------------------------------------------------
/**
* Convert a single {@link SchemaProp} to its JSON Schema `properties` entry.
* The per-property `required` flag is collected; the caller builds the
* top-level `required` array.
*/
function propToJsonSchema(prop: SchemaProp): { schema: Record<string, unknown>; required: boolean } {
const result: Record<string, unknown> = { type: prop.type }
if (prop.description) result.description = prop.description
if (prop.enum) result.enum = prop.enum
if (prop.default !== undefined) result.default = prop.default
const required = prop.required === true
if (prop.type === 'object' && prop.properties) {
const nested = schemaSpecToJsonSchema(prop.properties)
result.properties = nested.properties
if (nested.required && nested.required.length > 0) {
result.required = nested.required
}
}
if (prop.type === 'array' && prop.items) {
const { schema: itemsSchema } = propToJsonSchema(prop.items)
result.items = itemsSchema
}
return { schema: result, required }
}
/** The return type of {@link schemaSpecToJsonSchema}. */
export interface JsonSchemaObject {
type: 'object'
properties: Record<string, unknown>
required?: string[]
}
/**
* Convert a {@link SchemaSpec} to standard JSON Schema (`type: 'object'`,
* `properties`, `required` array).
*
* This is a plain function — no schemastery or other framework dependency.
*/
export function schemaSpecToJsonSchema(spec: SchemaSpec): JsonSchemaObject {
const properties: Record<string, unknown> = {}
const required: string[] = []
for (const [key, prop] of Object.entries(spec)) {
const { schema, required: isRequired } = propToJsonSchema(prop)
properties[key] = schema
if (isRequired) required.push(key)
}
const result: JsonSchemaObject = {
type: 'object',
properties,
}
if (required.length > 0) result.required = required
return result
}
// ---------------------------------------------------------------------------
// Runtime validation: model-generated args ↔ SchemaSpec
// ---------------------------------------------------------------------------
/**
* Thrown by a {@link defineTool} tool when the model-generated arguments don't
* match the declared {@link SchemaSpec}. Extends {@link HarnessError}
* (`code: 'INVALID_ARGS'`); the registry's execute waterfall catches it and
* returns an `isError` ToolExecutionResult carrying the structured error, so
* the model can self-correct and downstream plugins can route on the code.
*/
export class ToolArgsError extends HarnessError {
/** The individual violation messages, in declaration order. */
readonly violations: string[]
constructor(violations: string[]) {
super(`invalid arguments: ${violations.join('; ')}`, 'INVALID_ARGS')
this.name = 'ToolArgsError'
this.violations = violations
}
}
/** Whether a value is a non-null, non-array object (a JSON Schema `object`). */
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/** Collect violations for one property value against its {@link SchemaProp}. */
function checkValue(prop: SchemaProp, value: unknown, path: string): string[] {
switch (prop.type) {
case 'string': {
if (typeof value !== 'string') return [`"${path}" must be a string`]
break
}
case 'number': {
if (typeof value !== 'number') return [`"${path}" must be a number`]
break
}
case 'boolean': {
if (typeof value !== 'boolean') return [`"${path}" must be a boolean`]
break
}
case 'object': {
if (!isPlainObject(value)) return [`"${path}" must be an object`]
// Mirror the converter: an object without `properties` only type-checks.
return prop.properties ? checkSpec(prop.properties, value, path) : []
}
case 'array': {
if (!Array.isArray(value)) return [`"${path}" must be an array`]
// Mirror the converter: an array without `items` only type-checks.
if (!prop.items) return []
const items = prop.items
return value.flatMap((el, i) => checkValue(items, el, `${path}[${i}]`))
}
default: return assertNever(prop.type, 'validateArgs')
}
// Enum membership, checked uniformly: the converter emits `enum` for any
// type ([prop.enum]), so the validator must too. `enum` is `string[]`, so a
// non-string value can never be a member — it falls out here, consistent
// with the schema the model was given.
if (prop.enum && !(prop.enum as unknown[]).includes(value)) {
return [`"${path}" must be one of ${JSON.stringify(prop.enum)}`]
}
return []
}
/** Collect violations for an object value against a {@link SchemaSpec}. */
function checkSpec(spec: SchemaSpec, value: unknown, path: string): string[] {
if (!isPlainObject(value)) return [`"${path || 'arguments'}" must be an object`]
const violations: string[] = []
for (const [key, prop] of Object.entries(spec)) {
const propPath = path ? `${path}.${key}` : key
const v = value[key]
if (v === undefined) {
// A required key absent OR present-but-undefined is a violation; an
// optional absent key is fine. `default` is NOT applied (validation only).
if (prop.required === true) violations.push(`missing required property "${propPath}"`)
continue
}
violations.push(...checkValue(prop, v, propPath))
}
return violations
}
/**
* Validate model-generated `args` against a {@link SchemaSpec}, returning a
* list of human-readable violation messages (empty = valid). Total — never
* throws, regardless of how malformed `args` is.
*
* Semantics mirror {@link schemaSpecToJsonSchema} exactly: the top level must
* be a non-array object; required keys come only from `required: true`; extra
* keys are allowed (no `additionalProperties: false`); `default` is not
* applied; an `object`/`array` prop without `properties`/`items` only
* type-checks; `enum` is membership (strings only).
*/
export function validateArgs(spec: SchemaSpec, args: unknown): string[] {
return checkSpec(spec, args, '')
}
// ---------------------------------------------------------------------------
// defineTool — typed helper for first-party plugin authors
// ---------------------------------------------------------------------------
/** Options for {@link defineTool}. */
export interface DefineToolOptions<S extends SchemaSpec> {
/** Tool name (must be unique). */
name: string
/** Human-readable description sent to the model. */
description: string
/**
* Parameter schema using the per-property-required DSL. Converted to
* standard JSON Schema at runtime.
*/
parameters: S
/**
* Tool execution function. `args` is typed as {@link InferArgs<S>} — zero
* casts needed.
*/
execute(args: InferArgs<S>, exec: ToolExecution): Promise<ContentBlock[]>
/**
* Optional: how to present the PENDING state of one call in a UI (an editor
* tool-call card, a CLI log line). `args` is the typed, schema-validated
* argument shape — zero casts. Pure and side-effect-free: a UI may call it
* during live streaming AND a session-log replay, so depend only on `args`.
* The tool owns its presentation so a UI never special-cases tool names. See
* {@link ToolCallPresentation}.
*/
presentCall?(args: InferArgs<S>): ToolCallPresentation | undefined
/**
* Optional: how to present the COMPLETED state, given the typed `args` and the
* `result`. Use it to reformat result content for a UI distinctly from the
* model-facing text (e.g. a fenced ```console block). Pure and side-effect-
* free for the same replay reason. See {@link ToolResultPresentation}.
*/
presentResult?(args: InferArgs<S>, result: ToolResult): ToolResultPresentation | undefined
/** Whether the tool requires structured output (default false). */
strict?: boolean
}
/**
* Define a tool with a typed parameter schema.
*
* Use this instead of constructing a raw {@link ToolDefinition} for all
* first-party tools. The `parameters` use the boolean-required style
* (`required: true` as a per-property flag), and `execute` receives typed
* args derived from the schema.
*
* ```ts
* const tool = defineTool({
* name: 'read_file',
* description: 'Read a file from disk.',
* parameters: {
* path: { type: 'string', required: true, description: 'Absolute file path' },
* offset: { type: 'number' },
* limit: { type: 'number', description: 'Max lines to read' },
* },
* async execute(args) {
* // args: { path: string; offset?: number; limit?: number }
* },
* })
* ```
*
* Raw JSON-Schema tool definitions (from MCP servers) are still accepted
* by `ToolRegistry.register()` directly — `defineTool` is sugar for
* first-party plugin authors.
*/
export function defineTool<S extends SchemaSpec>(options: DefineToolOptions<S>): ToolDefinition {
// Object-literal execute methods don't use `this`; the reference is safe.
// eslint-disable-next-line @typescript-eslint/unbound-method
const userExecute = options.execute
// eslint-disable-next-line @typescript-eslint/unbound-method
const userPresentCall = options.presentCall
// eslint-disable-next-line @typescript-eslint/unbound-method
const userPresentResult = options.presentResult
const tool: ToolDefinition = {
name: options.name,
description: options.description,
parameters: schemaSpecToJsonSchema(options.parameters) as unknown as Record<string, unknown>,
...options.strict !== undefined ? { strict: options.strict } : {},
async execute(args: unknown, exec: ToolExecution): Promise<ContentBlock[]> {
// Validate the model-generated args before the typed body runs. On
// mismatch we throw ToolArgsError; the registry turns it into an
// isError result so the model can self-correct. After this guard, the
// cast to InferArgs<S> reflects the validated shape.
const violations = validateArgs(options.parameters, args)
if (violations.length > 0) throw new ToolArgsError(violations)
return userExecute(args as InferArgs<S>, exec)
},
}
// Presentation is display-only and may run on REPLAY of arbitrary logged args
// (possibly from an older schema), so it must never throw: validate softly and
// fall back to `undefined` (a generic UI presentation) on any mismatch, rather
// than the hard `ToolArgsError` the execute path raises.
if (userPresentCall) {
tool.presentCall = (args: unknown): ToolCallPresentation | undefined => {
if (validateArgs(options.parameters, args).length > 0) return undefined
return userPresentCall(args as InferArgs<S>)
}
}
if (userPresentResult) {
tool.presentResult = (args: unknown, result: ToolResult): ToolResultPresentation | undefined => {
if (validateArgs(options.parameters, args).length > 0) return undefined
return userPresentResult(args as InferArgs<S>, result)
}
}
return tool
}