refactor(packages): dissolve ui/ and rename sdk/ to scaffold/
git mv per the regrouping RFC: the five human-collaboration seams and tui join packages/interaction/, app-boot becomes packages/boot/, and jsonrpc joins the renamed scaffold/ (formerly sdk/) as its server half beside client/protocol/create-sdk/helper/scripts/telemetry, whose folders drop the legacy sdk- prefix. Three new group README triplets replace the ui/ and sdk/ ones; tsconfig references/paths/globs, knip keys, vitest globs, gate scripts, catalogs, docs, and the lockfile follow. Adds the four settled FIXME rename markers (dsh-sdk-server, dsh-sdk-telemetry, dsh-sdk-helper, dsh-sdk-scripts). The scaffold folders diverge from their npm names until those renames land, so tsconfig.base.json maps the three affected names explicitly beside the group wildcard. Also repairs two pre-existing stale-path classes the strengthened sweep surfaced: docs/web-styling.md's retired web-ui host package and type-model spec fixture-literal joins. app-boot's three Loader-composition specs time out at the default 5s under full-suite parallel load on this filesystem (pre-existing; pass isolated with --testTimeout=30000); interaction/scaffold/boot suites otherwise green (687 passed).
This commit is contained in:
6
packages/scaffold/create-sdk/README.i18n.yaml
Normal file
6
packages/scaffold/create-sdk/README.i18n.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/scaffold/create-sdk/README.md
|
||||
README.md: aa09236832a50abdcd2b158e0561db26bce19cf6
|
||||
README.zh.md: a4685e66bc3eb7924dd247a7b6b420f6bcc70990
|
||||
25
packages/scaffold/create-sdk/README.md
Normal file
25
packages/scaffold/create-sdk/README.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# `@deepseek-ai/create-sdk`
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Interactive initializer for `npm create @deepseek-ai/sdk [directory]`. Directory/name/description have visible editable defaults. A tree picker selects features and configures finite options with Right/Left navigation; secret text follows only for selected options. Local plugin creation is one none/plugin/tool choice.
|
||||
|
||||
The supported package surface is the `create-sdk` bin. The package root exports no symbols, and workflow, bin, source, and package-manifest subpaths are not exported.
|
||||
|
||||
The initializer rejects every existing target path, creates one `SdkProject` edit session, validates and commits it, then asks whether to install NPM dependencies and build. Install or build failures keep the generated project and print a retry command.
|
||||
|
||||
Public flags are `[directory]`, `--description`, `--provider`, `--base-url`, `--api-key`, `--model`, `--interface`, `--pm`, `--install`/`--no-install`, plus the headless flags `--config <path>` / `--config-json <json>` and `--json`. Interactive flags prefill matching questions; a headless spec (`--config`/`--config-json`) supplies every answer and its feature plan up front, so creation runs without a TTY and drives through a `HeadlessPromptPort` that fails loud on any missing required answer. `--json` emits NDJSON lifecycle events (`done` / `action-required` / `error`) so an agent can fill the named missing input and re-run.
|
||||
|
||||
The provider choice is DeepSeek or a custom endpoint backed by `llm-pi-ai`. DeepSeek asks only for an API key and uses the public endpoint plus `deepseek-v4-flash`; custom also asks for a base URL. An empty key requires confirmation and creates a commented empty `.env` variable so provider startup fails clearly until it is filled. Existing plugin defaults are omitted; required SDK presets remain typed against the owning package's Config.
|
||||
|
||||
## Model Experience
|
||||
|
||||
Indirectly, through the generated project composition and its selected runtime plugins; the headless `--config-json` + `--json` surface additionally lets an agent create a project end to end and react to `action-required` events.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
No direct invalidation; the named consumer owns any request-prefix changes.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Headless local plugins** — the headless spec supplies project answers and the feature plan; scaffolding a local plugin (the interactive none/plugin/tool choice) is not yet expressible in the spec and defaults to none.
|
||||
25
packages/scaffold/create-sdk/README.zh.md
Normal file
25
packages/scaffold/create-sdk/README.zh.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# `@deepseek-ai/create-sdk`
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
用于 `npm create @deepseek-ai/sdk [directory]` 的交互式初始化器。目录/名称/描述都提供可见且可编辑的默认值。树形选择器用于选择功能,并通过 Right/Left 导航配置取值有限的选项;只有选中相应选项后才会询问密钥文本。本地插件创建提供 none/plugin/tool 三选一。
|
||||
|
||||
受支持的包接口是 `create-sdk` bin。包根不导出任何符号,也不导出 workflow、bin、source 或 package-manifest 子路径。
|
||||
|
||||
初始化器拒绝任何已经存在的目标路径,创建一个 `SdkProject` 编辑会话,验证并提交该会话,然后询问是否安装 NPM 依赖并构建。安装或构建失败时会保留生成的项目,并打印重试命令。
|
||||
|
||||
公开标志包括 `[directory]`、`--description`、`--provider`、`--base-url`、`--api-key`、`--model`、`--interface`、`--pm`、`--install`/`--no-install`,以及无头模式标志 `--config <path>`/`--config-json <json>` 和 `--json`。交互式标志会预填对应问题;无头 spec(`--config`/`--config-json`)会预先提供所有答案和功能方案,因此创建过程无需 TTY,并通过 `HeadlessPromptPort` 驱动;若缺少任何必填答案,该端口会明确失败。`--json` 会发送 NDJSON 生命周期事件(`done`/`action-required`/`error`),使 agent(智能体)能够补充其中点名的缺失输入并重新运行。
|
||||
|
||||
提供方可以选择 DeepSeek,也可以选择由 `llm-pi-ai` 支持的自定义端点。选择 DeepSeek 时只询问 API key,并使用公共端点与 `deepseek-v4-flash`;自定义端点还会询问 base URL。密钥为空时必须确认;系统会在 `.env` 中创建一个被注释掉的空变量,从而使提供方在为该变量填入值之前启动时明确失败。现有插件的默认值会被省略;必填 SDK 预设仍按所属包的 Config 保持类型约束。
|
||||
|
||||
## 模型体验
|
||||
|
||||
通过生成的项目组合及其所选运行时插件间接提供;此外,无头 `--config-json` + `--json` 接口允许 agent 端到端创建项目,并响应 `action-required` 事件。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
不会直接导致 KV Cache 失效;由具名消费方负责请求前缀变更。
|
||||
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- **无头本地插件**:无头 spec 会提供项目答案和功能方案;目前还不能在 spec 中表达本地插件脚手架(交互式 none/plugin/tool 选择),默认使用 none。
|
||||
42
packages/scaffold/create-sdk/package.json
Normal file
42
packages/scaffold/create-sdk/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@deepseek-ai/create-sdk",
|
||||
"description": "Create a DeepSeek Harness SDK project with npm create @deepseek-ai/sdk",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"bin": {
|
||||
"create-sdk": "lib/bin.js"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/bin.js",
|
||||
"lib/assets",
|
||||
"lib/types/**/*.d.ts"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-helper": "workspace:^",
|
||||
"commander": "^15.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
}
|
||||
}
|
||||
96
packages/scaffold/create-sdk/src/args.ts
Normal file
96
packages/scaffold/create-sdk/src/args.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Commander adapter for the create-sdk command surface.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/args
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'commander'
|
||||
import type { PackageManagerName, RunInterface } from '@deepseek-ai/dsh-helper'
|
||||
|
||||
/** Parsed create command flags before interactive resolution. */
|
||||
export interface CreateArgs {
|
||||
directory?: string
|
||||
description?: string
|
||||
provider?: 'deepseek-official' | 'custom'
|
||||
baseURL?: string
|
||||
apiKey?: string
|
||||
model?: string
|
||||
runInterface?: RunInterface
|
||||
packageManager?: PackageManagerName
|
||||
install?: boolean
|
||||
linkWorkspace?: boolean
|
||||
config?: string
|
||||
configJson?: string
|
||||
json?: boolean
|
||||
help: boolean
|
||||
}
|
||||
|
||||
interface CommanderCreateOptions {
|
||||
description?: string
|
||||
provider?: 'deepseek-official' | 'custom'
|
||||
baseUrl?: string
|
||||
apiKey?: string
|
||||
model?: string
|
||||
interface?: RunInterface
|
||||
pm?: PackageManagerName
|
||||
install?: boolean
|
||||
linkWorkspace?: boolean
|
||||
config?: string
|
||||
configJson?: string
|
||||
json?: boolean
|
||||
help?: boolean
|
||||
}
|
||||
|
||||
function createProgram(): Command {
|
||||
return new Command()
|
||||
.name('create-sdk')
|
||||
.description('Create a DeepSeek Harness SDK project')
|
||||
.helpOption(false)
|
||||
.showHelpAfterError(false)
|
||||
.exitOverride()
|
||||
.configureOutput({
|
||||
/* v8 ignore next -- the command wrapper renders the package-owned usage template */
|
||||
writeOut: () => {},
|
||||
/* v8 ignore next -- Commander output is deliberately suppressed; errors are returned to the bin wrapper */
|
||||
writeErr: () => {},
|
||||
})
|
||||
.argument('[directory]')
|
||||
.option('-h, --help')
|
||||
.option('--description <text>')
|
||||
.addOption(new Option('--provider <name>').choices(['deepseek-official', 'custom']))
|
||||
.option('--base-url <url>')
|
||||
.option('--api-key <key>')
|
||||
.option('--model <name>')
|
||||
.addOption(new Option('--interface <name>').choices(['acp', 'embed']))
|
||||
.addOption(new Option('--pm <name>').choices(['npm', 'pnpm', 'yarn']))
|
||||
.addOption(new Option('--install').default(undefined))
|
||||
.addOption(new Option('--no-install').default(undefined))
|
||||
.option('--link-workspace')
|
||||
.option('--config <path>')
|
||||
.option('--config-json <json>')
|
||||
.addOption(new Option('--json').default(undefined))
|
||||
}
|
||||
|
||||
/** Parse create-sdk positionals/options through Commander into a domain-neutral value. */
|
||||
export function parseCreateArgs(argv: readonly string[]): CreateArgs {
|
||||
const program = createProgram()
|
||||
program.parse([...argv], { from: 'user' })
|
||||
const options = program.opts<CommanderCreateOptions>()
|
||||
const directory = program.processedArgs[0] as string | undefined
|
||||
return {
|
||||
...directory === undefined ? {} : { directory },
|
||||
...options.description === undefined ? {} : { description: options.description },
|
||||
...options.provider === undefined ? {} : { provider: options.provider },
|
||||
...options.baseUrl === undefined ? {} : { baseURL: options.baseUrl },
|
||||
...options.apiKey === undefined ? {} : { apiKey: options.apiKey },
|
||||
...options.model === undefined ? {} : { model: options.model },
|
||||
...options.interface === undefined ? {} : { runInterface: options.interface },
|
||||
...options.pm === undefined ? {} : { packageManager: options.pm },
|
||||
...options.install === undefined ? {} : { install: options.install },
|
||||
...options.linkWorkspace ? { linkWorkspace: true } : {},
|
||||
...options.config === undefined ? {} : { config: options.config },
|
||||
...options.configJson === undefined ? {} : { configJson: options.configJson },
|
||||
...options.json === undefined ? {} : { json: options.json },
|
||||
help: options.help ?? false,
|
||||
}
|
||||
}
|
||||
10
packages/scaffold/create-sdk/src/bin.ts
Normal file
10
packages/scaffold/create-sdk/src/bin.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Self-executing create-sdk command.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/bin
|
||||
*/
|
||||
|
||||
import { runCreateCommand } from './command.ts'
|
||||
|
||||
process.exitCode = await runCreateCommand()
|
||||
144
packages/scaffold/create-sdk/src/command.ts
Normal file
144
packages/scaffold/create-sdk/src/command.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Internal create-sdk command composition used by the package bin.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/command
|
||||
*/
|
||||
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import {
|
||||
ClackPromptPort,
|
||||
HeadlessPromptError,
|
||||
HeadlessPromptPort,
|
||||
NodeCommandRunner,
|
||||
PromptCancelledError,
|
||||
type PackageManagerVersionProbe,
|
||||
type PromptPort,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
import { parseCreateArgs, type CreateArgs } from './args.ts'
|
||||
import { CreateWizard, type ResolvedCreateRequest } from './create-wizard.ts'
|
||||
import { resolveHeadless } from './headless.ts'
|
||||
import { scaffoldProject, type ScaffoldResult } from './project-scaffolder.ts'
|
||||
import { CREATE_TEMPLATES, packageManagerTemplateModel } from './templates/create-templates.ts'
|
||||
|
||||
/** Process and terminal slice used by the initializer. */
|
||||
export interface CreateCommandContext {
|
||||
cwd: string
|
||||
stdin: NodeJS.ReadStream
|
||||
stdout: NodeJS.WriteStream
|
||||
stderr: NodeJS.WriteStream
|
||||
releaseVersion?: string
|
||||
versionProbe?: PackageManagerVersionProbe
|
||||
port?: PromptPort
|
||||
setup?: (request: ResolvedCreateRequest) => Promise<void>
|
||||
}
|
||||
|
||||
/** Read this initializer package's release version in source and built layouts. */
|
||||
export async function readCreateSdkVersion(): Promise<string> {
|
||||
const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) as { version?: unknown }
|
||||
/* v8 ignore next -- this package's checked-in manifest always carries its version */
|
||||
if (typeof manifest.version !== 'string') throw new Error('create-sdk package version is missing')
|
||||
return manifest.version
|
||||
}
|
||||
|
||||
/** Resolve, write, optionally install, and build one new project. */
|
||||
export async function createProject(
|
||||
argv: readonly string[],
|
||||
context: CreateCommandContext,
|
||||
): Promise<ScaffoldResult | undefined> {
|
||||
const args = parseCreateArgs(argv)
|
||||
// Under --json, stdout carries only NDJSON events: human-readable progress
|
||||
// and package-manager child output move to stderr.
|
||||
const progress = args.json === true ? context.stderr : context.stdout
|
||||
if (args.help) {
|
||||
context.stdout.write(CREATE_TEMPLATES.usage.render({}))
|
||||
return undefined
|
||||
}
|
||||
const headless = await resolveHeadless(args)
|
||||
if (!headless && !context.port && (!context.stdin.isTTY || !context.stdout.isTTY)) {
|
||||
throw new Error('create-sdk requires an interactive TTY, --config <file>, or --config-json <json>')
|
||||
}
|
||||
const wizard = new CreateWizard({
|
||||
args: headless ? headless.args : args,
|
||||
/* v8 ignore next -- production TTY wiring is exercised by the built-bin smoke */
|
||||
port: context.port ?? (headless ? new HeadlessPromptPort() : new ClackPromptPort(context.stdin, context.stdout)),
|
||||
cwd: context.cwd,
|
||||
releaseVersion: context.releaseVersion ?? await readCreateSdkVersion(),
|
||||
...context.versionProbe ? { versionProbe: context.versionProbe } : {},
|
||||
...headless?.features ? { features: headless.features } : {},
|
||||
})
|
||||
const resolved = await wizard.run()
|
||||
const result = await scaffoldProject(resolved.directory, resolved.request)
|
||||
progress.write(CREATE_TEMPLATES.created.render({
|
||||
name: resolved.request.name,
|
||||
directory: resolved.directory,
|
||||
}))
|
||||
if (resolved.install) {
|
||||
try {
|
||||
if (context.setup) await context.setup(resolved)
|
||||
else {
|
||||
const runner = args.json === true ? new NodeCommandRunner(context.stderr) : new NodeCommandRunner()
|
||||
await resolved.request.packageManager.install(resolved.directory, runner)
|
||||
await resolved.request.packageManager.build(resolved.directory, runner)
|
||||
}
|
||||
} catch (error) {
|
||||
context.stderr.write(CREATE_TEMPLATES.setupFailure.render({
|
||||
directory: resolved.directory,
|
||||
error: String(error),
|
||||
...packageManagerTemplateModel(resolved.request.packageManager),
|
||||
}))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
progress.write(CREATE_TEMPLATES.nextSteps.render({
|
||||
directory: resolved.directory,
|
||||
setupRequired: !resolved.install,
|
||||
...packageManagerTemplateModel(resolved.request.packageManager),
|
||||
}))
|
||||
return result
|
||||
}
|
||||
|
||||
/** Whether NDJSON lifecycle events were requested, tolerating unparseable argv. */
|
||||
function wantsJsonEvents(argv: readonly string[]): boolean {
|
||||
let parsed: CreateArgs
|
||||
try {
|
||||
parsed = parseCreateArgs(argv)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return parsed.json === true
|
||||
}
|
||||
|
||||
/** Run the create command with process defaults and convert cancellation to a clean exit. */
|
||||
export async function runCreateCommand(
|
||||
argv: readonly string[] = process.argv.slice(2),
|
||||
context: CreateCommandContext = {
|
||||
cwd: process.cwd(),
|
||||
stdin: process.stdin,
|
||||
stdout: process.stdout,
|
||||
stderr: process.stderr,
|
||||
},
|
||||
): Promise<number> {
|
||||
const json = wantsJsonEvents(argv)
|
||||
const emit = (event: Record<string, unknown>): void => {
|
||||
context.stdout.write(`${JSON.stringify(event)}\n`)
|
||||
}
|
||||
try {
|
||||
await createProject(argv, context)
|
||||
if (json) emit({ type: 'done' })
|
||||
return 0
|
||||
} catch (error) {
|
||||
if (error instanceof PromptCancelledError) {
|
||||
if (json) emit({ type: 'error', reason: 'cancelled' })
|
||||
else context.stderr.write('create-sdk: cancelled\n')
|
||||
return 1
|
||||
}
|
||||
if (json && error instanceof HeadlessPromptError) {
|
||||
emit({ type: 'action-required', prompt: error.prompt })
|
||||
return 1
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
if (json) emit({ type: 'error', message })
|
||||
else context.stderr.write(`create-sdk: ${message}\n`)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
204
packages/scaffold/create-sdk/src/create-questions.ts
Normal file
204
packages/scaffold/create-sdk/src/create-questions.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* Static create-sdk question sequence; dynamic feature/plugin loops remain
|
||||
* in the wizard orchestrator.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/create-questions
|
||||
*/
|
||||
|
||||
import { existsSync } from 'node:fs'
|
||||
import { basename, resolve } from 'node:path'
|
||||
import {
|
||||
ConfirmQuestion,
|
||||
SecretQuestion,
|
||||
SelectQuestion,
|
||||
TextQuestion,
|
||||
requireAnswer,
|
||||
type PromptPort,
|
||||
type Question,
|
||||
type RunInterface,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
import type { CreateArgs } from './args.ts'
|
||||
|
||||
/** Answers that establish project identity and feature applicability. */
|
||||
export interface ProjectAnswers {
|
||||
directory: string
|
||||
name: string
|
||||
description: string
|
||||
provider: 'deepseek-official' | 'custom'
|
||||
baseURL: string
|
||||
apiKey: string
|
||||
model: string
|
||||
runInterface: RunInterface
|
||||
}
|
||||
|
||||
interface ProjectAnswerState extends Partial<ProjectAnswers> {
|
||||
readonly args: CreateArgs
|
||||
readonly cwd: string
|
||||
}
|
||||
|
||||
interface WizardStep<TState> {
|
||||
run(port: PromptPort, state: TState): Promise<void>
|
||||
}
|
||||
|
||||
function questionStep<TState, TValue>(options: {
|
||||
question: (state: TState) => Question<TValue>
|
||||
when?: (state: TState) => boolean
|
||||
prefilled?: (state: TState) => TValue | undefined
|
||||
apply: (state: TState, value: TValue) => void
|
||||
}): WizardStep<TState> {
|
||||
return {
|
||||
async run(port, state) {
|
||||
if (options.when && !options.when(state)) return
|
||||
const value = requireAnswer(await options.question(state).resolve(port, options.prefilled?.(state)))
|
||||
options.apply(state, value)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate one required text answer. */
|
||||
function nonEmpty(value: string): string | undefined {
|
||||
return value.trim().length === 0 ? 'A value is required' : undefined
|
||||
}
|
||||
|
||||
function packageName(value: string): string | undefined {
|
||||
if (!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(value)) {
|
||||
return 'Use a lowercase npm package name'
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function projectDirectory(value: string, cwd: string): string | undefined {
|
||||
const empty = nonEmpty(value)
|
||||
if (empty) return empty
|
||||
return existsSync(resolve(cwd, value)) ? 'Target already exists' : undefined
|
||||
}
|
||||
|
||||
const API_KEY_STEP: WizardStep<ProjectAnswerState> = {
|
||||
async run(port, state) {
|
||||
let prefilled = state.args.apiKey
|
||||
while (true) {
|
||||
const apiKey = requireAnswer(await new SecretQuestion({
|
||||
id: 'apiKey',
|
||||
message: state.provider === 'custom' ? 'Custom provider API key' : 'DeepSeek API key',
|
||||
}).resolve(port, prefilled))
|
||||
if (apiKey.length > 0) {
|
||||
state.apiKey = apiKey
|
||||
return
|
||||
}
|
||||
const keepEmpty = requireAnswer(await new ConfirmQuestion({
|
||||
id: 'apiKey.empty',
|
||||
message: 'Keep the API key empty and fill .env later?',
|
||||
initialValue: false,
|
||||
tone: 'warning',
|
||||
}).resolve(port))
|
||||
if (keepEmpty) {
|
||||
state.apiKey = ''
|
||||
return
|
||||
}
|
||||
prefilled = undefined
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const PROJECT_QUESTION_STEPS: readonly WizardStep<ProjectAnswerState>[] = [
|
||||
questionStep({
|
||||
question: state => new TextQuestion({
|
||||
id: 'directory',
|
||||
message: 'Where should the project be created?',
|
||||
placeholder: 'my-agent',
|
||||
defaultValue: 'my-agent',
|
||||
validate: value => projectDirectory(value, state.cwd),
|
||||
}),
|
||||
prefilled: state => state.args.directory,
|
||||
apply: (state, value) => { state.directory = resolve(state.cwd, value) },
|
||||
}),
|
||||
questionStep({
|
||||
question: (state) => {
|
||||
/* v8 ignore next -- the preceding directory step always populates this state */
|
||||
if (!state.directory) throw new Error('directory must resolve before package name')
|
||||
return new TextQuestion({
|
||||
id: 'name',
|
||||
message: 'Package name',
|
||||
placeholder: basename(state.directory),
|
||||
defaultValue: basename(state.directory),
|
||||
validate: packageName,
|
||||
})
|
||||
},
|
||||
apply: (state, value) => { state.name = value },
|
||||
}),
|
||||
questionStep({
|
||||
question: (state) => {
|
||||
/* v8 ignore next -- the preceding package-name step always populates this state */
|
||||
if (!state.name) throw new Error('package name must resolve before description')
|
||||
return new TextQuestion({
|
||||
id: 'description',
|
||||
message: 'Project description',
|
||||
placeholder: `A DeepSeek Harness agent named ${state.name}`,
|
||||
defaultValue: `A DeepSeek Harness agent named ${state.name}`,
|
||||
validate: nonEmpty,
|
||||
})
|
||||
},
|
||||
prefilled: state => state.args.description,
|
||||
apply: (state, value) => { state.description = value },
|
||||
}),
|
||||
questionStep({
|
||||
question: () => new SelectQuestion<'deepseek-official' | 'custom'>({
|
||||
id: 'provider',
|
||||
message: 'Model provider',
|
||||
options: [
|
||||
{ value: 'deepseek-official', label: 'DeepSeek' },
|
||||
{ value: 'custom', label: 'Custom endpoint (pi-ai)' },
|
||||
],
|
||||
initialValue: 'deepseek-official',
|
||||
}),
|
||||
prefilled: state => state.args.provider,
|
||||
apply: (state, value) => { state.provider = value },
|
||||
}),
|
||||
questionStep({
|
||||
question: () => new TextQuestion({
|
||||
id: 'baseURL', message: 'Custom provider base URL', validate: nonEmpty,
|
||||
}),
|
||||
when: state => state.provider === 'custom' || state.args.baseURL !== undefined,
|
||||
prefilled: state => state.args.baseURL,
|
||||
apply: (state, value) => { state.baseURL = value },
|
||||
}),
|
||||
API_KEY_STEP,
|
||||
questionStep({
|
||||
question: () => new SelectQuestion<RunInterface>({
|
||||
id: 'interface',
|
||||
message: 'Run interface',
|
||||
options: [
|
||||
{ value: 'acp', label: 'ACP automation server' },
|
||||
{ value: 'embed', label: 'Embedded context' },
|
||||
],
|
||||
initialValue: 'acp',
|
||||
}),
|
||||
prefilled: state => state.args.runInterface,
|
||||
apply: (state, value) => { state.runInterface = value },
|
||||
}),
|
||||
]
|
||||
|
||||
function completeAnswers(state: ProjectAnswerState): ProjectAnswers {
|
||||
const keys = ['directory', 'name', 'description', 'provider', 'baseURL', 'apiKey', 'model', 'runInterface'] as const
|
||||
for (const key of keys) {
|
||||
/* v8 ignore next -- the fixed step list above populates every key or throws/cancels first */
|
||||
if (state[key] === undefined) throw new Error(`create question did not resolve ${key}`)
|
||||
}
|
||||
return state as ProjectAnswerState & ProjectAnswers
|
||||
}
|
||||
|
||||
/** Run the fixed project-context sequence in declaration order. */
|
||||
export async function collectProjectAnswers(
|
||||
port: PromptPort,
|
||||
args: CreateArgs,
|
||||
cwd: string,
|
||||
): Promise<ProjectAnswers> {
|
||||
const state: ProjectAnswerState = {
|
||||
args,
|
||||
cwd,
|
||||
baseURL: args.baseURL ?? '',
|
||||
model: args.model ?? 'deepseek-v4-flash',
|
||||
}
|
||||
for (const step of PROJECT_QUESTION_STEPS) await step.run(port, state)
|
||||
return completeAnswers(state)
|
||||
}
|
||||
233
packages/scaffold/create-sdk/src/create-wizard.ts
Normal file
233
packages/scaffold/create-sdk/src/create-wizard.ts
Normal file
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* Declarative create questions with dynamic feature and plugin orchestration.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/create-wizard
|
||||
*/
|
||||
|
||||
import { resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
FeatureConfigurator,
|
||||
ConfirmQuestion,
|
||||
LocalPluginBlueprint,
|
||||
NpmPackageManager,
|
||||
SelectQuestion,
|
||||
featureId,
|
||||
createBuiltinRegistry,
|
||||
createPackageManager,
|
||||
inferPackageManagerName,
|
||||
probePackageManagerVersion,
|
||||
requireAnswer,
|
||||
type FeatureRegistry,
|
||||
type FeatureSelection,
|
||||
type LocalPluginKind,
|
||||
type PackageManager,
|
||||
type PackageManagerName,
|
||||
type PackageManagerVersionProbe,
|
||||
type ProjectCreationRequest,
|
||||
type ProjectProfile,
|
||||
type PromptPort,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
import type { CreateArgs } from './args.ts'
|
||||
import { collectProjectAnswers, type ProjectAnswers } from './create-questions.ts'
|
||||
import { CREATE_TEMPLATES, packageManagerTemplateModel } from './templates/create-templates.ts'
|
||||
|
||||
/** Fully resolved initializer request and post-create choice. */
|
||||
export interface ResolvedCreateRequest {
|
||||
directory: string
|
||||
request: ProjectCreationRequest
|
||||
install: boolean
|
||||
}
|
||||
|
||||
/** Create-specific orchestration around declarative questions and dynamic selections. */
|
||||
export class CreateWizard {
|
||||
private readonly args: CreateArgs
|
||||
private readonly port: PromptPort
|
||||
private readonly cwd: string
|
||||
private readonly releaseVersion: string
|
||||
private readonly versionProbe: PackageManagerVersionProbe
|
||||
private readonly userAgent: string
|
||||
private readonly linkWorkspaceRoot: string | undefined
|
||||
private readonly featurePlan: readonly FeatureSelection[] | undefined
|
||||
|
||||
/** Bind parsed args and infrastructure to one wizard run. */
|
||||
constructor(options: {
|
||||
args: CreateArgs
|
||||
port: PromptPort
|
||||
cwd?: string
|
||||
releaseVersion: string
|
||||
versionProbe?: PackageManagerVersionProbe
|
||||
userAgent?: string
|
||||
features?: readonly FeatureSelection[]
|
||||
}) {
|
||||
this.args = options.args
|
||||
this.port = options.port
|
||||
this.cwd = resolve(options.cwd ?? process.cwd())
|
||||
this.releaseVersion = options.releaseVersion
|
||||
this.versionProbe = options.versionProbe ?? probePackageManagerVersion
|
||||
/* v8 ignore next -- pnpm supplies npm_config_user_agent while direct invocations may omit it */
|
||||
this.userAgent = options.userAgent ?? process.env.npm_config_user_agent ?? ''
|
||||
this.linkWorkspaceRoot = options.args.linkWorkspace
|
||||
? fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
: undefined
|
||||
this.featurePlan = options.features
|
||||
}
|
||||
|
||||
/** Collect all answers before constructing any project files. */
|
||||
async run(): Promise<ResolvedCreateRequest> {
|
||||
const answers = await this.collectProjectAnswers()
|
||||
const profile = this.provisionalProfile(answers)
|
||||
const registry = createBuiltinRegistry(profile)
|
||||
const features = await this.collectFeatures(profile, registry, answers)
|
||||
const localPlugins = await this.collectPlugins()
|
||||
const { manager, install } = await this.collectPackageManager()
|
||||
return {
|
||||
directory: answers.directory,
|
||||
install,
|
||||
request: {
|
||||
name: answers.name,
|
||||
description: answers.description,
|
||||
runtime: { model: answers.model },
|
||||
packageManager: manager,
|
||||
releaseVersion: this.releaseVersion,
|
||||
...this.linkWorkspaceRoot ? { linkWorkspaceRoot: this.linkWorkspaceRoot } : {},
|
||||
features,
|
||||
localPlugins,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
private async collectProjectAnswers(): Promise<ProjectAnswers> {
|
||||
return collectProjectAnswers(this.port, this.args, this.cwd)
|
||||
}
|
||||
|
||||
private provisionalProfile(answers: ProjectAnswers): ProjectProfile {
|
||||
return {
|
||||
name: answers.name,
|
||||
description: answers.description,
|
||||
runtime: { model: answers.model },
|
||||
runInterface: answers.runInterface,
|
||||
packageManager: new NpmPackageManager('10.0.0'),
|
||||
releaseVersion: this.releaseVersion,
|
||||
...this.linkWorkspaceRoot ? { linkWorkspaceRoot: this.linkWorkspaceRoot } : {},
|
||||
}
|
||||
}
|
||||
|
||||
private async collectFeatures(
|
||||
profile: ProjectProfile,
|
||||
registry: FeatureRegistry,
|
||||
answers: ProjectAnswers,
|
||||
): Promise<FeatureSelection[]> {
|
||||
const configurator = new FeatureConfigurator(this.port)
|
||||
const selections: FeatureSelection[] = [
|
||||
{
|
||||
id: featureId('provider'),
|
||||
options: [answers.provider],
|
||||
...answers.baseURL ? { values: { baseURL: answers.baseURL } } : {},
|
||||
secrets: { apiKey: answers.apiKey },
|
||||
},
|
||||
{ id: featureId('spine'), options: ['default'] },
|
||||
{ id: featureId('app'), options: [answers.runInterface] },
|
||||
]
|
||||
const configurable = registry.all().filter(feature => feature.id === 'bash'
|
||||
|| feature.id === 'persistence'
|
||||
|| (!feature.required && feature.isApplicable(profile)))
|
||||
const selected = this.featurePlan
|
||||
? this.featurePlan.map(feature => ({ value: feature.id, choices: feature.options }))
|
||||
: [...requireAnswer(await this.port.nestedMultiselect({
|
||||
message: 'Select features',
|
||||
options: configurable.map((feature) => {
|
||||
const nested = feature.mode !== 'single'
|
||||
const defaults = new Set(feature.defaultOptions(profile))
|
||||
return {
|
||||
value: feature.id,
|
||||
label: feature.summary,
|
||||
required: feature.required,
|
||||
default: feature.required || feature.id === 'hmr' || feature.id === 'fs' || feature.id === 'todo'
|
||||
|| feature.id === 'skill',
|
||||
...nested ? {
|
||||
choiceMode: feature.mode === 'multiple' ? 'multiple' as const : 'exclusive' as const,
|
||||
choices: feature.options.map(option => ({
|
||||
value: option.id,
|
||||
label: option.label,
|
||||
default: defaults.has(option.id),
|
||||
})),
|
||||
} : {},
|
||||
}
|
||||
}),
|
||||
}))]
|
||||
if (!this.featurePlan) {
|
||||
for (const { value: id } of [...selected]) {
|
||||
const feature = registry.get(id)
|
||||
for (const suggestedId of feature.suggests) {
|
||||
if (selected.some(item => item.value === suggestedId)) continue
|
||||
const suggested = registry.get(suggestedId)
|
||||
const add = requireAnswer(await new ConfirmQuestion({
|
||||
id: `${feature.id}.${suggested.id}`,
|
||||
message: `Add the recommended ${suggested.summary.toLowerCase()} for ${feature.summary.toLowerCase()}?`,
|
||||
initialValue: true,
|
||||
}).resolve(this.port))
|
||||
if (add) selected.push({ value: suggested.id, choices: suggested.defaultOptions(profile) })
|
||||
}
|
||||
}
|
||||
}
|
||||
const fixed = new Set(selections.map(selection => selection.id))
|
||||
const choices = new Map<FeatureSelection['id'], readonly string[] | undefined>()
|
||||
for (const feature of registry.all()) {
|
||||
if (feature.required && feature.isApplicable(profile) && !fixed.has(feature.id)) {
|
||||
choices.set(feature.id, feature.defaultOptions(profile))
|
||||
}
|
||||
}
|
||||
for (const choice of selected) {
|
||||
choices.set(choice.value, choice.choices.length > 0 ? choice.choices : undefined)
|
||||
}
|
||||
const plannedById = new Map((this.featurePlan ?? []).map(feature => [feature.id, feature]))
|
||||
for (const [id, options] of choices) {
|
||||
const planned = plannedById.get(id)
|
||||
selections.push(await configurator.configure(
|
||||
registry.get(id),
|
||||
profile,
|
||||
undefined,
|
||||
options,
|
||||
planned?.secrets ?? {},
|
||||
planned?.values ?? {},
|
||||
))
|
||||
}
|
||||
return selections
|
||||
}
|
||||
|
||||
private async collectPlugins(): Promise<LocalPluginBlueprint[]> {
|
||||
const kind = requireAnswer(await new SelectQuestion<LocalPluginKind | 'none'>({
|
||||
id: 'plugins.kind',
|
||||
message: 'Local plugin',
|
||||
options: [
|
||||
{ value: 'none', label: 'No local plugin' },
|
||||
{ value: 'plugin', label: 'Cordis plugin' },
|
||||
{ value: 'tool', label: 'Model-facing tool' },
|
||||
],
|
||||
initialValue: 'none',
|
||||
}).resolve(this.port))
|
||||
return kind === 'none' ? [] : [new LocalPluginBlueprint(kind, kind)]
|
||||
}
|
||||
|
||||
private async collectPackageManager(): Promise<{ manager: PackageManager; install: boolean }> {
|
||||
const inferred = inferPackageManagerName(this.args.packageManager, this.userAgent)
|
||||
const name = requireAnswer(await new SelectQuestion<PackageManagerName>({
|
||||
id: 'packageManager',
|
||||
message: 'Package manager',
|
||||
options: [
|
||||
{ value: 'npm', label: 'npm' },
|
||||
{ value: 'pnpm', label: 'pnpm' },
|
||||
{ value: 'yarn', label: 'Yarn' },
|
||||
],
|
||||
initialValue: inferred ?? 'npm',
|
||||
}).resolve(this.port, inferred))
|
||||
const manager = createPackageManager(name, await this.versionProbe(name, this.cwd))
|
||||
const install = requireAnswer(await new ConfirmQuestion({
|
||||
id: 'install',
|
||||
message: CREATE_TEMPLATES.installQuestion.render(packageManagerTemplateModel(manager)).trimEnd(),
|
||||
initialValue: true,
|
||||
}).resolve(this.port, this.args.install))
|
||||
return { manager, install }
|
||||
}
|
||||
}
|
||||
98
packages/scaffold/create-sdk/src/headless.ts
Normal file
98
packages/scaffold/create-sdk/src/headless.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Headless create input: a structured project spec supplied by an agent or CI
|
||||
* instead of interactive prompts.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/headless
|
||||
*/
|
||||
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import type { FeatureSelection, PackageManagerName, RunInterface } from '@deepseek-ai/dsh-helper'
|
||||
import type { CreateArgs } from './args.ts'
|
||||
|
||||
/**
|
||||
* Structured, non-interactive create input. Scalar fields mirror {@link CreateArgs}
|
||||
* project answers; `features` is the headless feature plan handed to `CreateWizard`
|
||||
* (the interactive tree/suggests prompts are skipped). Absent required answers make
|
||||
* the run fail loud through `HeadlessPromptPort` rather than blocking.
|
||||
*/
|
||||
interface HeadlessCreateSpec {
|
||||
directory?: string
|
||||
description?: string
|
||||
provider?: 'deepseek-official' | 'custom'
|
||||
baseURL?: string
|
||||
apiKey?: string
|
||||
model?: string
|
||||
interface?: RunInterface
|
||||
pm?: PackageManagerName
|
||||
install?: boolean
|
||||
linkWorkspace?: boolean
|
||||
features?: readonly FeatureSelection[]
|
||||
}
|
||||
|
||||
/** Resolved headless input: the args the wizard reads plus the feature plan. */
|
||||
export interface ResolvedHeadless {
|
||||
args: CreateArgs
|
||||
features: readonly FeatureSelection[] | undefined
|
||||
}
|
||||
|
||||
function asRecord(value: unknown, source: string): Record<string, unknown> {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error(`${source}: expected a JSON object`)
|
||||
}
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Parse and shallow-validate a headless spec from JSON text. */
|
||||
function parseHeadlessSpec(text: string, source: string): HeadlessCreateSpec {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch (error) {
|
||||
/* v8 ignore next -- JSON.parse only throws Error instances; the String() branch is defensive */
|
||||
throw new Error(`${source}: invalid JSON (${error instanceof Error ? error.message : String(error)})`)
|
||||
}
|
||||
const record = asRecord(parsed, source)
|
||||
if (record.features !== undefined && !Array.isArray(record.features)) {
|
||||
throw new Error(`${source}: "features" must be an array`)
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a headless spec from `--config-json` (inline) or `--config` (a JSON file),
|
||||
* returning `undefined` when neither is supplied.
|
||||
* @param args - parsed create args.
|
||||
* @param readFileText - file reader seam for tests.
|
||||
* @returns the resolved args + feature plan, or `undefined` for interactive runs.
|
||||
*/
|
||||
export async function resolveHeadless(
|
||||
args: CreateArgs,
|
||||
readFileText: (path: string) => Promise<string> = path => readFile(path, 'utf8'),
|
||||
): Promise<ResolvedHeadless | undefined> {
|
||||
let text: string
|
||||
let source: string
|
||||
if (args.configJson !== undefined) {
|
||||
text = args.configJson
|
||||
source = '--config-json'
|
||||
} else if (args.config !== undefined) {
|
||||
source = args.config
|
||||
text = await readFileText(args.config)
|
||||
} else {
|
||||
return undefined
|
||||
}
|
||||
const spec = parseHeadlessSpec(text, source)
|
||||
const resolvedArgs: CreateArgs = {
|
||||
...spec.directory === undefined ? {} : { directory: spec.directory },
|
||||
...spec.description === undefined ? {} : { description: spec.description },
|
||||
...spec.provider === undefined ? {} : { provider: spec.provider },
|
||||
...spec.baseURL === undefined ? {} : { baseURL: spec.baseURL },
|
||||
...spec.apiKey === undefined ? {} : { apiKey: spec.apiKey },
|
||||
...spec.model === undefined ? {} : { model: spec.model },
|
||||
...spec.interface === undefined ? {} : { runInterface: spec.interface },
|
||||
...spec.pm === undefined ? {} : { packageManager: spec.pm },
|
||||
...spec.install === undefined ? {} : { install: spec.install },
|
||||
...spec.linkWorkspace ? { linkWorkspace: true } : {},
|
||||
help: false,
|
||||
}
|
||||
return { args: resolvedArgs, features: spec.features }
|
||||
}
|
||||
7
packages/scaffold/create-sdk/src/index.ts
Normal file
7
packages/scaffold/create-sdk/src/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* The create-sdk package is a CLI initializer; its library entry exports no symbols.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk
|
||||
*/
|
||||
|
||||
export {}
|
||||
30
packages/scaffold/create-sdk/src/invariant.ts
Normal file
30
packages/scaffold/create-sdk/src/invariant.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/create-sdk`.
|
||||
* @module @deepseek-ai/create-sdk/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/create-sdk'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'create-sdk-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this SDK build-time package owns no live event stream or mutable data;
|
||||
* generated output and consumer tests cover its contract.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
/* jscpd:ignore-end */
|
||||
41
packages/scaffold/create-sdk/src/project-scaffolder.ts
Normal file
41
packages/scaffold/create-sdk/src/project-scaffolder.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Project creation use case over the shared SDK aggregate and edit session.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/project-scaffolder
|
||||
*/
|
||||
|
||||
import { stat } from 'node:fs/promises'
|
||||
import {
|
||||
SdkProject,
|
||||
createBuiltinRegistry,
|
||||
type ChangeSet,
|
||||
type ProjectCreationRequest,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
|
||||
/** Result of writing one new SDK project. */
|
||||
export interface ScaffoldResult {
|
||||
project: SdkProject
|
||||
changes: ChangeSet
|
||||
}
|
||||
|
||||
/** Create a project entirely in memory, then validate and commit it once. */
|
||||
export async function scaffoldProject(root: string, request: ProjectCreationRequest): Promise<ScaffoldResult> {
|
||||
let targetExists = true
|
||||
try {
|
||||
await stat(root)
|
||||
} catch (error) {
|
||||
/* v8 ignore else -- the other arm requires a filesystem permission/IO fault from stat */
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') targetExists = false
|
||||
/* v8 ignore next -- paired with the ignored defensive stat-error arm above */
|
||||
else throw error
|
||||
}
|
||||
if (targetExists) throw new Error(`target already exists: ${root}`)
|
||||
const project = SdkProject.create(root, request)
|
||||
const registry = createBuiltinRegistry(project.profile)
|
||||
const edit = project.edit(registry)
|
||||
for (const selection of request.features) {
|
||||
edit.installFeature(registry.get(selection.id), selection)
|
||||
}
|
||||
for (const plugin of request.localPlugins) edit.addPlugin(plugin)
|
||||
return edit.commit()
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Created {{name}} in {{directory}}
|
||||
@@ -0,0 +1 @@
|
||||
Run {{packageManager}} {{installArgs}} and then build the project?
|
||||
@@ -0,0 +1,5 @@
|
||||
{{#if setupRequired}}
|
||||
Next: cd {{directory}} && {{packageManager}} {{installArgs}} && {{packageManager}} {{buildArgs}} && {{packageManager}} start
|
||||
{{else}}
|
||||
Next: cd {{directory}} && {{packageManager}} start
|
||||
{{/if}}
|
||||
@@ -0,0 +1,2 @@
|
||||
Project files are ready, but setup failed: {{error}}
|
||||
Retry: cd {{directory}} && {{packageManager}} {{installArgs}} && {{packageManager}} {{buildArgs}}
|
||||
@@ -0,0 +1,14 @@
|
||||
Usage: create-sdk [directory] [options]
|
||||
|
||||
Options:
|
||||
--description <text>
|
||||
--provider <deepseek-official|custom>
|
||||
--base-url <url>
|
||||
--api-key <key>
|
||||
--model <name>
|
||||
--interface <acp|embed>
|
||||
--pm <npm|pnpm|yarn>
|
||||
--install / --no-install
|
||||
--config <path>
|
||||
--config-json <json>
|
||||
--json
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Package-owned terminal templates for create-sdk.
|
||||
*
|
||||
* @module @deepseek-ai/create-sdk/templates/create-templates
|
||||
*/
|
||||
|
||||
import {
|
||||
TextTemplate,
|
||||
type PackageManager,
|
||||
type PackageManagerName,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
|
||||
interface CreatedTemplateModel {
|
||||
name: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
interface NextStepsTemplateModel extends PackageManagerTemplateModel {
|
||||
directory: string
|
||||
setupRequired: boolean
|
||||
}
|
||||
|
||||
interface SetupFailureTemplateModel extends PackageManagerTemplateModel {
|
||||
directory: string
|
||||
error: string
|
||||
}
|
||||
|
||||
/** Package-manager execution data consumed by create-sdk templates. */
|
||||
export interface PackageManagerTemplateModel {
|
||||
packageManager: PackageManagerName
|
||||
installArgs: string
|
||||
buildArgs: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Map package-manager execution data into terminal-template fields.
|
||||
* @param manager - selected package-manager strategy.
|
||||
* @returns executable name and operation arguments.
|
||||
*/
|
||||
export function packageManagerTemplateModel(manager: PackageManager): PackageManagerTemplateModel {
|
||||
return {
|
||||
packageManager: manager.name,
|
||||
installArgs: manager.installCommand().join(' '),
|
||||
buildArgs: manager.buildCommand().join(' '),
|
||||
}
|
||||
}
|
||||
|
||||
/** Compiled create-sdk terminal templates. */
|
||||
export const CREATE_TEMPLATES = {
|
||||
usage: TextTemplate.fromFile<Record<string, never>>(new URL('./assets/usage.txt.tpl', import.meta.url)),
|
||||
created: TextTemplate.fromFile<CreatedTemplateModel>(new URL('./assets/created.txt.tpl', import.meta.url)),
|
||||
nextSteps: TextTemplate.fromFile<NextStepsTemplateModel>(new URL('./assets/next-steps.txt.tpl', import.meta.url)),
|
||||
setupFailure: TextTemplate.fromFile<SetupFailureTemplateModel>(
|
||||
new URL('./assets/setup-failure.txt.tpl', import.meta.url),
|
||||
),
|
||||
installQuestion: TextTemplate.fromFile<PackageManagerTemplateModel>(
|
||||
new URL('./assets/install-question.txt.tpl', import.meta.url),
|
||||
),
|
||||
} as const
|
||||
28
packages/scaffold/create-sdk/tests/built-artifacts.e2e.ts
Normal file
28
packages/scaffold/create-sdk/tests/built-artifacts.e2e.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { promisify } from 'node:util'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
const createBin = join(repoRoot, 'packages/scaffold/create-sdk/lib/bin.js')
|
||||
const scriptsBin = join(repoRoot, 'packages/scaffold/scripts/lib/bin.js')
|
||||
|
||||
describe.skipIf(!existsSync(createBin) || !existsSync(scriptsBin))(
|
||||
'SDK built artifacts',
|
||||
() => {
|
||||
it('runs the published dsh-sdk bin help path under plain Node', async () => {
|
||||
const result = await execFileAsync(process.execPath, [scriptsBin, '--help'], { encoding: 'utf8' })
|
||||
expect(result.stdout).toContain('Usage: dsh-sdk <command>')
|
||||
expect(result.stderr).toBe('')
|
||||
})
|
||||
|
||||
it('runs the published create-sdk bin help path under plain Node', async () => {
|
||||
const result = await execFileAsync(process.execPath, [createBin, '--help'], { encoding: 'utf8' })
|
||||
expect(result.stdout).toContain('Usage: create-sdk [directory]')
|
||||
expect(result.stderr).toBe('')
|
||||
})
|
||||
},
|
||||
)
|
||||
391
packages/scaffold/create-sdk/tests/create.snapshot.ts
Normal file
391
packages/scaffold/create-sdk/tests/create.snapshot.ts
Normal file
@@ -0,0 +1,391 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
featureId,
|
||||
createPackageManager,
|
||||
type NestedMultiSelectValue,
|
||||
type PromptPort,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
import type {
|
||||
ConfirmPromptRequest,
|
||||
MultiSelectPromptRequest,
|
||||
NestedMultiSelectRequest,
|
||||
PromptOutcome,
|
||||
SecretPromptRequest,
|
||||
SelectPromptRequest,
|
||||
TextPromptRequest,
|
||||
} from '../../helper/src/questions/prompt-port.ts'
|
||||
import { parseCreateArgs } from '../src/args.ts'
|
||||
import { CreateWizard } from '../src/create-wizard.ts'
|
||||
import { CREATE_TEMPLATES, packageManagerTemplateModel } from '../src/templates/create-templates.ts'
|
||||
|
||||
class RecordingPort implements PromptPort {
|
||||
readonly transcript: unknown[] = []
|
||||
readonly #answers: unknown[]
|
||||
|
||||
constructor(answers: unknown[]) { this.#answers = [...answers] }
|
||||
|
||||
answer<T>(record: unknown): Promise<PromptOutcome<T>> {
|
||||
this.transcript.push(record)
|
||||
return Promise.resolve({ status: 'answered', value: this.#answers.shift() as T })
|
||||
}
|
||||
|
||||
text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
|
||||
return this.answer({
|
||||
kind: 'text',
|
||||
message: request.message,
|
||||
defaultValue: request.defaultValue,
|
||||
initialValue: request.initialValue,
|
||||
})
|
||||
}
|
||||
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> {
|
||||
return this.answer({ kind: 'secret', message: request.message })
|
||||
}
|
||||
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> {
|
||||
return this.answer({
|
||||
kind: 'select', message: request.message, options: request.options.map(option => option.label),
|
||||
initialValue: request.initialValue,
|
||||
})
|
||||
}
|
||||
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
|
||||
return this.answer({
|
||||
kind: 'multiselect', message: request.message, options: request.options.map(option => option.label),
|
||||
initialValues: request.initialValues,
|
||||
})
|
||||
}
|
||||
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> {
|
||||
return this.answer({ kind: 'confirm', message: request.message, initialValue: request.initialValue })
|
||||
}
|
||||
nestedMultiselect<TValue, TChoice>(
|
||||
request: NestedMultiSelectRequest<TValue, TChoice>,
|
||||
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
|
||||
return this.answer({
|
||||
kind: 'nested-multiselect',
|
||||
message: request.message,
|
||||
options: request.options.map(option => ({
|
||||
label: option.label,
|
||||
required: option.required,
|
||||
default: option.default,
|
||||
choices: option.choices?.map(choice => choice.label),
|
||||
})),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('create-sdk terminal contract', () => {
|
||||
it('renders package-manager-specific setup commands', () => {
|
||||
const model = packageManagerTemplateModel(createPackageManager('yarn', '4.0.0'))
|
||||
expect(CREATE_TEMPLATES.installQuestion.render(model)).toBe('Run yarn install and then build the project?\n')
|
||||
expect(CREATE_TEMPLATES.setupFailure.render({
|
||||
directory: '/workspace/agent',
|
||||
error: 'offline',
|
||||
...model,
|
||||
})).toContain('yarn install && yarn build')
|
||||
})
|
||||
|
||||
it('pins the full unresolved question order and completion messages', async () => {
|
||||
const port = new RecordingPort([
|
||||
'my-agent',
|
||||
'my-agent',
|
||||
'Snapshot agent',
|
||||
'deepseek-official',
|
||||
'secret-key',
|
||||
'acp',
|
||||
[
|
||||
{ value: featureId('persistence'), choices: ['jsonl'] },
|
||||
{ value: featureId('hmr'), choices: [] },
|
||||
{ value: featureId('web'), choices: ['exa'] },
|
||||
{ value: featureId('workflow'), choices: [] },
|
||||
],
|
||||
true,
|
||||
'exa-key',
|
||||
'none',
|
||||
'npm',
|
||||
false,
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs([]),
|
||||
port,
|
||||
cwd: '/workspace',
|
||||
releaseVersion: '0.0.1',
|
||||
userAgent: '',
|
||||
versionProbe: async () => '10.0.0',
|
||||
}).run()
|
||||
expect({
|
||||
prompts: port.transcript,
|
||||
result: {
|
||||
directory: resolved.directory,
|
||||
name: resolved.request.name,
|
||||
manager: resolved.request.packageManager.name,
|
||||
install: resolved.install,
|
||||
features: resolved.request.features.map(item => ({ id: item.id, options: item.options })),
|
||||
},
|
||||
messages: {
|
||||
created: CREATE_TEMPLATES.created.render({
|
||||
name: resolved.request.name,
|
||||
directory: resolved.directory,
|
||||
}),
|
||||
next: CREATE_TEMPLATES.nextSteps.render({
|
||||
directory: resolved.directory,
|
||||
setupRequired: false,
|
||||
...packageManagerTemplateModel(resolved.request.packageManager),
|
||||
}),
|
||||
failure: CREATE_TEMPLATES.setupFailure.render({
|
||||
directory: resolved.directory,
|
||||
error: String(new Error('offline')),
|
||||
...packageManagerTemplateModel(resolved.request.packageManager),
|
||||
}),
|
||||
},
|
||||
}).toMatchInlineSnapshot(`
|
||||
{
|
||||
"messages": {
|
||||
"created": "Created my-agent in /workspace/my-agent
|
||||
",
|
||||
"failure": "Project files are ready, but setup failed: Error: offline
|
||||
Retry: cd /workspace/my-agent && npm install && npm run build
|
||||
",
|
||||
"next": "Next: cd /workspace/my-agent && npm start
|
||||
",
|
||||
},
|
||||
"prompts": [
|
||||
{
|
||||
"defaultValue": "my-agent",
|
||||
"initialValue": undefined,
|
||||
"kind": "text",
|
||||
"message": "Where should the project be created?",
|
||||
},
|
||||
{
|
||||
"defaultValue": "my-agent",
|
||||
"initialValue": undefined,
|
||||
"kind": "text",
|
||||
"message": "Package name",
|
||||
},
|
||||
{
|
||||
"defaultValue": "A DeepSeek Harness agent named my-agent",
|
||||
"initialValue": undefined,
|
||||
"kind": "text",
|
||||
"message": "Project description",
|
||||
},
|
||||
{
|
||||
"initialValue": "deepseek-official",
|
||||
"kind": "select",
|
||||
"message": "Model provider",
|
||||
"options": [
|
||||
"DeepSeek",
|
||||
"Custom endpoint (pi-ai)",
|
||||
],
|
||||
},
|
||||
{
|
||||
"kind": "secret",
|
||||
"message": "DeepSeek API key",
|
||||
},
|
||||
{
|
||||
"initialValue": "acp",
|
||||
"kind": "select",
|
||||
"message": "Run interface",
|
||||
"options": [
|
||||
"ACP automation server",
|
||||
"Embedded context",
|
||||
],
|
||||
},
|
||||
{
|
||||
"kind": "nested-multiselect",
|
||||
"message": "Select features",
|
||||
"options": [
|
||||
{
|
||||
"choices": [
|
||||
"Local executor",
|
||||
"Sandboxed executor",
|
||||
],
|
||||
"default": true,
|
||||
"label": "Command execution",
|
||||
"required": true,
|
||||
},
|
||||
{
|
||||
"choices": [
|
||||
"JSONL files",
|
||||
"SQLite database",
|
||||
],
|
||||
"default": true,
|
||||
"label": "Durable session storage",
|
||||
"required": true,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": true,
|
||||
"label": "Hot-module reload",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": true,
|
||||
"label": "Read, write, and edit local files",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": true,
|
||||
"label": "Model-facing task tracking",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": true,
|
||||
"label": "Local skill discovery",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": [
|
||||
"DeepSeek search",
|
||||
"Exa search",
|
||||
"Perplexity search",
|
||||
"Fetch only",
|
||||
],
|
||||
"default": false,
|
||||
"label": "Web search and fetch tools",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": [
|
||||
"Fresh child agent",
|
||||
"Fork parent history",
|
||||
],
|
||||
"default": false,
|
||||
"label": "Delegate work to child agents",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": false,
|
||||
"label": "Scripted multi-agent workflows",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": false,
|
||||
"label": "Automatic context compaction",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": [
|
||||
"Claude Code hooks",
|
||||
"Codex hooks",
|
||||
],
|
||||
"default": false,
|
||||
"label": "Run Claude Code or Codex hooks",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": false,
|
||||
"label": "Loop-hygiene reminders",
|
||||
"required": false,
|
||||
},
|
||||
{
|
||||
"choices": undefined,
|
||||
"default": false,
|
||||
"label": "Tool timeout policy",
|
||||
"required": false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"initialValue": true,
|
||||
"kind": "confirm",
|
||||
"message": "Add the recommended tool timeout policy for web search and fetch tools?",
|
||||
},
|
||||
{
|
||||
"kind": "secret",
|
||||
"message": "Exa API key",
|
||||
},
|
||||
{
|
||||
"initialValue": "none",
|
||||
"kind": "select",
|
||||
"message": "Local plugin",
|
||||
"options": [
|
||||
"No local plugin",
|
||||
"Cordis plugin",
|
||||
"Model-facing tool",
|
||||
],
|
||||
},
|
||||
{
|
||||
"initialValue": "npm",
|
||||
"kind": "select",
|
||||
"message": "Package manager",
|
||||
"options": [
|
||||
"npm",
|
||||
"pnpm",
|
||||
"Yarn",
|
||||
],
|
||||
},
|
||||
{
|
||||
"initialValue": true,
|
||||
"kind": "confirm",
|
||||
"message": "Run npm install and then build the project?",
|
||||
},
|
||||
],
|
||||
"result": {
|
||||
"directory": "/workspace/my-agent",
|
||||
"features": [
|
||||
{
|
||||
"id": "provider",
|
||||
"options": [
|
||||
"deepseek-official",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "spine",
|
||||
"options": [
|
||||
"default",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "app",
|
||||
"options": [
|
||||
"acp",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "bash",
|
||||
"options": [
|
||||
"local",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "persistence",
|
||||
"options": [
|
||||
"jsonl",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "hmr",
|
||||
"options": [
|
||||
"default",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "web",
|
||||
"options": [
|
||||
"exa",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "workflow",
|
||||
"options": [
|
||||
"workerthread",
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "timeout-policy",
|
||||
"options": [
|
||||
"default",
|
||||
],
|
||||
},
|
||||
],
|
||||
"install": false,
|
||||
"manager": "npm",
|
||||
"name": "my-agent",
|
||||
},
|
||||
}
|
||||
`)
|
||||
})
|
||||
})
|
||||
674
packages/scaffold/create-sdk/tests/create.spec.ts
Normal file
674
packages/scaffold/create-sdk/tests/create.spec.ts
Normal file
@@ -0,0 +1,674 @@
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { PassThrough, Writable } from 'node:stream'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
HeadlessPromptPort,
|
||||
LocalPluginBlueprint,
|
||||
featureId,
|
||||
NodeCommandRunner,
|
||||
NpmPackageManager,
|
||||
type FeatureSelection,
|
||||
type NestedMultiSelectValue,
|
||||
type PromptPort,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
import type {
|
||||
ConfirmPromptRequest,
|
||||
MultiSelectPromptRequest,
|
||||
NestedMultiSelectRequest,
|
||||
PromptOutcome,
|
||||
SecretPromptRequest,
|
||||
SelectPromptRequest,
|
||||
TextPromptRequest,
|
||||
} from '../../helper/src/questions/prompt-port.ts'
|
||||
import { parseCreateArgs } from '../src/args.ts'
|
||||
import {
|
||||
createProject,
|
||||
readCreateSdkVersion,
|
||||
runCreateCommand,
|
||||
type CreateCommandContext,
|
||||
} from '../src/command.ts'
|
||||
import { CreateWizard } from '../src/create-wizard.ts'
|
||||
import { resolveHeadless } from '../src/headless.ts'
|
||||
import { scaffoldProject } from '../src/project-scaffolder.ts'
|
||||
|
||||
class ScriptedPort implements PromptPort {
|
||||
readonly requests: string[] = []
|
||||
readonly #answers: unknown[]
|
||||
|
||||
constructor(answers: unknown[]) {
|
||||
this.#answers = [...answers]
|
||||
}
|
||||
|
||||
answer<T>(message: string): Promise<PromptOutcome<T>> {
|
||||
this.requests.push(message)
|
||||
const value = this.#answers.shift()
|
||||
return Promise.resolve(value === ScriptedPort.cancel
|
||||
? { status: 'cancelled' }
|
||||
: { status: 'answered', value: value as T })
|
||||
}
|
||||
|
||||
async text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
|
||||
const outcome = await this.answer<string>(request.message)
|
||||
if (outcome.status === 'cancelled') return outcome
|
||||
const value = outcome.value || request.defaultValue || ''
|
||||
const diagnostic = request.validate?.(value)
|
||||
if (diagnostic) throw new Error(diagnostic)
|
||||
return { status: 'answered', value }
|
||||
}
|
||||
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> { return this.answer(request.message) }
|
||||
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> { return this.answer(request.message) }
|
||||
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
|
||||
return this.answer(request.message)
|
||||
}
|
||||
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> { return this.answer(request.message) }
|
||||
nestedMultiselect<TValue, TChoice>(
|
||||
request: NestedMultiSelectRequest<TValue, TChoice>,
|
||||
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
|
||||
return this.answer(request.message)
|
||||
}
|
||||
|
||||
static readonly cancel = Symbol('cancel')
|
||||
}
|
||||
|
||||
const temporary: string[] = []
|
||||
const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
|
||||
interface GeneratedPackageManifest {
|
||||
scripts?: Record<string, string>
|
||||
dependencies?: Record<string, string>
|
||||
devDependencies?: Record<string, string>
|
||||
}
|
||||
|
||||
interface GeneratedTsConfig {
|
||||
compilerOptions: {
|
||||
types?: readonly string[]
|
||||
}
|
||||
}
|
||||
|
||||
function parseGeneratedPackageManifest(text: string): GeneratedPackageManifest {
|
||||
return JSON.parse(text) as GeneratedPackageManifest
|
||||
}
|
||||
|
||||
function parseGeneratedTsConfig(text: string): GeneratedTsConfig {
|
||||
return JSON.parse(text) as GeneratedTsConfig
|
||||
}
|
||||
|
||||
function commandContext(
|
||||
cwd: string,
|
||||
port?: PromptPort,
|
||||
setup?: CreateCommandContext['setup'],
|
||||
): CreateCommandContext & { readStdout: () => string; readStderr: () => string } {
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
const input = Object.assign(new PassThrough(), { isTTY: true }) as unknown as NodeJS.ReadStream
|
||||
const output = Object.assign(new Writable({
|
||||
write(chunk, _encoding, callback) { stdout += String(chunk); callback() },
|
||||
}), { isTTY: true }) as unknown as NodeJS.WriteStream
|
||||
const error = new Writable({
|
||||
write(chunk, _encoding, callback) { stderr += String(chunk); callback() },
|
||||
}) as unknown as NodeJS.WriteStream
|
||||
return {
|
||||
cwd,
|
||||
stdin: input,
|
||||
stdout: output,
|
||||
stderr: error,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
...port ? { port } : {},
|
||||
...setup ? { setup } : {},
|
||||
readStdout: () => stdout,
|
||||
readStderr: () => stderr,
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
describe('create arguments', () => {
|
||||
it('parses public options and the private repository link mode', () => {
|
||||
expect(parseCreateArgs([
|
||||
'agent', '--description=demo', '--provider', 'deepseek-official', '--base-url=https://api.example',
|
||||
'--api-key', 'key', '--model=m', '--interface', 'acp', '--pm=pnpm', '--no-install',
|
||||
'--link-workspace',
|
||||
])).toEqual({
|
||||
directory: 'agent',
|
||||
description: 'demo',
|
||||
provider: 'deepseek-official',
|
||||
baseURL: 'https://api.example',
|
||||
apiKey: 'key',
|
||||
model: 'm',
|
||||
runInterface: 'acp',
|
||||
packageManager: 'pnpm',
|
||||
install: false,
|
||||
linkWorkspace: true,
|
||||
help: false,
|
||||
})
|
||||
expect(parseCreateArgs(['--link-workspace']).linkWorkspace).toBe(true)
|
||||
expect(() => parseCreateArgs(['--link-packages-workspace'])).toThrow("unknown option '--link-packages-workspace'")
|
||||
expect(parseCreateArgs(['--provider=custom']).provider).toBe('custom')
|
||||
expect(parseCreateArgs(['--help']).help).toBe(true)
|
||||
expect(() => parseCreateArgs(['--interface=bad'])).toThrow('Allowed choices are acp, embed')
|
||||
expect(() => parseCreateArgs(['--unknown'])).toThrow("unknown option '--unknown'")
|
||||
expect(() => parseCreateArgs(['one', 'two'])).toThrow('too many arguments')
|
||||
})
|
||||
|
||||
it('validates empty directories and package names', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-validation-'))
|
||||
temporary.push(root)
|
||||
await expect(new CreateWizard({
|
||||
args: parseCreateArgs(['']), port: new ScriptedPort([]), cwd: root,
|
||||
releaseVersion: '0.0.1', versionProbe: async () => '10.0.0',
|
||||
}).run()).rejects.toThrow('A value is required')
|
||||
await expect(new CreateWizard({
|
||||
args: parseCreateArgs(['agent']), port: new ScriptedPort(['Invalid Name']), cwd: root,
|
||||
releaseVersion: '0.0.1', versionProbe: async () => '10.0.0',
|
||||
}).run()).rejects.toThrow('lowercase npm package name')
|
||||
})
|
||||
|
||||
it('rejects an existing target before asking project questions', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-existing-target-'))
|
||||
temporary.push(cwd)
|
||||
await mkdir(join(cwd, 'taken'))
|
||||
const port = new ScriptedPort([])
|
||||
const wizard = new CreateWizard({
|
||||
args: parseCreateArgs(['taken']),
|
||||
port,
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
})
|
||||
await expect(wizard.run()).rejects.toThrow('directory: Target already exists')
|
||||
expect(port.requests).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('CreateWizard and scaffolder', () => {
|
||||
it('asks only unresolved questions in requirement-safe order', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-wizard-'))
|
||||
temporary.push(cwd)
|
||||
const port = new ScriptedPort([
|
||||
'my-agent',
|
||||
[
|
||||
{ value: featureId('persistence'), choices: ['sqlite'] },
|
||||
{ value: featureId('hmr'), choices: [] },
|
||||
{ value: featureId('fs'), choices: [] },
|
||||
{ value: featureId('web'), choices: ['exa'] },
|
||||
],
|
||||
false,
|
||||
'exa-key',
|
||||
'tool',
|
||||
])
|
||||
const args = parseCreateArgs([
|
||||
'my-agent',
|
||||
'--description=demo',
|
||||
'--provider=deepseek-official',
|
||||
'--api-key=deepseek-key',
|
||||
'--model=deepseek-v4-flash',
|
||||
'--interface=acp',
|
||||
'--pm=npm',
|
||||
'--no-install',
|
||||
'--link-workspace',
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args,
|
||||
port,
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
}).run()
|
||||
expect(port.requests).toEqual([
|
||||
'Package name',
|
||||
'Select features',
|
||||
'Add the recommended tool timeout policy for web search and fetch tools?',
|
||||
'Exa API key',
|
||||
'Local plugin',
|
||||
])
|
||||
expect(resolved.install).toBe(false)
|
||||
expect(resolved.request.packageManager.name).toBe('npm')
|
||||
expect(resolved.request.linkWorkspaceRoot).toBe(repoRoot)
|
||||
expect(resolved.request.localPlugins[0]).toMatchObject({ name: 'tool', kind: 'tool' })
|
||||
expect(resolved.request.features.find(item => item.id === 'web')).toMatchObject({
|
||||
options: ['exa'], secrets: { apiKey: 'exa-key' },
|
||||
})
|
||||
expect(resolved.request.features.find(item => item.id === 'hmr')).toMatchObject({ options: ['default'] })
|
||||
})
|
||||
|
||||
it('runs headlessly from a feature plan without reaching the terminal', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-headless-'))
|
||||
temporary.push(cwd)
|
||||
const features: FeatureSelection[] = [
|
||||
{ id: featureId('persistence'), options: ['sqlite'], values: { region: 'us' } },
|
||||
{ id: featureId('web'), options: ['exa'], secrets: { apiKey: 'exa-key' } },
|
||||
]
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs([
|
||||
'my-agent', '--description=demo', '--provider=deepseek-official', '--api-key=deepseek-key',
|
||||
'--model=deepseek-v4-flash', '--interface=acp', '--pm=npm', '--no-install',
|
||||
]),
|
||||
port: new HeadlessPromptPort(),
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
features,
|
||||
}).run()
|
||||
expect(resolved.install).toBe(false)
|
||||
expect(resolved.request.localPlugins).toEqual([])
|
||||
expect(resolved.request.features.find(item => item.id === 'web')).toMatchObject({
|
||||
options: ['exa'], secrets: { apiKey: 'exa-key' },
|
||||
})
|
||||
expect(resolved.request.features.find(item => item.id === 'persistence')).toMatchObject({ options: ['sqlite'] })
|
||||
expect(resolved.request.features.find(item => item.id === 'provider')).toMatchObject({
|
||||
secrets: { apiKey: 'deepseek-key' },
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a non-string feature value in a headless plan', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-headless-bad-'))
|
||||
temporary.push(cwd)
|
||||
const features = [
|
||||
{ id: featureId('persistence'), options: ['sqlite'], values: { bad: 1 } },
|
||||
] as unknown as FeatureSelection[]
|
||||
await expect(new CreateWizard({
|
||||
args: parseCreateArgs([
|
||||
'my-agent', '--description=demo', '--provider=deepseek-official', '--api-key=k',
|
||||
'--model=m', '--interface=acp', '--pm=npm', '--no-install',
|
||||
]),
|
||||
port: new HeadlessPromptPort(),
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
features,
|
||||
}).run()).rejects.toThrow('must be a string')
|
||||
})
|
||||
|
||||
it('writes the project once and refuses every existing target', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-scaffold-'))
|
||||
temporary.push(root)
|
||||
const request = {
|
||||
name: 'agent',
|
||||
description: 'demo',
|
||||
runtime: { model: 'deepseek-v4-flash' },
|
||||
packageManager: new NpmPackageManager('10.0.0'),
|
||||
releaseVersion: '0.0.1',
|
||||
features: [
|
||||
{ id: featureId('provider'), options: ['deepseek-official'], secrets: { apiKey: 'key' } },
|
||||
{ id: featureId('bash'), options: ['local'] },
|
||||
{ id: featureId('app'), options: ['embed'] },
|
||||
{ id: featureId('persistence'), options: ['jsonl'] },
|
||||
],
|
||||
localPlugins: [new LocalPluginBlueprint('plugin', 'plugin')],
|
||||
}
|
||||
const target = join(root, 'project')
|
||||
const result = await scaffoldProject(target, request)
|
||||
expect(result.changes.changedFiles).toContain('README.md')
|
||||
const index = await readFile(join(target, 'index.ts'), 'utf8')
|
||||
expect(index).toContain('SdkBootContext')
|
||||
expect(index).toContain('ctx.agents.create')
|
||||
expect(index).toContain('agentOptions: { model: "deepseek-v4-flash" }')
|
||||
expect(index).not.toContain('AgentId')
|
||||
const tsconfig = parseGeneratedTsConfig(await readFile(join(target, 'tsconfig.base.json'), 'utf8'))
|
||||
const manifest = parseGeneratedPackageManifest(await readFile(join(target, 'package.json'), 'utf8'))
|
||||
expect(tsconfig.compilerOptions.types).toEqual(['node'])
|
||||
expect(manifest.scripts).toEqual({
|
||||
dev: 'dsh-sdk dev index.ts',
|
||||
build: 'dsh-sdk build',
|
||||
typecheck: 'tsc -b',
|
||||
start: 'dsh-sdk start index.js',
|
||||
config: 'dsh-sdk config',
|
||||
})
|
||||
expect(manifest.dependencies).not.toHaveProperty('node-addon-require-builtin')
|
||||
expect(manifest.devDependencies?.['@types/node']).toBe('^22.20.0')
|
||||
expect(await readFile(join(target, 'plugins/plugin/src/index.ts'), 'utf8')).toContain('export function apply')
|
||||
const cordis = await readFile(join(target, 'cordis.yml'), 'utf8')
|
||||
expect(cordis).toMatch(/^- id:/)
|
||||
expect(cordis).not.toMatch(/^\[/)
|
||||
const occupied = join(root, 'occupied')
|
||||
await mkdir(occupied)
|
||||
await expect(scaffoldProject(occupied, request)).rejects.toThrow('already exists')
|
||||
await writeFile(join(occupied, 'keep'), 'x')
|
||||
await expect(scaffoldProject(occupied, request)).rejects.toThrow('already exists')
|
||||
})
|
||||
|
||||
it('installs workflow requirements before validating the next feature', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-workflow-requires-'))
|
||||
temporary.push(cwd)
|
||||
const port = new ScriptedPort([
|
||||
'workflow-agent',
|
||||
[
|
||||
{ value: featureId('persistence'), choices: ['jsonl'] },
|
||||
{ value: featureId('workflow'), choices: [] },
|
||||
],
|
||||
'none',
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs([
|
||||
'workflow-agent', '--description=test', '--provider=deepseek-official', '--api-key=key',
|
||||
'--interface=embed', '--pm=npm', '--no-install',
|
||||
]),
|
||||
port,
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
}).run()
|
||||
const result = await scaffoldProject(resolved.directory, resolved.request)
|
||||
expect(result.project.cordis.entry('subagent-spawn')).toBeDefined()
|
||||
expect(result.project.cordis.entry('tool-subagent')).toBeDefined()
|
||||
})
|
||||
|
||||
it('confirms an empty provider key and leaves a documented .env placeholder', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-empty-key-'))
|
||||
temporary.push(cwd)
|
||||
const port = new ScriptedPort([
|
||||
'empty-key-agent',
|
||||
'',
|
||||
true,
|
||||
[{ value: featureId('persistence'), choices: ['jsonl'] }],
|
||||
'none',
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs([
|
||||
'empty-key-agent', '--description=test', '--provider=deepseek-official',
|
||||
'--interface=embed', '--pm=npm', '--no-install',
|
||||
]),
|
||||
port,
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
}).run()
|
||||
await scaffoldProject(resolved.directory, resolved.request)
|
||||
expect(await readFile(join(resolved.directory, '.env'), 'utf8')).toBe(
|
||||
'# Required before the first model request.\nDEEPSEEK_API_KEY=\n',
|
||||
)
|
||||
expect(port.requests).toContain('Keep the API key empty and fill .env later?')
|
||||
})
|
||||
|
||||
it('collects custom provider inputs, retries an empty key, and accepts a recommendation', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-custom-inputs-'))
|
||||
temporary.push(cwd)
|
||||
const port = new ScriptedPort([
|
||||
'custom-agent',
|
||||
'test custom provider',
|
||||
'custom',
|
||||
'https://provider.example/v1',
|
||||
'', false, 'custom-key',
|
||||
'embed',
|
||||
[
|
||||
{ value: featureId('persistence'), choices: ['jsonl'] },
|
||||
{ value: featureId('web'), choices: ['deepseek-official'] },
|
||||
],
|
||||
true,
|
||||
'none',
|
||||
'npm',
|
||||
false,
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs(['custom-agent']),
|
||||
port,
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
userAgent: '',
|
||||
}).run()
|
||||
expect(resolved.request.features.find(item => item.id === 'provider')).toMatchObject({
|
||||
options: ['custom'], values: { baseURL: 'https://provider.example/v1' }, secrets: { apiKey: 'custom-key' },
|
||||
})
|
||||
expect(resolved.request.features.some(item => item.id === 'timeout-policy')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not re-suggest an already selected feature', async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), 'create-selected-suggestion-'))
|
||||
temporary.push(cwd)
|
||||
const port = new ScriptedPort([
|
||||
'agent',
|
||||
[
|
||||
{ value: featureId('persistence'), choices: ['jsonl'] },
|
||||
{ value: featureId('web'), choices: ['deepseek-official'] },
|
||||
{ value: featureId('timeout-policy'), choices: ['default'] },
|
||||
],
|
||||
'none',
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs([
|
||||
'agent', '--description=test', '--provider=deepseek-official', '--api-key=key',
|
||||
'--interface=embed', '--pm=npm', '--no-install',
|
||||
]),
|
||||
port,
|
||||
cwd,
|
||||
releaseVersion: '0.0.1',
|
||||
versionProbe: async () => '10.0.0',
|
||||
}).run()
|
||||
expect(resolved.request.features.filter(item => item.id === 'timeout-policy')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('uses process defaults when constructor infrastructure is omitted', async () => {
|
||||
const name = `default-infra-${String(process.pid)}`
|
||||
const port = new ScriptedPort([
|
||||
name, [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
|
||||
])
|
||||
const resolved = await new CreateWizard({
|
||||
args: parseCreateArgs([
|
||||
name, '--description=test', '--provider=deepseek-official', '--api-key=key',
|
||||
'--interface=embed', '--pm=npm', '--no-install',
|
||||
]),
|
||||
port,
|
||||
releaseVersion: '0.0.1',
|
||||
}).run()
|
||||
expect(resolved.request.packageManager.name).toBe('npm')
|
||||
})
|
||||
|
||||
it('reads the release batch from the initializer package', async () => {
|
||||
await expect(readCreateSdkVersion()).resolves.toBe('0.0.1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('create command composition', () => {
|
||||
const argv = (directory: string, install: boolean): string[] => [
|
||||
directory, '--description=test', '--provider=deepseek-official', '--api-key=key',
|
||||
'--interface=embed', '--pm=npm', install ? '--install' : '--no-install',
|
||||
]
|
||||
|
||||
it('prints help before requiring a TTY and rejects non-interactive creation', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-command-help-'))
|
||||
temporary.push(root)
|
||||
const context = commandContext(root)
|
||||
context.stdin.isTTY = false
|
||||
context.stdout.isTTY = false
|
||||
await expect(createProject(['--help'], context)).resolves.toBeUndefined()
|
||||
expect(context.readStdout()).toContain('Usage: create-sdk')
|
||||
expect(context.readStdout()).toContain('--config-json <json>')
|
||||
expect(context.readStdout()).not.toContain('--link-workspace')
|
||||
await expect(createProject(argv('agent', false), context)).rejects.toThrow('interactive TTY')
|
||||
context.stdin.isTTY = true
|
||||
await expect(createProject(argv('agent', false), context)).rejects.toThrow('interactive TTY')
|
||||
})
|
||||
|
||||
it('creates headlessly from --config-json with no TTY', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-headless-cmd-'))
|
||||
temporary.push(root)
|
||||
const spec = JSON.stringify({
|
||||
directory: 'agent', description: 'test', provider: 'deepseek-official', apiKey: 'key',
|
||||
model: 'deepseek-v4-flash', interface: 'embed', pm: 'npm', install: false,
|
||||
features: [{ id: 'persistence', options: ['jsonl'] }],
|
||||
})
|
||||
const context = commandContext(root)
|
||||
context.stdin.isTTY = false
|
||||
context.stdout.isTTY = false
|
||||
const result = await createProject(['--config-json', spec], context)
|
||||
expect(result?.project.root).toBe(join(root, 'agent'))
|
||||
})
|
||||
|
||||
it('emits NDJSON lifecycle events under --json', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-headless-json-'))
|
||||
temporary.push(root)
|
||||
const base = {
|
||||
description: 'test', model: 'deepseek-v4-flash', interface: 'embed', pm: 'npm', install: false,
|
||||
}
|
||||
const ok = commandContext(root)
|
||||
ok.stdin.isTTY = false
|
||||
ok.stdout.isTTY = false
|
||||
const okSpec = JSON.stringify({ ...base, directory: 'done-agent', provider: 'deepseek-official', apiKey: 'key', features: [] })
|
||||
await expect(runCreateCommand(['--config-json', okSpec, '--json'], ok)).resolves.toBe(0)
|
||||
expect(ok.readStdout()).toContain('{"type":"done"}')
|
||||
// stdout stays pure NDJSON: every line parses, human progress goes to stderr
|
||||
for (const line of ok.readStdout().split('\n').filter(line => line.length > 0)) {
|
||||
expect(() => { JSON.parse(line) }).not.toThrow()
|
||||
}
|
||||
expect(ok.readStderr()).toContain('Created done-agent')
|
||||
expect(ok.readStderr()).toContain('Next: cd')
|
||||
|
||||
const missing = commandContext(root)
|
||||
missing.stdin.isTTY = false
|
||||
missing.stdout.isTTY = false
|
||||
const missingSpec = JSON.stringify({ ...base, directory: 'miss-agent', provider: 'custom', baseURL: 'https://x', features: [] })
|
||||
await expect(runCreateCommand(['--config-json', missingSpec, '--json'], missing)).resolves.toBe(1)
|
||||
expect(missing.readStdout()).toContain('"type":"action-required"')
|
||||
|
||||
const broken = commandContext(root)
|
||||
broken.stdin.isTTY = false
|
||||
broken.stdout.isTTY = false
|
||||
await expect(runCreateCommand(['--config-json', '{bad', '--json'], broken)).resolves.toBe(1)
|
||||
expect(broken.readStdout()).toContain('"type":"error"')
|
||||
|
||||
const cancelled = commandContext(root, new ScriptedPort([ScriptedPort.cancel]))
|
||||
await expect(runCreateCommand(['--json', ...argv('cancel-agent', false)], cancelled)).resolves.toBe(1)
|
||||
expect(cancelled.readStdout()).toContain('"reason":"cancelled"')
|
||||
})
|
||||
|
||||
it('creates through an injected prompt port and delegates optional setup', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-command-success-'))
|
||||
temporary.push(root)
|
||||
const port = new ScriptedPort([
|
||||
'agent', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
|
||||
])
|
||||
let setupDirectory = ''
|
||||
const context = commandContext(root, port, async (request) => { setupDirectory = request.directory })
|
||||
const result = await createProject(argv('agent', true), context)
|
||||
expect(result?.project.root).toBe(join(root, 'agent'))
|
||||
expect(setupDirectory).toBe(join(root, 'agent'))
|
||||
expect(context.readStdout()).toContain('Created agent')
|
||||
expect(context.readStdout()).toContain('Next: cd')
|
||||
const noInstall = commandContext(root, new ScriptedPort([
|
||||
'next', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
|
||||
]))
|
||||
await expect(createProject(argv('next', false), noInstall)).resolves.toBeDefined()
|
||||
expect(noInstall.readStdout()).toContain('npm install && npm run build && npm start')
|
||||
})
|
||||
|
||||
it('uses the package manager setup path when no setup override is supplied', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-command-default-setup-'))
|
||||
temporary.push(root)
|
||||
const port = new ScriptedPort([
|
||||
'agent', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
|
||||
])
|
||||
const install = vi.spyOn(NpmPackageManager.prototype, 'install').mockResolvedValue()
|
||||
const build = vi.spyOn(NpmPackageManager.prototype, 'build').mockResolvedValue()
|
||||
const context = commandContext(root, port)
|
||||
delete context.releaseVersion
|
||||
delete context.versionProbe
|
||||
await createProject(argv('agent', true), context)
|
||||
expect(install).toHaveBeenCalledOnce()
|
||||
expect(build).toHaveBeenCalledOnce()
|
||||
const spec = JSON.stringify({
|
||||
directory: 'json-agent', description: 'test', provider: 'deepseek-official', apiKey: 'key',
|
||||
model: 'deepseek-v4-flash', interface: 'embed', pm: 'npm', install: true, features: [],
|
||||
})
|
||||
const json = commandContext(root)
|
||||
json.stdin.isTTY = false
|
||||
json.stdout.isTTY = false
|
||||
await createProject(['--config-json', spec, '--json'], json)
|
||||
// json mode hands install/build a runner that redirects child output to stderr
|
||||
expect(install).toHaveBeenCalledTimes(2)
|
||||
expect(install.mock.calls[1]?.[1]).toBeInstanceOf(NodeCommandRunner)
|
||||
install.mockRestore()
|
||||
build.mockRestore()
|
||||
})
|
||||
|
||||
it('reports setup failures after preserving generated files', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-command-failure-'))
|
||||
temporary.push(root)
|
||||
const port = new ScriptedPort([
|
||||
'agent', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
|
||||
])
|
||||
const context = commandContext(root, port, async () => { throw new Error('offline') })
|
||||
await expect(createProject(argv('agent', true), context)).rejects.toThrow('offline')
|
||||
expect(context.readStderr()).toContain('Project files are ready, but setup failed')
|
||||
expect(context.readStderr()).toContain('npm install && npm run build')
|
||||
const stringFailure = commandContext(root, new ScriptedPort([
|
||||
'next', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
|
||||
]), async () => { throw 'offline-string' })
|
||||
await expect(runCreateCommand(argv('next', true), stringFailure)).resolves.toBe(1)
|
||||
expect(stringFailure.readStderr()).toContain('offline-string')
|
||||
})
|
||||
|
||||
it('maps cancellation and ordinary errors to command exit codes', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'create-command-exit-'))
|
||||
temporary.push(root)
|
||||
const cancelled = commandContext(root, new ScriptedPort([ScriptedPort.cancel]))
|
||||
await expect(runCreateCommand([], cancelled)).resolves.toBe(1)
|
||||
expect(cancelled.readStderr()).toContain('cancelled')
|
||||
const invalid = commandContext(root)
|
||||
await expect(runCreateCommand(['--unknown'], invalid)).resolves.toBe(1)
|
||||
expect(invalid.readStderr()).toContain('unknown option')
|
||||
const help = commandContext(root)
|
||||
await expect(runCreateCommand(['--help'], help)).resolves.toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveHeadless', () => {
|
||||
it('returns undefined without a config source', async () => {
|
||||
expect(await resolveHeadless(parseCreateArgs(['agent']))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('maps every inline --config-json field into args plus the feature plan', async () => {
|
||||
const spec = JSON.stringify({
|
||||
directory: 'a', description: 'd', provider: 'custom', baseURL: 'https://x', apiKey: 'k',
|
||||
model: 'm', interface: 'acp', pm: 'pnpm', install: true, linkWorkspace: true,
|
||||
features: [{ id: 'todo', options: ['default'] }],
|
||||
})
|
||||
const resolved = await resolveHeadless(parseCreateArgs(['--config-json', spec]))
|
||||
expect(resolved?.args).toMatchObject({
|
||||
directory: 'a', description: 'd', provider: 'custom', baseURL: 'https://x', apiKey: 'k',
|
||||
model: 'm', runInterface: 'acp', packageManager: 'pnpm', install: true, linkWorkspace: true, help: false,
|
||||
})
|
||||
expect(resolved?.features).toEqual([{ id: 'todo', options: ['default'] }])
|
||||
})
|
||||
|
||||
it('reads --config from a file via the injected reader and omits absent fields', async () => {
|
||||
const resolved = await resolveHeadless(
|
||||
parseCreateArgs(['--config', '/spec.json']),
|
||||
async () => JSON.stringify({ description: 'from-file' }),
|
||||
)
|
||||
expect(resolved?.args.description).toBe('from-file')
|
||||
expect(resolved?.args.directory).toBeUndefined()
|
||||
expect(resolved?.args.linkWorkspace).toBeUndefined()
|
||||
expect(resolved?.features).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads --config from disk with the default reader', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'create-headless-file-'))
|
||||
temporary.push(dir)
|
||||
const file = join(dir, 'spec.json')
|
||||
await writeFile(file, JSON.stringify({ description: 'on-disk' }))
|
||||
const resolved = await resolveHeadless(parseCreateArgs(['--config', file]))
|
||||
expect(resolved?.args.description).toBe('on-disk')
|
||||
})
|
||||
|
||||
it('fails loud on invalid JSON, a non-object root, or a non-array features field', async () => {
|
||||
await expect(resolveHeadless(parseCreateArgs(['--config-json', '{bad']))).rejects.toThrow('invalid JSON')
|
||||
await expect(resolveHeadless(parseCreateArgs(['--config-json', '[]']))).rejects.toThrow('expected a JSON object')
|
||||
await expect(resolveHeadless(parseCreateArgs(['--config-json', 'null']))).rejects.toThrow('expected a JSON object')
|
||||
await expect(resolveHeadless(parseCreateArgs(['--config-json', '5']))).rejects.toThrow('expected a JSON object')
|
||||
await expect(resolveHeadless(parseCreateArgs(['--config-json', '{"features":1}']))).rejects.toThrow('must be an array')
|
||||
})
|
||||
|
||||
it('accepts a minimal spec, leaving unspecified answers undefined', async () => {
|
||||
const resolved = await resolveHeadless(parseCreateArgs(['--config-json', '{"directory":"x"}']))
|
||||
expect(resolved?.args.directory).toBe('x')
|
||||
expect(resolved?.args.description).toBeUndefined()
|
||||
expect(resolved?.features).toBeUndefined()
|
||||
})
|
||||
})
|
||||
126
packages/scaffold/create-sdk/tests/link-workspace.e2e.ts
Normal file
126
packages/scaffold/create-sdk/tests/link-workspace.e2e.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { homedir, tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { promisify } from 'node:util'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
LocalPluginBlueprint,
|
||||
featureId,
|
||||
createPackageManager,
|
||||
type PackageManagerName,
|
||||
} from '@deepseek-ai/dsh-helper'
|
||||
import { scrubEnvironment } from '../../helper/src/package-managers/package-manager.ts'
|
||||
import { scaffoldProject } from '../src/project-scaffolder.ts'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
const builtScripts = join(repoRoot, 'packages/scaffold/scripts/lib/bin.js')
|
||||
const temporary: string[] = []
|
||||
|
||||
function resolveCorepackHome(): string {
|
||||
return process.env.COREPACK_HOME ?? join(
|
||||
process.env.XDG_CACHE_HOME
|
||||
?? process.env.LOCALAPPDATA
|
||||
?? join(homedir(), process.platform === 'win32' ? 'AppData/Local' : '.cache'),
|
||||
'node/corepack',
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
async function managerVersion(name: PackageManagerName): Promise<string | undefined> {
|
||||
try {
|
||||
return (await execFileAsync(name, ['--version'], { encoding: 'utf8' })).stdout.trim()
|
||||
} catch {
|
||||
// An unavailable optional manager skips only its own live-link case.
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const managers: PackageManagerName[] = ['npm', 'pnpm', 'yarn']
|
||||
|
||||
describe.skipIf(!existsSync(builtScripts))('live-linked generated projects', () => {
|
||||
for (const name of managers) {
|
||||
it(`${name}: installs the local closure and resolves plugin TypeScript in dev`, async (context) => {
|
||||
const version = await managerVersion(name)
|
||||
if (!version) {
|
||||
context.skip()
|
||||
return
|
||||
}
|
||||
const parent = await mkdtemp(join(tmpdir(), `dsh-link-${name}-`))
|
||||
const root = join(parent, 'project')
|
||||
temporary.push(parent)
|
||||
const manager = createPackageManager(name, version)
|
||||
await scaffoldProject(root, {
|
||||
name: `linked-${name}`,
|
||||
description: 'link e2e',
|
||||
runtime: { model: 'deepseek-v4-flash' },
|
||||
packageManager: manager,
|
||||
releaseVersion: '0.0.1',
|
||||
linkWorkspaceRoot: repoRoot,
|
||||
features: [
|
||||
{ id: featureId('provider'), options: ['deepseek-official'], secrets: { apiKey: 'test-key' } },
|
||||
{ id: featureId('bash'), options: ['local'] },
|
||||
{ id: featureId('app'), options: ['embed'] },
|
||||
{ id: featureId('persistence'), options: ['jsonl'] },
|
||||
],
|
||||
localPlugins: [new LocalPluginBlueprint('probe', 'plugin')],
|
||||
})
|
||||
await writeFile(join(root, 'plugins/probe/src/index.ts'), `
|
||||
import { writeFileSync } from 'node:fs'
|
||||
import type { Context } from 'cordis'
|
||||
export const name = 'probe'
|
||||
export function apply(_ctx: Context): void {
|
||||
writeFileSync(new URL('../../../plugin-loaded', import.meta.url), 'loaded\\n')
|
||||
}
|
||||
`)
|
||||
const cacheRoot = join(tmpdir(), 'dsh-sdk-link-cache', name)
|
||||
const pnpmStore = name === 'pnpm'
|
||||
? (await execFileAsync(name, ['store', 'path', '--silent'], { encoding: 'utf8' })).stdout.trim()
|
||||
: undefined
|
||||
const commandEnvironment = {
|
||||
...scrubEnvironment(),
|
||||
COREPACK_HOME: resolveCorepackHome(),
|
||||
...name === 'pnpm' ? {} : { XDG_CACHE_HOME: join(cacheRoot, 'cache') },
|
||||
XDG_DATA_HOME: join(cacheRoot, 'data'),
|
||||
npm_config_cache: join(cacheRoot, 'npm'),
|
||||
...pnpmStore === undefined ? {} : { pnpm_config_store_dir: pnpmStore },
|
||||
// A generated project has no lockfile yet; ambient CI must not make its first Yarn install immutable.
|
||||
...name === 'yarn' ? { YARN_ENABLE_IMMUTABLE_INSTALLS: 'false' } : {},
|
||||
}
|
||||
await execFileAsync(name, manager.installCommand(), {
|
||||
cwd: root,
|
||||
env: commandEnvironment,
|
||||
encoding: 'utf8',
|
||||
timeout: 120_000,
|
||||
})
|
||||
await execFileAsync(name, manager.buildCommand(), {
|
||||
cwd: root,
|
||||
env: commandEnvironment,
|
||||
encoding: 'utf8',
|
||||
timeout: 120_000,
|
||||
})
|
||||
expect(existsSync(join(root, 'index.js'))).toBe(true)
|
||||
expect(existsSync(join(root, 'plugins/probe/lib/index.js'))).toBe(true)
|
||||
const dshSdk = join(root, 'node_modules/@deepseek-ai/dsh-scripts/lib/bin.js')
|
||||
const run = await execFileAsync(process.execPath, [dshSdk, 'dev', 'index.ts'], {
|
||||
cwd: root,
|
||||
env: { ...commandEnvironment, DEEPSEEK_API_KEY: 'test-key' },
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
})
|
||||
expect(run.stderr).not.toContain('without inject')
|
||||
expect(await readFile(join(root, 'plugin-loaded'), 'utf8')).toBe('loaded\n')
|
||||
const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8')) as {
|
||||
dependencies: Record<string, string>
|
||||
}
|
||||
expect(manifest.dependencies.cordis).toMatch(name === 'npm' ? /^file:/ : name === 'pnpm' ? /^link:/ : /^portal:/)
|
||||
expect(manifest.dependencies).not.toHaveProperty('node-addon-require-builtin')
|
||||
}, 180_000)
|
||||
}
|
||||
})
|
||||
19
packages/scaffold/create-sdk/tsconfig.json
Normal file
19
packages/scaffold/create-sdk/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [
|
||||
{
|
||||
"path": "../helper"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
14
packages/scaffold/create-sdk/tsdown.config.ts
Normal file
14
packages/scaffold/create-sdk/tsdown.config.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
|
||||
/** Bundle the library and create bin, then mirror package-owned terminal templates. */
|
||||
export default defineConfig({
|
||||
entry: ['lib/types/index.js', 'lib/types/invariant.js', 'lib/types/bin.js'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
copy: [{ from: 'src/templates/assets/*', to: 'lib/assets' }],
|
||||
})
|
||||
Reference in New Issue
Block a user