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:
Tianyi Cui
2026-07-30 03:13:49 +08:00
parent 7e445c3a67
commit 3fc35c91ff
351 changed files with 368 additions and 311 deletions

View 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/interaction/tool-ask-user/README.md
README.md: 7af356263ea6582a081e7c6de22fd317ca8b96df
README.zh.md: 3f7b814b83c8c6957a4b2574ee69e87d45f65ae6

View File

@@ -0,0 +1,58 @@
# @deepseek-ai/dsh-tool-ask-user
English | [中文](README.zh.md)
Model-facing `ask_user_question` tool over `ctx.userInteraction`. It lets the model ask the human a concise question when it needs confirmation, a choice, or missing information before continuing.
## Tool
`ask_user_question` accepts:
- `questions` — required non-empty array of question objects.
- `id` — required stable id on each question, echoed in the answer.
- `question` — required question text for each question.
- `header` — optional short heading.
- `options` — optional choices with `label` and `description`. If recommending a choice, put it first and append `(Recommended)` to that label.
- `multi_select` — whether that question may return more than one selected option.
The tool calls `ctx.userInteraction.ask()` and returns canonical `{ answers: [{ id, selected, custom? }] }`. `selected` contains option labels; `custom` carries a free-form answer, supplementing `selected` for a multi-select question and overriding it for a single-select question. The Native renderer preserves the compact JSON text shape `{ "answers": [{ "id": "...", "selected": ["..."], "custom": "..." }] }`.
## Role
This is the consumer package for the user-interaction seam. It does not render UI and does not know how input is collected; it only translates model arguments into `AskUserQuestionRequest` and returns the human answer to the agent loop.
## Model Experience
### Tool schema
#### What the model sees
The model sees the generated [`ask_user_question` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-ask-user), including question ids, prompts, headings, options, and multi-select flags.
#### Token effect
Fixed schema cost on every request where the tool is visible.
#### KV Cache effect
Prefix-stable while the definition and visibility are unchanged. Plugin lifecycle or scoped restrictions may invalidate reuse from this schema.
### Tool-call history and result
#### What the model sees
The model's full questions remain in the assistant tool-call arguments. After the human answers, the next step sees compact JSON in the exact shape `{"answers":[{"id":"<id>","selected":["<label>"],"custom":"<text>"}]}`; `custom` is omitted when unused and `selected` can contain zero, one, or several labels. UI interaction while the call is pending is not model context.
#### Token effect
Arguments and answer JSON are data-dependent retained tokens; there is no token cost while waiting for the human.
#### KV Cache effect
Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
## Known Limitations and Deferred Work
- **A pending question blocks the tool call until the human answers** — the tool declares no `timeout-policy` budget; cancellation rides the turn's `exec.signal` only.
- **Runtime-owned subagents cannot ask the user** — `ask_user_question` rejects a live child owned by another agent with `DELEGATED_CALLER`; the child must include the unresolved question or decision in its final result. Durable lineage does not decide this boundary, so a lineage-bearing session resumed as a runtime root may ask normally.
- **Native answers render as JSON text** — the canonical value remains structured, but the model-facing result uses compact JSON rather than a richer content-block vocabulary.

View File

@@ -0,0 +1,58 @@
# @deepseek-ai/dsh-tool-ask-user
[English](README.md) | 中文
模型侧 `ask_user_question` 工具,基于 `ctx.userInteraction` 实现。当模型需要确认、选择结果或缺失的信息才能继续时,它可以借此向用户提出简明问题。
## 工具
`ask_user_question` 接受以下参数:
- `questions`:必填的非空问题对象数组。
- `id`:每个问题必填的稳定 id会原样包含在回答中。
- `question`:每个问题必填的问题文本。
- `header`:可选的简短标题。
- `options`:可选选项,包含 `label``description`。如需推荐某个选项,请将其置于首位,并在该标签末尾追加 `(Recommended)`
- `multi_select`:该问题是否可以返回多个选中的选项。
工具调用 `ctx.userInteraction.ask()`,并返回规范的 `{ answers: [{ id, selected, custom? }] }``selected` 包含选项标签;`custom` 携带自由填写的回答,对于多选题会补充 `selected`对于单选题则会覆盖它。Native 渲染器会保留紧凑的 JSON 文本形式 `{ "answers": [{ "id": "...", "selected": ["..."], "custom": "..." }] }`
## 职责
此包是用户交互 seam 的消费方。它不渲染 UI也不了解输入的收集方式它只将模型参数转换为 `AskUserQuestionRequest`,并把用户回答返回给 agent loop智能体循环
## 模型体验
### 工具 schema
#### 模型看到的内容
模型会看到生成的 [`ask_user_question` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-ask-user),其中包含问题 id、提示语、标题、选项和多选标志。
#### Token 影响
工具可见时,每个请求都会产生固定的 schema token 开销。
#### KV Cache 影响
只要定义和可见性保持不变,前缀即可稳定复用。插件生命周期变化或作用域限制可能会使从此 schema 起的缓存复用失效。
### 工具调用历史与结果
#### 模型看到的内容
模型提出的完整问题保留在 assistant 工具调用参数中。用户回答后,下一步会看到精确采用 `{"answers":[{"id":"<id>","selected":["<label>"],"custom":"<text>"}]}` 形式的紧凑 JSON不使用 `custom` 时会省略该字段,`selected` 可以包含零个、一个或多个标签。调用等待期间的 UI 交互不属于模型上下文。
#### Token 影响
参数和回答 JSON 是依数据而定的保留 token等待用户时不会产生 token 开销。
#### KV Cache 影响
仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。
## 已知限制与暂缓事项
- **待处理问题会阻塞工具调用,直至用户作答**:该工具未声明 `timeout-policy` 预算;取消仅沿用当前轮次的 `exec.signal`
- **运行时中归属于其他 agent 的 subagent 不能向用户提问**`ask_user_question` 会以 `DELEGATED_CALLER` 拒绝由另一个 agent 所有的存活子级;该子级必须在最终结果中包含尚未解决的问题或决策。持久化会话谱系不能决定这一边界,因此带有谱系的会话恢复为运行时根后可以正常提问。
- **Native 回答渲染为 JSON 文本**:规范值仍为结构化数据,但模型侧结果使用紧凑 JSON而非更丰富的内容块词汇。

View File

@@ -0,0 +1,43 @@
{
"name": "@deepseek-ai/dsh-tool-ask-user",
"description": "Model-facing ask_user_question tool over the ctx.userInteraction seam",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-agent": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-tools": "^0.0.1",
"@deepseek-ai/dsh-user-interaction": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"@deepseek-ai/dsh-user-interaction": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,101 @@
/**
* Model-facing `ask_user_question` tool over the `ctx.userInteraction` seam.
* The tool pauses until a UI provider returns a human answer, then feeds that
* answer back into the agent loop as an ordinary tool result.
*
* @module @deepseek-ai/dsh-tool-ask-user
*/
import type { Context } from 'cordis'
import { defineTool } from '@deepseek-ai/dsh-tools'
import '@deepseek-ai/dsh-user-interaction'
export const name = 'tool-ask-user'
export const inject = ['tools', 'userInteraction']
const description = 'Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. '
+ 'Send one or more questions, each with a stable id that will be echoed in the answer.'
export function apply(ctx: Context): void {
ctx.tools.register(defineTool({
name: 'ask_user_question',
description,
parameters: {
questions: {
type: 'array',
required: true,
description: 'Questions to ask the user before continuing.',
items: {
type: 'object',
additionalProperties: true,
properties: {
id: { type: 'string', required: true, description: 'Stable id for this question; echoed in the answer.' },
question: { type: 'string', required: true, description: 'The specific question to ask the user.' },
header: {
type: 'string',
description: 'Optional short heading for the question, such as "Confirm" or "Choose Mode".',
},
options: {
type: 'array',
description: 'Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label.',
items: {
type: 'object',
additionalProperties: true,
properties: {
label: { type: 'string', required: true, description: 'Short user-facing option label.' },
description: { type: 'string', description: 'One sentence explaining the tradeoff or impact.' },
},
},
},
multi_select: {
type: 'boolean',
description: 'Whether the user may select more than one option. Defaults to false.',
},
},
},
},
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
answers: {
type: 'array',
required: true,
items: {
type: 'object',
additionalProperties: false,
properties: {
id: { type: 'string', required: true },
selected: { type: 'array', required: true, items: { type: 'string' } },
custom: { type: 'string' },
},
},
},
},
},
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
},
async execute(args, exec) {
const result = await ctx.userInteraction.ask({
questions: args.questions.map(question => ({
id: question.id,
question: question.question,
...question.header !== undefined ? { header: question.header } : {},
...question.options !== undefined ? { options: question.options } : {},
...question.multi_select !== undefined ? { multiSelect: question.multi_select } : {},
})),
...exec.agent !== undefined ? { agent: exec.agent } : {},
signal: exec.signal,
})
return {
answers: result.answers.map(answer => ({
id: answer.id,
selected: [...answer.selected],
...answer.custom !== undefined ? { custom: answer.custom } : {},
})),
}
},
}))
}

View File

@@ -0,0 +1,30 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-ask-user`.
* @module @deepseek-ai/dsh-tool-ask-user/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-tool-ask-user'
/** Cordis companion plugin name. */
export const name = 'tool-ask-user-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
* relations are owned by the capability seam it calls.
*/
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 */

View File

@@ -0,0 +1,320 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { CallId } from '@deepseek-ai/dsh-llm'
import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import UserInteractionService, { type AskUserQuestionRequest } from '@deepseek-ai/dsh-user-interaction'
import * as toolAskUser from '@deepseek-ai/dsh-tool-ask-user'
const testToolSignal = new AbortController().signal
interface OptionSchemaShape {
properties: {
questions: {
items: {
properties: {
options: {
items: {
properties: Record<string, { type: string }>
}
}
} & Record<string, unknown>
}
}
}
}
async function setup() {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(UserInteractionService)
await ctx.plugin(toolAskUser)
return ctx
}
function stubAgent(id: string, delegationDepth = 0): Agent {
const agentId = id as Agent['id']
return {
id: agentId,
session: { id: agentId, header: { delegationDepth } },
} as unknown as Agent
}
describe('ask_user_question tool', () => {
it('registers a model-facing tool schema', async () => {
const ctx = await setup()
const schema = ctx.tools.schemas().find(tool => tool.name === 'ask_user_question')
expect(schema).toMatchObject({
name: 'ask_user_question',
parameters: {
type: 'object',
properties: {
questions: { type: 'array' },
},
required: ['questions'],
},
})
const parameters = schema?.parameters as unknown as OptionSchemaShape
expect(parameters.properties.questions.items.properties).toMatchObject({
id: { type: 'string' },
question: { type: 'string' },
header: { type: 'string' },
options: { type: 'array' },
multi_select: { type: 'boolean' },
})
expect(parameters.properties.questions.items.properties.options.items.properties).toMatchObject({
label: { type: 'string' },
description: { type: 'string' },
})
expect(parameters.properties.questions.items.properties.options.items.properties).not.toHaveProperty('value')
expect(parameters.properties.questions.items.properties.options.items.properties).not.toHaveProperty('recommended')
expect(parameters.properties.questions.items.properties.options.items.properties).not.toHaveProperty('preview')
})
it('asks the registered user-interaction provider and projects structured answers to text', async () => {
const ctx = await setup()
const seen: AskUserQuestionRequest[] = []
ctx.userInteraction.registerProvider({
async ask(request) {
seen.push(request)
return { answers: [{ id: 'pkg', selected: ['pnpm'] }] }
},
})
const result = await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-1'),
name: 'ask_user_question',
arguments: {
questions: [{
id: 'pkg',
question: 'Which package manager should I use?',
options: [{ label: 'pnpm', description: 'Use pnpm workspaces.' }],
}],
},
})
expect(result).toMatchObject({
isError: false,
content: [{ type: 'text', text: '{"answers":[{"id":"pkg","selected":["pnpm"]}]}' }],
})
expect(seen).toMatchObject([{
questions: [{
id: 'pkg',
question: 'Which package manager should I use?',
options: [{ label: 'pnpm', description: 'Use pnpm workspaces.' }],
}],
}])
})
it('passes recommended option labels through without adding schema fields', async () => {
const ctx = await setup()
const seen: AskUserQuestionRequest[] = []
ctx.userInteraction.registerProvider({
async ask(request) {
seen.push(request)
return { answers: [{ id: 'pkg', selected: ['pnpm (Recommended)'] }] }
},
})
await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-recommended'),
name: 'ask_user_question',
arguments: {
questions: [{
id: 'pkg',
question: 'Which package manager should I use?',
options: [
{ label: 'pnpm (Recommended)' },
{ label: 'npm' },
],
}],
},
})
expect(seen[0]?.questions[0]?.options).toEqual([
{ label: 'pnpm (Recommended)' },
{ label: 'npm' },
])
})
it('projects custom answers and multi-select choices', async () => {
const ctx = await setup()
ctx.userInteraction.registerProvider({
async ask() {
return {
answers: [
{ id: 'targets', selected: ['tests', 'docs'], custom: 'release notes' },
{ id: 'labels-only', selected: ['tests'] },
{ id: 'notes', selected: [], custom: 'ship today' },
],
}
},
})
const result = await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-multi'),
name: 'ask_user_question',
arguments: {
questions: [
{
id: 'targets',
question: 'What should I update?',
options: [{ label: 'tests' }, { label: 'docs' }],
multi_select: true,
},
{
id: 'labels-only',
question: 'Which labels should I keep?',
options: [{ label: 'tests' }, { label: 'docs' }],
multi_select: true,
},
{ id: 'notes', question: 'Any note?' },
],
},
})
expect(result.isError).toBe(false)
if (result.isError) throw new Error('expected ask_user_question success')
expect(result.value).toEqual({
answers: [
{ id: 'targets', selected: ['tests', 'docs'], custom: 'release notes' },
{ id: 'labels-only', selected: ['tests'] },
{ id: 'notes', selected: [], custom: 'ship today' },
],
})
expect(result.content).toEqual([{
type: 'text',
text: '{"answers":[{"id":"targets","selected":["tests","docs"],"custom":"release notes"},{"id":"labels-only","selected":["tests"]},{"id":"notes","selected":[],"custom":"ship today"}]}',
}])
})
it('passes the tool abort signal to the user-interaction request', async () => {
const ctx = await setup()
const seen: AskUserQuestionRequest[] = []
ctx.userInteraction.registerProvider({
async ask(request) {
seen.push(request)
return { answers: [{ id: 'continue', selected: ['ok'] }] }
},
})
const controller = new AbortController()
await ctx.tools.execute({
callId: CallId('ask-2'),
name: 'ask_user_question',
arguments: { questions: [{ id: 'continue', question: 'Continue?' }] },
signal: controller.signal,
})
expect(seen[0]?.signal).toBe(controller.signal)
})
it('passes optional header and a resumed runtime root through to the user-interaction request', async () => {
const ctx = await setup()
const seen: AskUserQuestionRequest[] = []
ctx.userInteraction.registerProvider({
async ask(request) {
seen.push(request)
return { answers: [{ id: 'continue', selected: ['ok'] }] }
},
})
const agent = stubAgent('resumed-root', 1)
ctx.agents.enter(agent, undefined)
const result = await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-3'),
name: 'ask_user_question',
arguments: { questions: [{ id: 'continue', header: 'Confirm', question: 'Continue?' }] },
agent,
})
expect(result.content).toEqual([{ type: 'text', text: '{"answers":[{"id":"continue","selected":["ok"]}]}' }])
expect(seen[0]).toMatchObject({ questions: [{ id: 'continue', header: 'Confirm', question: 'Continue?' }], agent })
})
it('returns structured user-interaction errors through tool execution', async () => {
const ctx = await setup()
const result = await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-no-provider'),
name: 'ask_user_question',
arguments: { questions: [{ id: 'continue', question: 'Continue?' }] },
})
expect(result).toMatchObject({
isError: true,
error: { info: { name: 'UserInteractionError', code: 'NO_PROVIDER' } },
})
})
it('rejects a live runtime-owned agent with a structured DELEGATED_CALLER error', async () => {
const ctx = await setup()
const seen: AskUserQuestionRequest[] = []
ctx.userInteraction.registerProvider({
async ask(request) {
seen.push(request)
return { answers: [{ id: 'continue', selected: ['ok'] }] }
},
})
const root = stubAgent('root', 0)
const child = stubAgent('child', 0)
ctx.agents.enter(root, undefined)
ctx.agents.enter(child, root)
const result = await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-delegated'),
name: 'ask_user_question',
arguments: { questions: [{ id: 'continue', question: 'Continue?' }] },
agent: child,
})
expect(result).toMatchObject({
isError: true,
error: { info: { name: 'UserInteractionError', code: 'DELEGATED_CALLER' } },
content: [{
type: 'text',
text: "Error: human interaction is unavailable while the calling agent is owned by another live agent; include the unresolved question or decision in the child agent's final result",
}],
})
expect(seen).toHaveLength(0)
})
it('returns a structured error for empty question batches', async () => {
const ctx = await setup()
const result = await ctx.tools.execute({
signal: testToolSignal,
callId: CallId('ask-empty'),
name: 'ask_user_question',
arguments: { questions: [] },
})
expect(result).toMatchObject({
isError: true,
error: { info: { name: 'UserInteractionError', code: 'EMPTY_QUESTIONS' } },
})
})
it('unregisters the tool when its plugin fiber is disposed', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(UserInteractionService)
const fiber = await ctx.plugin(toolAskUser)
expect(ctx.tools.get('ask_user_question')).toBeDefined()
await fiber.dispose()
expect(ctx.tools.get('ask_user_question')).toBeUndefined()
})
})

View File

@@ -0,0 +1,39 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cosmokit"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../llm/llm"
},
{
"path": "../../core/agent"
},
{
"path": "../../core/system-prompt"
},
{
"path": "../../core/tools"
},
{
"path": "../user-interaction"
},
{
"path": "../../support/invariants"
}
]
}