mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
feat(dsh): integrate DeepSeek Harness through ACP (#1632)
* feat(dsh): add DeepSeek Harness ACP flavor * fix(dsh): update mobile flavor catalogs * fix(dsh): keep mobile spawn policy managed * fix(dsh): keep managed policy and prompt retry * fix(dsh): suppress unsupported runner policy flags * fix(dsh): align native managed-policy UX
This commit is contained in:
@@ -100,6 +100,7 @@ ${chalk.bold('Usage:')}
|
||||
hapi codex Start Codex mode
|
||||
hapi cursor Start Cursor Agent mode
|
||||
hapi opencode Start OpenCode ACP mode
|
||||
hapi dsh Start DeepSeek Harness ACP mode
|
||||
hapi resume [id] Resume an existing HAPI session locally
|
||||
hapi mcp Start MCP stdio bridge
|
||||
hapi connect (not available in direct-connect mode)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDshCommandOptions } from './dsh'
|
||||
|
||||
describe('parseDshCommandOptions', () => {
|
||||
it('forces remote mode and accepts an existing HAPI row', () => {
|
||||
expect(parseDshCommandOptions([
|
||||
'--hapi-starting-mode', 'remote',
|
||||
'--existing-session-id', 'hapi-session'
|
||||
])).toEqual({
|
||||
startingMode: 'remote',
|
||||
existingSessionId: 'hapi-session'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects native resume, model, and HAPI permission controls unsupported by DSH ACP', () => {
|
||||
expect(() => parseDshCommandOptions(['--resume', 'native-id']))
|
||||
.toThrow('fresh sessions')
|
||||
expect(() => parseDshCommandOptions(['--model', 'deepseek-v4-pro']))
|
||||
.toThrow('configured by the ACP server')
|
||||
expect(() => parseDshCommandOptions(['--yolo']))
|
||||
.toThrow('permission policy')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import chalk from 'chalk'
|
||||
import { initializeToken } from '@/ui/tokenInit'
|
||||
import { maybeAutoStartServer } from '@/utils/autoStartServer'
|
||||
import { authAndSetupMachineIfNeeded } from '@/ui/auth'
|
||||
import { parseRemoteAgentCommandOptions } from './agentCommandOptions'
|
||||
import type { CommandDefinition } from './types'
|
||||
|
||||
export function parseDshCommandOptions(commandArgs: string[]) {
|
||||
const options = parseRemoteAgentCommandOptions(commandArgs, [], ['remote'])
|
||||
if (commandArgs.includes('--yolo')) {
|
||||
throw new Error('DeepSeek Harness permission policy is configured by the ACP server')
|
||||
}
|
||||
if (options.resumeSessionId) {
|
||||
throw new Error('DeepSeek Harness ACP only supports fresh sessions; resume is unavailable')
|
||||
}
|
||||
if (options.model || options.effort || options.modelReasoningEffort) {
|
||||
throw new Error('DeepSeek Harness model and effort are configured by the ACP server')
|
||||
}
|
||||
return { ...options, startingMode: 'remote' as const }
|
||||
}
|
||||
|
||||
export const dshCommand: CommandDefinition = {
|
||||
name: 'dsh',
|
||||
requiresRuntimeAssets: true,
|
||||
run: async ({ commandArgs }) => {
|
||||
try {
|
||||
const options = parseDshCommandOptions(commandArgs)
|
||||
await initializeToken()
|
||||
await maybeAutoStartServer()
|
||||
await authAndSetupMachineIfNeeded()
|
||||
|
||||
const { runDsh } = await import('@/dsh/runDsh')
|
||||
await runDsh(options)
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error:'), error instanceof Error ? error.message : 'Unknown error')
|
||||
if (process.env.DEBUG) console.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { agyCommand } from './agy'
|
||||
import { authCommand } from './auth'
|
||||
import { claudeCommand } from './claude'
|
||||
import { codexCommand } from './codex'
|
||||
import { dshCommand } from './dsh'
|
||||
import { cursorCommand } from './cursor'
|
||||
import { connectCommand } from './connect'
|
||||
import { runnerCommand } from './runner'
|
||||
@@ -42,6 +43,7 @@ const COMMANDS: CommandDefinition[] = [
|
||||
authCommand,
|
||||
connectCommand,
|
||||
codexCommand,
|
||||
dshCommand,
|
||||
cursorCommand,
|
||||
removedGeminiCommand,
|
||||
grokCommand,
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MessageQueue2 } from '@/utils/MessageQueue2'
|
||||
import type { DshMode } from './types'
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
backend: null as Record<string, ReturnType<typeof vi.fn>> | null,
|
||||
newSessionConfig: null as unknown,
|
||||
prompts: [] as unknown[][]
|
||||
}))
|
||||
|
||||
vi.mock('./utils/dshBackend', () => ({
|
||||
createDshBackend: vi.fn(() => {
|
||||
const backend = {
|
||||
initialize: vi.fn(async () => {}),
|
||||
newSession: vi.fn(async (config: unknown) => {
|
||||
harness.newSessionConfig = config
|
||||
return 'dsh-session-1'
|
||||
}),
|
||||
prompt: vi.fn(async (_sessionId: string, content: unknown[], onUpdate: (message: unknown) => void) => {
|
||||
harness.prompts.push(content)
|
||||
onUpdate({ type: 'text', text: 'answer' })
|
||||
}),
|
||||
cancelPrompt: vi.fn(async () => {}),
|
||||
onStderrError: vi.fn(),
|
||||
onPermissionRequest: vi.fn(),
|
||||
disconnect: vi.fn(async () => {})
|
||||
}
|
||||
harness.backend = backend
|
||||
return backend
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/modules/common/permission/AcpPermissionHandler', () => ({
|
||||
AcpPermissionHandler: class {
|
||||
async cancelAll(): Promise<void> {}
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/ink/RemoteModeDisplay', () => ({ RemoteModeDisplay: () => null }))
|
||||
vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), warn: vi.fn() } }))
|
||||
|
||||
import { DshRemoteLauncher } from './dshRemoteLauncher'
|
||||
|
||||
function createSession() {
|
||||
const queue = new MessageQueue2<DshMode>((mode) => JSON.stringify(mode))
|
||||
queue.push('first', 'dsh')
|
||||
queue.close()
|
||||
|
||||
return {
|
||||
path: '/tmp/dsh-test',
|
||||
logPath: '/tmp/dsh-test/hapi.log',
|
||||
client: { rpcHandlerManager: { registerHandler: vi.fn() } },
|
||||
queue,
|
||||
sessionId: null as string | null,
|
||||
getPermissionMode: () => 'default' as const,
|
||||
onThinkingChange: vi.fn(),
|
||||
sendAgentMessage: vi.fn(),
|
||||
sendSessionEvent: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
describe('DshRemoteLauncher', () => {
|
||||
afterEach(() => {
|
||||
harness.backend = null
|
||||
harness.newSessionConfig = null
|
||||
harness.prompts = []
|
||||
})
|
||||
|
||||
it('creates a fresh ACP session without MCP injection and forwards text prompts', async () => {
|
||||
const session = createSession()
|
||||
const launcher = new DshRemoteLauncher(session as never)
|
||||
|
||||
await launcher.launch()
|
||||
|
||||
expect(harness.backend?.newSession).toHaveBeenCalledWith({
|
||||
cwd: '/tmp/dsh-test',
|
||||
mcpServers: []
|
||||
})
|
||||
expect(harness.prompts).toEqual([[{ type: 'text', text: 'first' }]])
|
||||
expect(session.sendAgentMessage).toHaveBeenCalledWith({
|
||||
type: 'message',
|
||||
message: 'answer'
|
||||
})
|
||||
expect(session.sendSessionEvent).toHaveBeenCalledWith({ type: 'ready' })
|
||||
expect(harness.backend?.disconnect).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import React from 'react'
|
||||
import { logger } from '@/ui/logger'
|
||||
import { convertAgentMessage } from '@/agent/messageConverter'
|
||||
import type { AgentMessage, PromptContent } from '@/agent/types'
|
||||
import {
|
||||
RemoteLauncherBase,
|
||||
type RemoteLauncherDisplayContext,
|
||||
type RemoteLauncherExitReason
|
||||
} from '@/modules/common/remote/RemoteLauncherBase'
|
||||
import { RemoteModeDisplay } from '@/ui/ink/RemoteModeDisplay'
|
||||
import { AcpPermissionHandler } from '@/modules/common/permission/AcpPermissionHandler'
|
||||
import { createDshBackend } from './utils/dshBackend'
|
||||
import type { DshSession } from './session'
|
||||
|
||||
export class DshRemoteLauncher extends RemoteLauncherBase {
|
||||
private backend: ReturnType<typeof createDshBackend> | null = null
|
||||
private permissionHandler: AcpPermissionHandler | null = null
|
||||
private abortController = new AbortController()
|
||||
|
||||
constructor(private readonly session: DshSession) {
|
||||
super(process.env.DEBUG ? session.logPath : undefined)
|
||||
}
|
||||
|
||||
async launch(): Promise<RemoteLauncherExitReason> {
|
||||
return this.start({ onExit: () => this.handleExitFromUi() })
|
||||
}
|
||||
|
||||
async kill(): Promise<void> {
|
||||
if (!this.backend) return
|
||||
await this.handleAbort()
|
||||
}
|
||||
|
||||
protected createDisplay(context: RemoteLauncherDisplayContext): React.ReactElement {
|
||||
return React.createElement(RemoteModeDisplay, {
|
||||
...context,
|
||||
agentLabel: 'DeepSeek Harness'
|
||||
})
|
||||
}
|
||||
|
||||
protected async runMainLoop(): Promise<void> {
|
||||
const backend = createDshBackend()
|
||||
this.backend = backend
|
||||
backend.onStderrError((error) => {
|
||||
logger.debug('[dsh-acp] stderr error', error)
|
||||
this.session.sendSessionEvent({ type: 'message', message: error.message })
|
||||
this.messageBuffer.addMessage(error.message, 'status')
|
||||
})
|
||||
|
||||
await backend.initialize()
|
||||
const acpSessionId = await backend.newSession({
|
||||
cwd: this.session.path,
|
||||
// The official DSH ACP composition rejects non-empty MCP servers;
|
||||
// its tools are configured by the DSH server itself.
|
||||
mcpServers: []
|
||||
})
|
||||
this.session.sessionId = acpSessionId
|
||||
|
||||
this.permissionHandler = new AcpPermissionHandler(
|
||||
this.session.client,
|
||||
backend,
|
||||
() => undefined
|
||||
)
|
||||
this.setupAbortHandlers(this.session.client.rpcHandlerManager, {
|
||||
onAbort: () => this.handleAbort(),
|
||||
onSwitch: () => this.handleExitFromUi()
|
||||
})
|
||||
|
||||
while (!this.shouldExit) {
|
||||
const batch = await this.session.queue.waitForMessagesAndGetAsString(this.abortController.signal)
|
||||
if (!batch) {
|
||||
if (this.abortController.signal.aborted && !this.shouldExit) continue
|
||||
break
|
||||
}
|
||||
|
||||
this.session.onThinkingChange(true)
|
||||
this.messageBuffer.addMessage(batch.message, 'user')
|
||||
const prompt: PromptContent[] = [{ type: 'text', text: batch.message }]
|
||||
try {
|
||||
await backend.prompt(acpSessionId, prompt, (message) => this.handleAgentMessage(message))
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
logger.warn('[dsh-acp] prompt failed', { message })
|
||||
this.session.sendSessionEvent({ type: 'message', message: `DSH prompt failed: ${message}` })
|
||||
this.messageBuffer.addMessage(`DSH prompt failed: ${message}`, 'status')
|
||||
} finally {
|
||||
this.session.onThinkingChange(false)
|
||||
await this.permissionHandler?.cancelAll('Prompt finished')
|
||||
if (this.session.queue.size() === 0 && !this.shouldExit) {
|
||||
this.session.sendSessionEvent({ type: 'ready' })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected async cleanup(): Promise<void> {
|
||||
this.clearAbortHandlers(this.session.client.rpcHandlerManager)
|
||||
await this.permissionHandler?.cancelAll('Session ended')
|
||||
this.permissionHandler = null
|
||||
await this.backend?.disconnect()
|
||||
this.backend = null
|
||||
}
|
||||
|
||||
private handleAgentMessage(message: AgentMessage): void {
|
||||
const converted = convertAgentMessage(message)
|
||||
if (converted) this.session.sendAgentMessage(converted)
|
||||
|
||||
switch (message.type) {
|
||||
case 'text':
|
||||
this.messageBuffer.addMessage(message.text, 'assistant')
|
||||
break
|
||||
case 'generated_image':
|
||||
this.messageBuffer.addMessage(`Generated image: ${message.fileName}`, 'assistant')
|
||||
break
|
||||
case 'error':
|
||||
this.messageBuffer.addMessage(message.message, 'status')
|
||||
break
|
||||
case 'turn_complete':
|
||||
this.messageBuffer.addMessage('Turn complete', 'status')
|
||||
break
|
||||
case 'usage':
|
||||
case 'reasoning':
|
||||
case 'tool_call':
|
||||
case 'tool_result':
|
||||
case 'plan':
|
||||
break
|
||||
default: {
|
||||
const _exhaustive: never = message
|
||||
return _exhaustive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async handleAbort(): Promise<void> {
|
||||
if (this.backend && this.session.sessionId) {
|
||||
await this.backend.cancelPrompt(this.session.sessionId)
|
||||
}
|
||||
await this.permissionHandler?.cancelAll('User aborted')
|
||||
this.session.sendSessionEvent({ type: 'message', message: 'Session aborted' })
|
||||
this.session.queue.reset()
|
||||
this.session.onThinkingChange(false)
|
||||
this.abortController.abort()
|
||||
this.abortController = new AbortController()
|
||||
this.messageBuffer.addMessage('Turn aborted', 'status')
|
||||
}
|
||||
|
||||
private async handleExitFromUi(): Promise<void> {
|
||||
await this.requestExit('exit', () => this.handleAbort())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { hashObject } from '@/utils/deterministicJson'
|
||||
import { MessageQueue2 } from '@/utils/MessageQueue2'
|
||||
import { registerKillSessionHandler } from '@/claude/registerKillSessionHandler'
|
||||
import { createRunnerLifecycle, setControlledByUser } from '@/agent/runnerLifecycle'
|
||||
import { bootstrapExistingSession, bootstrapSession } from '@/agent/sessionFactory'
|
||||
import { formatMessageWithAttachments } from '@/utils/attachmentFormatter'
|
||||
import { getInvokedCwd } from '@/utils/invokedCwd'
|
||||
import { logger } from '@/ui/logger'
|
||||
import type { AgentState } from '@/api/types'
|
||||
import { DshRemoteLauncher } from './dshRemoteLauncher'
|
||||
import { DshSession } from './session'
|
||||
import type { DshMode } from './types'
|
||||
|
||||
export async function runDsh(opts: {
|
||||
startedBy?: 'runner' | 'terminal'
|
||||
startingMode?: 'remote'
|
||||
existingSessionId?: string
|
||||
workingDirectory?: string
|
||||
} = {}): Promise<void> {
|
||||
const workingDirectory = opts.workingDirectory ?? getInvokedCwd()
|
||||
const startedBy = opts.startedBy ?? 'terminal'
|
||||
const startingMode = 'remote' as const
|
||||
const initialState: AgentState = {
|
||||
controlledByUser: false,
|
||||
startingMode
|
||||
}
|
||||
|
||||
const bootstrap = opts.existingSessionId
|
||||
? await bootstrapExistingSession({
|
||||
sessionId: opts.existingSessionId,
|
||||
flavor: 'dsh',
|
||||
startedBy,
|
||||
workingDirectory
|
||||
})
|
||||
: await bootstrapSession({
|
||||
flavor: 'dsh',
|
||||
startedBy,
|
||||
workingDirectory,
|
||||
agentState: initialState
|
||||
})
|
||||
const { api, session } = bootstrap
|
||||
setControlledByUser(session, startingMode)
|
||||
|
||||
const queue = new MessageQueue2<DshMode>((mode) => hashObject(mode))
|
||||
const sessionRef: { current: DshSession | null } = { current: null }
|
||||
const launcherRef: { current: DshRemoteLauncher | null } = { current: null }
|
||||
|
||||
session.onUserMessage((message, localId) => {
|
||||
queue.push(
|
||||
formatMessageWithAttachments(message.content.text, message.content.attachments),
|
||||
'dsh',
|
||||
localId
|
||||
)
|
||||
})
|
||||
session.onCancelQueuedMessage((localId) => queue.cancelByLocalId(localId))
|
||||
|
||||
const lifecycle = createRunnerLifecycle({
|
||||
session,
|
||||
logTag: 'dsh',
|
||||
stopKeepAlive: () => sessionRef.current?.stopKeepAlive(),
|
||||
onBeforeClose: () => launcherRef.current?.kill()
|
||||
})
|
||||
lifecycle.registerProcessHandlers()
|
||||
registerKillSessionHandler(session.rpcHandlerManager, lifecycle)
|
||||
|
||||
const dshSession = new DshSession({
|
||||
api,
|
||||
client: session,
|
||||
path: workingDirectory,
|
||||
logPath: logger.getLogPath(),
|
||||
messageQueue: queue,
|
||||
onModeChange: () => {},
|
||||
startedBy
|
||||
})
|
||||
const launcher = new DshRemoteLauncher(dshSession)
|
||||
sessionRef.current = dshSession
|
||||
launcherRef.current = launcher
|
||||
|
||||
let crashed = false
|
||||
try {
|
||||
await launcher.launch()
|
||||
} catch (error) {
|
||||
crashed = true
|
||||
lifecycle.markCrash(error)
|
||||
} finally {
|
||||
if (!crashed) lifecycle.setSessionEndReason('completed')
|
||||
await lifecycle.cleanupAndExit()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { ApiClient, ApiSessionClient } from '@/lib'
|
||||
import { MessageQueue2 } from '@/utils/MessageQueue2'
|
||||
import { AgentSessionBase } from '@/agent/sessionBase'
|
||||
import type { DshMode } from './types'
|
||||
|
||||
/** Remote-only HAPI session wrapper for the fresh-session DSH ACP server. */
|
||||
export class DshSession extends AgentSessionBase<DshMode> {
|
||||
readonly startedBy: 'runner' | 'terminal'
|
||||
|
||||
constructor(opts: {
|
||||
api: ApiClient
|
||||
client: ApiSessionClient
|
||||
path: string
|
||||
logPath: string
|
||||
messageQueue: MessageQueue2<DshMode>
|
||||
onModeChange: (mode: 'local' | 'remote') => void
|
||||
startedBy: 'runner' | 'terminal'
|
||||
}) {
|
||||
super({
|
||||
api: opts.api,
|
||||
client: opts.client,
|
||||
path: opts.path,
|
||||
logPath: opts.logPath,
|
||||
sessionId: null,
|
||||
messageQueue: opts.messageQueue,
|
||||
onModeChange: opts.onModeChange,
|
||||
mode: 'remote',
|
||||
sessionLabel: 'DshSession',
|
||||
sessionIdLabel: 'DeepSeek Harness ACP',
|
||||
// The official ACP server supports fresh sessions only. Keep its
|
||||
// process-local id out of HAPI metadata so inactive rows cannot
|
||||
// advertise a resume path the server does not implement.
|
||||
applySessionIdToMetadata: (metadata) => metadata
|
||||
})
|
||||
this.startedBy = opts.startedBy
|
||||
}
|
||||
|
||||
sendAgentMessage = (message: unknown): void => {
|
||||
this.client.sendAgentMessage(message)
|
||||
}
|
||||
|
||||
sendSessionEvent = (event: Parameters<ApiSessionClient['sendSessionEvent']>[0]): void => {
|
||||
this.client.sendSessionEvent(event)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export type DshMode = 'dsh'
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveDshAcpCommand } from './dshBackend'
|
||||
|
||||
describe('resolveDshAcpCommand', () => {
|
||||
it('uses the official ACP demo executable by default', () => {
|
||||
expect(resolveDshAcpCommand({})).toEqual({
|
||||
command: 'dsh-acp-demo',
|
||||
args: []
|
||||
})
|
||||
})
|
||||
|
||||
it('supports a config path for dsh-acp-demo', () => {
|
||||
expect(resolveDshAcpCommand({ HAPI_DSH_ACP_CONFIG: '/tmp/cordis.yml' })).toEqual({
|
||||
command: 'dsh-acp-demo',
|
||||
args: ['--config', '/tmp/cordis.yml']
|
||||
})
|
||||
})
|
||||
|
||||
it('supports source checkouts and community servers through JSON args', () => {
|
||||
expect(resolveDshAcpCommand({
|
||||
HAPI_DSH_ACP_COMMAND: 'pnpm',
|
||||
HAPI_DSH_ACP_ARGS_JSON: '["--dir", "/opt/dsh", "run", "demo:acp"]'
|
||||
})).toEqual({
|
||||
command: 'pnpm',
|
||||
args: ['--dir', '/opt/dsh', 'run', 'demo:acp']
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects shell-like or malformed argument values', () => {
|
||||
expect(() => resolveDshAcpCommand({ HAPI_DSH_ACP_ARGS_JSON: 'pnpm --dir /opt/dsh' }))
|
||||
.toThrow('HAPI_DSH_ACP_ARGS_JSON must be a JSON array of strings')
|
||||
expect(() => resolveDshAcpCommand({ HAPI_DSH_ACP_ARGS_JSON: '["pnpm", 1]' }))
|
||||
.toThrow('HAPI_DSH_ACP_ARGS_JSON must be a JSON array of strings')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { AcpSdkBackend } from '@/agent/backends/acp'
|
||||
|
||||
type DshAcpEnvironment = Record<string, string | undefined>
|
||||
|
||||
function filterEnv(env: NodeJS.ProcessEnv): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)
|
||||
)
|
||||
}
|
||||
|
||||
function parseArgsJson(raw: string): string[] {
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(raw)
|
||||
} catch {
|
||||
throw new Error('HAPI_DSH_ACP_ARGS_JSON must be a JSON array of strings')
|
||||
}
|
||||
if (!Array.isArray(value) || value.some((arg) => typeof arg !== 'string')) {
|
||||
throw new Error('HAPI_DSH_ACP_ARGS_JSON must be a JSON array of strings')
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
export function resolveDshAcpCommand(env: DshAcpEnvironment = process.env): {
|
||||
command: string
|
||||
args: string[]
|
||||
} {
|
||||
const command = env.HAPI_DSH_ACP_COMMAND?.trim() || 'dsh-acp-demo'
|
||||
if (env.HAPI_DSH_ACP_ARGS_JSON?.trim()) {
|
||||
return { command, args: parseArgsJson(env.HAPI_DSH_ACP_ARGS_JSON.trim()) }
|
||||
}
|
||||
const config = env.HAPI_DSH_ACP_CONFIG?.trim()
|
||||
return { command, args: config ? ['--config', config] : [] }
|
||||
}
|
||||
|
||||
export function createDshBackend(env: NodeJS.ProcessEnv = process.env): AcpSdkBackend {
|
||||
const { command, args } = resolveDshAcpCommand(env)
|
||||
return new AcpSdkBackend({
|
||||
command,
|
||||
args,
|
||||
env: filterEnv(env),
|
||||
flavor: 'dsh'
|
||||
})
|
||||
}
|
||||
@@ -1,170 +1,3 @@
|
||||
import type { ApiSessionClient } from '@/api/apiSession';
|
||||
import type { AgentBackend, PermissionRequest, PermissionResponse } from '@/agent/types';
|
||||
import type { KimiPermissionMode } from '@hapi/protocol/types';
|
||||
import { deriveToolName } from '@/agent/utils';
|
||||
import { logger } from '@/ui/logger';
|
||||
import {
|
||||
BasePermissionHandler,
|
||||
type AutoApprovalDecision,
|
||||
type PendingPermissionRequest,
|
||||
type PermissionCompletion
|
||||
} from '@/modules/common/permission/BasePermissionHandler';
|
||||
|
||||
interface PermissionResponseMessage {
|
||||
id: string;
|
||||
approved: boolean;
|
||||
decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort';
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
function deriveToolInput(request: PermissionRequest): unknown {
|
||||
if (request.rawInput !== undefined) {
|
||||
return request.rawInput;
|
||||
}
|
||||
return request.rawOutput;
|
||||
}
|
||||
|
||||
function pickOptionId(request: PermissionRequest, preferredKinds: string[]): string | null {
|
||||
for (const kind of preferredKinds) {
|
||||
const match = request.options.find((option) => option.kind === kind);
|
||||
if (match) {
|
||||
return match.optionId;
|
||||
}
|
||||
}
|
||||
return request.options.length > 0 ? request.options[0].optionId : null;
|
||||
}
|
||||
|
||||
function mapDecisionToOutcome(request: PermissionRequest, decision: PermissionResponseMessage['decision']): PermissionResponse {
|
||||
if (decision === 'abort') {
|
||||
return { outcome: 'cancelled' };
|
||||
}
|
||||
|
||||
if (decision === 'approved_for_session') {
|
||||
const optionId = pickOptionId(request, ['allow_always', 'allow_once']);
|
||||
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
|
||||
}
|
||||
|
||||
if (decision === 'approved') {
|
||||
const optionId = pickOptionId(request, ['allow_once', 'allow_always']);
|
||||
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
|
||||
}
|
||||
|
||||
const optionId = pickOptionId(request, ['reject_once', 'reject_always']);
|
||||
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
|
||||
}
|
||||
|
||||
export class KimiPermissionHandler extends BasePermissionHandler<PermissionResponseMessage, void> {
|
||||
private readonly pendingBackendRequests = new Map<string, PermissionRequest>();
|
||||
|
||||
constructor(
|
||||
session: ApiSessionClient,
|
||||
private readonly backend: AgentBackend,
|
||||
private readonly getPermissionMode: () => KimiPermissionMode | undefined
|
||||
) {
|
||||
super(session);
|
||||
this.backend.onPermissionRequest((request) => this.handlePermissionRequest(request));
|
||||
}
|
||||
|
||||
private handlePermissionRequest(request: PermissionRequest): void {
|
||||
const toolName = deriveToolName({
|
||||
title: request.title,
|
||||
kind: request.kind,
|
||||
rawInput: request.rawInput
|
||||
});
|
||||
const toolInput = deriveToolInput(request);
|
||||
const mode = this.getPermissionMode() ?? 'default';
|
||||
|
||||
const autoDecision = this.resolveAutoApprovalDecision(mode, toolName, request.toolCallId);
|
||||
if (autoDecision) {
|
||||
void this.autoApprove(request, toolName, toolInput, autoDecision);
|
||||
return;
|
||||
}
|
||||
|
||||
this.pendingBackendRequests.set(request.id, request);
|
||||
this.addPendingRequest(request.id, toolName, toolInput, {
|
||||
resolve: () => {},
|
||||
reject: () => {}
|
||||
});
|
||||
|
||||
logger.debug(`[Kimi] Permission request queued for ${toolName} (${request.id})`);
|
||||
}
|
||||
|
||||
private async autoApprove(
|
||||
request: PermissionRequest,
|
||||
toolName: string,
|
||||
toolInput: unknown,
|
||||
decision: AutoApprovalDecision
|
||||
): Promise<void> {
|
||||
const outcome = mapDecisionToOutcome(request, decision);
|
||||
await this.backend.respondToPermission(request.sessionId, request, outcome);
|
||||
|
||||
this.client.updateAgentState((currentState) => ({
|
||||
...currentState,
|
||||
completedRequests: {
|
||||
...currentState.completedRequests,
|
||||
[request.id]: {
|
||||
tool: toolName,
|
||||
arguments: toolInput,
|
||||
createdAt: Date.now(),
|
||||
completedAt: Date.now(),
|
||||
status: 'approved',
|
||||
decision
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
logger.debug(`[Kimi] Auto-approved ${toolName} (${request.id}) mode=${decision}`);
|
||||
}
|
||||
|
||||
protected async handlePermissionResponse(
|
||||
response: PermissionResponseMessage,
|
||||
pending: PendingPermissionRequest<void>
|
||||
): Promise<PermissionCompletion> {
|
||||
const pendingRequest = this.pendingBackendRequests.get(response.id);
|
||||
if (pendingRequest) {
|
||||
this.pendingBackendRequests.delete(response.id);
|
||||
} else {
|
||||
logger.debug('[Kimi] Permission response missing backend request', response.id);
|
||||
}
|
||||
|
||||
const decision = response.decision ?? (response.approved ? 'approved' : 'denied');
|
||||
|
||||
if (decision === 'abort' && pendingRequest) {
|
||||
await this.backend.cancelPrompt(pendingRequest.sessionId);
|
||||
}
|
||||
|
||||
if (pendingRequest) {
|
||||
const outcome = mapDecisionToOutcome(pendingRequest, decision);
|
||||
await this.backend.respondToPermission(pendingRequest.sessionId, pendingRequest, outcome);
|
||||
}
|
||||
|
||||
pending.resolve();
|
||||
|
||||
logger.debug(`[Kimi] Permission ${response.approved ? 'approved' : 'denied'} for ${pending.toolName}`);
|
||||
|
||||
return {
|
||||
status: response.approved ? 'approved' : 'denied',
|
||||
decision,
|
||||
reason: response.reason
|
||||
};
|
||||
}
|
||||
|
||||
protected handleMissingPendingResponse(response: PermissionResponseMessage): void {
|
||||
logger.debug('[Kimi] Permission response received for unknown request', response.id);
|
||||
}
|
||||
|
||||
async cancelAll(reason: string): Promise<void> {
|
||||
const pending = Array.from(this.pendingBackendRequests.values());
|
||||
this.pendingBackendRequests.clear();
|
||||
|
||||
for (const request of pending) {
|
||||
await this.backend.respondToPermission(request.sessionId, request, { outcome: 'cancelled' });
|
||||
}
|
||||
|
||||
this.cancelPendingRequests({
|
||||
completedReason: reason,
|
||||
rejectMessage: reason,
|
||||
decision: 'abort'
|
||||
});
|
||||
}
|
||||
}
|
||||
// Kimi uses the shared one-shot ACP permission bridge. Keep the old export
|
||||
// name so the launcher and its mocks remain flavor-local.
|
||||
export { AcpPermissionHandler as KimiPermissionHandler } from '@/modules/common/permission/AcpPermissionHandler'
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import type { ApiSessionClient } from '@/api/apiSession'
|
||||
import type { AgentBackend, PermissionRequest, PermissionResponse } from '@/agent/types'
|
||||
import type { PermissionMode } from '@hapi/protocol/types'
|
||||
import { deriveToolName } from '@/agent/utils'
|
||||
import { logger } from '@/ui/logger'
|
||||
import {
|
||||
BasePermissionHandler,
|
||||
type AutoApprovalDecision,
|
||||
type PendingPermissionRequest,
|
||||
type PermissionCompletion
|
||||
} from './BasePermissionHandler'
|
||||
|
||||
interface PermissionResponseMessage {
|
||||
id: string
|
||||
approved: boolean
|
||||
decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort'
|
||||
reason?: string
|
||||
}
|
||||
|
||||
function deriveToolInput(request: PermissionRequest): unknown {
|
||||
return request.rawInput !== undefined ? request.rawInput : request.rawOutput
|
||||
}
|
||||
|
||||
function pickOptionId(request: PermissionRequest, preferredKinds: string[]): string | null {
|
||||
for (const kind of preferredKinds) {
|
||||
const match = request.options.find((option) => option.kind === kind)
|
||||
if (match) return match.optionId
|
||||
}
|
||||
return request.options[0]?.optionId ?? null
|
||||
}
|
||||
|
||||
function mapDecisionToOutcome(
|
||||
request: PermissionRequest,
|
||||
decision: PermissionResponseMessage['decision']
|
||||
): PermissionResponse {
|
||||
if (decision === 'abort') return { outcome: 'cancelled' }
|
||||
if (decision === 'approved_for_session') {
|
||||
const optionId = pickOptionId(request, ['allow_always', 'allow_once'])
|
||||
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' }
|
||||
}
|
||||
if (decision === 'approved') {
|
||||
const optionId = pickOptionId(request, ['allow_once', 'allow_always'])
|
||||
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' }
|
||||
}
|
||||
const optionId = pickOptionId(request, ['reject_once', 'reject_always'])
|
||||
return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' }
|
||||
}
|
||||
|
||||
/** Shared HAPI permission bridge for ACP agents with one-shot choices. */
|
||||
export class AcpPermissionHandler extends BasePermissionHandler<PermissionResponseMessage, void> {
|
||||
private readonly pendingBackendRequests = new Map<string, PermissionRequest>()
|
||||
|
||||
constructor(
|
||||
session: ApiSessionClient,
|
||||
private readonly backend: AgentBackend,
|
||||
private readonly getPermissionMode: () => PermissionMode | undefined
|
||||
) {
|
||||
super(session)
|
||||
this.backend.onPermissionRequest((request) => this.handlePermissionRequest(request))
|
||||
}
|
||||
|
||||
private handlePermissionRequest(request: PermissionRequest): void {
|
||||
const toolName = deriveToolName({
|
||||
title: request.title,
|
||||
kind: request.kind,
|
||||
rawInput: request.rawInput
|
||||
})
|
||||
const toolInput = deriveToolInput(request)
|
||||
const autoDecision = this.resolveAutoApprovalDecision(
|
||||
this.getPermissionMode(),
|
||||
toolName,
|
||||
request.toolCallId
|
||||
)
|
||||
if (autoDecision) {
|
||||
void this.autoApprove(request, toolName, toolInput, autoDecision)
|
||||
return
|
||||
}
|
||||
|
||||
this.pendingBackendRequests.set(request.id, request)
|
||||
this.addPendingRequest(request.id, toolName, toolInput, {
|
||||
resolve: () => {},
|
||||
reject: () => {}
|
||||
})
|
||||
logger.debug(`[ACP] Permission request queued for ${toolName} (${request.id})`)
|
||||
}
|
||||
|
||||
private async autoApprove(
|
||||
request: PermissionRequest,
|
||||
toolName: string,
|
||||
toolInput: unknown,
|
||||
decision: AutoApprovalDecision
|
||||
): Promise<void> {
|
||||
await this.backend.respondToPermission(request.sessionId, request, mapDecisionToOutcome(request, decision))
|
||||
const timestamp = Date.now()
|
||||
this.client.updateAgentState((currentState) => ({
|
||||
...currentState,
|
||||
completedRequests: {
|
||||
...currentState.completedRequests,
|
||||
[request.id]: {
|
||||
tool: toolName,
|
||||
arguments: toolInput,
|
||||
createdAt: timestamp,
|
||||
completedAt: timestamp,
|
||||
status: 'approved',
|
||||
decision
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
protected async handlePermissionResponse(
|
||||
response: PermissionResponseMessage,
|
||||
pending: PendingPermissionRequest<void>
|
||||
): Promise<PermissionCompletion> {
|
||||
const request = this.pendingBackendRequests.get(response.id)
|
||||
this.pendingBackendRequests.delete(response.id)
|
||||
const decision = response.decision ?? (response.approved ? 'approved' : 'denied')
|
||||
|
||||
if (decision === 'abort' && request) {
|
||||
await this.backend.cancelPrompt(request.sessionId)
|
||||
}
|
||||
if (request) {
|
||||
await this.backend.respondToPermission(request.sessionId, request, mapDecisionToOutcome(request, decision))
|
||||
}
|
||||
pending.resolve()
|
||||
|
||||
return {
|
||||
status: response.approved ? 'approved' : 'denied',
|
||||
decision,
|
||||
reason: response.reason
|
||||
}
|
||||
}
|
||||
|
||||
protected handleMissingPendingResponse(response: PermissionResponseMessage): void {
|
||||
logger.debug('[ACP] Permission response received for unknown request', response.id)
|
||||
}
|
||||
|
||||
async cancelAll(reason: string): Promise<void> {
|
||||
const pending = Array.from(this.pendingBackendRequests.values())
|
||||
this.pendingBackendRequests.clear()
|
||||
for (const request of pending) {
|
||||
await this.backend.respondToPermission(request.sessionId, request, { outcome: 'cancelled' })
|
||||
}
|
||||
this.cancelPendingRequests({
|
||||
completedReason: reason,
|
||||
rejectMessage: reason,
|
||||
decision: 'abort'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -355,6 +355,21 @@ describe('buildCliArgs', () => {
|
||||
expect(args).not.toContain('--hapi-session-id')
|
||||
})
|
||||
|
||||
it('builds a remote DSH ACP runner command without unsupported policy flags', () => {
|
||||
const args = buildCliArgs('dsh', {
|
||||
directory: '/tmp',
|
||||
existingSessionId: 'existing-hub-id',
|
||||
startingMode: 'remote',
|
||||
permissionMode: 'read-only'
|
||||
}, true)
|
||||
expect(args).toEqual([
|
||||
'dsh',
|
||||
'--hapi-starting-mode', 'remote',
|
||||
'--started-by', 'runner',
|
||||
'--existing-session-id', 'existing-hub-id'
|
||||
])
|
||||
})
|
||||
|
||||
it('does not emit --hapi-session-id for a non-pty flavor', () => {
|
||||
const args = buildCliArgs('opencode', {
|
||||
directory: '/tmp',
|
||||
|
||||
@@ -1481,11 +1481,13 @@ export function buildCliArgs(
|
||||
? 'copilot'
|
||||
: agent === 'opencode'
|
||||
? 'opencode'
|
||||
: agent === 'pi'
|
||||
? 'pi'
|
||||
: agent === 'agy'
|
||||
? 'agy'
|
||||
: 'claude';
|
||||
: agent === 'dsh'
|
||||
? 'dsh'
|
||||
: agent === 'pi'
|
||||
? 'pi'
|
||||
: agent === 'agy'
|
||||
? 'agy'
|
||||
: 'claude';
|
||||
const args = [agentCommand];
|
||||
if (options.resumeSessionId) {
|
||||
if (agent === 'codex') {
|
||||
@@ -1512,6 +1514,7 @@ export function buildCliArgs(
|
||||
if (agent === 'codex' || agent === 'cursor' || agent === 'pi'
|
||||
|| agent === 'opencode'
|
||||
|| agent === 'agy'
|
||||
|| agent === 'dsh'
|
||||
|| (agentCommand === 'claude' && options.forkSession)) {
|
||||
const existingSessionId = options.existingSessionId ?? options.sessionId;
|
||||
if (existingSessionId) {
|
||||
@@ -1545,7 +1548,7 @@ export function buildCliArgs(
|
||||
}
|
||||
// Pi RPC mode has no permission switching; never pass these flags to it
|
||||
// (the Pi parser rejects --permission-mode and ignores --yolo).
|
||||
if (agent !== 'pi') {
|
||||
if (agent !== 'pi' && agent !== 'dsh') {
|
||||
if (options.permissionMode && (PERMISSION_MODES as readonly string[]).includes(options.permissionMode)) {
|
||||
args.push('--permission-mode', options.permissionMode);
|
||||
} else if (yolo) {
|
||||
|
||||
@@ -8,9 +8,10 @@ interface RemoteModeDisplayProps {
|
||||
logPath?: string
|
||||
onExit?: () => void
|
||||
onSwitchToLocal?: () => void
|
||||
agentLabel?: string
|
||||
}
|
||||
|
||||
export const RemoteModeDisplay: React.FC<RemoteModeDisplayProps> = ({ messageBuffer, logPath, onExit, onSwitchToLocal }) => {
|
||||
export const RemoteModeDisplay: React.FC<RemoteModeDisplayProps> = ({ messageBuffer, logPath, onExit, onSwitchToLocal, agentLabel = 'Claude' }) => {
|
||||
const [messages, setMessages] = useState<BufferedMessage[]>([])
|
||||
const { confirmationMode, actionInProgress } = useSwitchControls({
|
||||
onExit,
|
||||
@@ -70,7 +71,7 @@ export const RemoteModeDisplay: React.FC<RemoteModeDisplayProps> = ({ messageBuf
|
||||
overflow="hidden"
|
||||
>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="gray" bold>📡 Remote Mode - Claude Messages</Text>
|
||||
<Text color="gray" bold>📡 Remote Mode - {agentLabel} Messages</Text>
|
||||
<Text color="gray" dimColor>{'─'.repeat(Math.min(terminalWidth - 4, 60))}</Text>
|
||||
</Box>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user