Merge remote-tracking branch 'origin/master' into codex/rfc-subagent-background-tasks
Adopts #185 (dsh-timeout: clampTimeout/deadline/timeoutOf drive bash run() timeout classification; runBash loses its own timer) and #108 (ask_user_question) across the task-runtime rework: bash-local keeps the BashProcess handle shape with master's deadline mechanics, tool catalogs/expectations carry both the task_* and ask-user tools, and generated docs are regenerated on the union.
This commit is contained in:
@@ -13,6 +13,8 @@ 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` and carrying its `persona` |
|
||||
| `@deepseek-ai/dsh-session-persistence-jsonl` | durable JSONL session log under `persistenceRoot` |
|
||||
| `@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 |
|
||||
| `stdio-chat` (in-package module) | the readline UI, bound to the `main` agent |
|
||||
|
||||
`@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:repl` leaves load it and pass `--expose-internals`.
|
||||
|
||||
@@ -39,6 +39,8 @@
|
||||
"@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-user-interaction": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.6",
|
||||
"schemastery": "^3.17.0"
|
||||
},
|
||||
@@ -53,6 +55,8 @@
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
|
||||
"@deepseek-ai/dsh-tool-ask-user": "workspace:^",
|
||||
"@deepseek-ai/dsh-user-interaction": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.6",
|
||||
"schemastery": "^3.17.0"
|
||||
}
|
||||
|
||||
@@ -45,6 +45,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 './stdio-chat.ts'
|
||||
|
||||
export const name = 'stdio-agent'
|
||||
@@ -107,5 +109,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' })
|
||||
}
|
||||
|
||||
@@ -20,9 +20,17 @@ 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 AskUserQuestionAnswerItem,
|
||||
type AskUserQuestionItem,
|
||||
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 {
|
||||
@@ -57,6 +65,20 @@ function isTTYPair(input: Readable, output: Writable): boolean {
|
||||
return Boolean((input as { isTTY?: boolean }).isTTY && (output as { isTTY?: boolean }).isTTY)
|
||||
}
|
||||
|
||||
interface PendingQuestion {
|
||||
request: AskUserQuestionRequest
|
||||
questionIndex: number
|
||||
answers: AskUserQuestionAnswerItem[]
|
||||
resolve(answer: AskUserQuestionAnswer): void
|
||||
reject(error: unknown): void
|
||||
onAbort: () => void
|
||||
}
|
||||
|
||||
type OptionSelection =
|
||||
| { kind: 'selected'; options: AskUserQuestionOption[] }
|
||||
| { kind: 'custom' }
|
||||
| { kind: 'invalid' }
|
||||
|
||||
/**
|
||||
* The plugin body, parameterized over its I/O runtime. `apply` is the thin
|
||||
* production wrapper that binds the real `process` streams; tests call this
|
||||
@@ -154,6 +176,8 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt
|
||||
let submittedWork = false
|
||||
let sawRunning = false
|
||||
let exitTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let activeQuestion: PendingQuestion | undefined
|
||||
const questionQueue: PendingQuestion[] = []
|
||||
|
||||
const maybeExit = (): void => {
|
||||
if (disposed || !stdinClosed) return
|
||||
@@ -180,7 +204,152 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt
|
||||
if (status === 'idle') maybeExit()
|
||||
})
|
||||
|
||||
const activeQuestionItem = (pending: PendingQuestion): AskUserQuestionItem =>
|
||||
pending.request.questions[pending.questionIndex] as AskUserQuestionItem
|
||||
|
||||
const renderQuestion = (pending: PendingQuestion): void => {
|
||||
const question = activeQuestionItem(pending)
|
||||
const options = question.options ?? []
|
||||
output.write('\n')
|
||||
output.write(question.header ? `[${question.header}] ${question.question}\n` : `${question.question}\n`)
|
||||
options.forEach((option, index) => {
|
||||
output.write(` ${index + 1}. ${option.label}\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
|
||||
// The queue never contains an aborted pending ask: the seam rejects an
|
||||
// already-aborted request synchronously, and queued asks attach their
|
||||
// abort listener before enqueueing.
|
||||
activeQuestion = pending
|
||||
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): void => {
|
||||
activeQuestion = undefined
|
||||
removeAbortListener(pending)
|
||||
pending.resolve({ answers: pending.answers })
|
||||
output.write('\n')
|
||||
startNextQuestion()
|
||||
}
|
||||
|
||||
const answerCurrentQuestion = (pending: PendingQuestion, answer: AskUserQuestionAnswerItem): void => {
|
||||
pending.answers.push(answer)
|
||||
pending.questionIndex += 1
|
||||
if (pending.questionIndex >= pending.request.questions.length) {
|
||||
finishQuestion(pending)
|
||||
return
|
||||
}
|
||||
renderQuestion(pending)
|
||||
}
|
||||
|
||||
const selectedOptions = (text: string, options: AskUserQuestionOption[], multiSelect: boolean): OptionSelection => {
|
||||
if (text === '') return { kind: 'invalid' }
|
||||
if (!multiSelect) {
|
||||
if (!/^\d+$/.test(text)) return { kind: 'custom' }
|
||||
const selected = options[Number(text) - 1]
|
||||
return selected === undefined ? { kind: 'invalid' } : { kind: 'selected', options: [selected] }
|
||||
}
|
||||
const indices = text.split(/[,\s]+/).filter(Boolean)
|
||||
if (indices.length === 0) return { kind: 'invalid' }
|
||||
if (indices.some(part => !/^\d+$/.test(part))) return { kind: 'custom' }
|
||||
const uniqueIndices = [...new Set(indices)]
|
||||
const selected = uniqueIndices.map(part => options[Number(part) - 1])
|
||||
return selected.some(option => option === undefined)
|
||||
? { kind: 'invalid' }
|
||||
: { kind: 'selected', options: selected as AskUserQuestionOption[] }
|
||||
}
|
||||
|
||||
const answerQuestion = (line: string): void => {
|
||||
const pending = activeQuestion as PendingQuestion
|
||||
const question = activeQuestionItem(pending)
|
||||
|
||||
const text = line.trim()
|
||||
const options = question.options ?? []
|
||||
const selection = options.length > 0
|
||||
? selectedOptions(text, options, question.multiSelect ?? false)
|
||||
: { kind: text === '' ? 'invalid' : 'custom' } as OptionSelection
|
||||
if (selection.kind === 'selected') {
|
||||
answerCurrentQuestion(pending, { id: question.id, selected: selection.options.map(option => option.label) })
|
||||
return
|
||||
}
|
||||
|
||||
if (selection.kind === 'custom' && text !== '') {
|
||||
answerCurrentQuestion(pending, { id: question.id, selected: [], custom: text })
|
||||
return
|
||||
}
|
||||
|
||||
output.write(options.length > 0
|
||||
? 'Please enter one of the option numbers'
|
||||
+ (question.multiSelect ? ' (comma or space separated)' : '')
|
||||
+ ' or a custom answer'
|
||||
+ '.\n> '
|
||||
: 'Please enter an answer.\n> ')
|
||||
}
|
||||
|
||||
const disposeUserInteractionProvider = ctx.userInteraction.registerProvider({
|
||||
ask(request) {
|
||||
if (disposed || stdinClosed) {
|
||||
return Promise.reject(
|
||||
new UserInteractionError('ask_user_question cannot be answered because stdin is closed', 'ASK_ABORTED'),
|
||||
)
|
||||
}
|
||||
return new Promise<AskUserQuestionAnswer>((resolve, reject) => {
|
||||
const pending: PendingQuestion = {
|
||||
request,
|
||||
questionIndex: 0,
|
||||
answers: [],
|
||||
resolve,
|
||||
reject,
|
||||
onAbort: () => {
|
||||
if (activeQuestion === pending) {
|
||||
activeQuestion = undefined
|
||||
disposeQuestion(pending)
|
||||
startNextQuestion()
|
||||
return
|
||||
}
|
||||
// If it is not active, this listener can only fire while the ask
|
||||
// remains queued; settled asks remove the listener first.
|
||||
questionQueue.splice(questionQueue.indexOf(pending), 1)
|
||||
disposeQuestion(pending)
|
||||
},
|
||||
}
|
||||
request.signal?.addEventListener('abort', pending.onAbort, { once: true })
|
||||
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)
|
||||
@@ -199,12 +368,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()
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ function fakeContext(): Context {
|
||||
// The UI seeds its label map from the registry at install; this suite only
|
||||
// exercises readline terminal-mode selection, so an empty roster suffices.
|
||||
agents: { list: vi.fn(() => []) },
|
||||
userInteraction: { registerProvider: vi.fn(() => vi.fn()) },
|
||||
} as unknown as Context
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,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()
|
||||
@@ -92,9 +94,10 @@ describe('dsh-stdio-agent app', () => {
|
||||
})
|
||||
}
|
||||
const assembly = await ctx.get('systemPrompt')!.assemble()
|
||||
// The rest-slot is lexicographic: the bundle's own task control tools
|
||||
// (tool-tasks needs no executor, unlike the pending bash tool) follow alpha.
|
||||
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'task_kill', 'task_list', 'task_output'])
|
||||
// The rest-slot is lexicographic: the app's ask_user_question and the
|
||||
// bundle's own task control tools (neither needs an executor, unlike the
|
||||
// pending bash tool) follow alpha.
|
||||
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'ask_user_question', 'task_kill', 'task_list', 'task_output'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Readable } from 'node:stream'
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { ContentBlock, StreamChunk } 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/stdio-chat.ts'
|
||||
|
||||
/**
|
||||
@@ -79,10 +80,11 @@ const CONFIG: Config = { welcome: 'hi there', agent: 'main' }
|
||||
async function setup(config: Config = CONFIG, runtimeOver: Partial<StdioRuntime> = {}) {
|
||||
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 }
|
||||
}
|
||||
|
||||
@@ -105,6 +107,30 @@ describe('createStdioChat rendering', () => {
|
||||
// And it drives the default agent id 'main'.
|
||||
})
|
||||
|
||||
it('detects readline terminal mode from both stream TTY flags', async () => {
|
||||
for (const [inputTTY, outputTTY] of [[true, false], [true, true]] as const) {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(UserInteractionService)
|
||||
let text = ''
|
||||
const output = new Writable({
|
||||
write(chunk, _encoding, callback) {
|
||||
text += String(chunk)
|
||||
callback()
|
||||
},
|
||||
}) as Writable & { isTTY?: boolean }
|
||||
const { runtime } = makeRuntime({ output })
|
||||
;(runtime.input as Readable & { isTTY?: boolean }).isTTY = inputTTY
|
||||
output.isTTY = outputTTY
|
||||
const fiber = await ctx.plugin(Object.assign((inner: Context) => {
|
||||
createStdioChat(inner, CONFIG, runtime)
|
||||
}, { inject: ['agents', 'userInteraction'] }))
|
||||
|
||||
expect(text).toContain('hi there')
|
||||
await fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('renders text-delta chunks verbatim', async () => {
|
||||
const { ctx, out } = await setup()
|
||||
ctx.emit('session/event', makeSession('main'), chunkEvent({ type: 'text-delta', index: 0, text: 'hello' }))
|
||||
@@ -160,12 +186,13 @@ describe('createStdioChat rendering', () => {
|
||||
// of the raw session id.
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(UserInteractionService)
|
||||
const agent = makeAgent('main')
|
||||
ctx.agents.register(agent) // registered BEFORE the UI plugin below
|
||||
const { runtime, out } = makeRuntime()
|
||||
await ctx.plugin(Object.assign((inner: Context) => {
|
||||
createStdioChat(inner, CONFIG, runtime)
|
||||
}, { inject: ['agents'] }))
|
||||
}, { inject: ['agents', 'userInteraction'] }))
|
||||
ctx.emit('session/event', makeSession('main'), {
|
||||
type: 'turn/start', seq: 1, time: 0, data: { turn: 5, trigger: { kind: 'message' } },
|
||||
} as SessionEvent)
|
||||
@@ -264,6 +291,347 @@ describe('createStdioChat rendering', () => {
|
||||
})
|
||||
|
||||
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({
|
||||
questions: [{
|
||||
id: 'confirm',
|
||||
header: 'Confirm',
|
||||
question: 'Proceed with the edit?',
|
||||
options: [{ label: 'Yes', description: 'Apply the edit now.' }],
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('Use a smaller change')
|
||||
|
||||
await expect(answer).resolves.toEqual({ answers: [{ id: 'confirm', selected: [], custom: 'Use a smaller change' }] })
|
||||
expect(agent.sent).toEqual([])
|
||||
expect(out.text()).toContain('[Confirm] Proceed with the edit?')
|
||||
expect(out.text()).toContain('1. Yes')
|
||||
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({
|
||||
questions: [{
|
||||
id: 'mode',
|
||||
question: 'Which mode?',
|
||||
options: [
|
||||
{ label: 'Safe' },
|
||||
{ label: 'Fast' },
|
||||
],
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('2')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'mode', selected: ['Fast'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('renders options in input order and selects by displayed number', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'topic',
|
||||
question: 'Which topic?',
|
||||
options: [
|
||||
{ label: 'Hobbies' },
|
||||
{ label: 'Work', description: 'Questions about current projects.' },
|
||||
{ label: 'Casual', description: 'Easy conversation.' },
|
||||
],
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
|
||||
expect(out.text()).toContain([
|
||||
'Which topic?',
|
||||
' 1. Hobbies',
|
||||
' 2. Work',
|
||||
' Questions about current projects.',
|
||||
' 3. Casual',
|
||||
' Easy conversation.',
|
||||
].join('\n'))
|
||||
input.feed('3')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'topic', selected: ['Casual'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('answers a multi-select question with multiple numeric selections', async () => {
|
||||
const { ctx, input } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'targets',
|
||||
question: 'What should I update?',
|
||||
options: [{ label: 'Tests' }, { label: 'Docs' }, { label: 'Code' }],
|
||||
multiSelect: true,
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('1 1, 3')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'targets', selected: ['Tests', 'Code'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts non-numeric multi-select input as a custom answer', async () => {
|
||||
const { ctx, input } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'targets',
|
||||
question: 'What should I update?',
|
||||
options: [{ label: 'Tests' }, { label: 'Docs' }],
|
||||
multiSelect: true,
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('the release notes')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'targets', selected: [], custom: 'the release notes' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('asks every question in a batch and returns answers by id', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [
|
||||
{ id: 'language', question: 'Which language?', options: [{ label: 'Python' }, { label: 'TypeScript' }] },
|
||||
{ id: 'note', question: 'Any note?' },
|
||||
],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('2')
|
||||
await new Promise(r => setImmediate(r))
|
||||
expect(out.text()).toContain('\nAny note?\n')
|
||||
input.feed('ship today')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [
|
||||
{ id: 'language', selected: ['TypeScript'] },
|
||||
{ id: 'note', selected: [], custom: 'ship today' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('re-prompts when option input is invalid', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'mode',
|
||||
question: 'Which mode?',
|
||||
options: [{ label: 'Safe' }],
|
||||
multiSelect: true,
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('2')
|
||||
await new Promise(r => setImmediate(r))
|
||||
expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.')
|
||||
input.feed('1')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'mode', selected: ['Safe'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('re-prompts when single-select option input is out of range', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'mode',
|
||||
question: 'Which mode?',
|
||||
options: [{ label: 'Safe' }],
|
||||
}],
|
||||
})
|
||||
await new Promise(r => setImmediate(r))
|
||||
input.feed('2')
|
||||
await new Promise(r => setImmediate(r))
|
||||
expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.')
|
||||
input.feed('1')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'mode', selected: ['Safe'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('re-prompts when multi-select input contains no option numbers', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'mode',
|
||||
question: 'Which mode?',
|
||||
options: [{ label: 'Safe' }],
|
||||
multiSelect: true,
|
||||
}],
|
||||
})
|
||||
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 (comma or space separated) or a custom answer.')
|
||||
input.feed('1')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'mode', selected: ['Safe'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('re-prompts when an option question receives an empty answer', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({
|
||||
questions: [{
|
||||
id: 'mode',
|
||||
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('1')
|
||||
|
||||
await expect(answer).resolves.toEqual({
|
||||
answers: [{ id: 'mode', selected: ['Safe'] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('re-prompts when a question receives an empty answer', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const answer = ctx.userInteraction.ask({ questions: [{ id: 'path', 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({ answers: [{ id: 'path', selected: [], custom: '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({ questions: [{ id: 'continue', 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({ questions: [{ id: 'first', question: 'First?' }], signal: controller.signal })
|
||||
const firstRejected = expect(first).rejects.toMatchObject({ code: 'ASK_ABORTED' })
|
||||
const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }] })
|
||||
await new Promise(r => setImmediate(r))
|
||||
|
||||
controller.abort()
|
||||
await firstRejected
|
||||
await new Promise(r => setImmediate(r))
|
||||
expect(out.text()).toContain('\nSecond?\n')
|
||||
input.feed('second answer')
|
||||
|
||||
await expect(second).resolves.toEqual({ answers: [{ id: 'second', selected: [], custom: '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({ questions: [{ id: 'first', question: 'First?' }] })
|
||||
const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal })
|
||||
await new Promise(r => setImmediate(r))
|
||||
|
||||
controller.abort()
|
||||
|
||||
await expect(Promise.race([
|
||||
second.then(
|
||||
() => 'resolved',
|
||||
(error: unknown) => (error as { code?: string }).code,
|
||||
),
|
||||
new Promise<string>((resolve) => { setImmediate(() => { resolve('pending') }) }),
|
||||
])).resolves.toBe('ASK_ABORTED')
|
||||
expect(out.text()).not.toContain('\nSecond?\n')
|
||||
input.feed('first answer')
|
||||
await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] })
|
||||
})
|
||||
|
||||
it('removes an aborted queued question without promoting later queued work early', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
const controller = new AbortController()
|
||||
const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] })
|
||||
const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal })
|
||||
const third = ctx.userInteraction.ask({ questions: [{ id: 'third', question: 'Third?' }] })
|
||||
await new Promise(r => setImmediate(r))
|
||||
|
||||
controller.abort()
|
||||
|
||||
await expect(second).rejects.toMatchObject({ code: 'ASK_ABORTED' })
|
||||
expect(out.text()).toContain('\nFirst?\n')
|
||||
expect(out.text()).not.toContain('\nSecond?\n')
|
||||
expect(out.text()).not.toContain('\nThird?\n')
|
||||
input.feed('first answer')
|
||||
await new Promise(r => setImmediate(r))
|
||||
|
||||
expect(out.text()).toContain('\nThird?\n')
|
||||
input.feed('third answer')
|
||||
|
||||
await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] })
|
||||
await expect(third).resolves.toEqual({ answers: [{ id: 'third', selected: [], custom: 'third answer' }] })
|
||||
})
|
||||
|
||||
it('rejects active and queued questions when the UI is disposed', async () => {
|
||||
const { ctx, fiber } = await setup()
|
||||
const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] })
|
||||
const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', 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({ questions: [{ id: 'active', question: 'Active?' }] })
|
||||
const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', 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('rejects new questions immediately after stdin has closed', async () => {
|
||||
const { ctx, input, out } = await setup()
|
||||
input.finish()
|
||||
await new Promise(r => setImmediate(r))
|
||||
const before = out.text()
|
||||
|
||||
const answer = ctx.userInteraction.ask({ questions: [{ id: 'late', question: 'Too late?' }] })
|
||||
|
||||
await expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' })
|
||||
expect(out.text()).toBe(before)
|
||||
})
|
||||
|
||||
it('sends a typed line to an idle agent', async () => {
|
||||
const { ctx, input } = await setup()
|
||||
const agent = makeAgent('main', 'idle')
|
||||
|
||||
@@ -32,6 +32,12 @@
|
||||
{
|
||||
"path": "../../core/agent-core"
|
||||
},
|
||||
{
|
||||
"path": "../user-interaction"
|
||||
},
|
||||
{
|
||||
"path": "../tool-ask-user"
|
||||
},
|
||||
{
|
||||
"path": "../../session-persistence/session-persistence-jsonl"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user