From be1ef2a2e4d6d8836ca28695d86ccff47d0c03a3 Mon Sep 17 00:00:00 2001 From: SSU-WEI HUANG Date: Sat, 22 Aug 2026 12:37:28 +0800 Subject: [PATCH] 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 --- README.md | 4 +- .../feature/newsession/NewSessionForm.kt | 2 +- .../feature/newsession/NewSessionViewModel.kt | 2 +- .../newsession/NewSessionViewModelTest.kt | 11 ++ .../app/hapi/protocol/catalog/Flavors.kt | 5 +- .../kotlin/app/hapi/protocol/catalog/Modes.kt | 1 + .../app/hapi/protocol/catalog/CatalogTest.kt | 6 +- cli/README.md | 30 ++- cli/src/commands/claude.ts | 1 + cli/src/commands/dsh.test.ts | 23 +++ cli/src/commands/dsh.ts | 40 ++++ cli/src/commands/registry.ts | 2 + cli/src/dsh/dshRemoteLauncher.test.ts | 87 +++++++++ cli/src/dsh/dshRemoteLauncher.ts | 149 +++++++++++++++ cli/src/dsh/runDsh.ts | 89 +++++++++ cli/src/dsh/session.ts | 45 +++++ cli/src/dsh/types.ts | 1 + cli/src/dsh/utils/dshBackend.test.ts | 35 ++++ cli/src/dsh/utils/dshBackend.ts | 44 +++++ cli/src/kimi/utils/permissionHandler.ts | 173 +----------------- .../common/permission/AcpPermissionHandler.ts | 150 +++++++++++++++ cli/src/runner/buildCliArgs.test.ts | 15 ++ cli/src/runner/run.ts | 15 +- cli/src/ui/ink/RemoteModeDisplay.tsx | 5 +- docs/guide/agents.md | 36 +++- docs/guide/installation.md | 2 +- hub/src/sync/sessionModel.test.ts | 33 ++++ hub/src/sync/syncEngine.ts | 3 + hub/src/web/routes/machines.test.ts | 18 +- hub/src/web/routes/machines.ts | 8 +- .../Features/NewSession/NewSessionModel.swift | 2 +- .../NewSession/NewSessionForm.swift | 4 +- .../HapiProtocol/Catalog/AgentFlavor.swift | 14 +- .../Catalog/PermissionModes.swift | 2 + .../HapiProtocol/Models/SummaryPatching.swift | 1 + .../HapiClientTests/NewSessionFormTests.swift | 10 + .../HapiProtocolTests/CatalogTests.swift | 11 +- shared/fixtures/catalogs/modes.json | 1 + shared/src/agentConfig.test.ts | 10 + shared/src/agentConfig.ts | 2 + shared/src/flavors.test.ts | 7 + shared/src/flavors.ts | 2 + shared/src/modes.test.ts | 6 + shared/src/modes.ts | 5 +- shared/src/sessionSummary.test.ts | 13 ++ shared/src/sessionSummary.ts | 5 +- web/src/components/AgentFlavorIcon.tsx | 2 + web/src/components/NewSession/index.test.tsx | 15 ++ web/src/components/NewSession/index.tsx | 4 +- web/src/components/NewSession/types.ts | 1 + web/src/lib/sessionResume.test.ts | 9 + web/src/lib/sessionResume.ts | 1 + 52 files changed, 947 insertions(+), 215 deletions(-) create mode 100644 cli/src/commands/dsh.test.ts create mode 100644 cli/src/commands/dsh.ts create mode 100644 cli/src/dsh/dshRemoteLauncher.test.ts create mode 100644 cli/src/dsh/dshRemoteLauncher.ts create mode 100644 cli/src/dsh/runDsh.ts create mode 100644 cli/src/dsh/session.ts create mode 100644 cli/src/dsh/types.ts create mode 100644 cli/src/dsh/utils/dshBackend.test.ts create mode 100644 cli/src/dsh/utils/dshBackend.ts create mode 100644 cli/src/modules/common/permission/AcpPermissionHandler.ts diff --git a/README.md b/README.md index 13eda0f9..493c5250 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # HAPI -Run official Claude Code / Codex / Cursor Agent / Grok Build / OpenCode / Kimi / Copilot / Antigravity / Pi sessions locally and control them remotely through a Web / PWA / Telegram Mini App. +Run official Claude Code / Codex / Cursor Agent / Grok Build / OpenCode / Kimi / Copilot / Antigravity / Pi / DeepSeek Harness sessions and control them remotely through a Web / PWA / Telegram Mini App. > **Why HAPI?** HAPI is a local-first alternative to Happy. See [Why Not Happy?](docs/guide/why-hapi.md) for the key differences. @@ -9,7 +9,7 @@ Run official Claude Code / Codex / Cursor Agent / Grok Build / OpenCode / Kimi / - **Seamless Handoff** - Work locally, switch to remote when needed, switch back anytime. No context loss, no session restart. - **Native First** - HAPI wraps your AI agent instead of replacing it. Same terminal, same experience, same muscle memory. - **AFK Without Stopping** - Step away from your desk? Approve AI requests from your phone with one tap. -- **Your AI, Your Choice** - Claude Code, Codex, Cursor Agent, Grok Build, OpenCode, Kimi, Copilot, Antigravity, Pi—different agents, one unified workflow. +- **Your AI, Your Choice** - Claude Code, Codex, Cursor Agent, Grok Build, OpenCode, Kimi, Copilot, Antigravity, Pi, DeepSeek Harness—different agents, one unified workflow. - **Terminal Anywhere** - Run commands from your phone or browser, directly connected to the working machine. - **Voice Control** - Talk to your AI agent hands-free using the built-in voice assistant. - **Workspace Browser** - Opt-in via one or more `hapi runner start --workspace-root ` flags: browse scoped file trees from the web and start sessions in allowed subdirectories. diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionForm.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionForm.kt index 30d70981..1aef24e6 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionForm.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionForm.kt @@ -95,7 +95,7 @@ object NewSessionLogic { } else { null }, - yolo = if (isGrok || codexFamily) null else form.yolo, + yolo = if (agent == "dsh" || isGrok || codexFamily) null else form.yolo, permissionMode = if (isGrok || codexFamily) form.permissionMode else null, sessionType = form.sessionType, worktreeName = if (form.sessionType == SESSION_TYPE_WORKTREE) { diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModel.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModel.kt index ca43c7d9..dd8b4d7f 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModel.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModel.kt @@ -602,7 +602,7 @@ class NewSessionViewModel( } val permission: PermissionUi = when { - agent == "pi" -> PermissionUi.Managed + agent == "pi" || agent == "dsh" -> PermissionUi.Managed usesNativePermissionSelect(agent) -> PermissionUi.NativeSelect( PermissionModes.forFlavor(agent).map { OptionItem(it.wireId, it.label) }, ) diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModelTest.kt index d4d679e7..3b323eaf 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModelTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/newsession/NewSessionViewModelTest.kt @@ -212,6 +212,17 @@ class SpawnBodyTest { assertEquals(true, cursor["yolo"]!!.jsonPrimitive.boolean) } + @Test + fun `dsh uses managed permission policy and omits yolo`() { + val body = encode( + NewSessionLogic.buildSpawnRequest( + NewSessionForm(directory = "/repo", agent = "dsh", yolo = true), + codexFastTierVisible = false, + ), + ) + assertEquals(setOf("directory", "agent", "sessionType"), body.keys) + } + @Test fun `codex default selections send no optional fields, fast tier hidden sends no serviceTier`() { val body = encode( diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Flavors.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Flavors.kt index 671f3194..2e110d5b 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Flavors.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Flavors.kt @@ -13,6 +13,7 @@ sealed interface AgentFlavor { data object Agy : AgentFlavor { override val id = "agy" } data object Claude : AgentFlavor { override val id = "claude" } data object Codex : AgentFlavor { override val id = "codex" } + data object Dsh : AgentFlavor { override val id = "dsh" } data object Copilot : AgentFlavor { override val id = "copilot" } data object Cursor : AgentFlavor { override val id = "cursor" } data object Gemini : AgentFlavor { override val id = "gemini" } @@ -29,7 +30,7 @@ sealed interface AgentFlavor { companion object { /** `AGENT_FLAVORS` — declaration order preserved. */ val KNOWN: List = listOf( - Agy, Claude, Codex, Copilot, Cursor, Gemini, Grok, Kimi, Opencode, Pi, + Agy, Claude, Codex, Dsh, Copilot, Cursor, Gemini, Grok, Kimi, Opencode, Pi, ) /** @@ -67,6 +68,7 @@ object Flavors { "copilot" to setOf(FlavorCapability.ModelChange), "grok" to setOf(FlavorCapability.ModelChange, FlavorCapability.Effort), "codex" to setOf(FlavorCapability.ModelChange), + "dsh" to emptySet(), "cursor" to setOf(FlavorCapability.ModelChange), "opencode" to setOf(FlavorCapability.ModelChange), "pi" to setOf(FlavorCapability.ModelChange, FlavorCapability.Effort), @@ -80,6 +82,7 @@ object Flavors { "copilot" to "Copilot", "grok" to "Grok Build", "codex" to "Codex", + "dsh" to "DeepSeek Harness", "cursor" to "Cursor", "opencode" to "OpenCode", "pi" to "Pi", diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt index 67629111..c51a2619 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/catalog/Modes.kt @@ -87,6 +87,7 @@ object PermissionModes { "copilot" -> CODEX "grok" -> GROK "opencode" -> OPENCODE + "dsh" -> emptyList() "agy" -> AGY "cursor" -> CURSOR "pi" -> emptyList() diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt index 49267ba4..a24d1319 100644 --- a/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/catalog/CatalogTest.kt @@ -90,7 +90,7 @@ class CatalogTest { @Test fun `agent flavors match AGENT_FLAVORS and CREATABLE excludes gemini`() { assertEquals( - listOf("agy", "claude", "codex", "copilot", "cursor", "gemini", "grok", "kimi", "opencode", "pi"), + listOf("agy", "claude", "codex", "dsh", "copilot", "cursor", "gemini", "grok", "kimi", "opencode", "pi"), AgentFlavor.KNOWN.map { it.id } ) assertFalse(AgentFlavor.CREATABLE.contains(AgentFlavor.Gemini)) @@ -109,11 +109,13 @@ class CatalogTest { assertTrue(Flavors.supportsEffort("pi")) assertFalse(Flavors.supportsEffort("codex")) assertFalse(Flavors.supportsEffort(null)) - assertTrue(AgentFlavor.KNOWN.all { Flavors.supportsModelChange(it.id) }) + assertTrue(AgentFlavor.KNOWN.filter { it != AgentFlavor.Dsh }.all { Flavors.supportsModelChange(it.id) }) + assertFalse(Flavors.supportsModelChange("dsh")) assertFalse(Flavors.supportsModelChange("unknown")) assertEquals("Antigravity", Flavors.label("agy")) assertEquals("Grok Build", Flavors.label("grok")) assertEquals("OpenCode", Flavors.label("opencode")) + assertEquals("DeepSeek Harness", Flavors.label("dsh")) assertEquals("Unknown", Flavors.label("mystery")) assertTrue(Flavors.isCodexFamily("copilot")) assertFalse(Flavors.isCodexFamily("claude")) diff --git a/cli/README.md b/cli/README.md index 5cc146be..3f938d42 100644 --- a/cli/README.md +++ b/cli/README.md @@ -1,6 +1,6 @@ # hapi CLI -Run Claude Code, Codex, Cursor Agent, Grok Build, or OpenCode sessions from your terminal and control them remotely through the hapi hub. +Run Claude Code, Codex, Cursor Agent, Grok Build, OpenCode, or DeepSeek Harness sessions from your terminal and control them remotely through the hapi hub. ## What it does @@ -9,6 +9,7 @@ Run Claude Code, Codex, Cursor Agent, Grok Build, or OpenCode sessions from your - Starts Cursor Agent mode for Cursor CLI sessions. - Starts Grok Build locally or via ACP for remote sessions. - Starts OpenCode mode via ACP and its plugin hook system. +- Starts DeepSeek Harness through an external ACP stdio server. - Provides an MCP stdio bridge for external tools. - Manages a background runner for long-running sessions. - Includes diagnostics and auth helpers. @@ -33,6 +34,8 @@ Run Claude Code, Codex, Cursor Agent, Grok Build, or OpenCode sessions from your - `hapi grok` - Start Grok Build mode. See `src/grok/runGrok.ts`. - `hapi opencode` - Start OpenCode mode via ACP. See `src/opencode/runOpencode.ts`. Note: OpenCode supports local and remote modes; local mode streams via OpenCode plugins. +- `hapi dsh` - Start DeepSeek Harness through ACP. See `src/dsh/runDsh.ts`. + DSH is remote-only and its ACP server must be configured separately. - `hapi resume [sessionId]` - List resumable sessions for this machine or resume one locally. - `hapi ping-peer ` - Resume (if needed) and message another session. Prefer this or MCP `ping_peer` / `list_peers` over reinventing JWT+curl. Also `--message-file` / `--list`. - `hapi inspect-peer ` - Read-only peer metadata + recent message text (no resume). Prefer this or MCP `inspect_peer` when a user cites `[title](/sessions/)` or Copy-reference `See session "…" (/sessions/) for context`. `/sessions/` is a hub path, not a local file. Optional `--limit`. @@ -90,6 +93,28 @@ See `src/ui/doctor.ts`. See `src/configuration.ts` for all options. +DeepSeek Harness ACP uses `dsh-acp-demo` by default. Override the executable or +its arguments without shell parsing: + +```bash +export HAPI_DSH_ACP_COMMAND=dsh-acp-demo +export HAPI_DSH_ACP_CONFIG=/path/to/deepseek-harness/examples/acp-agent/cordis.yml +hapi dsh +``` + +For a source checkout, use JSON arguments: + +```bash +export HAPI_DSH_ACP_COMMAND=pnpm +export HAPI_DSH_ACP_ARGS_JSON='["--dir", "/path/to/deepseek-harness", "run", "demo:acp"]' +``` + +The official ACP demo is fresh-session-only and does not support native resume, +model switching, MCP injection, or live tool/reasoning telemetry. HAPI uses the +standard chat and pending one-shot permission surfaces; the ACP composition +owns the overall permission policy and HAPI does not advertise resume or model +controls for DSH. + ### Required - `CLI_API_TOKEN` - Shared secret; must match the hub. Can be set via env or `~/.hapi/settings.json` (env wins). @@ -101,6 +126,9 @@ See `src/configuration.ts` for all options. - `HAPI_EXPERIMENTAL` - Enable experimental features (true/1/yes). - `HAPI_EXTRA_HEADERS_JSON` - JSON object of extra headers to send on CLI → hub requests, e.g. `{"Cookie":"CF_Authorization=..."}`. Can also be set as the `extraHeaders` object in `~/.hapi/settings.json` (environment variable wins). - `HAPI_CLAUDE_PATH` - Path to a specific `claude` executable. +- `HAPI_DSH_ACP_COMMAND` - ACP server executable for `hapi dsh` (default: `dsh-acp-demo`). +- `HAPI_DSH_ACP_CONFIG` - Optional `dsh-acp-demo --config` path. +- `HAPI_DSH_ACP_ARGS_JSON` - Optional JSON array of ACP server arguments. - `HAPI_HTTP_MCP_URL` - Default MCP target for `hapi mcp`. ### Runner diff --git a/cli/src/commands/claude.ts b/cli/src/commands/claude.ts index 01401de2..3d7305a2 100644 --- a/cli/src/commands/claude.ts +++ b/cli/src/commands/claude.ts @@ -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) diff --git a/cli/src/commands/dsh.test.ts b/cli/src/commands/dsh.test.ts new file mode 100644 index 00000000..cdc08b83 --- /dev/null +++ b/cli/src/commands/dsh.test.ts @@ -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') + }) +}) diff --git a/cli/src/commands/dsh.ts b/cli/src/commands/dsh.ts new file mode 100644 index 00000000..33e9eb08 --- /dev/null +++ b/cli/src/commands/dsh.ts @@ -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) + } + } +} diff --git a/cli/src/commands/registry.ts b/cli/src/commands/registry.ts index 8bab771e..24d547dc 100644 --- a/cli/src/commands/registry.ts +++ b/cli/src/commands/registry.ts @@ -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, diff --git a/cli/src/dsh/dshRemoteLauncher.test.ts b/cli/src/dsh/dshRemoteLauncher.test.ts new file mode 100644 index 00000000..fb879c77 --- /dev/null +++ b/cli/src/dsh/dshRemoteLauncher.test.ts @@ -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> | 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 {} + } +})) + +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((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() + }) +}) diff --git a/cli/src/dsh/dshRemoteLauncher.ts b/cli/src/dsh/dshRemoteLauncher.ts new file mode 100644 index 00000000..42f214a8 --- /dev/null +++ b/cli/src/dsh/dshRemoteLauncher.ts @@ -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 | 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 { + return this.start({ onExit: () => this.handleExitFromUi() }) + } + + async kill(): Promise { + 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 { + 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 { + 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 { + 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 { + await this.requestExit('exit', () => this.handleAbort()) + } +} diff --git a/cli/src/dsh/runDsh.ts b/cli/src/dsh/runDsh.ts new file mode 100644 index 00000000..ed3004cf --- /dev/null +++ b/cli/src/dsh/runDsh.ts @@ -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 { + 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((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() + } +} diff --git a/cli/src/dsh/session.ts b/cli/src/dsh/session.ts new file mode 100644 index 00000000..920aaefa --- /dev/null +++ b/cli/src/dsh/session.ts @@ -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 { + readonly startedBy: 'runner' | 'terminal' + + constructor(opts: { + api: ApiClient + client: ApiSessionClient + path: string + logPath: string + messageQueue: MessageQueue2 + 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[0]): void => { + this.client.sendSessionEvent(event) + } +} diff --git a/cli/src/dsh/types.ts b/cli/src/dsh/types.ts new file mode 100644 index 00000000..2f354a6b --- /dev/null +++ b/cli/src/dsh/types.ts @@ -0,0 +1 @@ +export type DshMode = 'dsh' diff --git a/cli/src/dsh/utils/dshBackend.test.ts b/cli/src/dsh/utils/dshBackend.test.ts new file mode 100644 index 00000000..5a378f43 --- /dev/null +++ b/cli/src/dsh/utils/dshBackend.test.ts @@ -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') + }) +}) diff --git a/cli/src/dsh/utils/dshBackend.ts b/cli/src/dsh/utils/dshBackend.ts new file mode 100644 index 00000000..3cbcf589 --- /dev/null +++ b/cli/src/dsh/utils/dshBackend.ts @@ -0,0 +1,44 @@ +import { AcpSdkBackend } from '@/agent/backends/acp' + +type DshAcpEnvironment = Record + +function filterEnv(env: NodeJS.ProcessEnv): Record { + 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' + }) +} diff --git a/cli/src/kimi/utils/permissionHandler.ts b/cli/src/kimi/utils/permissionHandler.ts index 04cd0bb0..3aec5fc8 100644 --- a/cli/src/kimi/utils/permissionHandler.ts +++ b/cli/src/kimi/utils/permissionHandler.ts @@ -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 { - private readonly pendingBackendRequests = new Map(); - - 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 { - 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 - ): Promise { - 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 { - 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' diff --git a/cli/src/modules/common/permission/AcpPermissionHandler.ts b/cli/src/modules/common/permission/AcpPermissionHandler.ts new file mode 100644 index 00000000..11650c8a --- /dev/null +++ b/cli/src/modules/common/permission/AcpPermissionHandler.ts @@ -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 { + private readonly pendingBackendRequests = new Map() + + 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 { + 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 + ): Promise { + 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 { + 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' + }) + } +} diff --git a/cli/src/runner/buildCliArgs.test.ts b/cli/src/runner/buildCliArgs.test.ts index cd6e537a..8cf7be59 100644 --- a/cli/src/runner/buildCliArgs.test.ts +++ b/cli/src/runner/buildCliArgs.test.ts @@ -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', diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index ee1f9d54..1bba2f32 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -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) { diff --git a/cli/src/ui/ink/RemoteModeDisplay.tsx b/cli/src/ui/ink/RemoteModeDisplay.tsx index a83957bf..3b7401e6 100644 --- a/cli/src/ui/ink/RemoteModeDisplay.tsx +++ b/cli/src/ui/ink/RemoteModeDisplay.tsx @@ -8,9 +8,10 @@ interface RemoteModeDisplayProps { logPath?: string onExit?: () => void onSwitchToLocal?: () => void + agentLabel?: string } -export const RemoteModeDisplay: React.FC = ({ messageBuffer, logPath, onExit, onSwitchToLocal }) => { +export const RemoteModeDisplay: React.FC = ({ messageBuffer, logPath, onExit, onSwitchToLocal, agentLabel = 'Claude' }) => { const [messages, setMessages] = useState([]) const { confirmationMode, actionInProgress } = useSwitchControls({ onExit, @@ -70,7 +71,7 @@ export const RemoteModeDisplay: React.FC = ({ messageBuf overflow="hidden" > - 📡 Remote Mode - Claude Messages + 📡 Remote Mode - {agentLabel} Messages {'─'.repeat(Math.min(terminalWidth - 4, 60))} diff --git a/docs/guide/agents.md b/docs/guide/agents.md index ab7b1ef9..d83e6930 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -13,6 +13,7 @@ HAPI is a wrapper around AI coding agents. One CLI (`hapi `) starts any s | GitHub Copilot | `hapi copilot` | ACP (`copilot --acp --stdio`) | ✓ | ✓ | `default` `read-only` `safe-yolo` `yolo` | ✓ | | Kimi | `hapi kimi` | ACP (`kimi acp`) | ✓ | ✓ | `default` `read-only` `safe-yolo` `yolo` | ✓ | | OpenCode | `hapi opencode` | ACP (`opencode acp`) | ✓ | ✓ | `default` `plan` `yolo` | ✓ | +| DeepSeek Harness | `hapi dsh` | ACP (`dsh-acp-demo` or configured server) | — | ✓ | Managed by DSH ACP composition | — | | Antigravity (agy) | `hapi agy` | Headless print mode (per-turn `agy -p` + NDJSON) | — | ✓ | `request-review` `always-proceed` | ✓ | | Pi | `hapi pi` | `pi --mode rpc` (JSON-line RPC over stdio) | — | ✓ | none (always auto-approve) | ✓ | | Gemini CLI | — | **Removed** — Google sunset the consumer Gemini CLI (2026-06-18) | — | — | — | — | @@ -23,7 +24,7 @@ Gemini is no longer launchable: `hapi gemini` is kept as a tombstone command tha ### ACP -Most remote integrations speak the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) over stdio through a shared HAPI backend. ACP gives remote sessions bidirectional permission approval, plan/todo updates, question UI, model catalogs, and session resume via `session/load`. Cursor, Grok, Copilot, Kimi, and OpenCode remote sessions all run over ACP. +Most remote integrations speak the [Agent Client Protocol](https://agentclientprotocol.com) (ACP) over stdio through a shared HAPI backend. ACP gives remote sessions bidirectional permission approval, plan/todo updates, question UI, model catalogs, and session resume via `session/load`. Cursor, Grok, Copilot, Kimi, OpenCode, and DeepSeek Harness remote sessions all run over ACP. DSH's official ACP server is intentionally automation-only and currently supports fresh sessions, committed assistant output, cancellation, and one-shot permissions; it does not provide native resume, model switching, MCP injection, or live tool/reasoning telemetry. ### Permission modes @@ -31,7 +32,7 @@ Permission modes are per-agent — each flavor exposes its own set (see the matr ### Local and remote mode -Every session is either **local** (driven from the terminal) or **remote** (driven from web/phone). Switching is seamless and keeps the same session state: +Every session is either **local** (driven from the terminal) or **remote** (driven from web/phone). DSH is remote-only because its ACP server has no local terminal surface. Switching is seamless and keeps the same session state for flavors that support both: - **Remote → local:** press double-space in the terminal. - **Local → remote:** send a message from the web UI or phone; the session switches automatically. @@ -45,7 +46,7 @@ hapi resume # Interactive picker of resumable sessions on this ma hapi resume # Resume a specific HAPI session ``` -`hapi resume` works for every flavor except Gemini. An active remote session is handed off to the local terminal first. Pi and Antigravity are the exceptions in the other direction: neither has a local input path, so their sessions always resume in remote mode. +`hapi resume` works for every resumable flavor except Gemini and fresh-session-only DSH. An active remote session is handed off to the local terminal first. Pi and Antigravity are the exceptions in the other direction: neither has a local input path, so their sessions always resume in remote mode. ## Cursor Agent @@ -232,6 +233,35 @@ HAPI also exposes Grok's common slash commands, discovers skills from `.grok/ski If a remote session reports authentication failure, run `grok login --device-auth` on the runner machine and retry. +## DeepSeek Harness + +`hapi dsh` uses the shared ACP transport and keeps DSH's runtime outside HAPI. The +default executable is `dsh-acp-demo`; configure a different ACP server or a +source checkout with `HAPI_DSH_ACP_COMMAND`, `HAPI_DSH_ACP_CONFIG`, or the JSON +argument array `HAPI_DSH_ACP_ARGS_JSON`. + +The official demo is published as `@deepseek-ai/dsh-acp-demo`; use an exact +version such as `0.1.0-rc.7` rather than npm's stale `latest` tag: + +```bash +npm install -g @deepseek-ai/dsh-acp-demo@0.1.0-rc.7 +``` + +A published package still needs a DSH Cordis composition/config. A source +checkout can be launched directly: + +```bash +export HAPI_DSH_ACP_COMMAND=pnpm +export HAPI_DSH_ACP_ARGS_JSON='["--dir", "/path/to/deepseek-harness", "run", "demo:acp"]' +hapi dsh +``` + +DSH sessions are remote-only and fresh-session-only. HAPI does not inject MCP +servers or expose model/effort pickers because the official ACP contract leaves +those surfaces to the DSH composition. Pending one-shot permission requests +remain answerable in the standard HAPI UI, but the ACP composition owns the +overall permission policy. + ## Other agents - **Claude Code** (`hapi` / `hapi claude`) — the default and recommended flavor; local sessions wrap the native TUI, remote sessions drive the Claude Agent SDK. [Claude Code docs](https://docs.anthropic.com/en/docs/claude-code) diff --git a/docs/guide/installation.md b/docs/guide/installation.md index e4ede585..568865be 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -4,7 +4,7 @@ Install the HAPI CLI and set up the hub. ## Prerequisites -- At least one supported agent CLI installed (Claude Code, Codex, Cursor Agent, Grok Build, OpenCode, and more — see [Supported Agents](./agents.md)) +- At least one supported agent CLI installed (Claude Code, Codex, Cursor Agent, Grok Build, OpenCode, DeepSeek Harness ACP server, and more — see [Supported Agents](./agents.md)) Verify your CLI is installed: diff --git a/hub/src/sync/sessionModel.test.ts b/hub/src/sync/sessionModel.test.ts index 9886076d..989649c2 100644 --- a/hub/src/sync/sessionModel.test.ts +++ b/hub/src/sync/sessionModel.test.ts @@ -3132,6 +3132,39 @@ describe('session model', () => { } }) + it('does not infer a DSH resume target from stale Claude metadata', () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + const session = engine.getOrCreateSession( + 'local-resume-dsh-fresh-only', + { + path: '/tmp/project', + host: 'localhost', + machineId: 'machine-1', + flavor: 'dsh', + claudeSessionId: 'stale-claude-id' + }, + null, + 'default' + ) + + expect(engine.resolveLocalResumeTarget(session.id, 'default')).toEqual({ + type: 'error', + message: 'Resume session ID unavailable. Start a new session in this directory, or retry after the agent has initialized.', + code: 'resume_unavailable' + }) + } finally { + engine.stop() + } + }) + it('returns resume_unavailable when a cursor session lacks cursorSessionId', () => { const store = new Store(':memory:') const engine = new SyncEngine( diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 42067f5a..2bf0987e 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -2404,6 +2404,9 @@ export class SyncEngine { if (flavor === 'kimi') return metadata.kimiSessionId ?? null if (flavor === 'copilot') return metadata.copilotSessionId ?? null if (flavor === 'pi') return metadata.piSessionId ?? null + // The official DSH ACP server creates fresh sessions only; never fall + // through to a stale Claude id and advertise a false resume path. + if (flavor === 'dsh') return null return metadata.claudeSessionId ?? this.recoverClaudeSessionIdFromMessages(session.id, namespace) } diff --git a/hub/src/web/routes/machines.test.ts b/hub/src/web/routes/machines.test.ts index 280bd75b..1b0c06cf 100644 --- a/hub/src/web/routes/machines.test.ts +++ b/hub/src/web/routes/machines.test.ts @@ -250,7 +250,7 @@ describe('machines routes', () => { expect(captured![15]).toBe('remote') }) - it('rejects a non-remote AGY machine spawn', async () => { + it('rejects a non-remote headless-agent machine spawn', async () => { const machine = createMachine() const spawnSession = () => { throw new Error('must not spawn') } const engine = { @@ -262,13 +262,15 @@ describe('machines routes', () => { app.use('*', async (c, next) => { c.set('namespace', 'default'); await next() }) app.route('/api', createMachinesRoutes(() => engine as SyncEngine)) - for (const startingMode of ['local', 'pty']) { - const response = await app.request('/api/machines/machine-1/spawn', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ directory: '/tmp/x', agent: 'agy', startingMode }) - }) - expect(response.status).toBe(400) + for (const agent of ['agy', 'dsh']) { + for (const startingMode of ['local', 'pty']) { + const response = await app.request('/api/machines/machine-1/spawn', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ directory: '/tmp/x', agent, startingMode }) + }) + expect(response.status).toBe(400) + } } }) diff --git a/hub/src/web/routes/machines.ts b/hub/src/web/routes/machines.ts index 770e7031..205ef896 100644 --- a/hub/src/web/routes/machines.ts +++ b/hub/src/web/routes/machines.ts @@ -81,8 +81,12 @@ export function createMachinesRoutes(getSyncEngine: () => SyncEngine | null): Ho if (!parsed.success) { return c.json({ error: 'Invalid body' }, 400) } - if (parsed.data.agent === 'agy' && parsed.data.startingMode && parsed.data.startingMode !== 'remote') { - return c.json({ error: 'AGY only supports remote mode' }, 400) + if ( + (parsed.data.agent === 'agy' || parsed.data.agent === 'dsh') + && parsed.data.startingMode + && parsed.data.startingMode !== 'remote' + ) { + return c.json({ error: `${parsed.data.agent.toUpperCase()} only supports remote mode` }, 400) } const startingMode = parsed.data.startingMode diff --git a/ios/Hapi/Features/NewSession/NewSessionModel.swift b/ios/Hapi/Features/NewSession/NewSessionModel.swift index 401d0c00..a72902b9 100644 --- a/ios/Hapi/Features/NewSession/NewSessionModel.swift +++ b/ios/Hapi/Features/NewSession/NewSessionModel.swift @@ -278,7 +278,7 @@ final class NewSessionModel { var permission: PermissionUI { let agent = form.agent - if agent == .pi { + if agent == .pi || agent == .dsh { return .managed } if NewSessionLogic.usesNativePermissionSelect(agent) { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift index 7513095c..0b9e9c29 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/NewSession/NewSessionForm.swift @@ -134,7 +134,7 @@ public enum NewSessionLogic { case .claude, .grok: return .bypassPermissions case .agy: return .alwaysProceed case .codex, .copilot, .cursor, .gemini, .kimi, .opencode: return .yolo - case .pi, .other: return nil + case .dsh, .pi, .other: return nil } } @@ -174,7 +174,7 @@ public enum NewSessionLogic { modelReasoningEffort: (agent == .codex && form.modelReasoningEffort != "default") ? form.modelReasoningEffort : nil, - yolo: (isGrok || codexFamily) ? nil : form.yolo, + yolo: (agent == .dsh || isGrok || codexFamily) ? nil : form.yolo, permissionMode: (isGrok || codexFamily) ? form.permissionMode : nil, sessionType: form.sessionType, worktreeName: (form.sessionType == .worktree && !trimmedWorktreeName.isEmpty) diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/AgentFlavor.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/AgentFlavor.swift index 2a483b93..aa75a9b5 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/AgentFlavor.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/AgentFlavor.swift @@ -11,6 +11,7 @@ public enum AgentFlavor: Equatable, Hashable, Sendable { case agy case claude case codex + case dsh case copilot case cursor case gemini @@ -22,7 +23,7 @@ public enum AgentFlavor: Equatable, Hashable, Sendable { /// Order matches `AGENT_FLAVORS`. public static let knownFlavors: [AgentFlavor] = [ - .agy, .claude, .codex, .copilot, .cursor, .gemini, .grok, .kimi, .opencode, .pi, + .agy, .claude, .codex, .dsh, .copilot, .cursor, .gemini, .grok, .kimi, .opencode, .pi, ] /// Flavors offered when creating a new session (`CREATABLE_AGENT_FLAVORS`). @@ -42,6 +43,7 @@ extension AgentFlavor: RawRepresentable { case "agy": self = .agy case "claude": self = .claude case "codex": self = .codex + case "dsh": self = .dsh case "copilot": self = .copilot case "cursor": self = .cursor case "gemini": self = .gemini @@ -58,6 +60,7 @@ extension AgentFlavor: RawRepresentable { case .agy: return "agy" case .claude: return "claude" case .codex: return "codex" + case .dsh: return "dsh" case .copilot: return "copilot" case .cursor: return "cursor" case .gemini: return "gemini" @@ -91,6 +94,7 @@ extension AgentFlavor { case .agy: return "Antigravity" case .claude: return "Claude" case .codex: return "Codex" + case .dsh: return "DeepSeek Harness" case .copilot: return "Copilot" case .cursor: return "Cursor" case .gemini: return "Gemini" @@ -102,9 +106,13 @@ extension AgentFlavor { } } - /// `hasCapability(flavor, 'model-change')` — true for every known flavor. + /// `hasCapability(flavor, 'model-change')` — false for DSH's server-owned + /// model selection and unknown flavors. public var supportsModelChange: Bool { - isKnown + switch self { + case .dsh, .other: return false + default: return true + } } /// `hasCapability(flavor, 'effort')` — claude, grok, and pi only. diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift index 2145f338..1a32837c 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Catalog/PermissionModes.swift @@ -95,6 +95,8 @@ extension AgentFlavor { return [.default, .auto, .plan, .bypassPermissions] case .opencode: return [.default, .plan, .yolo] + case .dsh: + return [] case .agy: return [.requestReview, .alwaysProceed] case .cursor: diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift index 3d9348f7..6c3b5e5d 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift @@ -115,6 +115,7 @@ public enum SummaryPatching { switch AgentFlavor(rawValue: flavor) { case .claude: flavorSessionId = metadata.claudeSessionId case .codex: flavorSessionId = metadata.codexSessionId + case .dsh: flavorSessionId = nil case .gemini: flavorSessionId = metadata.geminiSessionId case .opencode: flavorSessionId = metadata.opencodeSessionId case .grok: flavorSessionId = metadata.grokSessionId diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift index 04eeca4a..f078b9ee 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/NewSessionFormTests.swift @@ -86,6 +86,16 @@ struct NewSessionSpawnBodyTests { """) } + @Test func dshUsesManagedPermissionPolicyAndOmitsYolo() throws { + let body = try canonicalBody( + NewSessionForm(directory: "/repo", agent: .dsh, yolo: true), + codexFastTierVisible: false + ) + #expect(body == """ + {"agent":"dsh","directory":"/repo","sessionType":"simple"} + """) + } + @Test func codexDefaultSelectionsSendNoOptionalFieldsAndHiddenFastTierNoServiceTier() throws { let body = try canonicalBody( NewSessionForm(directory: "/repo", agent: .codex, serviceTier: .fast), diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift index 2c806980..e7bc77ca 100644 --- a/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/CatalogTests.swift @@ -154,13 +154,13 @@ struct CatalogTests { @Test func knownFlavorsMatchAgentFlavorsOrder() { #expect(AgentFlavor.knownFlavors.map(\.rawValue) == [ - "agy", "claude", "codex", "copilot", "cursor", + "agy", "claude", "codex", "dsh", "copilot", "cursor", "gemini", "grok", "kimi", "opencode", "pi", ]) } @Test func creatableFlavorsExcludeOnlyGemini() { - #expect(AgentFlavor.creatableFlavors.count == 9) + #expect(AgentFlavor.creatableFlavors.count == 10) #expect(!AgentFlavor.creatableFlavors.contains(.gemini)) #expect(AgentFlavor.creatableFlavors.contains(.claude)) } @@ -180,6 +180,7 @@ struct CatalogTests { #expect(AgentFlavor.agy.displayLabel == "Antigravity") #expect(AgentFlavor.grok.displayLabel == "Grok Build") #expect(AgentFlavor.opencode.displayLabel == "OpenCode") + #expect(AgentFlavor.dsh.displayLabel == "DeepSeek Harness") #expect(AgentFlavor.other("x").displayLabel == "Unknown") #expect(flavorLabel(forFlavor: "pi") == "Pi") #expect(flavorLabel(forFlavor: nil) == "Unknown") @@ -196,10 +197,11 @@ struct CatalogTests { #expect(!supportsEffort(forFlavor: nil)) } - @Test func modelChangeIsSupportedByEveryKnownFlavor() { - for flavor in AgentFlavor.knownFlavors { + @Test func modelChangeIsSupportedByEveryModelConfigFlavor() { + for flavor in AgentFlavor.knownFlavors where flavor != .dsh { #expect(flavor.supportsModelChange, "\(flavor.rawValue) should support model change") } + #expect(!AgentFlavor.dsh.supportsModelChange) #expect(!AgentFlavor.other("x").supportsModelChange) #expect(!supportsModelChange(forFlavor: nil)) } @@ -211,6 +213,7 @@ struct CatalogTests { #expect(isCodexFamilyFlavor("kimi")) #expect(isCodexFamilyFlavor("copilot")) #expect(isCodexFamilyFlavor("opencode")) + #expect(!isCodexFamilyFlavor("dsh")) #expect(!isCodexFamilyFlavor("claude")) #expect(!isCodexFamilyFlavor("cursor")) #expect(!isCodexFamilyFlavor("pi")) diff --git a/shared/fixtures/catalogs/modes.json b/shared/fixtures/catalogs/modes.json index 2a676168..e83f63e5 100644 --- a/shared/fixtures/catalogs/modes.json +++ b/shared/fixtures/catalogs/modes.json @@ -125,6 +125,7 @@ "tone": "danger" } ], + "dsh": [], "gemini": [ { "label": "Default", diff --git a/shared/src/agentConfig.test.ts b/shared/src/agentConfig.test.ts index 50877ae9..3fc8e0a3 100644 --- a/shared/src/agentConfig.test.ts +++ b/shared/src/agentConfig.test.ts @@ -27,6 +27,16 @@ describe('agent config descriptors', () => { })) }) + test('reports DSH permission as managed by its ACP composition', () => { + const descriptor = getAgentConfigDescriptor('dsh') + expect(descriptor.fields).toEqual([expect.objectContaining({ + id: 'permission', + kind: 'status', + availability: 'managed' + })]) + expect(resolveHapiYoloPermissionMode('dsh')).toBeNull() + }) + test('reports Pi permission as managed rather than pretending YOLO applies', () => { const descriptor = getAgentConfigDescriptor('pi') expect(descriptor.fields).toContainEqual(expect.objectContaining({ diff --git a/shared/src/agentConfig.ts b/shared/src/agentConfig.ts index 919438ad..a5d2ce83 100644 --- a/shared/src/agentConfig.ts +++ b/shared/src/agentConfig.ts @@ -66,6 +66,7 @@ const BUILTIN_DESCRIPTORS: Record = { { id: 'serviceTier', section: 'settings', kind: 'select', optionSource: 'model', availability: 'both' }, { id: 'collaborationMode', section: 'settings', kind: 'select', optionSource: 'static', availability: 'both' } ), + dsh: fields(MANAGED_PERMISSION), copilot: fields({ ...MODEL, optionSource: 'directory' }, PERMISSION), cursor: fields({ id: 'model', section: 'model', kind: 'dependent-select', optionSource: 'machine', availability: 'both' }, PERMISSION), gemini: fields(MODEL, PERMISSION), @@ -109,6 +110,7 @@ export function resolveHapiYoloPermissionMode(flavor: AgentFlavor): PermissionMo case 'kimi': case 'opencode': return 'yolo' + case 'dsh': case 'pi': return null } diff --git a/shared/src/flavors.test.ts b/shared/src/flavors.test.ts index 988438da..065d8b27 100644 --- a/shared/src/flavors.test.ts +++ b/shared/src/flavors.test.ts @@ -28,6 +28,11 @@ describe('hasCapability', () => { expect(hasCapability('gemini', Capabilities.Effort)).toBe(false) }) + test('dsh has no runtime model or effort switching', () => { + expect(hasCapability('dsh', Capabilities.ModelChange)).toBe(false) + expect(hasCapability('dsh', Capabilities.Effort)).toBe(false) + }) + test('codex supports model-change but not effort', () => { expect(hasCapability('codex', Capabilities.ModelChange)).toBe(true) expect(hasCapability('codex', Capabilities.Effort)).toBe(false) @@ -79,6 +84,7 @@ describe('getFlavorLabel', () => { expect(getFlavorLabel('claude')).toBe('Claude') expect(getFlavorLabel('gemini')).toBe('Gemini') expect(getFlavorLabel('codex')).toBe('Codex') + expect(getFlavorLabel('dsh')).toBe('DeepSeek Harness') expect(getFlavorLabel('cursor')).toBe('Cursor') expect(getFlavorLabel('opencode')).toBe('OpenCode') expect(getFlavorLabel('pi')).toBe('Pi') @@ -103,6 +109,7 @@ describe('isKnownFlavor', () => { expect(isKnownFlavor('claude')).toBe(true) expect(isKnownFlavor('gemini')).toBe(true) expect(isKnownFlavor('codex')).toBe(true) + expect(isKnownFlavor('dsh')).toBe(true) expect(isKnownFlavor('cursor')).toBe(true) expect(isKnownFlavor('opencode')).toBe(true) expect(isKnownFlavor('pi')).toBe(true) diff --git a/shared/src/flavors.ts b/shared/src/flavors.ts index 5ad13dae..7cd111e0 100644 --- a/shared/src/flavors.ts +++ b/shared/src/flavors.ts @@ -17,6 +17,7 @@ const FLAVOR_CAPS: Record> = { copilot: new Set([Capabilities.ModelChange]), grok: new Set([Capabilities.ModelChange, Capabilities.Effort]), codex: new Set([Capabilities.ModelChange]), + dsh: new Set(), cursor: new Set([Capabilities.ModelChange]), opencode: new Set([Capabilities.ModelChange]), pi: new Set([Capabilities.ModelChange, Capabilities.Effort]), @@ -31,6 +32,7 @@ const FLAVOR_LABELS: Record = { copilot: 'Copilot', grok: 'Grok Build', codex: 'Codex', + dsh: 'DeepSeek Harness', cursor: 'Cursor', opencode: 'OpenCode', pi: 'Pi', diff --git a/shared/src/modes.test.ts b/shared/src/modes.test.ts index 69ab759f..4664313b 100644 --- a/shared/src/modes.test.ts +++ b/shared/src/modes.test.ts @@ -40,6 +40,10 @@ describe('getPermissionModesForFlavor', () => { ]) }) + test("returns no HAPI mode selector for DSH's server-owned permission policy", () => { + expect(getPermissionModesForFlavor('dsh')).toEqual([]) + }) + test("returns [] for flavor 'pi' (RPC mode has no runtime permission switching)", () => { expect(getPermissionModesForFlavor('pi')).toEqual([]) }) @@ -72,6 +76,8 @@ describe('isPermissionModeAllowedForFlavor', () => { expect(isPermissionModeAllowedForFlavor('acceptEdits', 'grok')).toBe(false) expect(isPermissionModeAllowedForFlavor('auto', 'grok')).toBe(true) expect(isPermissionModeAllowedForFlavor('yolo', 'grok')).toBe(false) + expect(isPermissionModeAllowedForFlavor('read-only', 'dsh')).toBe(false) + expect(isPermissionModeAllowedForFlavor('plan', 'dsh')).toBe(false) }) test("no mode is allowed for pi", () => { diff --git a/shared/src/modes.ts b/shared/src/modes.ts index 73162e49..1e502383 100644 --- a/shared/src/modes.ts +++ b/shared/src/modes.ts @@ -7,7 +7,7 @@ import { z } from 'zod' */ export const AGENT_MESSAGE_PAYLOAD_TYPE = 'codex' as const -export const AGENT_FLAVORS = ['agy', 'claude', 'codex', 'copilot', 'cursor', 'gemini', 'grok', 'kimi', 'opencode', 'pi'] as const +export const AGENT_FLAVORS = ['agy', 'claude', 'codex', 'dsh', 'copilot', 'cursor', 'gemini', 'grok', 'kimi', 'opencode', 'pi'] as const export type AgentFlavor = typeof AGENT_FLAVORS[number] export const AgentFlavorSchema = z.enum(AGENT_FLAVORS) @@ -139,6 +139,9 @@ export function getPermissionModesForFlavor(flavor?: string | null): readonly Pe if (flavor === 'kimi') { return KIMI_PERMISSION_MODES } + if (flavor === 'dsh') { + return [] + } if (flavor === 'copilot') { return COPILOT_PERMISSION_MODES } diff --git a/shared/src/sessionSummary.test.ts b/shared/src/sessionSummary.test.ts index 379b79dd..792dcba8 100644 --- a/shared/src/sessionSummary.test.ts +++ b/shared/src/sessionSummary.test.ts @@ -102,6 +102,19 @@ describe('toSessionSummary', () => { expect(summary.metadata?.agentSessionId).toBe('cursor-session-1') }) + it('does not claim a native resume token for fresh-only DSH ACP', () => { + const summary = toSessionSummary(makeSession({ + metadata: { + path: '/proj', + host: 'local', + flavor: 'dsh', + codexSessionId: 'stale-codex-id' + } + })) + + expect(summary.metadata?.agentSessionId).toBeUndefined() + }) + it('does not fall back to a stale cross-agent id for a known flavor', () => { const summary = toSessionSummary(makeSession({ metadata: { diff --git a/shared/src/sessionSummary.ts b/shared/src/sessionSummary.ts index bf8bc485..909afa3e 100644 --- a/shared/src/sessionSummary.ts +++ b/shared/src/sessionSummary.ts @@ -148,7 +148,7 @@ export function computeTodoProgress(todos: TodoItem[] | undefined): SessionSumma } } -const AGENT_SESSION_ID_FIELD_BY_FLAVOR = { +const AGENT_SESSION_ID_FIELD_BY_FLAVOR: Partial> = { claude: 'claudeSessionId', codex: 'codexSessionId', gemini: 'geminiSessionId', @@ -159,12 +159,13 @@ const AGENT_SESSION_ID_FIELD_BY_FLAVOR = { kimi: 'kimiSessionId', copilot: 'copilotSessionId', pi: 'piSessionId' -} as const satisfies Record +} function getSummaryAgentSessionId(metadata: Metadata): string | undefined { const flavor = metadata.flavor if (isKnownFlavor(flavor)) { const flavorField = AGENT_SESSION_ID_FIELD_BY_FLAVOR[flavor] + if (!flavorField) return undefined const flavorSessionId = metadata[flavorField] return typeof flavorSessionId === 'string' && flavorSessionId.trim() ? flavorSessionId.trim() diff --git a/web/src/components/AgentFlavorIcon.tsx b/web/src/components/AgentFlavorIcon.tsx index fa53977f..d31b8bd4 100644 --- a/web/src/components/AgentFlavorIcon.tsx +++ b/web/src/components/AgentFlavorIcon.tsx @@ -5,6 +5,7 @@ import AntigravityColor from '@lobehub/icons/es/Antigravity/components/Color' import ClaudeColor from '@lobehub/icons/es/Claude/components/Color' import CodexColor from '@lobehub/icons/es/Codex/components/Color' import CursorMono from '@lobehub/icons/es/Cursor/components/Mono' +import DeepSeekColor from '@lobehub/icons/es/DeepSeek/components/Color' import GeminiColor from '@lobehub/icons/es/Gemini/components/Color' import GrokMono from '@lobehub/icons/es/Grok/components/Mono' import KimiMono from '@lobehub/icons/es/Kimi/components/Mono' @@ -20,6 +21,7 @@ const FLAVOR_LOGOS: Record = { agy: AntigravityColor, claude: ClaudeColor, codex: CodexColor, + dsh: DeepSeekColor, cursor: CursorMono, gemini: GeminiColor, grok: GrokMono, diff --git a/web/src/components/NewSession/index.test.tsx b/web/src/components/NewSession/index.test.tsx index cc9f532b..b5c11cdd 100644 --- a/web/src/components/NewSession/index.test.tsx +++ b/web/src/components/NewSession/index.test.tsx @@ -525,6 +525,21 @@ describe('NewSession launch preferences', () => { await waitFor(() => expect(screen.getByTestId('create')).toBeDisabled()) }) + it('does not forward the global YOLO preference to managed DSH ACP', async () => { + savePreferredAgent('dsh') + savePreferredYoloMode(true) + mocks.spawnSession.mockResolvedValue({ type: 'success', sessionId: 'dsh-session' }) + render( {}} />) + + fireEvent.click(screen.getByTestId('create')) + await waitFor(() => expect(mocks.onSuccess).toHaveBeenCalledWith('dsh-session')) + expect(mocks.spawnSession).toHaveBeenCalledWith(expect.objectContaining({ + agent: 'dsh', + yolo: undefined, + permissionMode: undefined + })) + }) + it('keeps an explicit OpenCode Default selection instead of restoring a concrete model', async () => { savePreferredAgent('opencode') mocks.spawnSession.mockResolvedValue({ type: 'success', sessionId: 'opencode-session' }) diff --git a/web/src/components/NewSession/index.tsx b/web/src/components/NewSession/index.tsx index 44f07200..325e1383 100644 --- a/web/src/components/NewSession/index.tsx +++ b/web/src/components/NewSession/index.tsx @@ -1509,7 +1509,7 @@ export function NewSession(props: { model: resolvedModel, effort: resolvedEffort, modelReasoningEffort: resolvedModelReasoningEffort, - yolo: agent === 'grok' || usesCodexFamilyPermissions ? undefined : yoloMode, + yolo: agent === 'dsh' || agent === 'grok' || usesCodexFamilyPermissions ? undefined : yoloMode, permissionMode: agent === 'grok' ? grokPermissionMode : usesCodexFamilyPermissions @@ -1660,7 +1660,7 @@ export function NewSession(props: { onClear={() => setSelectedPiImportSessionId(null)} /> ) : null} - {agent === 'agy' ? ( + {agent === 'dsh' ? null : agent === 'agy' ? ( { }), 3)).toBe(true) }) + it('does not infer a DSH resume id from stale cross-flavor metadata', () => { + expect(resolveAgentSessionIdFromMetadata({ + path: '/p', + host: 'h', + flavor: 'dsh', + claudeSessionId: 'stale-claude-id' + })).toBeUndefined() + }) + it('inactiveSessionCanResume rejects non-recovering flavors with messages but no flavor-specific id', () => { expect(inactiveSessionCanResume(makeSession({ metadata: { path: '/tmp/project', host: 'localhost', flavor: 'grok' }, diff --git a/web/src/lib/sessionResume.ts b/web/src/lib/sessionResume.ts index 77ed5c77..5837d013 100644 --- a/web/src/lib/sessionResume.ts +++ b/web/src/lib/sessionResume.ts @@ -22,6 +22,7 @@ export function resolveAgentSessionIdFromMetadata( case 'kimi': return metadata.kimiSessionId ?? undefined case 'copilot': return metadata.copilotSessionId ?? undefined case 'pi': return metadata.piSessionId ?? undefined + case 'dsh': return undefined default: return metadata.claudeSessionId ?? undefined } }