mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
feat(acp): show OpenCode and Antigravity questions in HAPI and return the answer (#2309)
* feat(acp): opt-in form elicitation capability advertisement * feat(acp): route elicitation/create forms to a registered handler * feat(opencode): map question forms to AskUserQuestion input and back * feat(opencode): queue question forms as AskUserQuestion requests without auto-answering * feat(opencode): advertise form elicitation for OpenCode v2 * feat(opencode): present the question tool call as AskUserQuestion * feat(opencode): cancel pending question forms on abort, turn end, archive and exit * test(opencode): cover the unshown question result surfacing * feat(acp): let a form elicitation be declined A form elicitation could only be accepted or cancelled. ACP also has decline, the user refusing to answer, and agents may record it differently from a cancel: Antigravity records a declined question as "User Skipped". FormElicitationResponse now includes it, and the backend passes it back to the agent unchanged. * feat(acp): let the ACP permission handler ask the user a question An agent's question (Antigravity's ask_question) is not a permission request: it needs the user's answers, and it must never be answered automatically. askUser() shows it as a pending request with the given tool name and input, whatever the permission mode, and resolves with the user's decision and answers. cancelAll() resolves an open question as aborted, and an open question counts as a pending request, so callers that wait for approvals also wait for it. onUserWait now covers these waits too and no longer takes the request. isUsed() tells whether an id is open or was already shown, since clients hide a pending request whose id was completed before. * feat(agy): answer agy's questions in the question card On agy acp, agy's ask_question used to arrive as a generic tool card and plain text. The turn ended, and whatever the user typed next became the answer. agy now gets form elicitation advertised, so it asks through elicitation/create and keeps the turn open. The launcher takes these forms through the backend's shared form elicitation handler, the same one OpenCode uses. - The question is shown as the AskUserQuestion card on agy's own tool call, with the options as choices, multi-select and an Other field. - The user's choice goes back as agy's answer: the chosen option values, plus free text under qN_other only when the user typed some, so agy records exactly the chosen label. - Denying declines the question, which agy records as "User Skipped". Stop and session end cancel it. - No permission mode answers a question, always-proceed included. - Steer is refused while a question is open. - An approval that carries no usable answer declines instead of sending an empty answer. - A question that arrives after Stop is cancelled. * fix(opencode): decline question forms that arrive after Stop cancelAll only swept requests that already existed, so a form delivered afterwards was queued as a card whose promise never settled. Close the gate synchronously in cancelAll and reopen it when the next prompt begins, matching the aborted-turn guard of the agy handler. * feat(web): let the question card be skipped Add a Skip button, also bound to Esc inside the card, that denies the pending question through the existing deny API and clears the draft like Submit does. A deny already becomes a decline for agy and a cancel for OpenCode, so the backend is unchanged. * fix(agy): decline questions that arrive after the turn has ended * fix(web): keep typed text when Esc is pressed in the question card's text field * fix(question): hide Other on question forms that do not allow free text Forms without qN_custom (OpenCode) or qN_other (agy) take no typed answer, yet the card always offered Other, and a typed answer was dropped so the result became a cancel. Carry an allowFreeText flag through the tool-call input and the synthesized question input, and hide Other on the card when it is false. Inputs without the flag keep showing Other.
This commit is contained in:
@@ -41,7 +41,7 @@ function setupWithHandler(mode: PermissionMode, options?: ConstructorParameters<
|
||||
() => mode,
|
||||
options
|
||||
)
|
||||
return { backend, handler, request: (request: PermissionRequest) => onRequest!(request) }
|
||||
return { backend, client, handler, request: (request: PermissionRequest) => onRequest!(request) }
|
||||
}
|
||||
|
||||
const commandRequest: PermissionRequest = {
|
||||
@@ -126,9 +126,9 @@ describe('AcpPermissionHandler auto-approval rules', () => {
|
||||
const waits: string[] = []
|
||||
const { request, handler } = setupWithHandler('request-review', {
|
||||
autoApprovalRules: { alwaysToolNameHints: [], alwaysToolIdHints: [] },
|
||||
onUserWait: (req) => {
|
||||
waits.push(`start ${req.id}`)
|
||||
return () => waits.push(`end ${req.id}`)
|
||||
onUserWait: () => {
|
||||
waits.push('start')
|
||||
return () => waits.push('end')
|
||||
}
|
||||
})
|
||||
|
||||
@@ -136,7 +136,7 @@ describe('AcpPermissionHandler auto-approval rules', () => {
|
||||
await handler.cancelAll('Prompt finished')
|
||||
await handler.cancelAll('Prompt finished')
|
||||
|
||||
expect(waits).toEqual(['start perm-1', 'end perm-1'])
|
||||
expect(waits).toEqual(['start', 'end'])
|
||||
|
||||
const auto = setupWithHandler('always-proceed', { onUserWait: () => { throw new Error('not a user wait') } })
|
||||
auto.request(commandRequest)
|
||||
@@ -152,3 +152,61 @@ describe('AcpPermissionHandler auto-approval rules', () => {
|
||||
expect(update({}).requests['perm-1']).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('AcpPermissionHandler questions for the user', () => {
|
||||
const questionInput = { questions: [{ question: 'RED or BLUE?', header: null, options: [{ label: 'RED', description: null }], multiSelect: false }] }
|
||||
|
||||
function answerQuestion(client: ReturnType<typeof setupWithHandler>['client'], response: Record<string, unknown>) {
|
||||
const register = client.rpcHandlerManager.registerHandler.mock.calls[0]!
|
||||
const permissionRpc = register[1] as (payload: unknown) => Promise<void>
|
||||
return permissionRpc(response)
|
||||
}
|
||||
|
||||
it.each(['request-review', 'always-proceed', 'yolo', 'bypassPermissions'] as const)(
|
||||
'waits for the user in %s and returns their answers',
|
||||
async (mode) => {
|
||||
const waits: string[] = []
|
||||
const { client, handler, backend } = setupWithHandler(mode, {
|
||||
onUserWait: () => {
|
||||
waits.push('start')
|
||||
return () => waits.push('end')
|
||||
}
|
||||
})
|
||||
const answer = handler.askUser('call_q', 'AskUserQuestion', questionInput)
|
||||
expect(handler.hasPendingRequests()).toBe(true)
|
||||
const update = client.updateAgentState.mock.calls.at(-1)![0] as (state: object) => { requests: Record<string, { tool: string }> }
|
||||
expect(update({}).requests['call_q']).toMatchObject({ tool: 'AskUserQuestion', arguments: questionInput })
|
||||
|
||||
await answerQuestion(client, { id: 'call_q', approved: true, answers: { '0': ['RED'] } })
|
||||
|
||||
await expect(answer).resolves.toEqual({ decision: 'approved', answers: { '0': ['RED'] } })
|
||||
expect(handler.hasPendingRequests()).toBe(false)
|
||||
expect(backend.respondToPermission).not.toHaveBeenCalled()
|
||||
expect(waits).toEqual(['start', 'end'])
|
||||
}
|
||||
)
|
||||
|
||||
it('reports a declined question, and cancels an open one when everything is cancelled', async () => {
|
||||
const { client, handler } = setupWithHandler('request-review')
|
||||
const declined = handler.askUser('call_a', 'AskUserQuestion', questionInput)
|
||||
await answerQuestion(client, { id: 'call_a', approved: false, decision: 'denied' })
|
||||
await expect(declined).resolves.toEqual({ decision: 'denied' })
|
||||
|
||||
const open = handler.askUser('call_b', 'AskUserQuestion', questionInput)
|
||||
await handler.cancelAll('User aborted')
|
||||
await expect(open).resolves.toEqual({ decision: 'abort' })
|
||||
expect(handler.hasPendingRequests()).toBe(false)
|
||||
})
|
||||
|
||||
it('cancels an open question even when replying to a permission request fails', async () => {
|
||||
const { backend, handler, request } = setupWithHandler('request-review', {
|
||||
autoApprovalRules: { alwaysToolNameHints: [], alwaysToolIdHints: [] }
|
||||
})
|
||||
request(commandRequest)
|
||||
const open = handler.askUser('call_b', 'AskUserQuestion', questionInput)
|
||||
backend.respondToPermission.mockRejectedValueOnce(new Error('agy is gone'))
|
||||
|
||||
await expect(handler.cancelAll('Antigravity stopped')).rejects.toThrow('agy is gone')
|
||||
await expect(open).resolves.toEqual({ decision: 'abort' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,12 @@ interface PermissionResponseMessage {
|
||||
approved: boolean
|
||||
decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort'
|
||||
reason?: string
|
||||
answers?: Record<string, string[]>
|
||||
}
|
||||
|
||||
export type UserAnswer = {
|
||||
decision: NonNullable<PermissionResponseMessage['decision']>
|
||||
answers?: Record<string, string[]>
|
||||
}
|
||||
|
||||
function pickOptionId(request: PermissionRequest, preferredKinds: string[]): string | null {
|
||||
@@ -47,6 +53,9 @@ function mapDecisionToOutcome(
|
||||
export class AcpPermissionHandler extends BasePermissionHandler<PermissionResponseMessage, void> {
|
||||
private readonly pendingBackendRequests = new Map<string, PermissionRequest>()
|
||||
private readonly userWaitEnds = new Map<string, () => void>()
|
||||
private readonly userQuestions = new Map<string, (answer: UserAnswer) => void>()
|
||||
// Clients hide a pending request whose id was already completed.
|
||||
private readonly usedIds = new Set<string>()
|
||||
|
||||
constructor(
|
||||
session: ApiSessionClient,
|
||||
@@ -63,7 +72,7 @@ export class AcpPermissionHandler extends BasePermissionHandler<PermissionRespon
|
||||
requiresUser?: (request: PermissionRequest) => boolean
|
||||
// Called when a request starts waiting for the user; the returned
|
||||
// callback runs once it is answered (agents timing their own work).
|
||||
onUserWait?: (request: PermissionRequest) => () => void
|
||||
onUserWait?: () => () => void
|
||||
} = {}
|
||||
) {
|
||||
super(session)
|
||||
@@ -94,8 +103,8 @@ export class AcpPermissionHandler extends BasePermissionHandler<PermissionRespon
|
||||
}
|
||||
|
||||
this.pendingBackendRequests.set(request.id, request)
|
||||
const endUserWait = this.options.onUserWait?.(request)
|
||||
if (endUserWait) this.userWaitEnds.set(request.id, endUserWait)
|
||||
this.usedIds.add(request.id)
|
||||
this.startUserWait(request.id)
|
||||
this.addPendingRequest(request.id, toolName, toolInput, {
|
||||
resolve: () => {},
|
||||
reject: () => {}
|
||||
@@ -127,10 +136,37 @@ export class AcpPermissionHandler extends BasePermissionHandler<PermissionRespon
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* A question the agent asks the user, shown as `toolName` with `input`.
|
||||
* Never answered automatically, whatever the permission mode.
|
||||
*/
|
||||
askUser(id: string, toolName: string, input: unknown): Promise<UserAnswer> {
|
||||
return new Promise((resolve) => {
|
||||
this.userQuestions.set(id, resolve)
|
||||
this.usedIds.add(id)
|
||||
this.startUserWait(id)
|
||||
this.addPendingRequest(id, toolName, input, { resolve: () => {}, reject: () => {} })
|
||||
})
|
||||
}
|
||||
|
||||
protected async handlePermissionResponse(
|
||||
response: PermissionResponseMessage,
|
||||
pending: PendingPermissionRequest<void>
|
||||
): Promise<PermissionCompletion> {
|
||||
const question = this.userQuestions.get(response.id)
|
||||
if (question) {
|
||||
this.userQuestions.delete(response.id)
|
||||
const decision = response.decision ?? (response.approved ? 'approved' : 'denied')
|
||||
this.endUserWait(response.id)
|
||||
question(response.answers ? { decision, answers: response.answers } : { decision })
|
||||
pending.resolve()
|
||||
return {
|
||||
status: response.approved ? 'approved' : 'denied',
|
||||
decision,
|
||||
reason: response.reason,
|
||||
answers: response.answers
|
||||
}
|
||||
}
|
||||
const request = this.pendingBackendRequests.get(response.id)
|
||||
this.pendingBackendRequests.delete(response.id)
|
||||
const decision = response.decision ?? (response.approved ? 'approved' : 'denied')
|
||||
@@ -155,17 +191,35 @@ export class AcpPermissionHandler extends BasePermissionHandler<PermissionRespon
|
||||
logger.debug('[ACP] Permission response received for unknown request', response.id)
|
||||
}
|
||||
|
||||
private startUserWait(id: string): void {
|
||||
const end = this.options.onUserWait?.()
|
||||
if (end) this.userWaitEnds.set(id, end)
|
||||
}
|
||||
|
||||
private endUserWait(id: string): void {
|
||||
const end = this.userWaitEnds.get(id)
|
||||
this.userWaitEnds.delete(id)
|
||||
end?.()
|
||||
}
|
||||
|
||||
/** Whether a request with this id is open or was already shown. */
|
||||
isUsed(id: string): boolean {
|
||||
return this.usedIds.has(id) || this.pendingRequests.has(id)
|
||||
}
|
||||
|
||||
hasPendingRequests(): boolean {
|
||||
return this.pendingBackendRequests.size > 0
|
||||
return this.pendingBackendRequests.size > 0 || this.userQuestions.size > 0
|
||||
}
|
||||
|
||||
async cancelAll(reason: string): Promise<void> {
|
||||
// Questions first: answering them cannot fail, while a permission
|
||||
// reply can throw once the agent process is gone.
|
||||
const questions = Array.from(this.userQuestions.entries())
|
||||
this.userQuestions.clear()
|
||||
for (const [id, answer] of questions) {
|
||||
this.endUserWait(id)
|
||||
answer({ decision: 'abort' })
|
||||
}
|
||||
const pending = Array.from(this.pendingBackendRequests.values())
|
||||
this.pendingBackendRequests.clear()
|
||||
for (const request of pending) {
|
||||
|
||||
Reference in New Issue
Block a user