Files
dify/cli/src/framework/command.ts
T

75 lines
2.2 KiB
TypeScript
Raw Normal View History

import type { CommandOutput } from './output'
2026-07-12 23:57:46 +08:00
import type {
ArgDefinition,
FlagDefinition,
ICommand,
InferArgs,
InferFlags,
OptionalArgValueType,
} from './types'
import { setVerbose } from './context'
import { hasBooleanFlag, parseArgv, VERBOSE_CHAR, VERBOSE_FLAG } from './flags'
2026-05-26 09:12:36 +08:00
2026-06-04 15:27:28 +08:00
// What invoking a command does to remote/persistent state. Drives the skill's
// safety section and the `effect` bit in machine-readable help. Defaults to
// `read`; write/destructive commands must opt in explicitly.
export type CommandEffect = 'read' | 'write' | 'destructive'
2026-05-26 09:12:36 +08:00
export type CommandConstructor = {
2026-07-12 23:57:46 +08:00
new (): Command
2026-05-26 09:12:36 +08:00
description?: string
flags?: Record<string, FlagDefinition<OptionalArgValueType>>
args?: Record<string, ArgDefinition<string | undefined>>
examples?: string[]
hidden?: boolean
deprecated?: string
2026-06-04 15:27:28 +08:00
effect?: CommandEffect
2026-05-26 09:12:36 +08:00
}
2026-07-12 23:57:46 +08:00
type InferCommandArgs<C extends CommandConstructor> =
C['args'] extends Record<string, ArgDefinition<string | undefined>>
? InferArgs<C['args']>
: Record<string, string | undefined>
2026-05-26 09:12:36 +08:00
2026-07-12 23:57:46 +08:00
type InferCommandFlags<C extends CommandConstructor> =
C['flags'] extends Record<string, FlagDefinition<OptionalArgValueType>>
? InferFlags<C['flags']>
: Record<string, OptionalArgValueType>
2026-05-26 09:12:36 +08:00
type ParseResult<C extends CommandConstructor> = {
args: InferCommandArgs<C>
flags: InferCommandFlags<C>
}
export abstract class Command implements ICommand {
static description?: string
static flags: Record<string, FlagDefinition<OptionalArgValueType>> = {}
2026-05-26 09:12:36 +08:00
static args: Record<string, ArgDefinition<string | undefined>> = {}
static examples: string[] = []
2026-06-04 15:27:28 +08:00
static effect: CommandEffect = 'read'
2026-05-26 09:12:36 +08:00
abstract run(argv: string[]): Promise<CommandOutput | void>
processGlobalFlags(argv: readonly string[]): void {
setVerbose(hasBooleanFlag(argv, VERBOSE_FLAG, VERBOSE_CHAR))
}
2026-05-26 09:12:36 +08:00
protected parse<C extends CommandConstructor>(ctor: C, argv: string[]): ParseResult<C> {
const meta = {
flags: ctor.flags ?? {},
args: ctor.args ?? {},
}
return parseArgv(argv, meta) as ParseResult<C>
}
error(message: string, opts?: { exit?: number }): never {
process.stderr.write(`${message}\n`)
process.exit(opts?.exit ?? 1)
}
agentGuide(): string {
return ''
}
}