From 08fc8467bc221d0c444567e9527973cccb0c723a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 25 Jun 2026 22:51:38 +0800 Subject: [PATCH] Add ask_user_question interaction tool --- docs/architecture.md | 3 +- docs/cordis-catalog/events-and-services.md | 13 +- docs/module-graph.md | 18 +- packages/README.md | 8 +- packages/core/README.md | 2 + packages/core/tool-ask-user/README.md | 18 ++ packages/core/tool-ask-user/package.json | 38 +++ packages/core/tool-ask-user/src/index.ts | 63 +++++ .../tool-ask-user/tests/tool-ask-user.spec.ts | 185 ++++++++++++++ packages/core/tool-ask-user/tsconfig.json | 36 +++ packages/core/user-interaction/README.md | 22 ++ packages/core/user-interaction/package.json | 32 +++ packages/core/user-interaction/src/index.ts | 105 ++++++++ .../tests/user-interaction.spec.ts | 75 ++++++ packages/core/user-interaction/tsconfig.json | 21 ++ packages/support/README.md | 2 +- packages/support/ui-stdio/README.md | 6 +- packages/support/ui-stdio/package.json | 3 +- packages/support/ui-stdio/src/index.ts | 146 ++++++++++- .../support/ui-stdio/tests/readline.spec.ts | 1 + .../support/ui-stdio/tests/ui-stdio.spec.ts | 231 +++++++++++++++++- packages/support/ui-stdio/tsconfig.json | 3 + packages/ui/stdio-agent/README.md | 6 +- packages/ui/stdio-agent/package.json | 4 + packages/ui/stdio-agent/src/index.ts | 4 + .../ui/stdio-agent/tests/built-bin.e2e.ts | 3 +- .../ui/stdio-agent/tests/stdio-agent.spec.ts | 2 + packages/ui/stdio-agent/tsconfig.json | 6 + pnpm-lock.yaml | 39 +++ tsconfig.build.json | 2 + tsconfig.json | 2 + 31 files changed, 1083 insertions(+), 16 deletions(-) create mode 100644 packages/core/tool-ask-user/README.md create mode 100644 packages/core/tool-ask-user/package.json create mode 100644 packages/core/tool-ask-user/src/index.ts create mode 100644 packages/core/tool-ask-user/tests/tool-ask-user.spec.ts create mode 100644 packages/core/tool-ask-user/tsconfig.json create mode 100644 packages/core/user-interaction/README.md create mode 100644 packages/core/user-interaction/package.json create mode 100644 packages/core/user-interaction/src/index.ts create mode 100644 packages/core/user-interaction/tests/user-interaction.spec.ts create mode 100644 packages/core/user-interaction/tsconfig.json diff --git a/docs/architecture.md b/docs/architecture.md index 216ed949b6..36f8aece28 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -50,6 +50,7 @@ Dependency rule: **extension** plugins depend on interface packages, never on `d | `ctx.sessionPersistence` | `SessionPersistence` (abstract) | dsh-session-persistence | durable persistence seam: create/append/load/list sessions | | `ctx.systemPrompt` | `SystemPrompt` | dsh-system-prompt | ordered sections + tool schemas → `assemble()` | | `ctx.tools` | `ToolRegistry` | dsh-tools | tool definitions; `execute()` through waterfall | +| `ctx.userInteraction` | `UserInteractionService` | dsh-user-interaction | UI-backed human question/answer seam for tools and permission flows | | `ctx.agents` | `AgentRegistry` | dsh-agent | live `Agent` handles + the create/resume factory seam (returns an `AgentHandle` = `{ agent, dispose() }` for owned per-agent teardown) | | `ctx.agentLoop` | `AgentLoop` | dsh-agent-loop | creates `ReactLoopAgent`s and drives their loops | | `ctx.bash` | `BashExecutor` (abstract) | dsh-bash | bash execution seam: foreground runs + background tasks | @@ -198,7 +199,7 @@ Every MVP feature (including the TODO-marked ones), with the mechanism that impl | Built-in tools (Read/Write/Edit/Bash/…) | `ctx.tools.register()`; schemas flow into the assembly automatically. **Bash: implemented** — `dsh-bash` (seam) + `dsh-bash-local` (subprocesses) + `dsh-tool-bash` (`bash`/`bash_output`/`bash_kill`, incl. background tasks) | | ToolSearch / progressive disclosure | wrap `agent/request`, filter `req.tools` | | Tool sandbox (landlock / sandbox-exec) | wrap `tools/execute`, or implement a sandboxing `BashExecutor` (the dsh-bash seam) | -| Permission system / AskUserQuestion | wrap `tools/execute` (veto or ask); register an ask tool | +| Permission system / AskUserQuestion | `dsh-user-interaction` provides `ctx.userInteraction`; `dsh-tool-ask-user` registers `ask_user_question`; permission plugins can also wrap `tools/execute` and ask before delegating | | Plan mode | wrap `tools/execute` (deny writes) + `agent/request` (inject mode prompt) | | Sub-agents (spawn / fork / steer) | TODO seam on `AgentLoop.create()`; fork = seed Session with parent events; `steer()` on the child handle | | MCP | one plugin per server: discover tools → `ctx.tools.register()` | diff --git a/docs/cordis-catalog/events-and-services.md b/docs/cordis-catalog/events-and-services.md index f424b8af09..7d926727a0 100644 --- a/docs/cordis-catalog/events-and-services.md +++ b/docs/cordis-catalog/events-and-services.md @@ -301,7 +301,7 @@ Source: [`packages/core/tools/src/index.ts:43`](../../packages/core/tools/src/in ## Services -The 9 `ctx.` services the harness provides. An abstract seam (e.g. `ctx.bash`) is implemented by a separate package; the interface is what consumers code against. +The 10 `ctx.` services the harness provides. An abstract seam (e.g. `ctx.bash`) is implemented by a separate package; the interface is what consumers code against. ### `ctx.agentLoop` — `AgentLoop` @@ -454,6 +454,17 @@ Types: [ToolDefinition](../core-data-structures/tools.md) · [ToolExecution](../ Source: [`packages/core/tools/src/index.ts:277`](../../packages/core/tools/src/index.ts) +### `ctx.userInteraction` — `UserInteractionService` + +`ctx.userInteraction`: one active UI provider plus an `ask()` surface. + +```ts cordis-catalog +registerProvider(provider: UserInteractionProvider): () => void +async ask(request: AskUserQuestionRequest): Promise +``` + +Source: [`packages/core/user-interaction/src/index.ts:72`](../../packages/core/user-interaction/src/index.ts) + ## Inherited tier (cordis core + loader/hmr/timer) The framework surface every plugin inherits, beyond the harness vocabulary above. This is pinned vendor source ([vendoring policy](../../vendor/README.md)); it is summarized here so the catalog is a complete picture of what `ctx` and the event bus offer, without elevating framework internals to the harness tier's prominence. diff --git a/docs/module-graph.md b/docs/module-graph.md index 93ad58725d..fb21a1184a 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -31,9 +31,7 @@ graph TD tools --> agent tools --> llm tools --> system-prompt - ui-stdio --> agent - ui-stdio --> llm - ui-stdio --> session + user-interaction --> agent acp --> agent acp --> llm acp --> session @@ -48,10 +46,16 @@ graph TD subagent --> agent subagent --> llm subagent --> tools + tool-ask-user --> agent + tool-ask-user --> tools + tool-ask-user --> user-interaction tool-bash --> agent tool-bash --> bash tool-bash --> llm tool-bash --> tools + ui-stdio --> agent + ui-stdio --> session + ui-stdio --> user-interaction agent-core --> agent agent-core --> agent-loop agent-core --> invariants @@ -81,7 +85,9 @@ graph TD stdio-agent --> agent-core stdio-agent --> session stdio-agent --> session-persistence-jsonl + stdio-agent --> tool-ask-user stdio-agent --> ui-stdio + stdio-agent --> user-interaction subagent-fork --> agent subagent-fork --> session subagent-fork --> subagent @@ -107,17 +113,19 @@ graph TD | `session-persistence-jsonl` | `session`, `session-persistence` | | `session-persistence-sqlite` | `session`, `session-persistence` | | `tools` | `agent`, `llm`, `system-prompt` | -| `ui-stdio` | `agent`, `llm`, `session` | +| `user-interaction` | `agent` | | `acp` | `agent`, `llm`, `session`, `session-persistence`, `tools` | | `agent-loop` | `agent`, `llm`, `session`, `session-persistence`, `system-prompt`, `tools` | | `subagent` | `agent`, `llm`, `tools` | +| `tool-ask-user` | `agent`, `tools`, `user-interaction` | | `tool-bash` | `agent`, `bash`, `llm`, `tools` | +| `ui-stdio` | `agent`, `session`, `user-interaction` | | `agent-core` | `agent`, `agent-loop`, `invariants`, `llm`, `session`, `system-prompt`, `tool-bash`, `tools` | | `subagent-acp` | `agent`, `llm`, `subagent` | | `subagent-inprocess` | `agent`, `llm`, `session`, `subagent` | | `subagent-mock` | `agent`, `llm`, `subagent` | | `tool-subagent` | `agent`, `llm`, `subagent`, `tools` | | `acp-agent` | `acp`, `agent-core`, `session-persistence-jsonl` | -| `stdio-agent` | `agent`, `agent-core`, `session`, `session-persistence-jsonl`, `ui-stdio` | +| `stdio-agent` | `agent`, `agent-core`, `session`, `session-persistence-jsonl`, `tool-ask-user`, `ui-stdio`, `user-interaction` | | `subagent-fork` | `agent`, `session`, `subagent`, `subagent-inprocess` | | `subagent-spawn` | `subagent`, `subagent-inprocess` | diff --git a/packages/README.md b/packages/README.md index c24e95838f..0fa915f3ef 100644 --- a/packages/README.md +++ b/packages/README.md @@ -28,7 +28,9 @@ dsh-bash ← dsh-brand (abstract executor seam; b dsh-session ← dsh-llm, dsh-brand dsh-system-prompt ← dsh-llm dsh-agent ← dsh-llm, dsh-session, dsh-brand +dsh-user-interaction ← dsh-agent dsh-tools ← dsh-llm, dsh-system-prompt, dsh-agent +dsh-tool-ask-user ← dsh-tools, dsh-user-interaction dsh-bash-local ← dsh-bash (BashExecutor impl) dsh-tool-bash ← dsh-bash, dsh-tools (bash tool schemas) dsh-llm-deepseek ← dsh-llm (DeepSeek adapter) @@ -36,7 +38,7 @@ dsh-llm-pi-ai ← dsh-llm (pi-ai-backed adapter) dsh-agent-loop ← dsh-llm, dsh-session, dsh-system-prompt, dsh-tools, dsh-agent dsh-invariants ← dsh-llm, dsh-session, dsh-agent (dev-mode contract checks) dsh-acp ← dsh-agent, dsh-llm, dsh-session, dsh-session-persistence (ACP JSON-RPC bridge) -dsh-ui-stdio ← dsh-agent, dsh-llm, dsh-session (stdio readline UI plugin) +dsh-ui-stdio ← dsh-agent, dsh-session, dsh-user-interaction (stdio readline UI plugin + user-interaction provider) dsh-llm-replay ← dsh-llm, dsh-session (record/replay adapter for keyless snapshot tests) dsh-subagent ← dsh-agent, dsh-llm, dsh-tools (abstract subagent provider-registry seam) dsh-subagent-mock ← dsh-subagent (scripted provider for tests) @@ -45,7 +47,7 @@ dsh-subagent-fork ← dsh-subagent-spawn, dsh-agent, dsh-session (in-proces dsh-subagent-acp ← dsh-subagent, dsh-agent, dsh-llm, @agentclientprotocol/sdk (out-of-process child over ACP) dsh-tool-subagent ← dsh-subagent, dsh-tools, dsh-agent (model-facing delegation tool) dsh-agent-core ← timer, dsh-llm, dsh-session, dsh-system-prompt, dsh-tools, dsh-agent, dsh-invariants, dsh-tool-bash, dsh-agent-loop (the providerless spine, as one bundle plugin) -dsh-stdio-agent ← dsh-agent-core, dsh-ui-stdio, dsh-session-persistence-jsonl, dsh-agent, dsh-session (stdio chat APP + bin) +dsh-stdio-agent ← dsh-agent-core, dsh-user-interaction, dsh-tool-ask-user, dsh-ui-stdio, dsh-session-persistence-jsonl, dsh-agent, dsh-session (stdio chat APP + bin) dsh-acp-agent ← dsh-agent-core, dsh-acp, dsh-session-persistence-jsonl (ACP server APP + bin) ``` @@ -59,6 +61,8 @@ The rule: **extension** plugins depend on interfaces, never on the concrete loop | `session/` | `core` | Event-sourced session log + in-memory store | `ctx.sessions` | | `system-prompt/` | `core` | Prompt-section + tool-schema assembly registry | `ctx.systemPrompt` | | `tools/` | `core` | Tool registry + `tools/execute` waterfall | `ctx.tools` | +| `user-interaction/` | `core` | Abstract human question/answer seam | `ctx.userInteraction` | +| `tool-ask-user/` | `core` | Model-facing `ask_user_question` tool | (registers on `ctx.tools`) | | `agent/` | `core` | Agent interface, registry, `agent/*` event vocabulary | `ctx.agents` | | `agent-loop/` | `core` | THE concrete loop plugin: `ReactLoopAgent` + the loop driver | `ctx.agentLoop` | | `agent-core/` | `core` | Bundle plugin: the providerless/executor-less/UI-less spine as code (forwards `agent-loop`'s `agents`) | (loads the spine) | diff --git a/packages/core/README.md b/packages/core/README.md index 8d8805471a..8f65eb9ab9 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -7,6 +7,8 @@ The packages every harness build is assembled from: the session log, the system- | `session/` | Event-sourced session log + in-memory store | `ctx.sessions` | | `system-prompt/` | Prompt-section + tool-schema assembly registry | `ctx.systemPrompt` | | `tools/` | Tool registry + `tools/execute` waterfall | `ctx.tools` | +| `user-interaction/` | Human question/answer seam for tools and permission flows | `ctx.userInteraction` | +| `tool-ask-user/` | Model-facing `ask_user_question` tool over `ctx.userInteraction` | (registers on `ctx.tools`) | | `agent/` | Agent interface, registry, `agent/*` event vocabulary | `ctx.agents` | | `agent-loop/` | The concrete loop plugin: `ReactLoopAgent` + the loop driver | `ctx.agentLoop` | | `agent-core/` | Bundle plugin: the providerless/executor-less/UI-less spine as code | (loads the spine) | diff --git a/packages/core/tool-ask-user/README.md b/packages/core/tool-ask-user/README.md new file mode 100644 index 0000000000..dc0b198d04 --- /dev/null +++ b/packages/core/tool-ask-user/README.md @@ -0,0 +1,18 @@ +# @deepseek-ai/dsh-tool-ask-user + +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: + +- `question` — required question text. +- `header` — optional short heading. +- `options` — optional choices with `label`, `value`, `description`, and `recommended`. +- `allow_custom` — whether free-form answers are allowed; defaults to the provider's normal `true` behavior. + +The tool calls `ctx.userInteraction.ask()` and returns the selected option value or custom answer as a text tool result. + +## 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. diff --git a/packages/core/tool-ask-user/package.json b/packages/core/tool-ask-user/package.json new file mode 100644 index 0000000000..c1860f48f0 --- /dev/null +++ b/packages/core/tool-ask-user/package.json @@ -0,0 +1,38 @@ +{ + "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" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "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.6" + } +} diff --git a/packages/core/tool-ask-user/src/index.ts b/packages/core/tool-ask-user/src/index.ts new file mode 100644 index 0000000000..e574db91f3 --- /dev/null +++ b/packages/core/tool-ask-user/src/index.ts @@ -0,0 +1,63 @@ +/** + * 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 type {} from '@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. ' + + 'Use options when possible; mark the recommended option when one is safest.' + +export function apply(ctx: Context): void { + ctx.tools.register(defineTool({ + name: 'ask_user_question', + description, + parameters: { + header: { + type: 'string', + description: 'Optional short heading for the question, such as "Confirm" or "Choose Mode".', + }, + question: { + type: 'string', + required: true, + description: 'The specific question to ask the user.', + }, + options: { + type: 'array', + description: 'Optional mutually exclusive choices to show the user.', + items: { + type: 'object', + properties: { + label: { type: 'string', required: true, description: 'Short user-facing option label.' }, + value: { type: 'string', description: 'Answer text returned to you if this option is selected. Defaults to label.' }, + description: { type: 'string', description: 'One sentence explaining the tradeoff or impact.' }, + recommended: { type: 'boolean', description: 'True for the recommended/default option.' }, + }, + }, + }, + allow_custom: { + type: 'boolean', + description: 'Whether the user may type a free-form answer instead of selecting an option. Defaults to true.', + }, + }, + async execute(args, exec) { + const result = await ctx.userInteraction.ask({ + question: args.question, + ...args.header !== undefined ? { header: args.header } : {}, + ...args.options !== undefined ? { options: args.options } : {}, + ...args.allow_custom !== undefined ? { allowCustom: args.allow_custom } : {}, + ...exec.agent !== undefined ? { agent: exec.agent } : {}, + ...exec.signal !== undefined ? { signal: exec.signal } : {}, + }) + return [{ type: 'text', text: result.answer }] + }, + })) +} diff --git a/packages/core/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/core/tool-ask-user/tests/tool-ask-user.spec.ts new file mode 100644 index 0000000000..ca929533ff --- /dev/null +++ b/packages/core/tool-ask-user/tests/tool-ask-user.spec.ts @@ -0,0 +1,185 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { CallId } from '@deepseek-ai/dsh-llm' +import 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' + +interface OptionSchemaShape { + properties: { + options: { + items: { + properties: Record + } + } + } +} + +async function setup() { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(UserInteractionService) + await ctx.plugin(toolAskUser) + return ctx +} + +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: { + question: { type: 'string' }, + options: { type: 'array' }, + allow_custom: { type: 'boolean' }, + }, + required: ['question'], + }, + }) + const parameters = schema?.parameters as unknown as OptionSchemaShape + expect(parameters.properties.options.items.properties).toMatchObject({ + description: { type: 'string' }, + recommended: { type: 'boolean' }, + }) + expect(parameters.properties.options.items.properties).not.toHaveProperty('desc') + }) + + it('asks the registered user-interaction provider and returns the answer text', async () => { + const ctx = await setup() + const seen: AskUserQuestionRequest[] = [] + ctx.userInteraction.registerProvider({ + async ask(request) { + seen.push(request) + const option = request.options?.[0] + return option === undefined ? { answer: 'Use pnpm' } : { answer: 'Use pnpm', option } + }, + }) + + const result = await ctx.tools.execute({ + callId: CallId('ask-1'), + name: 'ask_user_question', + arguments: { + question: 'Which package manager should I use?', + options: [{ label: 'pnpm', value: 'Use pnpm', recommended: true }], + allow_custom: false, + }, + }) + + expect(result).toMatchObject({ + isError: false, + content: [{ type: 'text', text: 'Use pnpm' }], + }) + expect(seen).toMatchObject([{ + question: 'Which package manager should I use?', + options: [{ label: 'pnpm', value: 'Use pnpm', recommended: true }], + allowCustom: false, + }]) + }) + + 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 { answer: 'ok' } + }, + }) + const controller = new AbortController() + + await ctx.tools.execute({ + callId: CallId('ask-2'), + name: 'ask_user_question', + arguments: { question: 'Continue?' }, + signal: controller.signal, + }) + + expect(seen[0]?.signal).toBe(controller.signal) + }) + + it('passes optional header and agent through to the user-interaction request', async () => { + const ctx = await setup() + const seen: AskUserQuestionRequest[] = [] + ctx.userInteraction.registerProvider({ + async ask(request) { + seen.push(request) + return { answer: 'ok' } + }, + }) + const agent = { id: 'main' } as unknown as Agent + + const result = await ctx.tools.execute({ + callId: CallId('ask-3'), + name: 'ask_user_question', + arguments: { header: 'Confirm', question: 'Continue?' }, + agent, + }) + + expect(result.content).toEqual([{ type: 'text', text: 'ok' }]) + expect(seen[0]).toMatchObject({ header: 'Confirm', agent }) + }) + + it('uses an option label when the selected option has no explicit value', async () => { + const ctx = await setup() + ctx.userInteraction.registerProvider({ + async ask(request) { + const option = request.options?.[0] + if (option === undefined) throw new Error('missing option') + return { answer: option.label, option } + }, + }) + + const result = await ctx.tools.execute({ + callId: CallId('ask-4'), + name: 'ask_user_question', + arguments: { + question: 'Pick one', + options: [{ label: 'Fallback label' }], + }, + }) + + expect(result.content).toEqual([{ type: 'text', text: 'Fallback label' }]) + }) + + it('returns the provider-computed answer even when option metadata is present', async () => { + const ctx = await setup() + ctx.userInteraction.registerProvider({ + async ask(request) { + const option = request.options?.[0] + if (option === undefined) throw new Error('missing option') + return { answer: `selected ${option.value}`, option } + }, + }) + + const result = await ctx.tools.execute({ + callId: CallId('ask-5'), + name: 'ask_user_question', + arguments: { + question: 'Pick one', + options: [{ label: 'A', value: 'a' }], + }, + }) + + expect(result.content).toEqual([{ type: 'text', text: 'selected a' }]) + }) + + 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() + }) +}) diff --git a/packages/core/tool-ask-user/tsconfig.json b/packages/core/tool-ask-user/tsconfig.json new file mode 100644 index 0000000000..f51b8c4495 --- /dev/null +++ b/packages/core/tool-ask-user/tsconfig.json @@ -0,0 +1,36 @@ +{ + "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": "../agent" + }, + { + "path": "../system-prompt" + }, + { + "path": "../tools" + }, + { + "path": "../user-interaction" + } + ] +} diff --git a/packages/core/user-interaction/README.md b/packages/core/user-interaction/README.md new file mode 100644 index 0000000000..0576495644 --- /dev/null +++ b/packages/core/user-interaction/README.md @@ -0,0 +1,22 @@ +# @deepseek-ai/dsh-user-interaction + +Abstract user-interaction seam. It owns `ctx.userInteraction`, the service a model-facing tool or permission plugin uses when it needs to pause work and ask the human for a decision. + +## Service: `UserInteractionService` (ctx key: `userInteraction`) + +### Public API + +- `ctx.userInteraction.registerProvider(provider): () => void` Register the UI-side provider. Only one provider may be active in a context; disposal unregisters it. +- `ctx.userInteraction.ask(request): Promise` Ask the active provider and wait for the answer. + +### Key Types + +- `AskUserQuestionRequest` — `{ question, header?, options?, allowCustom?, agent?, signal? }`. +- `AskUserQuestionOption` — `{ label, value?, description?, recommended? }`. +- `AskUserQuestionAnswer` — `{ answer, option? }`. +- `UserInteractionProvider` — UI implementation with `ask(request)`. +- `UserInteractionError` — `HarnessError` subclass with codes such as `NO_PROVIDER`, `DUPLICATE_PROVIDER`, and `ASK_ABORTED`. + +## Role + +This is the interface package. Model-facing consumers such as `@deepseek-ai/dsh-tool-ask-user` depend on this seam; UI implementations such as `@deepseek-ai/dsh-ui-stdio` provide the provider. The loop stays unchanged: a tool call simply awaits a promise, and the tool result resumes the normal agent loop. diff --git a/packages/core/user-interaction/package.json b/packages/core/user-interaction/package.json new file mode 100644 index 0000000000..2b96284aca --- /dev/null +++ b/packages/core/user-interaction/package.json @@ -0,0 +1,32 @@ +{ + "name": "@deepseek-ai/dsh-user-interaction", + "description": "Abstract user-interaction seam (ctx.userInteraction) for asking the human during agent runs", + "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" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/core/user-interaction/src/index.ts b/packages/core/user-interaction/src/index.ts new file mode 100644 index 0000000000..95c0847e27 --- /dev/null +++ b/packages/core/user-interaction/src/index.ts @@ -0,0 +1,105 @@ +/** + * User-interaction seam (`ctx.userInteraction`): a UI-backed service for + * pausing an agent tool call until the human answers a question. The model- + * facing tool lives in `@deepseek-ai/dsh-tool-ask-user`; UI packages provide + * the single active provider. + * + * @module @deepseek-ai/dsh-user-interaction + */ + +import { Context, Service } from 'cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' + +declare module 'cordis' { + interface Context { + userInteraction: UserInteractionService + } +} + +/** One selectable answer offered to the user. */ +export interface AskUserQuestionOption { + /** User-facing label. */ + label: string + /** Value returned to the model when selected. Defaults to `label`. */ + value?: string + /** Optional extra context rendered by capable UIs. */ + description?: string + /** Marks the recommended/default option. */ + recommended?: boolean +} + +/** Request for a human answer. */ +export interface AskUserQuestionRequest { + /** The question to display. */ + question: string + /** Optional short heading/group label. */ + header?: string + /** Optional choices the UI can render as a menu. */ + options?: AskUserQuestionOption[] + /** Whether free-form answers are accepted. Defaults to `true`. */ + allowCustom?: boolean + /** Calling agent, when the request came from an agent tool call. */ + agent?: Agent + /** Abort signal for the owning tool/step. */ + signal?: AbortSignal +} + +/** The human's answer. */ +export interface AskUserQuestionAnswer { + /** Model-facing answer text. */ + answer: string + /** The selected option, when the answer came from `options`. */ + option?: AskUserQuestionOption +} + +/** UI-side provider for user questions. */ +export interface UserInteractionProvider { + ask(request: AskUserQuestionRequest): Promise +} + +/** Stable error taxonomy for user-interaction failures. */ +export class UserInteractionError extends Error { + readonly code: string + + constructor(message: string, code: string, options?: ErrorOptions) { + super(message, options) + this.code = code + this.name = 'UserInteractionError' + } +} + +/** `ctx.userInteraction`: one active UI provider plus an `ask()` surface. */ +export class UserInteractionService extends Service { + private provider: UserInteractionProvider | undefined + + constructor(ctx: Context) { + super(ctx, 'userInteraction') + } + + /** Register the UI provider. Only one provider may be active in a context. */ + registerProvider(provider: UserInteractionProvider): () => void { + const dispose = this.ctx.effect(function* (this: UserInteractionService) { + if (this.provider !== undefined) { + throw new UserInteractionError('a user-interaction provider is already registered', 'DUPLICATE_PROVIDER') + } + this.provider = provider + yield () => { + this.provider = undefined + } + }.bind(this), 'userInteraction.registerProvider()') + return () => void dispose() + } + + /** Ask the active UI provider and wait for the user's answer. */ + async ask(request: AskUserQuestionRequest): Promise { + if (request.signal?.aborted) { + throw new UserInteractionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED') + } + if (this.provider === undefined) { + throw new UserInteractionError('no user-interaction provider is registered', 'NO_PROVIDER') + } + return this.provider.ask(request) + } +} + +export default UserInteractionService diff --git a/packages/core/user-interaction/tests/user-interaction.spec.ts b/packages/core/user-interaction/tests/user-interaction.spec.ts new file mode 100644 index 0000000000..8b7eefc48c --- /dev/null +++ b/packages/core/user-interaction/tests/user-interaction.spec.ts @@ -0,0 +1,75 @@ +import { describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import UserInteractionService, { + UserInteractionError, + type AskUserQuestionRequest, + type UserInteractionProvider, +} from '@deepseek-ai/dsh-user-interaction' + +function provider(answer = 'approved'): UserInteractionProvider & { seen: AskUserQuestionRequest[] } { + const seen: AskUserQuestionRequest[] = [] + return { + seen, + async ask(request) { + seen.push(request) + return { answer } + }, + } +} + +describe('UserInteractionService', () => { + it('delegates ask requests to the registered provider', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = provider('yes') + ctx.userInteraction.registerProvider(p) + + const result = await ctx.userInteraction.ask({ question: 'Proceed?' }) + + expect(result).toEqual({ answer: 'yes' }) + expect(p.seen).toEqual([{ question: 'Proceed?' }]) + }) + + it('rejects ask requests when no provider is registered', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + + await expect(ctx.userInteraction.ask({ question: 'Proceed?' })) + .rejects.toMatchObject({ name: 'UserInteractionError', code: 'NO_PROVIDER' }) + }) + + it('registers providers with HMR-safe disposal', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = provider() + const dispose = ctx.userInteraction.registerProvider(p) + + dispose() + dispose() + + await expect(ctx.userInteraction.ask({ question: 'Proceed?' })) + .rejects.toMatchObject({ code: 'NO_PROVIDER' }) + }) + + it('rejects duplicate providers instead of replacing the active UI', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + ctx.userInteraction.registerProvider(provider('first')) + + expect(() => ctx.userInteraction.registerProvider(provider('second'))) + .toThrow(UserInteractionError) + }) + + it('fails before reaching the provider when the signal is already aborted', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = { ask: vi.fn(async () => ({ answer: 'too late' })) } + ctx.userInteraction.registerProvider(p) + const controller = new AbortController() + controller.abort() + + await expect(ctx.userInteraction.ask({ question: 'Proceed?', signal: controller.signal })) + .rejects.toMatchObject({ code: 'ASK_ABORTED' }) + expect(p.ask).not.toHaveBeenCalled() + }) +}) diff --git a/packages/core/user-interaction/tsconfig.json b/packages/core/user-interaction/tsconfig.json new file mode 100644 index 0000000000..41720b3057 --- /dev/null +++ b/packages/core/user-interaction/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../agent" + } + ] +} diff --git a/packages/support/README.md b/packages/support/README.md index 52f7f6fe25..5358dce364 100644 --- a/packages/support/README.md +++ b/packages/support/README.md @@ -5,7 +5,7 @@ Packages that exist to serve development, testing, and the examples rather than | Package | Role | ctx key | |---|---|---| | `invariants/` | Dev-mode event-contract invariants + session-log freeze | (listens on `session/*`, `agent/*`) | -| `ui-stdio/` | Minimal stdio (readline) UI plugin: renders `agent/*` events, feeds stdin lines to the agent | (drives `ctx.agents`) | +| `ui-stdio/` | Minimal stdio (readline) UI plugin: renders `agent/*` events, feeds stdin lines to the agent, and provides `ctx.userInteraction` answers | (drives `ctx.agents`, registers a user-interaction provider) | | `llm-replay/` | Record/replay adapter: short-circuits `llm/stream` from a recorded session JSONL (keyless snapshot tests) | (listens on `llm/stream`) | `invariants` runs only in dev mode (contract checks, not runtime behavior). `ui-stdio` and `llm-replay` were extracted from the examples for reuse and to bring them under the per-file coverage gate; they back the demos and the snapshot test tier. A package graduates OUT of `support/` into a product group only when it gains documented product consumers. diff --git a/packages/support/ui-stdio/README.md b/packages/support/ui-stdio/README.md index b65fd4d8e1..f65452ace5 100644 --- a/packages/support/ui-stdio/README.md +++ b/packages/support/ui-stdio/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-ui-stdio -A minimal stdio (readline) UI, as a plugin. It reads lines from stdin and feeds them to an agent (`send` when idle, `steer` while a turn is running), and renders that agent's streamed output and tool activity to stdout. A UI is "just a plugin" here — it only consumes the `agent/*` event taxonomy plus the `agents` service (`inject: ['agents']`), so the same plugin drives any example or product surface. +A minimal stdio (readline) UI, as a plugin. It reads lines from stdin and feeds them to an agent (`send` when idle, `steer` while a turn is running), renders that agent's streamed output and tool activity to stdout, and provides the `ctx.userInteraction` answer provider for `ask_user_question`. A UI is "just a plugin" here — it consumes the `agent/*` event taxonomy plus the `agents` and `userInteraction` services (`inject: ['agents', 'userInteraction']`), so the same plugin drives any example or product surface with the required seam loaded. This package consolidates what were two near-identical copies under `examples/echo-agent` and `examples/coding-agent`. The coding copy was a superset; this package IS that superset — dimmed chain-of-thought rendering plus robust piped-stdin EOF handling — with the per-consumer differences moved into `Config`. @@ -26,6 +26,10 @@ Rendering is **global** — every agent's events are written to stdout, not just - `agent/turn-start` / `agent/turn-end` — a `[ turn N]` header and a trailing `> ` prompt. - `session/event` — `tool/call` renders `[tool call] name(args)`; `tool/result` renders the joined text blocks as `[tool result] …`. +## User Questions + +When `ctx.userInteraction.ask()` is called, the UI writes the question, renders numbered options when provided, and treats the next stdin line as the answer instead of sending it to the agent. Recommended options render first, option details render from `description`, a numeric line selects the displayed option, an empty line selects the recommended option when one exists, and a non-empty free-form line is accepted when `allowCustom` is not `false`. + ## The I/O seam The production entry point `apply(ctx, config)` binds the real `process` streams. The testable core is `createStdioChat(ctx, config, runtime)`, where `runtime: StdioRuntime` supplies `input` / `output` / `exit`. This seam is deliberately **not** part of the serializable `Config` (streams and functions do not belong in YAML config); it exists so the render, EOF, and disposal branches can be exercised with fakes instead of hijacking globals. diff --git a/packages/support/ui-stdio/package.json b/packages/support/ui-stdio/package.json index 5d65356e79..aa4edbc37e 100644 --- a/packages/support/ui-stdio/package.json +++ b/packages/support/ui-stdio/package.json @@ -23,8 +23,8 @@ "license": "BSD-3-Clause", "peerDependencies": { "@deepseek-ai/dsh-agent": "^0.0.1", - "@deepseek-ai/dsh-llm": "^0.0.1", "@deepseek-ai/dsh-session": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", "cordis": "^4.0.0-rc.6" }, "dependencies": { @@ -34,6 +34,7 @@ "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-user-interaction": "workspace:^", "cordis": "^4.0.0-rc.6" } } diff --git a/packages/support/ui-stdio/src/index.ts b/packages/support/ui-stdio/src/index.ts index 070e842094..26a1e37754 100644 --- a/packages/support/ui-stdio/src/index.ts +++ b/packages/support/ui-stdio/src/index.ts @@ -23,9 +23,15 @@ import type { Readable, Writable } from 'node:stream' import type { Context } from 'cordis' import z from 'schemastery' import { AgentId } from '@deepseek-ai/dsh-agent' +import { + UserInteractionError, + type AskUserQuestionAnswer, + type AskUserQuestionOption, + type AskUserQuestionRequest, +} from '@deepseek-ai/dsh-user-interaction' export const name = 'ui-stdio' -export const inject = ['agents'] +export const inject = ['agents', 'userInteraction'] /** Serializable plugin configuration (cordis-native, schemastery). */ export interface Config { @@ -60,6 +66,27 @@ function isTTYPair(input: Readable, output: Writable): boolean { return Boolean((input as { isTTY?: boolean }).isTTY && (output as { isTTY?: boolean }).isTTY) } +function optionAnswer(option: AskUserQuestionOption): string { + return option.value ?? option.label +} + +function displayOptions(options: AskUserQuestionOption[] = []): AskUserQuestionOption[] { + return options + .map((option, index) => ({ option, index })) + .sort((left, right) => { + if (left.option.recommended === right.option.recommended) return left.index - right.index + return left.option.recommended ? -1 : 1 + }) + .map(({ option }) => option) +} + +interface PendingQuestion { + request: AskUserQuestionRequest + resolve(answer: AskUserQuestionAnswer): void + reject(error: unknown): void + onAbort: () => void +} + /** * The plugin body, parameterized over its I/O runtime. `apply` is the thin * production wrapper that binds the real `process` streams; tests call this @@ -100,6 +127,12 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt output.write('\n> ') }) + ctx.on('agent/error', (agent, turn, step, error) => { + if (inReasoning) output.write('\x1B[0m') + inReasoning = false + output.write(`\n[${agent.id} turn ${turn} step ${step} error] ${error.message}\n> `) + }) + ctx.on('session/event', (_session, event) => { if (event.type === 'tool/call') { const { name: toolName, arguments: args } = event.data @@ -130,6 +163,8 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt let submittedWork = false let sawRunning = false let exitTimer: ReturnType | undefined + let activeQuestion: PendingQuestion | undefined + const questionQueue: PendingQuestion[] = [] const maybeExit = (): void => { if (disposed || !stdinClosed) return @@ -156,7 +191,113 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt if (status === 'idle') maybeExit() }) + const renderQuestion = (pending: PendingQuestion): void => { + const { request } = pending + output.write('\n') + output.write(request.header ? `[${request.header}] ${request.question}\n` : `[question] ${request.question}\n`) + displayOptions(request.options).forEach((option, index) => { + output.write(` ${index + 1}. ${option.label}${option.recommended ? ' (recommended)' : ''}\n`) + if (option.description) output.write(` ${option.description}\n`) + }) + output.write('> ') + } + + const removeAbortListener = (pending: PendingQuestion): void => { + pending.request.signal?.removeEventListener('abort', pending.onAbort) + } + + const startNextQuestion = (): void => { + if (activeQuestion !== undefined) return + const pending = questionQueue.shift() + if (pending === undefined) return + if (pending.request.signal?.aborted) { + pending.reject(new UserInteractionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED')) + startNextQuestion() + return + } + activeQuestion = pending + pending.request.signal?.addEventListener('abort', pending.onAbort, { once: true }) + renderQuestion(pending) + } + + const disposeQuestion = (pending: PendingQuestion): void => { + removeAbortListener(pending) + pending.reject(new UserInteractionError('ask_user_question was interrupted before the user answered', 'ASK_ABORTED')) + } + + const disposePendingQuestions = (): void => { + if (activeQuestion !== undefined) { + disposeQuestion(activeQuestion) + activeQuestion = undefined + } + for (const pending of questionQueue.splice(0)) { + disposeQuestion(pending) + } + } + + const finishQuestion = (pending: PendingQuestion, answer: AskUserQuestionAnswer): void => { + removeAbortListener(pending) + activeQuestion = undefined + pending.resolve(answer) + output.write('\n') + startNextQuestion() + } + + const answerQuestion = (line: string): void => { + const pending = activeQuestion as PendingQuestion + + const text = line.trim() + const options = displayOptions(pending.request.options) + const selectedIndex = /^\d+$/.test(text) ? Number(text) - 1 : -1 + const selected = selectedIndex >= 0 ? options[selectedIndex] : undefined + if (selected !== undefined) { + finishQuestion(pending, { answer: optionAnswer(selected), option: selected }) + return + } + + const recommended = options.find(option => option.recommended) + if (text === '' && recommended !== undefined) { + finishQuestion(pending, { answer: optionAnswer(recommended), option: recommended }) + return + } + + const allowCustom = pending.request.allowCustom ?? true + if (allowCustom && text !== '') { + finishQuestion(pending, { answer: text }) + return + } + + output.write(options.length > 0 + ? 'Please enter one of the option numbers' + + (allowCustom ? ' or a custom answer' : '') + + '.\n> ' + : 'Please enter an answer.\n> ') + } + + const disposeUserInteractionProvider = ctx.userInteraction.registerProvider({ + ask(request) { + return new Promise((resolve, reject) => { + const pending: PendingQuestion = { + request, + resolve, + reject, + onAbort: () => { + activeQuestion = undefined + disposeQuestion(pending) + startNextQuestion() + }, + } + questionQueue.push(pending) + startNextQuestion() + }) + }, + }) + reader.on('line', (line) => { + if (activeQuestion !== undefined) { + answerQuestion(line) + return + } const text = line.trim() if (!text) return const agent = ctx.agents.get(agentId) @@ -175,12 +316,15 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt // Fires for BOTH stdin EOF and plugin disposal (reader.close() below); // `disposed` guards teardown so HMR/dispose never exits the process. stdinClosed = true + if (!disposed) disposePendingQuestions() maybeExit() }) output.write(`${welcome}\n> `) return () => { disposed = true if (exitTimer !== undefined) clearTimeout(exitTimer) + disposePendingQuestions() + disposeUserInteractionProvider() disposeStatusListener() reader.close() } diff --git a/packages/support/ui-stdio/tests/readline.spec.ts b/packages/support/ui-stdio/tests/readline.spec.ts index c8b147ddab..2b7e115026 100644 --- a/packages/support/ui-stdio/tests/readline.spec.ts +++ b/packages/support/ui-stdio/tests/readline.spec.ts @@ -16,6 +16,7 @@ function fakeContext(): Context { return { on: vi.fn(() => vi.fn()), effect: vi.fn((callback: () => () => void) => callback()), + userInteraction: { registerProvider: vi.fn(() => vi.fn()) }, } as unknown as Context } diff --git a/packages/support/ui-stdio/tests/ui-stdio.spec.ts b/packages/support/ui-stdio/tests/ui-stdio.spec.ts index bd5e0f7f91..e40847ae51 100644 --- a/packages/support/ui-stdio/tests/ui-stdio.spec.ts +++ b/packages/support/ui-stdio/tests/ui-stdio.spec.ts @@ -5,6 +5,7 @@ import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import { createStdioChat, type Config, type StdioRuntime } from '../src/index.ts' /** @@ -66,10 +67,11 @@ const CONFIG: Config = { welcome: 'hi there', agent: 'main' } async function setup(config: Config = CONFIG, runtimeOver: Partial = {}) { const ctx = new Context() await ctx.plugin(AgentRegistry) + await ctx.plugin(UserInteractionService) const { runtime, input, out, exit } = makeRuntime(runtimeOver) const fiber = await ctx.plugin(Object.assign((inner: Context) => { createStdioChat(inner, config, runtime) - }, { inject: ['agents'] })) + }, { inject: ['agents', 'userInteraction'] })) return { ctx, fiber, input, out, exit } } @@ -171,9 +173,236 @@ describe('createStdioChat rendering', () => { } as SessionEvent) expect(out.text()).toBe(before) }) + + it('renders agent errors so failed model requests are visible in stdio', async () => { + const { ctx, out } = await setup() + const agent = makeAgent('main') + + ctx.emit('agent/error', agent, 1, 1, new Error('fetch failed')) + + expect(out.text()).toContain('\n[main turn 1 step 1 error] fetch failed\n> ') + }) + + it('resets dim styling when an agent error interrupts reasoning', async () => { + const { ctx, out } = await setup() + const agent = makeAgent('main') + + ctx.emit('agent/stream-chunk', agent, 1, 0, { type: 'reasoning-delta', index: 0, text: 'thinking' }) + ctx.emit('agent/error', agent, 1, 1, new Error('fetch failed')) + + expect(out.text()).toContain('\x1B[2mthinking\x1B[0m\n[main turn 1 step 1 error] fetch failed') + }) }) describe('createStdioChat input', () => { + it('answers a pending user question instead of sending the line to the agent', async () => { + const { ctx, input, out } = await setup() + const agent = makeAgent('main', 'idle') + ctx.agents.register(agent) + + const answer = ctx.userInteraction.ask({ + header: 'Confirm', + question: 'Proceed with the edit?', + options: [{ label: 'Yes', value: 'Proceed', description: 'Apply the edit now.', recommended: true }], + }) + await new Promise(r => setImmediate(r)) + input.feed('Use a smaller change') + + await expect(answer).resolves.toEqual({ answer: 'Use a smaller change' }) + expect(agent.sent).toEqual([]) + expect(out.text()).toContain('[Confirm] Proceed with the edit?') + expect(out.text()).toContain('1. Yes (recommended)') + expect(out.text()).toContain('Apply the edit now.') + }) + + it('answers a pending user question by numeric option selection', async () => { + const { ctx, input } = await setup() + const answer = ctx.userInteraction.ask({ + question: 'Which mode?', + options: [ + { label: 'Safe', value: 'Use safe mode', recommended: true }, + { label: 'Fast', value: 'Use fast mode' }, + ], + allowCustom: false, + }) + await new Promise(r => setImmediate(r)) + input.feed('2') + + await expect(answer).resolves.toEqual({ + answer: 'Use fast mode', + option: { label: 'Fast', value: 'Use fast mode' }, + }) + }) + + it('renders recommended options first and selects by displayed number', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + question: 'Which topic?', + options: [ + { label: 'Hobbies', value: 'hobbies' }, + { label: 'Work', value: 'work', description: 'Questions about current projects.' }, + { label: 'Casual', value: 'casual', recommended: true, description: 'Easy conversation.' }, + ], + allowCustom: false, + }) + await new Promise(r => setImmediate(r)) + + expect(out.text()).toContain([ + '[question] Which topic?', + ' 1. Casual (recommended)', + ' Easy conversation.', + ' 2. Hobbies', + ' 3. Work', + ' Questions about current projects.', + ].join('\n')) + input.feed('1') + + await expect(answer).resolves.toEqual({ + answer: 'casual', + option: { label: 'Casual', value: 'casual', recommended: true, description: 'Easy conversation.' }, + }) + }) + + it('uses the recommended option when the user submits an empty answer', async () => { + const { ctx, input } = await setup() + const answer = ctx.userInteraction.ask({ + question: 'Continue?', + options: [ + { label: 'No' }, + { label: 'Yes', value: 'Continue', recommended: true }, + ], + allowCustom: false, + }) + await new Promise(r => setImmediate(r)) + input.feed('') + + await expect(answer).resolves.toEqual({ + answer: 'Continue', + option: { label: 'Yes', value: 'Continue', recommended: true }, + }) + }) + + it('re-prompts when options are required and the input is invalid', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + question: 'Which mode?', + options: [{ label: 'Safe' }], + allowCustom: false, + }) + await new Promise(r => setImmediate(r)) + input.feed('custom') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter one of the option numbers.') + input.feed('1') + + await expect(answer).resolves.toEqual({ + answer: 'Safe', + option: { label: 'Safe' }, + }) + }) + + it('re-prompts with custom-answer guidance when options also allow free-form input', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + question: 'Which mode?', + options: [{ label: 'Safe' }], + }) + await new Promise(r => setImmediate(r)) + input.feed('') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.') + input.feed('Use custom mode') + + await expect(answer).resolves.toEqual({ answer: 'Use custom mode' }) + }) + + it('re-prompts when a free-form question receives an empty answer', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ question: 'What should I use?' }) + await new Promise(r => setImmediate(r)) + input.feed('') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter an answer.') + input.feed('Use defaults') + + await expect(answer).resolves.toEqual({ answer: 'Use defaults' }) + }) + + it('rejects an active question when its signal aborts', async () => { + const { ctx } = await setup() + const controller = new AbortController() + const answer = ctx.userInteraction.ask({ question: 'Continue?', signal: controller.signal }) + const rejected = expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + controller.abort() + + await rejected + }) + + it('continues to the next queued question when the active question aborts', async () => { + const { ctx, input, out } = await setup() + const controller = new AbortController() + const first = ctx.userInteraction.ask({ question: 'First?', signal: controller.signal }) + const firstRejected = expect(first).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + const second = ctx.userInteraction.ask({ question: 'Second?' }) + await new Promise(r => setImmediate(r)) + + controller.abort() + await firstRejected + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('[question] Second?') + input.feed('second answer') + + await expect(second).resolves.toEqual({ answer: 'second answer' }) + }) + + it('skips a queued question whose signal aborted before it became active', async () => { + const { ctx, input, out } = await setup() + const controller = new AbortController() + const first = ctx.userInteraction.ask({ question: 'First?' }) + const second = ctx.userInteraction.ask({ question: 'Second?', signal: controller.signal }) + const secondRejected = expect(second).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + controller.abort() + input.feed('first answer') + + await expect(first).resolves.toEqual({ answer: 'first answer' }) + await secondRejected + expect(out.text()).not.toContain('[question] Second?') + }) + + it('rejects active and queued questions when the UI is disposed', async () => { + const { ctx, fiber } = await setup() + const active = ctx.userInteraction.ask({ question: 'Active?' }) + const queued = ctx.userInteraction.ask({ question: 'Queued?' }) + const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + await fiber.dispose() + + await activeRejected + await queuedRejected + }) + + it('rejects active and queued questions when stdin closes before the user answers', async () => { + const { ctx, input, exit } = await setup() + const active = ctx.userInteraction.ask({ question: 'Active?' }) + const queued = ctx.userInteraction.ask({ question: 'Queued?' }) + const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + input.finish() + await new Promise(r => setImmediate(r)) + + await activeRejected + await queuedRejected + expect(exit).not.toHaveBeenCalled() + }) + it('sends a typed line to an idle agent', async () => { const { ctx, input } = await setup() const agent = makeAgent('main', 'idle') diff --git a/packages/support/ui-stdio/tsconfig.json b/packages/support/ui-stdio/tsconfig.json index b333de0302..e778da89bf 100644 --- a/packages/support/ui-stdio/tsconfig.json +++ b/packages/support/ui-stdio/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../../core/agent" }, + { + "path": "../../core/user-interaction" + }, { "path": "../../llm/llm" }, diff --git a/packages/ui/stdio-agent/README.md b/packages/ui/stdio-agent/README.md index a78df0fa72..1cde841449 100644 --- a/packages/ui/stdio-agent/README.md +++ b/packages/ui/stdio-agent/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-stdio-agent +Terminal stdio chat app. It composes the agent-core spine with JSONL persistence, the readline stdio UI, the user-interaction seam, and the `ask_user_question` tool so the demo/coding front door can pause for human confirmation. + The **terminal stdio chat app**: a Cordis app plugin that composes the providerless agent spine ([`@deepseek-ai/dsh-agent-core`](../../core/agent-core/README.md)) with the front-door cluster a terminal chat needs, and a `bin` that boots a leaf `cordis.yml`. It is the readline counterpart to [`@deepseek-ai/dsh-acp-agent`](../acp-agent/README.md): both consume the same spine, but each bakes in the OPPOSITE front-door cluster. @@ -13,7 +15,9 @@ A terminal chat always wants the same cluster, so the package owns it rather tha | `@cordisjs/plugin-logger-console` | the console logger — stdout is just the terminal here, so logging to it is correct (the ACP app must NOT have this) | | `@deepseek-ai/dsh-agent-core` | the spine, pre-creating a `main` agent from this app's `model`/`systemPrompt` | | `@deepseek-ai/dsh-session-persistence-jsonl` | durable JSONL session log under `persistenceRoot` | -| `@deepseek-ai/dsh-ui-stdio` | the readline UI, bound to the `main` agent | +| `@deepseek-ai/dsh-user-interaction` | the human question/answer seam used by confirmation tools | +| `@deepseek-ai/dsh-tool-ask-user` | the model-facing `ask_user_question` tool | +| `@deepseek-ai/dsh-ui-stdio` | the readline UI, bound to the `main` agent, and the user-interaction provider | `@cordisjs/plugin-hmr` (the dev/demo edit-reload loop) is deliberately a **leaf** entry, NOT baked in here: it is a Loader-only, subprocess-only dev plugin — its constructor throws without `node --expose-internals` + a live `loader`, and the in-process test tier cannot even import it (so a package whose `apply` statically pulled it in could never carry the per-file coverage gate). Unlike the console logger, a stray `hmr` is not a stdout-purity footgun, so leaving it at the leaf costs no safety. The `demo:echo` / `demo:coding` leaves load it and pass `--expose-internals`. diff --git a/packages/ui/stdio-agent/package.json b/packages/ui/stdio-agent/package.json index bc9c98a411..caf56210cc 100644 --- a/packages/ui/stdio-agent/package.json +++ b/packages/ui/stdio-agent/package.json @@ -37,7 +37,9 @@ "@deepseek-ai/dsh-agent-core": "^0.0.1", "@deepseek-ai/dsh-session": "^0.0.1", "@deepseek-ai/dsh-session-persistence-jsonl": "^0.0.1", + "@deepseek-ai/dsh-tool-ask-user": "^0.0.1", "@deepseek-ai/dsh-ui-stdio": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", "cordis": "^4.0.0-rc.6", "schemastery": "^3.17.0" }, @@ -49,7 +51,9 @@ "@deepseek-ai/dsh-agent-core": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-tool-ask-user": "workspace:^", "@deepseek-ai/dsh-ui-stdio": "workspace:^", + "@deepseek-ai/dsh-user-interaction": "workspace:^", "cordis": "^4.0.0-rc.6", "schemastery": "^3.17.0" } diff --git a/packages/ui/stdio-agent/src/index.ts b/packages/ui/stdio-agent/src/index.ts index c4b9ed202c..efdf55f0a1 100644 --- a/packages/ui/stdio-agent/src/index.ts +++ b/packages/ui/stdio-agent/src/index.ts @@ -41,6 +41,8 @@ import { AgentId } from '@deepseek-ai/dsh-agent' import { SessionId } from '@deepseek-ai/dsh-session' import * as agentCore from '@deepseek-ai/dsh-agent-core' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' +import * as toolAskUser from '@deepseek-ai/dsh-tool-ask-user' import * as uiStdio from '@deepseek-ai/dsh-ui-stdio' export const name = 'stdio-agent' @@ -94,5 +96,7 @@ export function apply(ctx: Context, config: Config): void { }], }) ctx.plugin(SessionPersistenceJsonl, { root: config.persistenceRoot ?? './.sessions' }) + ctx.plugin(UserInteractionService) + ctx.plugin(toolAskUser) ctx.plugin(uiStdio, { welcome: config.welcome ?? 'ready.', agent: 'main' }) } diff --git a/packages/ui/stdio-agent/tests/built-bin.e2e.ts b/packages/ui/stdio-agent/tests/built-bin.e2e.ts index 7605b35bb7..d53296929d 100644 --- a/packages/ui/stdio-agent/tests/built-bin.e2e.ts +++ b/packages/ui/stdio-agent/tests/built-bin.e2e.ts @@ -34,7 +34,8 @@ const stdioBin = join(repoRoot, 'packages/ui/stdio-agent/lib/bin.js') // to the built `lib/` (package.json `main`), exactly as an installed dep would. const dshPackages = [ 'core/agent-core', 'core/agent', 'core/session', 'core/system-prompt', - 'core/tools', 'core/agent-loop', 'llm/llm', 'bash/bash', 'bash/bash-local', + 'core/tools', 'core/user-interaction', 'core/tool-ask-user', + 'core/agent-loop', 'llm/llm', 'bash/bash', 'bash/bash-local', 'bash/tool-bash', 'support/invariants', 'support/ui-stdio', 'session-persistence/session-persistence', 'session-persistence/session-persistence-jsonl', 'ui/stdio-agent', diff --git a/packages/ui/stdio-agent/tests/stdio-agent.spec.ts b/packages/ui/stdio-agent/tests/stdio-agent.spec.ts index f72de0a1da..c21b1c8812 100644 --- a/packages/ui/stdio-agent/tests/stdio-agent.spec.ts +++ b/packages/ui/stdio-agent/tests/stdio-agent.spec.ts @@ -33,6 +33,8 @@ describe('dsh-stdio-agent app', () => { expect(ctx.get('agents')).toBeDefined() expect(ctx.get('agentLoop')).toBeDefined() expect(ctx.get('sessionPersistence')).toBeDefined() + expect(ctx.get('userInteraction')).toBeDefined() + expect(ctx.get('tools')?.get('ask_user_question')).toBeDefined() // The pre-created `main` agent the UI drives. expect(ctx.get('agents')?.get(AgentId('main'))).toBeDefined() await ctx.fiber.dispose() diff --git a/packages/ui/stdio-agent/tsconfig.json b/packages/ui/stdio-agent/tsconfig.json index 58b492a549..6cb6130fb7 100644 --- a/packages/ui/stdio-agent/tsconfig.json +++ b/packages/ui/stdio-agent/tsconfig.json @@ -29,6 +29,12 @@ { "path": "../../core/agent-core" }, + { + "path": "../../core/user-interaction" + }, + { + "path": "../../core/tool-ask-user" + }, { "path": "../../session-persistence/session-persistence-jsonl" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 55e565cad2..c6554ad952 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -221,6 +221,27 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/core/tool-ask-user: + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../agent + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../tools + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../user-interaction + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/core/tools: devDependencies: '@deepseek-ai/dsh-agent': @@ -236,6 +257,15 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/core/user-interaction: + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../agent + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/llm/llm: devDependencies: '@deepseek-ai/dsh-brand': @@ -578,6 +608,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../../core/user-interaction cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) @@ -675,9 +708,15 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session-persistence/session-persistence-jsonl + '@deepseek-ai/dsh-tool-ask-user': + specifier: workspace:^ + version: link:../../core/tool-ask-user '@deepseek-ai/dsh-ui-stdio': specifier: workspace:^ version: link:../../support/ui-stdio + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../../core/user-interaction cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@vendor+include)(@cordisjs/plugin-loader@vendor+loader) diff --git a/tsconfig.build.json b/tsconfig.build.json index 4c71d2f14e..bd6073825d 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -18,7 +18,9 @@ { "path": "./packages/session-persistence/session-persistence-sqlite" }, { "path": "./packages/core/system-prompt" }, { "path": "./packages/core/agent" }, + { "path": "./packages/core/user-interaction" }, { "path": "./packages/core/tools" }, + { "path": "./packages/core/tool-ask-user" }, { "path": "./packages/core/agent-loop" }, { "path": "./packages/core/agent-core" }, { "path": "./packages/bash/bash" }, diff --git a/tsconfig.json b/tsconfig.json index dcc23b2fbe..59c69f9684 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -29,7 +29,9 @@ { "path": "./packages/session-persistence/session-persistence-sqlite" }, { "path": "./packages/core/system-prompt" }, { "path": "./packages/core/agent" }, + { "path": "./packages/core/user-interaction" }, { "path": "./packages/core/tools" }, + { "path": "./packages/core/tool-ask-user" }, { "path": "./packages/core/agent-loop" }, { "path": "./packages/core/agent-core" }, { "path": "./packages/bash/bash" },