Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Add local agent drivers and the LLM adapter

Fei2411b276faecbbc4
diff --git a/ds-bot/src/host/local-agents/acp.js b/ds-bot/src/host/local-agents/acp.js
new file mode 100644
index 00000000..10957d50
--- /dev/null
+++ b/ds-bot/src/host/local-agents/acp.js
@@ -0,0 +1,201 @@
+// The Agent Client Protocol engine: one child process per route, ACP over
+// stdio. A process multiplexes sessions: each DS Bot Session maps to one ACP
+// session, created or resumed with our loopback MCP server attached.
+import { spawn } from 'node:child_process'
+import { JsonRpcPeer, wireProcess, EventQueue } from './jsonrpc.js'
+import { cleanEnv } from './discover.js'
+
+const CLIENT = { name: 'ds-bot', version: '1' }
+
+// Events a driver reports, normalized for the adapter:
+// {type:'text'|'thought',text} | {type:'activity',text} (one compact line of the
+// agent's own work) | {type:'permission',id,action,detail,options,reply} |
+// {type:'done',reason} | {type:'error',error} | {type:'usage',usage}
+export class AcpEngine {
+ constructor(route, engine, { findExecutable }) {
+ this.route = route
+ this.engine = engine
+ this.findExecutable = findExecutable
+ this.child = undefined
+ this.peer = undefined
+ this.sessions = new Map()
+ this.caps = {}
+ }
+
+ async ensure() {
+ if (this.peer !== undefined) return this.peer
+ const bin = this.engine.command.startsWith('/') || this.engine.command.startsWith('~')
+ ? this.findExecutable(this.engine.command)
+ : this.findExecutable(this.engine.command)
+ if (bin === undefined) throw Object.assign(new Error(`${this.engine.name} is not installed`), { code: 'NO_ADAPTER' })
+ const child = spawn(bin, this.engine.args ?? [], {
+ env: cleanEnv(this.engine.env ?? {}),
+ stdio: ['pipe', 'pipe', 'inherit'],
+ windowsHide: true,
+ })
+ this.child = child
+ const peer = this.peer = new JsonRpcPeer(line => child.stdin.write(`${JSON.stringify(line)}\n`))
+ wireProcess(child, peer)
+ child.on('exit', (code, signal) => {
+ peer.close(new Error(`${this.engine.name} exited${signal ? ` (${signal})` : code !== null ? ` (${code})` : ''}`))
+ this.child = undefined
+ this.peer = undefined
+ for (const session of this.sessions.values()) {
+ session.dead = true
+ session.push({ type: 'error', error: new Error(`${this.engine.name} exited`) })
+ }
+ })
+ peer.notificationHandler = (method, params) => this.onNotice(method, params)
+ peer.requestHandler = (method, params) => this.onRequest(method, params)
+ const reply = await peer.request('initialize', {
+ protocolVersion: 1,
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
+ clientInfo: CLIENT,
+ }, { timeout: 30_000 })
+ this.caps = { mcpHttp: reply?.agentCapabilities?.mcpCapabilities?.http === true, mcpSse: reply?.agentCapabilities?.mcpCapabilities?.sse === true }
+ return peer
+ }
+
+ sessionFor(dshSessionId) {
+ let session = this.sessions.get(dshSessionId)
+ if (session === undefined) {
+ const queue = new EventQueue()
+ session = { dshSessionId, acpSessionId: undefined, dead: false, modes: [], push: event => queue.push(event), next: () => queue.next() }
+ this.sessions.set(dshSessionId, session)
+ }
+ return session
+ }
+
+ onNotice(method, params) {
+ if (method !== 'session/update') return
+ const update = params?.update ?? {}
+ const session = [...this.sessions.values()].find(entry => entry.acpSessionId === params?.sessionId)
+ if (session === undefined) return
+ switch (update.sessionUpdate) {
+ case 'agent_message_chunk': session.push({ type: 'text', text: textOf(update.content) }); break
+ case 'agent_thought_chunk': session.push({ type: 'thought', text: textOf(update.content) }); break
+ case 'tool_call':
+ case 'tool_call_update': {
+ const label = update.title ?? update.kind ?? 'tool'
+ const status = update.status
+ if (status === undefined || status === 'in_progress' || status === 'pending') session.push({ type: 'activity', text: `▸ ${label}` })
+ else if (status === 'failed') session.push({ type: 'activity', text: `▸ ${label} (failed)` })
+ break
+ }
+ case 'plan': session.push({ type: 'thought', text: planText(update.entries) }); break
+ case 'usage_update': {
+ const usage = usageOf(update)
+ if (usage !== undefined) session.push({ type: 'usage', usage })
+ break
+ }
+ default: break
+ }
+ }
+
+ // Agent → client requests: permission prompts bridge to the approval tool;
+ // the rest are refused — we hold no editor or terminal of our own.
+ onRequest(method, params) {
+ if (method === 'session/request_permission') {
+ const session = [...this.sessions.values()].find(entry => entry.acpSessionId === params?.sessionId)
+ if (session === undefined) return Promise.reject({ code: -32603, message: 'unknown session' })
+ const options = (params?.options ?? []).map(option => ({ optionId: option.optionId, name: option.name, kind: option.kind }))
+ return new Promise((resolve) => {
+ const id = `perm-${Math.random().toString(36).slice(2)}`
+ const reply = (optionId) => {
+ if (optionId === null) resolve({ outcome: { outcome: 'cancelled' } })
+ else resolve({ outcome: { outcome: 'selected', optionId } })
+ }
+ session.push({
+ type: 'permission', id, reply,
+ action: params?.toolCall?.title ?? params?.toolCall?.kind ?? 'The agent asks to run an action',
+ detail: detailText(params?.toolCall),
+ options,
+ })
+ })
+ }
+ return Promise.reject({ code: -32601, message: `method not found: ${method}` })
+ }
+
+ // A new or resumed ACP session for one DS Bot Session.
+ async open(dshSessionId, { cwd, mcp, resumeId, mode }) {
+ const peer = await this.ensure()
+ const session = this.sessionFor(dshSessionId)
+ const mcpServers = mcp === undefined ? [] : [{ type: 'http', name: 'dsbot', url: mcp.url, headers: [{ name: 'Authorization', value: `Bearer ${mcp.token}` }] }]
+ if (mcp !== undefined && this.caps.mcpHttp === false) throw Object.assign(new Error(`${this.engine.name} cannot use HTTP MCP servers; the team tools cannot reach it`), { code: 'NOT_SUPPORTED' })
+ const params = { cwd, mcpServers }
+ let reply
+ if (resumeId !== undefined) {
+ try {
+ reply = await peer.request('session/load', { ...params, sessionId: resumeId }, { timeout: 30_000 })
+ } catch {
+ reply = await peer.request('session/new', params, { timeout: 60_000 })
+ }
+ } else {
+ reply = await peer.request('session/new', params, { timeout: 60_000 })
+ }
+ session.acpSessionId = reply?.sessionId ?? resumeId
+ session.configOptions = reply?.configOptions ?? []
+ session.modes = reply?.modes?.availableModes ?? configOptionsOf(session.configOptions, 'mode')?.options ?? []
+ if (mode !== undefined) await this.setOption(session, 'mode', mode).catch(() => {})
+ return session
+ }
+
+ async setOption(session, category, value) {
+ const peer = await this.ensure()
+ try {
+ await peer.request('session/set_config_option', { sessionId: session.acpSessionId, configId: category, value }, { timeout: 15_000 })
+ } catch {
+ if (category === 'mode') await peer.request('session/set_mode', { sessionId: session.acpSessionId, modeId: value }, { timeout: 15_000 }).catch(() => {})
+ }
+ }
+
+ async prompt(session, blocks, { signal }) {
+ const peer = await this.ensure()
+ const reply = peer.request('session/prompt', { sessionId: session.acpSessionId, prompt: blocks }, { signal, timeout: undefined })
+ reply.then(
+ result => session.push({ type: 'done', reason: result?.stopReason ?? 'end_turn' }),
+ error => session.push({ type: 'error', error }),
+ )
+ return reply
+ }
+
+ cancel(session) {
+ this.peer?.notify('session/cancel', { sessionId: session.acpSessionId })
+ }
+
+ async close() {
+ const child = this.child
+ this.child = undefined
+ this.peer = undefined
+ if (child !== undefined) {
+ child.kill('SIGTERM')
+ setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 5_000).unref?.()
+ }
+ }
+
+ // Models the agent advertises on a probe session (configOptions 'model').
+ async listModels({ cwd, mcp }) {
+ const peer = await this.ensure()
+ const probe = await peer.request('session/new', { cwd, mcpServers: mcp === undefined ? [] : [{ type: 'http', name: 'dsbot', url: mcp.url, headers: [{ name: 'Authorization', value: `Bearer ${mcp.token}` }] }] }, { timeout: 60_000 })
+ const option = configOptionsOf(probe?.configOptions ?? [], 'model')
+ return (option?.options ?? []).map(entry => ({ id: String(entry.id ?? entry.value ?? entry.name), name: String(entry.name ?? entry.id ?? entry.value) }))
+ }
+}
+
+const configOptionsOf = (options, category) => options.find(option => (option.category ?? option.id) === category)
+const textOf = content => (Array.isArray(content) ? content : [content]).filter(block => block?.type === 'text').map(block => block.text).join('')
+const planText = entries => (entries ?? []).map(entry => `- ${entry.content ?? entry.title ?? ''}`).join('\n')
+const detailText = (toolCall) => {
+ if (toolCall === undefined) return ''
+ const parts = []
+ if (toolCall.rawInput !== undefined) parts.push(JSON.stringify(toolCall.rawInput))
+ if (Array.isArray(toolCall.locations) && toolCall.locations.length > 0) parts.push(toolCall.locations.map(location => location.path).join(', '))
+ return parts.join('\n').slice(0, 4_000)
+}
+const usageOf = update => {
+ const used = update.used ?? update
+ const input = used.inputTokens ?? used.input_tokens
+ const output = used.outputTokens ?? used.output_tokens
+ if (typeof input !== 'number' && typeof output !== 'number') return undefined
+ return { inputTokens: input ?? 0, outputTokens: output ?? 0 }
+}
diff --git a/ds-bot/src/host/local-agents/adapter.js b/ds-bot/src/host/local-agents/adapter.js
new file mode 100644
index 00000000..352aa1e0
--- /dev/null
+++ b/ds-bot/src/host/local-agents/adapter.js
@@ -0,0 +1,469 @@
+// The LlmAdapter that serves every local-agent route. A DS Bot Bot whose model
+// is one of these routes answers through a local agent CLI instead of a model
+// API: the loop, Sessions, tools and approvals are the ordinary ones; this
+// adapter turns each request into a prompt for the CLI session the Session is
+// mapped to, and the CLI's output back into stream chunks.
+import { createHash } from 'node:crypto'
+import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm'
+import { textOf } from '../text.js'
+import { engineOf, cliMode } from './engines.js'
+import { LoopbackMcp } from './mcp.js'
+
+export const DEFAULT_CONTEXT_WINDOW = 200_000
+// The replay window when a CLI session is new or its resume failed.
+const REPLAY_MESSAGES = 12
+const REPLAY_BYTES = 24 * 1024
+const IDLE_CLOSE_MS = 10 * 60_000
+const APPROVE_TOOL = 'approve_agent_action'
+
+// A title request never reaches the CLI.
+function titleChunk(text) {
+ const title = text.slice(0, 60)
+ return [
+ { type: 'block-start', index: 0, blockType: 'text' },
+ { type: 'text-delta', index: 0, text: title },
+ { type: 'block-end', index: 0, block: { type: 'text', text: title } },
+ { type: 'finish', reason: { kind: 'stop' } },
+ ]
+}
+
+// A compaction request neither: a deterministic digest of the messages.
+function digestChunks(messages) {
+ const lines = []
+ let used = 0
+ for (const message of messages ?? []) {
+ const text = textOf(message.content).replace(/\s+/g, ' ').trim()
+ if (text === '') continue
+ const line = `${message.role}: ${text.slice(0, 300)}`
+ if (used + line.length > 8 * 1024) break
+ lines.push(line)
+ used += line.length
+ }
+ const text = `[Earlier conversation, condensed]\n${lines.join('\n')}`
+ return [
+ { type: 'block-start', index: 0, blockType: 'text' },
+ { type: 'text-delta', index: 0, text },
+ { type: 'block-end', index: 0, block: { type: 'text', text } },
+ { type: 'finish', reason: { kind: 'stop' } },
+ ]
+}
+
+export class LocalAgentAdapter extends LlmAdapter {
+ // deps: {rt, findExecutable, spawnEngine(kind,route,engine), record(sessionId),
+ // saveRecord, dropRecord, presetFor(sessionId), toolsFor(options), signInHint(route)}
+ constructor(deps) {
+ super()
+ this.deps = deps
+ this.engines = new Map() // route -> engine driver
+ this.live = new Map() // sessionId -> live session
+ this.modelCache = new Map()
+ this.disposed = false
+ }
+
+ providerInfo(route) {
+ const engine = engineOf(route, this.deps.customAgents())
+ return { id: route, name: engine?.name ?? route }
+ }
+ providerRetryPolicy() { return undefined }
+ imageRequestPricing() { return undefined }
+
+ engine(route) {
+ let driver = this.engines.get(route)
+ if (driver === undefined) {
+ const spec = engineOf(route, this.deps.customAgents())
+ if (spec === undefined) throw new LlmError(`Unknown local agent ${route}`, 'NO_ADAPTER')
+ driver = this.deps.spawnEngine(spec.kind, route, spec)
+ this.engines.set(route, driver)
+ }
+ return driver
+ }
+
+ async listModels(route) {
+ const cached = this.modelCache.get(route)
+ if (cached !== undefined) return cached
+ const spec = engineOf(route, this.deps.customAgents())
+ if (spec === undefined) return []
+ const fallback = [{ provider: route, id: 'default', name: 'CLI default' }]
+ let models
+ try {
+ models = await this.engine(route).listModels({ cwd: this.deps.probeCwd(), mcp: undefined })
+ } catch {
+ models = []
+ }
+ const value = [...fallback, ...(models ?? []).filter(model => model.id !== 'default')
+ .map(model => ({ provider: route, id: model.id, name: model.name ?? model.id }))]
+ this.modelCache.set(route, value)
+ return value
+ }
+
+ dropModelCache(route) {
+ if (route === undefined) this.modelCache.clear()
+ else this.modelCache.delete(route)
+ }
+
+ async resolveModel(route, model) {
+ const spec = engineOf(route, this.deps.customAgents())
+ const listed = (await this.listModels(route).catch(() => [])).find(entry => entry.id === model)
+ return {
+ provider: route,
+ id: model,
+ name: listed?.name ?? model,
+ inputModalities: ['text', 'image'],
+ context: { contextWindow: spec?.contextWindow ?? DEFAULT_CONTEXT_WINDOW },
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // The live bridge for one DS Bot Session.
+ async liveFor(options) {
+ const sessionId = String(options.sessionId)
+ let live = this.live.get(sessionId)
+ const record = this.deps.record(sessionId)
+ if (live !== undefined && !live.dead && live.route === options.provider) return live
+ const route = options.provider
+ const spec = engineOf(route, this.deps.customAgents())
+ if (spec === undefined) throw new LlmError(`Unknown local agent ${route}`, 'NO_ADAPTER')
+ const engine = this.engine(route)
+ live = {
+ sessionId, route, spec, engine, dead: false,
+ record,
+ cliSessionId: record?.cliSessionId,
+ handed: record?.handedId,
+ promptHash: record?.promptHash,
+ engineSession: undefined,
+ mcp: undefined,
+ events: [],
+ waiters: [],
+ pending: new Map(), // dshCallId -> {name, mcpCallId?, reply?}
+ started: false,
+ idle: undefined,
+ cwd: record?.cwd,
+ model: options.model,
+ }
+ live.push = (event) => {
+ clearTimeout(live.idle)
+ live.idle = setTimeout(() => void this.closeLive(live, { idle: true }), IDLE_CLOSE_MS)
+ live.idle.unref?.()
+ const waiter = live.waiters.shift()
+ if (waiter !== undefined) waiter(event)
+ else live.events.push(event)
+ }
+ live.next = () => (live.events.length > 0 ? Promise.resolve(live.events.shift()) : new Promise(resolve => live.waiters.push(resolve)))
+ this.live.set(sessionId, live)
+ return live
+ }
+
+ async closeLive(live, { idle = false } = {}) {
+ if (live.dead) return
+ live.dead = true
+ clearTimeout(live.idle)
+ this.live.delete(live.sessionId)
+ live.mcp?.close()
+ if (idle) {
+ // The CLI session survives on the agent side; the process leaves and the
+ // next prompt resumes it.
+ live.engineSession = undefined
+ live.started = false
+ }
+ for (const waiter of live.waiters.splice(0)) waiter({ type: 'done', reason: 'stop' })
+ const stillUsed = [...this.live.values()].some(other => other.engine === live.engine && !other.dead)
+ if (!stillUsed) await live.engine.close?.().catch(() => {})
+ }
+
+ // The loopback MCP server for one live session; tools/call lands in its event queue.
+ async ensureMcp(live, tools) {
+ if (live.mcp !== undefined) return live.mcp
+ const mcp = new LoopbackMcp(() => tools, ({ name, arguments: args, callId }) => {
+ const dshCallId = `dsbot-${callId}`
+ return new Promise((resolve) => {
+ live.pending.set(dshCallId, { name, mcpCallId: callId, resolve })
+ live.push({ type: 'call', name, args, dshCallId })
+ })
+ })
+ await mcp.listen()
+ live.mcp = mcp
+ return mcp
+ }
+
+ // ---------------------------------------------------------------------------
+ async *stream(options) {
+ if (this.disposed) throw new LlmError('the local agents adapter is disposed', 'NO_ADAPTER')
+ if (options.purpose === 'session-title') {
+ const first = (options.messages ?? []).find(message => message.role === 'user')
+ const title = (textOf(first?.content).split('\n').find(line => line.trim() !== '') ?? 'Chat').trim()
+ yield* titleChunk(title === '' ? 'Chat' : title)
+ return
+ }
+ if (options.purpose === 'compaction') {
+ yield* digestChunks(options.messages)
+ return
+ }
+ const sessionId = options.sessionId
+ if (sessionId === undefined) throw new LlmError('a local agent request needs a session', 'INVALID_REQUEST')
+ const live = await this.liveFor(options)
+
+ // What the request carries past the last handed message. When the marker is
+ // gone the CLI session is stale or new: it gets a replay instead of a delta.
+ const messages = options.messages ?? []
+ const at = live.handed === undefined ? -1 : messages.findIndex(message => message.id === live.handed)
+ const fresh = live.handed === undefined || at === -1
+ const delta = fresh ? [] : messages.slice(at + 1)
+
+ // Results of the calls the last step emitted answer the suspended CLI calls.
+ for (const message of delta) {
+ if (message.role !== 'tool') continue
+ const pending = live.pending.get(message.toolCallId ?? message.source?.callId)
+ if (pending === undefined) continue
+ live.pending.delete(message.toolCallId ?? message.source?.callId)
+ pending.resolve({ text: textOf(message.content) || (message.isError ? 'the call failed' : ''), isError: message.isError === true })
+ }
+ const users = delta.filter(message => message.role === 'user')
+ // A turn that ended with a question still open resolves it with the user's
+ // next message; the rest, if any, are new input.
+ const answers = [...live.pending.values()]
+ const remaining = []
+ for (const message of users) {
+ const pending = answers.shift()
+ if (pending !== undefined && ![...live.pending.values()].includes(pending)) { remaining.push(message); continue }
+ if (pending !== undefined) {
+ for (const [id, entry] of live.pending) if (entry === pending) { live.pending.delete(id); pending.resolve({ text: textOf(message.content) }) }
+ } else {
+ remaining.push(message)
+ }
+ }
+
+ const system = messages.filter(message => message.role === 'system').map(message => textOf(message.content)).join('\n').trim()
+ const promptHash = system === '' ? undefined : createHash('sha256').update(system).digest('hex')
+ const mcp = await this.ensureMcp(live, () => this.deps.toolsFor(options))
+ const cwd = live.cwd ?? await this.deps.cwdFor(sessionId)
+ live.cwd = cwd
+
+ const preset = this.deps.presetFor(sessionId)
+ const mode = cliMode(live.spec.kind, preset, live.engineSession?.modes)
+ const instructions = system === '' ? undefined : system
+
+ const freshCli = live.cliSessionId === undefined
+ if (live.engineSession === undefined) {
+ const openArgs = {
+ cwd,
+ mcp,
+ resumeId: live.cliSessionId,
+ mode,
+ model: options.model,
+ // Codex carries the team instructions as developer config on a new
+ // thread; Claude gets them appended at spawn; ACP reads them in the
+ // first prompt below.
+ instructions: live.spec.kind === 'codex' && freshCli ? instructions : undefined,
+ system: live.spec.kind === 'claude' ? instructions : undefined,
+ }
+ live.engineSession = await live.engine.open(sessionId, openArgs)
+ .catch(error => { throw toLlmError(error, live) })
+ live.cliSessionId = live.engineSession.acpSessionId ?? live.engineSession.threadId ?? live.engineSession.cliSessionId
+ live.started = true
+ // The session's events feed this Session's queue: a call from any engine
+ // kind reaches drain() through live.next().
+ const session = live.engineSession
+ const token = live.pumpToken = {}
+ void (async () => {
+ while (live.pumpToken === token && !live.dead) {
+ const event = await session.next()
+ if (live.pumpToken === token && !live.dead) live.push(event)
+ }
+ })()
+ if (live.spec.kind !== 'acp' && instructions !== undefined) live.promptHash = promptHash
+ this.deps.saveRecord(sessionId, { route: live.route, cliSessionId: live.cliSessionId, cwd, handedId: live.handed, promptHash: live.promptHash ?? promptHash, model: options.model })
+ }
+
+ let promptText = fresh ? renderReplay(messages, system)
+ : remaining.map(message => textOf(message.content)).filter(text => text !== '').join('\n\n')
+ let sentInstructions = live.spec.kind !== 'acp' && freshCli && instructions !== undefined
+ if (instructions !== undefined && live.promptHash !== promptHash) {
+ const updated = `Updated team instructions (replace earlier ones):\n\n${instructions}`
+ if (live.spec.kind === 'codex') {
+ await live.engine.instruct?.(live.engineSession, updated)
+ sentInstructions = true
+ } else if (promptText !== '' || live.spec.kind === 'acp' || live.spec.kind === 'claude') {
+ promptText = `${updated}\n\n${promptText}`
+ sentInstructions = true
+ }
+ }
+ if (promptText !== '') {
+ this.sendPrompt(live, promptText, options.signal)
+ if (sentInstructions) live.promptHash = promptHash
+ // ACP only counts instructions once they reach the agent with a prompt.
+ if (live.spec.kind === 'acp' && (freshCli || sentInstructions)) live.promptHash = promptHash
+ }
+ if (live.spec.kind === 'acp' && freshCli && promptText === '' && instructions !== undefined) {
+ this.sendPrompt(live, `Follow these instructions from the user's team for everything you do here. They sit on top of your own; when they conflict, these win.\n\n${instructions}`, options.signal)
+ live.promptHash = promptHash
+ }
+
+ // The last DSH message is handed now; a later call sends only what follows.
+ const last = messages.at(-1)
+ if (last !== undefined) {
+ live.handed = last.id
+ this.deps.saveRecord(sessionId, { route: live.route, cliSessionId: live.cliSessionId, cwd, handedId: live.handed, promptHash: live.promptHash ?? promptHash, model: options.model })
+ }
+
+ yield* this.drain(live, options)
+ }
+
+ // Prompt the engine. The request stays open for the whole turn (ACP
+ // session/prompt ends when the agent's turn does), so it is sent but not
+ // awaited: the drain below consumes the turn's events, bridged calls
+ // included. A send failure lands in the queue as an error event.
+ sendPrompt(live, text, signal) {
+ try {
+ Promise.resolve(live.engine.prompt(live.engineSession, [{ type: 'text', text }], { signal }))
+ .catch(error => live.push({ type: 'error', error }))
+ } catch (error) {
+ live.push({ type: 'error', error })
+ }
+ }
+
+ // Consume the CLI's events until the turn ends or a bridged call suspends it.
+ async *drain(live, options) {
+ let index = 0
+ let textBuf = ''
+ let textIndex = -1
+ let thinkBuf = ''
+ let thinkIndex = -1
+ // Open text and reasoning stay open in parallel; each closes when it has to.
+ const closeBlocks = function* () {
+ if (textIndex !== -1) { yield { type: 'block-end', index: textIndex, block: { type: 'text', text: textBuf } }; textIndex = -1; textBuf = '' }
+ if (thinkIndex !== -1) { yield { type: 'block-end', index: thinkIndex, block: { type: 'reasoning', text: thinkBuf } }; thinkIndex = -1; thinkBuf = '' }
+ }
+ const emitCalls = (calls) => {
+ const chunks = []
+ calls.forEach((call, offset) => {
+ const at = index + offset
+ chunks.push(
+ { type: 'block-start', index: at, blockType: 'tool-call' },
+ { type: 'tool-call-delta', index: at, id: call.dshCallId, name: call.name, argumentsDelta: JSON.stringify(call.args ?? {}) },
+ { type: 'block-end', index: at, block: { type: 'tool-call', id: call.dshCallId, name: call.name, arguments: JSON.stringify(call.args ?? {}) } },
+ )
+ })
+ index += calls.length
+ return chunks
+ }
+ const abortable = promise => Promise.race([
+ promise,
+ new Promise((_, reject) => {
+ if (options.signal?.aborted) reject(options.signal.reason ?? new Error('aborted'))
+ else options.signal?.addEventListener('abort', () => reject(options.signal.reason ?? new Error('aborted')), { once: true })
+ }),
+ ])
+ for (;;) {
+ const event = await abortable(live.next()).catch(error => ({ type: 'abort', error }))
+ if (event.type === 'abort') {
+ live.engine.cancel?.(live.engineSession)
+ live.mcp?.failAll(new Error('the turn was stopped'))
+ for (const pending of live.pending.values()) pending.resolve({ text: 'the turn was stopped', isError: true })
+ live.pending.clear()
+ yield { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'the turn was stopped' } } }
+ return
+ }
+ switch (event.type) {
+ case 'text': {
+ if (textIndex === -1) {
+ if (thinkIndex !== -1) { yield { type: 'block-end', index: thinkIndex, block: { type: 'reasoning', text: thinkBuf } }; thinkIndex = -1; thinkBuf = '' }
+ yield { type: 'block-start', index: index++, blockType: 'text' }
+ textIndex = index - 1
+ }
+ textBuf += event.text
+ yield { type: 'text-delta', index: textIndex, text: event.text }
+ break
+ }
+ case 'thought':
+ case 'activity': {
+ const text = event.type === 'activity' ? `${event.text}\n` : event.text
+ if (thinkIndex === -1) {
+ if (textIndex !== -1) { yield { type: 'block-end', index: textIndex, block: { type: 'text', text: textBuf } }; textIndex = -1; textBuf = '' }
+ yield { type: 'block-start', index: index++, blockType: 'reasoning' }
+ thinkIndex = index - 1
+ }
+ thinkBuf += text
+ yield { type: 'reasoning-delta', index: thinkIndex, text }
+ break
+ }
+ case 'usage': yield { type: 'usage', usage: event.usage }; break
+ case 'call': {
+ yield* closeBlocks()
+ // A team tool the CLI invoked over the loopback MCP server.
+ for (const chunk of emitCalls([{ name: event.name, args: event.args, dshCallId: event.dshCallId }])) yield chunk
+ yield { type: 'finish', reason: { kind: 'tool-calls' } }
+ return
+ }
+ case 'permission': {
+ yield* closeBlocks()
+ // The CLI's own permission prompt, bridged as an approval tool call.
+ const call = { name: APPROVE_TOOL, args: { action: event.action, ...(event.detail ? { detail: event.detail } : {}) }, dshCallId: event.id }
+ live.pending.set(event.id, { name: APPROVE_TOOL, resolve: (result) => event.reply(pickAllowOption(event.options, result)) })
+ for (const chunk of emitCalls([call])) yield chunk
+ yield { type: 'finish', reason: { kind: 'tool-calls' } }
+ return
+ }
+ case 'done': {
+ yield* closeBlocks()
+ if (event.usage !== undefined) yield { type: 'usage', usage: event.usage }
+ yield { type: 'finish', reason: { kind: 'stop' } }
+ return
+ }
+ case 'error': {
+ throw toLlmError(event.error, live)
+ }
+ default: break
+ }
+ }
+ }
+
+ async dispose() {
+ this.disposed = true
+ for (const live of [...this.live.values()]) await this.closeLive(live)
+ for (const live of Array.from(this.live.values())) await this.closeLive(live)
+ for (const engine of Array.from(this.engines.values())) await engine.close?.().catch(() => {})
+ this.engines.clear()
+ }
+}
+
+// The result DSH gives approve_agent_action decides the agent's option:
+// 'allow' picks the first allow-kind option; anything else fails closed.
+function pickAllowOption(options, result) {
+ const allowed = result.isError !== true && /allow|yes|approve/i.test(result.text ?? '')
+ if (!allowed) return null
+ const option = (options ?? []).find(entry => /allow/.test(entry.kind ?? ''))
+ return option?.optionId ?? null
+}
+
+// The replay a fresh CLI session stands up on: the system prompt, then the
+// recent messages rendered as text, newest first, always with the latest input.
+function renderReplay(messages, system) {
+ const picked = []
+ let used = 0
+ const body = (messages ?? []).filter(message => message.role !== 'system')
+ const latest = body.at(-1)
+ for (const message of [...body].reverse()) {
+ const line = `${message.role === 'assistant' ? 'You' : message.role === 'tool' ? `Tool result (${message.toolCallId ?? 'call'})` : 'User'}: ${textOf(message.content).slice(0, 2_000)}`
+ if (message === latest) { picked.unshift(line); used += line.length; continue }
+ if (picked.length >= REPLAY_MESSAGES || used + line.length > REPLAY_BYTES) break
+ picked.unshift(line)
+ used += line.length
+ }
+ if (picked.length === 0) return ''
+ const head = system === '' ? '' : `The team instructions for this conversation:\n${system}\n\n`
+ return `${head}The conversation so far (oldest first):\n\n${picked.join('\n\n')}`
+}
+
+// Process exits, missing CLIs, quota and sign-in failures get typed codes so DS
+// Bot's repair card can act on them.
+function toLlmError(error, live) {
+ if (error instanceof LlmError) return error
+ const text = String(error?.message ?? error)
+ const code = error?.code === 'NO_ADAPTER' ? 'LOCAL_AGENT_MISSING'
+ : /not signed in|not logged in|login required|unauthorized|authentication/i.test(text) ? 'LOCAL_AGENT_SIGNIN'
+ : /quota|rate.?limit|usage limit|exceeded/i.test(text) ? 'LOCAL_AGENT_QUOTA'
+ : /exited|spawn|ENOENT/i.test(text) ? 'LOCAL_AGENT_EXIT'
+ : error?.code ?? 'LOCAL_AGENT_ERROR'
+ const hint = code === 'LOCAL_AGENT_SIGNIN' ? ` Sign in with: ${live?.spec?.signIn ?? `${live?.spec?.command ?? 'the CLI'} login`}.` : ''
+ return new LlmError(`${text}${hint}`, code, error?.status === undefined ? {} : { status: error.status })
+}
diff --git a/ds-bot/src/host/local-agents/claude.js b/ds-bot/src/host/local-agents/claude.js
new file mode 100644
index 00000000..ac0ca65b
--- /dev/null
+++ b/ds-bot/src/host/local-agents/claude.js
@@ -0,0 +1,179 @@
+// The Claude Code engine: one process per session, stream-json both ways.
+// stdin takes user/control JSON messages; stdout streams the assistant's
+// events until a `result` ends the turn.
+import { spawn } from 'node:child_process'
+import { cleanEnv } from './discover.js'
+
+export class ClaudeEngine {
+ constructor(route, engine, { findExecutable }) {
+ this.route = route
+ this.engine = engine
+ this.findExecutable = findExecutable
+ this.sessions = new Map()
+ }
+
+ // A live process holds its own event queue; the adapter drains it.
+ open(dshSessionId, { cwd, resumeId, system, mode, mcp, model }) {
+ let session = this.sessions.get(dshSessionId)
+ if (session !== undefined && session.dead) session = undefined
+ if (session === undefined) {
+ session = new ClaudeSession(this, dshSessionId)
+ this.sessions.set(dshSessionId, session)
+ }
+ return session.start({ cwd, resumeId, system, mode, mcp, model })
+ }
+
+ prompt(session, blocks) {
+ return session.prompt(blocks)
+ }
+
+ cancel(session) {
+ session.cancel()
+ }
+
+ async listModels() {
+ return ['default', 'opus', 'sonnet', 'haiku'].map(id => ({ id, name: id === 'default' ? 'CLI default' : id }))
+ }
+
+ async close() {
+ for (const session of this.sessions.values()) session.kill()
+ }
+}
+
+class ClaudeSession {
+ constructor(engine, dshSessionId) {
+ this.engine = engine
+ this.dshSessionId = dshSessionId
+ this.events = []
+ this.waiters = []
+ this.dead = false
+ }
+
+ emit(event) {
+ const waiter = this.waiters.shift()
+ if (waiter !== undefined) waiter(event)
+ else this.events.push(event)
+ }
+ next() {
+ if (this.events.length > 0) return Promise.resolve(this.events.shift())
+ return new Promise(resolve => this.waiters.push(resolve))
+ }
+
+ write(message) {
+ try { this.child?.stdin.write(`${JSON.stringify(message)}\n`) } catch { this.dead = true }
+ }
+
+ async start({ cwd, resumeId, system, mode, mcp, model }) {
+ if (this.child !== undefined) return this
+ const bin = this.engine.findExecutable(this.engine.engine.command)
+ if (bin === undefined) throw Object.assign(new Error(`${this.engine.engine.name} is not installed`), { code: 'NO_ADAPTER' })
+ // Fixture scripts in tests ride in spec.args ahead of the real CLI flags.
+ const args = [...(this.engine.engine.args ?? []), '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose']
+ if (resumeId !== undefined) args.push('--resume', resumeId)
+ if (system !== undefined) args.push('--append-system-prompt', system)
+ if (mode !== undefined) args.push('--permission-mode', mode)
+ if (model !== undefined && model !== 'default') args.push('--model', model)
+ if (mcp !== undefined) {
+ args.push('--mcp-config', JSON.stringify({
+ mcpServers: { dsbot: { type: 'http', url: mcp.url, headers: { Authorization: `Bearer ${mcp.token}` } } },
+ }))
+ }
+ const child = this.child = spawn(bin, args, {
+ env: cleanEnv(this.engine.env ?? {}),
+ cwd,
+ stdio: ['pipe', 'pipe', 'inherit'],
+ windowsHide: true,
+ })
+ let rest = ''
+ child.stdout.setEncoding('utf8')
+ child.stdout.on('data', (chunk) => {
+ rest += chunk
+ let at
+ while ((at = rest.indexOf('\n')) !== -1) {
+ const line = rest.slice(0, at).trim()
+ rest = rest.slice(at + 1)
+ if (line !== '') this.onLine(line)
+ }
+ })
+ child.on('exit', () => {
+ this.dead = true
+ this.emit({ type: 'error', error: new Error(`${this.engine.engine.name} exited`) })
+ })
+ this.started = new Promise((resolve, reject) => {
+ this.onInit = resolve
+ setTimeout(() => reject(new Error('the agent did not start')), 60_000).unref?.()
+ })
+ return this.started.then(() => this)
+ }
+
+ onLine(line) {
+ let event
+ try { event = JSON.parse(line) } catch { return }
+ switch (event?.type) {
+ case 'system':
+ if (event.subtype === 'init') {
+ this.cliSessionId = event.session_id
+ this.onInit?.(this)
+ }
+ break
+ case 'assistant': {
+ for (const block of event.message?.content ?? []) {
+ if (block.type === 'text') this.emit({ type: 'text', text: block.text ?? '' })
+ else if (block.type === 'thinking') this.emit({ type: 'thought', text: block.thinking ?? '' })
+ else if (block.type === 'tool_use') this.emit({ type: 'activity', text: `▸ ${block.name ?? 'tool'}` })
+ }
+ break
+ }
+ case 'control_request': {
+ const request = event.request ?? {}
+ if (request.subtype === 'can_use_tool') {
+ const tool = request.tool_name ?? 'tool'
+ this.emit({
+ type: 'permission', id: event.request_id,
+ reply: (allowed) => this.write({
+ type: 'control_response',
+ response: { subtype: 'success', request_id: event.request_id, response: allowed === null ? { behavior: 'deny' } : { behavior: 'allow', updatedInput: request.input ?? {} } },
+ }),
+ action: `Run ${tool}`,
+ detail: JSON.stringify(request.input ?? {}).slice(0, 4_000),
+ options: [{ optionId: 'allow', kind: 'allow_once', name: 'Allow' }, { optionId: 'deny', kind: 'reject_once', name: 'Deny' }],
+ })
+ }
+ break
+ }
+ case 'result':
+ this.emit(event.subtype === 'success' || event.is_error !== true
+ ? { type: 'done', reason: 'stop', usage: usageOf(event.usage) }
+ : { type: 'error', error: new Error(event.result ?? 'the agent failed') })
+ break
+ default: break
+ }
+ }
+
+ prompt(blocks) {
+ this.write({ type: 'user', message: { role: 'user', content: blocks } })
+ return Promise.resolve()
+ }
+
+ async steer(thread, text) {
+ this.prompt([{ type: 'text', text }])
+ }
+
+ cancel() {
+ // The documented interrupt asks the turn to stop cleanly.
+ this.write({ type: 'control_request', request: { subtype: 'interrupt' } })
+ }
+
+ kill() {
+ this.dead = true
+ this.child?.kill('SIGTERM')
+ setTimeout(() => { try { this.child?.kill('SIGKILL') } catch {} }, 5_000).unref?.()
+ this.child = undefined
+ }
+}
+
+const usageOf = usage => (usage === undefined ? undefined : {
+ inputTokens: usage.input_tokens ?? 0,
+ outputTokens: usage.output_tokens ?? 0,
+ ...(usage.cache_read_input_tokens ? { cacheReadTokens: usage.cache_read_input_tokens } : {}),
+})
diff --git a/ds-bot/src/host/local-agents/codex.js b/ds-bot/src/host/local-agents/codex.js
new file mode 100644
index 00000000..bd0b4a6e
--- /dev/null
+++ b/ds-bot/src/host/local-agents/codex.js
@@ -0,0 +1,175 @@
+// The Codex app-server engine: `codex app-server --listen stdio://`, one
+// JSON-RPC process per route that multiplexes threads. DS Bot Sessions map to
+// threads; turns stream item notifications back.
+import { spawn } from 'node:child_process'
+import { JsonRpcPeer, wireProcess, EventQueue } from './jsonrpc.js'
+import { cleanEnv } from './discover.js'
+
+export class CodexEngine {
+ constructor(route, engine, { findExecutable }) {
+ this.route = route
+ this.engine = engine
+ this.findExecutable = findExecutable
+ this.child = undefined
+ this.peer = undefined
+ this.threads = new Map()
+ }
+
+ threadFor(dshSessionId) {
+ let thread = this.threads.get(dshSessionId)
+ if (thread === undefined) {
+ const queue = new EventQueue()
+ thread = { dshSessionId, threadId: undefined, dead: false, push: event => queue.push(event), next: () => queue.next() }
+ this.threads.set(dshSessionId, thread)
+ }
+ return thread
+ }
+
+ async ensure() {
+ if (this.peer !== undefined) return this.peer
+ const bin = this.findExecutable(this.engine.command)
+ if (bin === undefined) throw Object.assign(new Error(`${this.engine.name} is not installed`), { code: 'NO_ADAPTER' })
+ const child = spawn(bin, this.engine.args ?? [], {
+ env: cleanEnv(this.engine.env ?? {}),
+ stdio: ['pipe', 'pipe', 'inherit'],
+ windowsHide: true,
+ })
+ this.child = child
+ const peer = this.peer = new JsonRpcPeer(line => child.stdin.write(`${JSON.stringify(line)}\n`))
+ wireProcess(child, peer)
+ child.on('exit', () => {
+ peer.close(new Error(`${this.engine.name} exited`))
+ this.child = undefined
+ this.peer = undefined
+ for (const thread of this.threads.values()) {
+ thread.dead = true
+ thread.push({ type: 'error', error: new Error(`${this.engine.name} exited`) })
+ }
+ })
+ peer.notificationHandler = (method, params) => this.onNotice(method, params)
+ peer.requestHandler = (method, params) => this.onRequest(method, params)
+ await peer.request('initialize', { clientInfo: { name: 'ds-bot', title: null, version: '1' } }, { timeout: 30_000 })
+ peer.notify('initialized', {})
+ return peer
+ }
+
+ onNotice(method, params) {
+ const thread = [...this.threads.values()].find(entry => entry.threadId === params?.threadId)
+ switch (method) {
+ case 'item/started':
+ case 'item/completed': {
+ const item = params?.item ?? {}
+ if (thread === undefined) break
+ if (item.type === 'agentMessage' || item.type === 'agent_message') thread.push({ type: 'text', text: item.text ?? '' })
+ else if (item.type === 'reasoning') thread.push({ type: 'thought', text: (item.content ?? []).join('') || item.text || '' })
+ else if (method === 'item/started' && item.type !== undefined) thread.push({ type: 'activity', text: `▸ ${activityOf(item)}` })
+ break
+ }
+ case 'turn/completed': {
+ if (thread === undefined) break
+ const turn = params?.turn ?? {}
+ if (turn.status === 'failed') thread.push({ type: 'error', error: new Error(turn.error?.message ?? 'the turn failed') })
+ else thread.push({ type: 'done', reason: 'stop' })
+ break
+ }
+ case 'thread/tokenUsage/updated': {
+ if (thread === undefined) break
+ const usage = params?.tokenUsage ?? params?.usage
+ if (usage !== undefined) thread.push({ type: 'usage', usage: { inputTokens: usage.inputTokens ?? usage.input_tokens ?? 0, outputTokens: usage.outputTokens ?? usage.output_tokens ?? 0 } })
+ break
+ }
+ default: break
+ }
+ }
+
+ // Server-initiated approval requests bridge to the approval tool.
+ onRequest(method, params) {
+ if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval' || method === 'execCommandApproval' || method === 'patchApproval') {
+ const thread = [...this.threads.values()].find(entry => entry.threadId === params?.threadId)
+ const options = (params?.availableDecisions ?? params?.decisions ?? ['accept', 'decline']).map(decision => ({ optionId: decision, kind: decision === 'accept' || decision === 'acceptForSession' ? 'allow_once' : 'reject_once', name: decision }))
+ return new Promise((resolve) => {
+ const reply = (decision) => resolve({ decision: decision ?? 'decline' })
+ thread?.push({
+ type: 'permission', id: `perm-${Math.random().toString(36).slice(2)}`, reply,
+ action: params?.reason ?? params?.command ?? 'The agent asks to run an action',
+ detail: detailText(params),
+ options,
+ })
+ })
+ }
+ return Promise.reject({ code: -32601, message: `method not found: ${method}` })
+ }
+
+ async open(dshSessionId, { cwd, mcp, resumeId, mode, instructions, model }) {
+ const peer = await this.ensure()
+ const thread = this.threadFor(dshSessionId)
+ if (resumeId !== undefined) thread.threadId = resumeId
+ const config = {
+ cwd,
+ ...(instructions ? { developer_instructions: instructions } : {}),
+ ...(mode ? { sandbox_mode: mode, approval_policy: mode === 'danger-full-access' ? 'never' : 'on-request' } : {}),
+ ...(model && model !== 'default' ? { model } : {}),
+ ...(mcp !== undefined ? { mcp_servers: { dsbot: { url: mcp.url, http_headers: { Authorization: `Bearer ${mcp.token}` } } } } : {}),
+ }
+ if (thread.threadId !== undefined) {
+ try {
+ await peer.request('thread/resume', { threadId: thread.threadId, config }, { timeout: 30_000 })
+ return thread
+ } catch {
+ thread.threadId = undefined
+ }
+ }
+ const reply = await peer.request('thread/start', config, { timeout: 60_000 })
+ thread.threadId = reply?.thread?.id ?? reply?.threadId
+ return thread
+ }
+
+ // Follow-up instructions while a thread lives (Codex injects a developer item).
+ async instruct(thread, text) {
+ if (text === '') return
+ await this.peer?.request('thread/inject_items', { threadId: thread.threadId, items: [{ type: 'developerMessage', text }] }, { timeout: 15_000 }).catch(() => {})
+ }
+
+ async prompt(thread, blocks, { signal }) {
+ const peer = await this.ensure()
+ const reply = await peer.request('turn/start', {
+ threadId: thread.threadId,
+ input: blocks.map(block => block.type === 'image' ? { type: 'image', url: block.url ?? block.data } : { type: 'text', text: block.text ?? '' }),
+ }, { signal, timeout: 60_000 })
+ thread.turnId = reply?.turn?.id ?? reply?.id
+ return thread.turnId
+ }
+
+ async steer(thread, text) {
+ await this.peer?.request('turn/steer', { threadId: thread.threadId, input: [{ type: 'text', text }] }, { timeout: 15_000 }).catch(() => {})
+ }
+
+ cancel(thread) {
+ this.peer?.request('turn/interrupt', { threadId: thread.threadId, turnId: thread.turnId }, { timeout: 15_000 }).catch(() => {})
+ }
+
+ async listModels() {
+ const peer = await this.ensure()
+ const reply = await peer.request('model/list', {}, { timeout: 30_000 })
+ return (reply?.data ?? reply?.models ?? []).map(entry => ({ id: String(entry.id ?? entry.model), name: String(entry.displayName ?? entry.name ?? entry.id ?? entry.model) }))
+ }
+
+ async close() {
+ const child = this.child
+ this.child = undefined
+ this.peer = undefined
+ if (child !== undefined) {
+ child.kill('SIGTERM')
+ setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 5_000).unref?.()
+ }
+ }
+}
+
+const activityOf = item => {
+ const kind = item.type === 'commandExecution' ? (item.command ?? 'command')
+ : item.type === 'fileChange' ? 'edit'
+ : item.type === 'mcpToolCall' ? (item.tool ?? 'tool')
+ : (item.title ?? item.type)
+ return String(kind).split('\n')[0].slice(0, 120)
+}
+const detailText = params => [params?.command, params?.reason, JSON.stringify(params?.changes ?? params?.patch ?? '')].filter(Boolean).join('\n').slice(0, 4_000)
diff --git a/ds-bot/src/host/local-agents/discover.js b/ds-bot/src/host/local-agents/discover.js
new file mode 100644
index 00000000..6970aa68
--- /dev/null
+++ b/ds-bot/src/host/local-agents/discover.js
@@ -0,0 +1,92 @@
+// Finding agent CLIs and the environment they run in: PATH plus the user's
+// login-shell PATH plus the usual install folders, and an environment that
+// keeps their own sign-in but leaks nothing of ours.
+import { execFile, execFileSync } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { delimiter, join } from 'node:path'
+
+// The CLI signs in by itself; an API key or another agent's backend variable in
+// our environment would shadow that or leak, so neither reaches the child.
+const DROP_EXACT = new Set([
+ 'ACP_BACKEND', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',
+ 'CLAUDE_CODE_OAUTH_TOKEN', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'XAI_API_KEY', 'ELECTRON_RUN_AS_NODE',
+])
+const DROP_PREFIX = ['DS_BOT_', 'DSH_']
+
+export function cleanEnv(extra = {}) {
+ const env = {}
+ for (const [key, value] of Object.entries(process.env)) {
+ if (DROP_EXACT.has(key) || DROP_PREFIX.some(prefix => key.startsWith(prefix))) continue
+ env[key] = value
+ }
+ return { ...env, ...extra }
+}
+
+// macOS/Linux apps launched from a dock icon inherit a sparse PATH; the login
+// shell knows where the user actually installed things. Cached for a minute:
+// a lookup burst (a page that scans every engine) pays for it once.
+let loginPath = { at: 0, value: undefined }
+function loginShellPath() {
+ if (Date.now() - loginPath.at < 60_000) return loginPath.value
+ loginPath = { at: Date.now(), value: undefined }
+ if (process.platform === 'win32') return undefined
+ const shell = process.env.SHELL ?? '/bin/sh'
+ try {
+ const out = execFileSync(shell, ['-l', '-c', 'printf %s "$PATH"'], { encoding: 'utf8', timeout: 5_000, env: cleanEnv() })
+ loginPath.value = out.split(delimiter).filter(Boolean)
+ } catch { /* no login shell PATH; what we have is enough */ }
+ return loginPath.value
+}
+
+function npmGlobalBin() {
+ try {
+ return execFileSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['bin', '-g'], { encoding: 'utf8', timeout: 5_000, env: cleanEnv() }).trim()
+ } catch { return undefined }
+}
+
+const WIN_EXT = ['.cmd', '.exe', '.bat', '']
+const candidates = (name) => (process.platform === 'win32' ? WIN_EXT.map(ext => `${name}${ext}`) : [name])
+
+// Every folder a CLI may hide in, in lookup order.
+function searchDirs() {
+ const home = homedir()
+ const dirs = (process.env.PATH ?? '').split(delimiter).filter(Boolean)
+ for (const dir of loginShellPath() ?? []) if (!dirs.includes(dir)) dirs.push(dir)
+ for (const extra of [
+ join(home, '.local', 'bin'),
+ join(home, '.local', 'share', 'devin', 'cli', '_versions', 'current', 'bin'),
+ join(home, 'bin'),
+ '/opt/homebrew/bin',
+ '/usr/local/bin',
+ npmGlobalBin(),
+ ]) {
+ if (extra !== undefined && extra !== '' && !dirs.includes(extra) && existsSync(extra)) dirs.push(extra)
+ }
+ return dirs
+}
+
+// The executable's full path, or undefined when the CLI is not installed.
+export function findExecutable(name) {
+ if (name.includes('/') || name.includes('\\')) {
+ const path = name.startsWith('~') ? join(homedir(), name.slice(1)) : name
+ return existsSync(path) ? path : undefined
+ }
+ for (const dir of searchDirs()) {
+ for (const file of candidates(name)) {
+ const path = join(dir, file)
+ if (existsSync(path)) return path
+ }
+ }
+ return undefined
+}
+
+// One `--version` call, bounded; the version line is for display only.
+export function probeVersion(executable, args, env) {
+ return new Promise((resolve) => {
+ execFile(executable, args, { encoding: 'utf8', timeout: 10_000, env }, (error, stdout, stderr) => {
+ const text = `${stdout ?? ''}${stderr ?? ''}`.split('\n').map(line => line.trim()).find(Boolean)
+ resolve({ ok: error === null, version: text })
+ })
+ })
+}
diff --git a/ds-bot/src/host/local-agents/engines.js b/ds-bot/src/host/local-agents/engines.js
new file mode 100644
index 00000000..9323164b
--- /dev/null
+++ b/ds-bot/src/host/local-agents/engines.js
@@ -0,0 +1,65 @@
+// The engines a local agent can run on. Each entry names its route, its display
+// name, how it starts, and which driver speaks its protocol: 'acp' (Agent
+// Client Protocol over stdio), 'codex' (the Codex app-server JSON-RPC), or
+// 'claude' (Claude Code's stream-json).
+export const KINDS = ['acp', 'codex', 'claude']
+
+// `args` run verbatim (no shell). `env` merges over the sanitized environment.
+export const ENGINES = {
+ 'devin-cli': { name: 'Devin CLI', kind: 'acp', command: 'devin', args: ['acp'], version: ['--version'] },
+ 'claude-code': { name: 'Claude Code', kind: 'claude', command: 'claude', args: [], version: ['--version'] },
+ 'codex-cli': { name: 'Codex CLI', kind: 'codex', command: 'codex', args: ['app-server', '--listen', 'stdio://'], version: ['--version'] },
+ 'opencode': { name: 'OpenCode', kind: 'acp', command: 'opencode', args: ['acp'], version: ['--version'] },
+ 'cursor-cli': { name: 'Cursor CLI', kind: 'acp', command: 'cursor-agent', args: ['acp'], version: ['--version'] },
+ 'gemini-cli': { name: 'Gemini CLI', kind: 'acp', command: 'gemini', args: ['--acp'], version: ['--version'] },
+ 'grok-cli': { name: 'Grok CLI', kind: 'acp', command: 'grok', args: ['agent', 'stdio'], version: ['--version'] },
+ 'cline': { name: 'Cline', kind: 'acp', command: 'cline', args: ['--acp'], version: ['--version'], env: { CLINE_SESSION_BACKEND_MODE: 'local' } },
+ 'qwen-code': { name: 'Qwen Code', kind: 'acp', command: 'qwen', args: ['--acp'], version: ['--version'] },
+ 'goose': { name: 'Goose', kind: 'acp', command: 'goose', args: ['acp'], version: ['--version'] },
+}
+
+export const CUSTOM_PREFIX = 'acp-'
+
+// A custom ACP agent's route id from its list position (stable across edits).
+export const customRoute = (id) => `${CUSTOM_PREFIX}${id}`
+
+export function engineOf(route, custom = []) {
+ if (ENGINES[route] !== undefined) return ENGINES[route]
+ if (route.startsWith(CUSTOM_PREFIX)) {
+ const entry = custom.find(agent => agent.id === route.slice(CUSTOM_PREFIX.length))
+ if (entry !== undefined) return { name: entry.name, kind: 'acp', command: entry.command, args: entry.args ?? [], custom: true }
+ }
+ return undefined
+}
+
+export const isLocalAgentRoute = route => typeof route === 'string' && (ENGINES[route] !== undefined || route.startsWith(CUSTOM_PREFIX))
+
+// A custom agent the user typed: a bare command name, an absolute path or
+// ~/path; args without NUL or newlines (they would smuggle extra arguments).
+export function validateCustom({ name, command, args }) {
+ const clean = {
+ name: String(name ?? '').trim().slice(0, 40),
+ command: String(command ?? '').trim(),
+ args: (Array.isArray(args) ? args : String(args ?? '').split(' ')).map(arg => String(arg).trim()).filter(Boolean),
+ }
+ if (clean.name === '') throw new Error('Name is required')
+ if (clean.command === '' || /[\s]/.test(clean.command) || !(clean.command.startsWith('/') || clean.command.startsWith('~/') || /^[A-Za-z]:[\\/]/.test(clean.command) || /^[\w.-]+$/.test(clean.command))) {
+ throw new Error('Command must be a program name, an absolute path, or a ~/path')
+ }
+ if (clean.args.some(arg => arg.includes('\0') || /[\r\n]/.test(arg))) throw new Error('Arguments must not contain newlines')
+ return clean
+}
+
+// The permission preset DS Bot gives the Bot, mapped to each driver's mode.
+// ACP mode ids the agent advertises win over these guesses (see acp.js).
+export const MODES = {
+ 'read-only': { acp: ['ask', 'plan'], claude: 'plan', codex: 'read-only' },
+ 'workspace-write': { acp: ['accept-edits', 'accept_edits', 'acceptEdits'], claude: 'acceptEdits', codex: 'workspace-write' },
+ 'danger-full-access': { acp: ['bypass', 'bypassPermissions', 'bypass-permissions'], claude: 'bypassPermissions', codex: 'danger-full-access' },
+}
+export const acpMode = (preset, advertised) => {
+ const wanted = MODES[preset]?.acp ?? []
+ const ids = (advertised ?? []).map(option => option.id ?? option)
+ return wanted.find(id => ids.includes(id)) ?? wanted[0]
+}
+export const cliMode = (kind, preset, advertised) => (kind === 'acp' ? acpMode(preset, advertised) : MODES[preset]?.[kind])
diff --git a/ds-bot/src/host/local-agents/index.js b/ds-bot/src/host/local-agents/index.js
new file mode 100644
index 00000000..71a69899
--- /dev/null
+++ b/ds-bot/src/host/local-agents/index.js
@@ -0,0 +1,219 @@
+// Local agents: ordinary Bots whose model route is a local agent CLI (Devin
+// CLI, Claude Code, Codex, ACP agents). install() scans for the CLIs, registers
+// one DSH LLM adapter for the routes it found, keeps the custom agents and the
+// Session→CLI-session map in state, and serves the Settings page.
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { defineTool } from '@deepseek-ai/dsh-tools'
+import { splitRef } from '../text.js'
+import { output } from '../tools.js'
+import { LocalAgentAdapter } from './adapter.js'
+import { AcpEngine } from './acp.js'
+import { CodexEngine } from './codex.js'
+import { ClaudeEngine } from './claude.js'
+import { ENGINES, customRoute, isLocalAgentRoute, validateCustom } from './engines.js'
+import { findExecutable, probeVersion } from './discover.js'
+
+const SIGN_IN = {
+ 'devin-cli': 'devin auth login',
+ 'claude-code': 'claude',
+ 'codex-cli': 'codex login',
+ 'opencode': 'opencode auth login',
+ 'cursor-cli': 'cursor-agent login',
+ 'gemini-cli': 'gemini',
+ 'grok-cli': 'grok',
+ 'cline': 'cline auth',
+ 'qwen-code': 'qwen',
+ 'goose': 'goose configure',
+}
+
+const spawnEngine = (kind, route, spec) => (kind === 'acp' ? new AcpEngine(route, spec, { findExecutable })
+ : kind === 'codex' ? new CodexEngine(route, spec, { findExecutable })
+ : new ClaudeEngine(route, spec, { findExecutable }))
+
+export function install(rt) {
+ const { ctx, state } = rt
+ state.localAgents ??= { custom: [], sessions: {} }
+ const store = state.localAgents
+ store.custom ??= []
+ store.sessions ??= {}
+
+ const customAgents = () => store.custom
+ const customRouteId = () => store.custom.map(agent => customRoute(agent.id))
+ const allRoutes = () => [...Object.keys(ENGINES), ...customRouteId()]
+
+ // Only CLIs found on this machine get a route; the scan result feeds the page.
+ const found = new Map()
+ async function scan() {
+ for (const route of Object.keys(ENGINES)) {
+ const spec = ENGINES[route]
+ const path = findExecutable(spec.command)
+ if (path === undefined) found.delete(route)
+ else found.set(route, { route, name: spec.name, path, version: undefined, signIn: SIGN_IN[route] })
+ }
+ applyRoutes()
+ return [...found.values()]
+ }
+ async function probeVersions() {
+ for (const entry of found.values()) {
+ if (entry.version !== undefined) continue
+ const spec = ENGINES[entry.route]
+ const result = await probeVersion(entry.path, spec.version ?? ['--version'], undefined).catch(() => undefined)
+ entry.version = result?.version
+ }
+ }
+
+ const adapter = new LocalAgentAdapter({
+ rt,
+ customAgents,
+ findExecutable,
+ spawnEngine,
+ record: sessionId => store.sessions[sessionId],
+ saveRecord: (sessionId, record) => {
+ store.sessions[sessionId] = record
+ void rt.save().catch(() => {})
+ },
+ presetFor: (sessionId) => {
+ const bot = rt.botOf(rt.selfOf(sessionId))
+ const room = rt.roomOf(rt.groupOwners.get(sessionId)?.roomId)
+ return room?.permission ?? bot?.permission ?? 'workspace-write'
+ },
+ cwdFor: async (sessionId) => {
+ try {
+ const agent = await rt.resolveAgent(sessionId)
+ return agent.session.header?.cwd ?? rt.workDirOf?.({ botId: rt.selfOf(sessionId), roomId: rt.groupOwners.get(sessionId)?.roomId }) ?? rt.teamFolder?.() ?? tmpdir()
+ } catch {
+ return rt.teamFolder?.() ?? tmpdir()
+ }
+ },
+ probeCwd: () => mkdtempSync(join(tmpdir(), 'dsb-probe-')),
+ toolsFor: (options) => {
+ // Only DS Bot's own team tools cross the bridge; the CLI keeps its own.
+ const names = new Set([...rt.teamTools.map(def => def.name), 'approve_agent_action'])
+ return (options.tools ?? []).filter(tool => names.has(tool.name))
+ },
+ })
+
+ let registration
+ const supported = () => typeof ctx.llm?.registerAdapter === 'function'
+ function applyRoutes() {
+ if (!supported()) return
+ const routes = [...found.keys(), ...customRouteId()]
+ if (registration === undefined) registration = ctx.llm.registerAdapter(routes, adapter)
+ else registration.replace(routes)
+ }
+ // Custom agents hold a route whether or not their command resolves yet; a
+ // missing one fails at prompt time with a typed error.
+ applyRoutes()
+ void scan()
+ ctx.effect(() => {
+ void adapter.dispose()
+ return () => { registration?.() }
+ }, 'ds-bot: local agents')
+
+ // ---------------------------------------------------------------------------
+ // Helpers the rest of the host asks.
+
+ const isLocalAgentRef = ref => isLocalAgentRoute(splitRef(ref)?.provider ?? '')
+ const localAgentOf = (bot) => {
+ const ref = bot?.appliedModel ?? bot?.model
+ return ref !== undefined && isLocalAgentRef(ref) ? ref : undefined
+ }
+ const isLocalAgentSession = (sessionId) => {
+ const bot = rt.botOf(rt.selfOf(sessionId))
+ return bot !== undefined && localAgentOf(bot) !== undefined
+ }
+
+ // ---------------------------------------------------------------------------
+ // approve_agent_action: served only to abot sessions; the CLI's permission
+ // prompts arrive through it as an ordinary approval card. It stays off
+ // rt.teamTools (the catalog every Bot gets) and joins the scope only for a
+ // local-agent Bot.
+
+ rt.localAgentTools = [defineTool({
+ name: 'approve_agent_action',
+ description: 'Ask the user to approve an action you want to take: running a command, changing files, or reaching the network. The agent runtime asks this on your behalf when its own permission system wants a decision.',
+ parameters: {
+ action: { type: 'string', required: true, description: 'What the action does, in one line' },
+ detail: { type: 'string', description: 'The exact command, paths, or arguments, when it helps the decision' },
+ },
+ output,
+ localAgentOnly: true,
+ async execute(args, exec) {
+ const approval = ctx.get?.('approval')
+ if (approval === undefined || exec.agent?.session === undefined) return 'denied: approvals are not available here'
+ const text = `${args.action}${args.detail ? `\n${args.detail}` : ''}`
+ const outcome = await approval.request({
+ agent: exec.agent,
+ toolName: exec.name,
+ ...(exec.callId !== undefined ? { callId: exec.callId } : {}),
+ reason: text.slice(0, 500),
+ displayReason: { en: text.slice(0, 500) },
+ ...(exec.signal ? { signal: exec.signal } : {}),
+ })
+ return outcome === 'allowed-once' ? 'allowed' : outcome
+ },
+ })]
+
+ // ---------------------------------------------------------------------------
+ // The Settings page's endpoints.
+
+ const detected = () => [...found.values()].map(entry => ({ route: entry.route, name: entry.name, path: entry.path, version: entry.version ?? null, signIn: entry.signIn }))
+ const customView = () => store.custom.map(agent => ({ ...agent, route: customRoute(agent.id) }))
+
+ async function localAgentsEndpoint(endpoint, body) {
+ switch (endpoint) {
+ case 'local-agents': {
+ await scan()
+ await probeVersions()
+ return { available: supported(), detected: detected(), custom: customView() }
+ }
+ case 'local-agent-refresh': {
+ adapter.dropModelCache()
+ await scan()
+ await probeVersions()
+ return { available: supported(), detected: detected(), custom: customView() }
+ }
+ case 'local-agent-add': {
+ const clean = validateCustom(body)
+ if (findExecutable(clean.command) === undefined && !clean.command.includes('/') && !clean.command.includes('\\')) {
+ throw new Error(`No program named ${clean.command} was found`)
+ }
+ const entry = { id: `agent-${Date.now().toString(36)}`, ...clean }
+ store.custom.push(entry)
+ applyRoutes()
+ await rt.save()
+ return { ...entry, route: customRoute(entry.id) }
+ }
+ case 'local-agent-update': {
+ const entry = store.custom.find(agent => agent.id === body.id)
+ if (entry === undefined) throw new Error('Unknown agent')
+ const clean = validateCustom({ name: body.name ?? entry.name, command: body.command ?? entry.command, args: body.args ?? entry.args })
+ Object.assign(entry, clean)
+ adapter.dropModelCache(customRoute(entry.id))
+ await rt.save()
+ return { ...entry, route: customRoute(entry.id) }
+ }
+ case 'local-agent-remove': {
+ const at = store.custom.findIndex(agent => agent.id === body.id)
+ if (at === -1) throw new Error('Unknown agent')
+ store.custom.splice(at, 1)
+ applyRoutes()
+ await rt.save()
+ return customView()
+ }
+ default:
+ throw new Error(`Unknown endpoint ${endpoint}`)
+ }
+ }
+
+ Object.assign(rt, {
+ isLocalAgentRoute, isLocalAgentRef, localAgentOf, isLocalAgentSession,
+ localAgentRoutes: allRoutes, localAgentsEndpoint,
+ localAgentBadge: (ref) => {
+ const provider = splitRef(ref)?.provider
+ return provider !== undefined && isLocalAgentRoute(provider) ? provider : undefined
+ },
+ })
+}
diff --git a/ds-bot/src/host/local-agents/jsonrpc.js b/ds-bot/src/host/local-agents/jsonrpc.js
new file mode 100644
index 00000000..d50d0a47
--- /dev/null
+++ b/ds-bot/src/host/local-agents/jsonrpc.js
@@ -0,0 +1,111 @@
+// Newline-delimited JSON-RPC over a child process's stdio: requests we send,
+// answers and server-initiated requests we receive. Shared by the ACP and the
+// Codex app-server engines.
+import { randomUUID } from 'node:crypto'
+
+// One wire message is one JSON value on one line.
+export class JsonRpcPeer {
+ constructor(write) {
+ this.write = write
+ this.nextId = 0
+ this.pending = new Map()
+ this.requestHandler = undefined
+ this.notificationHandler = undefined
+ this.closed = undefined
+ }
+
+ // The process ended: every request still waiting fails.
+ close(error = new Error('the connection closed')) {
+ for (const [, call] of this.pending) call.reject(error)
+ this.pending.clear()
+ this.closed?.()
+ }
+
+ handleLine(line) {
+ let message
+ try { message = JSON.parse(line) } catch { return }
+ if (message === null || typeof message !== 'object') return
+ if (message.id !== undefined && (message.result !== undefined || message.error !== undefined)) {
+ const call = this.pending.get(message.id)
+ if (call === undefined) return
+ this.pending.delete(message.id)
+ if (message.error !== undefined) call.reject(Object.assign(new Error(message.error.message ?? 'request failed'), { code: message.error.code, data: message.error.data }))
+ else call.resolve(message.result)
+ return
+ }
+ if (typeof message.method !== 'string') return
+ if (message.id !== undefined) {
+ const respond = (result) => this.write({ jsonrpc: '2.0', id: message.id, result })
+ const refuse = (error) => this.write({ jsonrpc: '2.0', id: message.id, error: typeof error === 'object' && error !== null ? { code: error.code ?? -32603, message: String(error.message ?? error) } : { code: -32603, message: String(error) } })
+ try {
+ const answer = this.requestHandler?.(message.method, message.params, message)
+ if (answer === undefined) { refuse({ code: -32601, message: `method not found: ${message.method}` }); return }
+ Promise.resolve(answer).then(respond, refuse)
+ } catch (error) { refuse(error) }
+ return
+ }
+ try { this.notificationHandler?.(message.method, message.params, message) } catch { /* one bad notice is dropped */ }
+ }
+
+ request(method, params, { signal, timeout = 120_000 } = {}) {
+ if (signal?.aborted) return Promise.reject(signal.reason ?? new Error('aborted'))
+ const id = ++this.nextId
+ return new Promise((resolve, reject) => {
+ let timer
+ const call = {
+ resolve: (value) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); resolve(value) },
+ reject: (error) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); reject(error) },
+ }
+ const onAbort = () => call.reject(signal.reason ?? new Error('aborted'))
+ this.pending.set(id, call)
+ if (timeout !== undefined) timer = setTimeout(() => { if (this.pending.delete(id)) call.reject(new Error(`${method} timed out`)) }, timeout)
+ if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
+ try {
+ this.write({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) })
+ } catch (error) {
+ this.pending.delete(id)
+ call.reject(error)
+ }
+ })
+ }
+
+ notify(method, params) {
+ this.write({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) })
+ }
+}
+
+// Feeds stdout into a peer line by line; resolves when the process ends.
+export function wireProcess(child, peer) {
+ let rest = ''
+ child.stdout.setEncoding('utf8')
+ child.stdout.on('data', (chunk) => {
+ rest += chunk
+ let at
+ while ((at = rest.indexOf('\n')) !== -1) {
+ const line = rest.slice(0, at).trim()
+ rest = rest.slice(at + 1)
+ if (line !== '') peer.handleLine(line)
+ }
+ })
+ return rest
+}
+
+export const newCallId = () => randomUUID()
+
+// A waitable event stream attached to one CLI session/thread: the engine pushes
+// normalized events, the adapter drains them per stream() call.
+export class EventQueue {
+ constructor() {
+ this.events = []
+ this.waiters = []
+ }
+ push(event) {
+ const waiter = this.waiters.shift()
+ if (waiter !== undefined) waiter(event)
+ else this.events.push(event)
+ }
+ next() {
+ if (this.events.length > 0) return Promise.resolve(this.events.shift())
+ return new Promise(resolve => this.waiters.push(resolve))
+ }
+}
diff --git a/ds-bot/src/host/local-agents/mcp.js b/ds-bot/src/host/local-agents/mcp.js
new file mode 100644
index 00000000..ccce768b
--- /dev/null
+++ b/ds-bot/src/host/local-agents/mcp.js
@@ -0,0 +1,141 @@
+// The loopback MCP server: one per CLI session, Streamable HTTP on 127.0.0.1
+// with a random port and a per-session bearer token. It serves only the DS
+// Bot team tools; every call is handed to the adapter, which emits it as a
+// DSH tool call and answers here once the result arrives.
+import { createServer } from 'node:http'
+import { randomBytes, randomUUID } from 'node:crypto'
+
+const PROTOCOL_VERSION = '2025-03-26'
+const KEEPALIVE_MS = 20_000
+
+// Several CLIs refuse schemas with unions, refs or const, so every schema is
+// flattened to plain JSON Schema before tools/list.
+export function flattenSchema(node) {
+ if (node === null || typeof node !== 'object') return node
+ if (Array.isArray(node)) return node.map(flattenSchema)
+ const out = {}
+ for (const [key, value] of Object.entries(node)) {
+ if (key === '$ref' || key === '$defs' || key === 'definitions' || key === 'const') continue
+ if (key === 'oneOf' || key === 'anyOf' || key === 'allOf') {
+ const branches = Array.isArray(value) ? value : []
+ const first = branches.find(branch => branch?.type !== 'null')
+ if (first !== undefined) Object.assign(out, flattenSchema(first))
+ continue
+ }
+ out[key] = flattenSchema(value)
+ }
+ return out
+}
+
+export class LoopbackMcp {
+ // onCall(name, args) -> Promise<{text, isError}> runs while the adapter waits
+ // for the DSH result; it resolves when the tool call settles.
+ constructor(tools, onCall) {
+ this.token = randomBytes(32).toString('hex')
+ this.tools = tools
+ this.onCall = onCall
+ this.calls = new Map()
+ this.server = createServer((request, response) => void this.serve(request, response).catch(() => {
+ if (!response.headersSent) response.writeHead(500)
+ response.end()
+ }))
+ this.url = undefined
+ }
+
+ async listen() {
+ await new Promise((resolve, reject) => this.server.listen(0, '127.0.0.1', () => resolve()).once('error', reject))
+ const { port } = this.server.address()
+ this.url = `http://127.0.0.1:${port}/mcp`
+ return this.url
+ }
+
+ // A queued or in-flight tool call that the CLI cancelled, or that an abort
+ // must fail instead of leaving the agent waiting.
+ failAll(error) {
+ for (const call of this.calls.values()) call.settle({ isError: true, text: error.message ?? String(error) })
+ this.calls.clear()
+ }
+
+ close() {
+ this.failAll(new Error('the session closed'))
+ this.server.close()
+ }
+
+ async serve(request, response) {
+ const auth = request.headers.authorization
+ if (auth !== `Bearer ${this.token}`) {
+ response.writeHead(401, { 'content-type': 'application/json' })
+ response.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32001, message: 'unauthorized' } }))
+ return
+ }
+ if (request.method !== 'POST') { response.writeHead(405); response.end(); return }
+ const body = await readBody(request)
+ let message
+ try { message = JSON.parse(body) } catch { response.writeHead(400); response.end(); return }
+ const messages = Array.isArray(message) ? message : [message]
+ // Notifications and responses get 202 with no body, per the spec.
+ const calls = messages.filter(item => item?.method !== undefined)
+ if (calls.length === 0) { response.writeHead(202); response.end(); return }
+ const toolsCall = calls.find(item => item.method === 'tools/call')
+ if (toolsCall !== undefined) {
+ this.serveCall(toolsCall, response)
+ return
+ }
+ const replies = calls.map(item => this.answer(item)).filter(Boolean)
+ response.writeHead(200, { 'content-type': 'application/json' })
+ response.end(JSON.stringify(Array.isArray(message) ? replies : replies[0]))
+ }
+
+ answer({ id, method, params }) {
+ switch (method) {
+ case 'initialize':
+ return { jsonrpc: '2.0', id, result: { protocolVersion: params?.protocolVersion ?? PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: { name: 'ds-bot', version: '1' } } }
+ case 'ping':
+ return { jsonrpc: '2.0', id, result: {} }
+ case 'tools/list':
+ return { jsonrpc: '2.0', id, result: { tools: this.tools().map(tool => ({ name: tool.name, description: tool.description ?? '', inputSchema: flattenSchema(tool.parameters ?? { type: 'object', properties: {} }) })) } }
+ default:
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } }
+ }
+ }
+
+ // tools/call answers on an SSE stream: progress notifications keep the agent
+ // patient while DSH runs the call, then the result arrives on the same stream.
+ serveCall({ id, params }, response) {
+ const callId = `mcp-${randomUUID()}`
+ const progressToken = params?._meta?.progressToken ?? callId
+ response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' })
+ const send = (value) => { try { response.write(`data: ${JSON.stringify(value)}\n\n`) } catch {} }
+ const entry = {
+ progress: 0,
+ settle: (result) => {
+ clearInterval(timer)
+ this.calls.delete(callId)
+ send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: result.text }], isError: result.isError === true } })
+ response.end()
+ },
+ cancel: () => {
+ clearInterval(timer)
+ this.calls.delete(callId)
+ send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: 'the call was cancelled' }], isError: true } })
+ response.end()
+ },
+ }
+ const timer = setInterval(() => {
+ entry.progress += 1
+ send({ jsonrpc: '2.0', method: 'notifications/progress', params: { progressToken, progress: entry.progress * KEEPALIVE_MS, message: 'waiting for the tool result' } })
+ }, KEEPALIVE_MS)
+ timer.unref?.()
+ this.calls.set(callId, entry)
+ this.onCall({ name: params?.name, arguments: params?.arguments ?? {}, callId })
+ .then(entry.settle, error => entry.settle({ isError: true, text: error?.message ?? String(error) }))
+ }
+}
+
+const readBody = (request) => new Promise((resolve, reject) => {
+ let body = ''
+ request.setEncoding('utf8')
+ request.on('data', chunk => { body += chunk })
+ request.on('end', () => resolve(body))
+ request.on('error', reject)
+})
diff --git a/ds-bot/test/fixtures/fake-acp.mjs b/ds-bot/test/fixtures/fake-acp.mjs
new file mode 100644
index 00000000..578134a8
--- /dev/null
+++ b/ds-bot/test/fixtures/fake-acp.mjs
@@ -0,0 +1,122 @@
+// A fake ACP agent for tests: newline JSON-RPC over stdio. The prompt text
+// picks its behavior so a test can drive each branch:
+// contains "call-tool" -> calls the dsbot MCP server's tools/call
+// contains "two-calls" -> two queued MCP calls
+// contains "ask-permission" -> session/request_permission to the client
+// contains "hang" -> never ends until session/cancel
+// otherwise -> a thought chunk, an activity line, "ok"
+const sessions = new Map()
+let nextId = 0
+const requests = new Map()
+
+const send = (message) => process.stdout.write(`${JSON.stringify(message)}\n`)
+const reply = (id, result) => send({ jsonrpc: '2.0', id, result })
+const fail = (id, message) => send({ jsonrpc: '2.0', id, error: { code: -32601, message } })
+const update = (sessionId, update) => send({ jsonrpc: '2.0', method: 'session/update', params: { sessionId, update } })
+const ask = (method, params) => {
+ const id = `fake-${++nextId}`
+ send({ jsonrpc: '2.0', id, method, params })
+ return new Promise(resolve => requests.set(id, resolve))
+}
+
+async function mcpCall(server, name, args) {
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${server.token}` }
+ const post = (body) => fetch(server.url, { method: 'POST', headers, body: JSON.stringify(body) })
+ await post({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'fake', version: '1' } } })
+ const response = await post({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name, arguments: args } })
+ const text = await response.text()
+ const line = text.split('\n').map(row => row.trim()).find(row => row.startsWith('data: ') && row.includes('"result"'))
+ return JSON.parse(line.slice(6)).result
+}
+
+async function runPrompt(session, prompt, requestId) {
+ const text = (prompt ?? []).map(block => block.text ?? '').join('\n')
+ const sessionId = session.id
+ const finish = (textOut) => {
+ update(sessionId, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: textOut } })
+ reply(requestId, { stopReason: 'end_turn' })
+ }
+ if (text.includes('hang')) return // session/cancel releases it below
+ if (text.includes('ask-permission')) {
+ const answer = await ask('session/request_permission', {
+ sessionId,
+ toolCall: { title: 'Run rm -rf /tmp/x', kind: 'execute', rawInput: { command: 'rm -rf /tmp/x' } },
+ options: [
+ { optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' },
+ { optionId: 'reject', name: 'Reject', kind: 'reject_once' },
+ ],
+ })
+ const outcome = answer?.result?.outcome
+ finish(outcome?.outcome === 'selected' ? `allowed via ${outcome.optionId}` : 'denied')
+ return
+ }
+ if (text.includes('call-tool') || text.includes('two-calls')) {
+ const server = session.mcp
+ update(sessionId, { sessionUpdate: 'tool_call', toolCallId: 't1', title: 'mcp dsbot message_bot', kind: 'other', status: 'in_progress' })
+ try {
+ const calls = text.includes('two-calls') ? 2 : 1
+ const results = await Promise.all([...Array(calls)].map((_, i) => mcpCall(server, 'message_bot', { bot: 'Kai', text: `hi ${i}` })))
+ finish(`tool said: ${results.map(result => (result.content ?? []).map(block => block.text).join('')).join(' | ')}`)
+ } catch (error) {
+ finish(`tool failed: ${error.message}`)
+ }
+ return
+ }
+ update(sessionId, { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: `thought about: ${text.slice(0, 40)}` } })
+ update(sessionId, { sessionUpdate: 'tool_call', toolCallId: 't0', title: 'edit src/a.js', kind: 'edit', status: 'in_progress' })
+ finish(`ok: ${text.slice(0, 60)}`)
+}
+
+let rest = ''
+process.stdin.setEncoding('utf8')
+process.stdin.on('data', (chunk) => {
+ rest += chunk
+ let at
+ while ((at = rest.indexOf('\n')) !== -1) {
+ const line = rest.slice(0, at).trim()
+ rest = rest.slice(at + 1)
+ if (line === '') continue
+ let message
+ try { message = JSON.parse(line) } catch { continue }
+ if (message.id !== undefined && (message.result !== undefined || message.error !== undefined)) {
+ requests.get(message.id)?.(message)
+ requests.delete(message.id)
+ continue
+ }
+ const { id, method, params = {} } = message
+ switch (method) {
+ case 'initialize':
+ reply(id, { protocolVersion: 1, agentCapabilities: { mcpCapabilities: { http: true, sse: false }, loadSession: true }, authMethods: [] })
+ break
+ case 'session/new': {
+ const session = { id: `acp-${++nextId}`, mcp: undefined }
+ const server = (params.mcpServers ?? []).find(entry => entry.name === 'dsbot')
+ if (server !== undefined) session.mcp = { url: server.url, token: (server.headers ?? []).find(header => header.name === 'Authorization')?.value?.replace('Bearer ', '') }
+ sessions.set(session.id, session)
+ reply(id, {
+ sessionId: session.id,
+ configOptions: [
+ { id: 'model', category: 'model', name: 'Model', options: [{ id: 'fake-large', name: 'Fake Large' }, { id: 'fake-small', name: 'Fake Small' }] },
+ { id: 'mode', category: 'mode', name: 'Mode', options: [{ id: 'ask', name: 'Ask' }, { id: 'accept-edits', name: 'Accept edits' }, { id: 'bypass', name: 'Bypass' }] },
+ ],
+ })
+ break
+ }
+ case 'session/load':
+ reply(id, { sessionId: params.sessionId })
+ break
+ case 'session/set_config_option':
+ case 'session/set_mode':
+ reply(id, {})
+ break
+ case 'session/prompt':
+ void runPrompt(sessions.get(params.sessionId) ?? { id: params.sessionId }, params.prompt, id)
+ break
+ case 'session/cancel':
+ update(params.sessionId, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'cancelled' } })
+ break
+ default:
+ if (id !== undefined) fail(id, `method not found: ${method}`)
+ }
+ }
+})
diff --git a/ds-bot/test/fixtures/fake-claude.mjs b/ds-bot/test/fixtures/fake-claude.mjs
new file mode 100644
index 00000000..3ecbac47
--- /dev/null
+++ b/ds-bot/test/fixtures/fake-claude.mjs
@@ -0,0 +1,28 @@
+// A fake Claude Code for tests: stream-json both ways. Prints the init system
+// line, then answers each user message with thinking + text + result events.
+const sessionId = `claude-${Math.random().toString(36).slice(2)}`
+const send = (message) => process.stdout.write(`${JSON.stringify(message)}\n`)
+
+send({ type: 'system', subtype: 'init', session_id: sessionId })
+
+let rest = ''
+process.stdin.setEncoding('utf8')
+process.stdin.on('data', (chunk) => {
+ rest += chunk
+ let at
+ while ((at = rest.indexOf('\n')) !== -1) {
+ const line = rest.slice(0, at).trim()
+ rest = rest.slice(at + 1)
+ if (line === '') continue
+ let message
+ try { message = JSON.parse(line) } catch { continue }
+ if (message.type === 'control_request' && message.request?.subtype === 'interrupt') {
+ send({ type: 'result', subtype: 'success', session_id: sessionId, result: 'interrupted', usage: { input_tokens: 1, output_tokens: 1 } })
+ continue
+ }
+ if (message.type !== 'user') continue
+ const text = (message.message?.content ?? []).map(block => block.text ?? '').join('\n')
+ send({ type: 'assistant', message: { content: [{ type: 'thinking', thinking: `thought about: ${text.slice(0, 40)}` }, { type: 'tool_use', name: 'Read' }, { type: 'text', text: `ok: ${text.slice(0, 60)}` }] } })
+ send({ type: 'result', subtype: 'success', session_id: sessionId, result: `ok: ${text.slice(0, 60)}`, usage: { input_tokens: 10, output_tokens: 5 } })
+ }
+})
diff --git a/ds-bot/test/fixtures/fake-codex.mjs b/ds-bot/test/fixtures/fake-codex.mjs
new file mode 100644
index 00000000..133c45ef
--- /dev/null
+++ b/ds-bot/test/fixtures/fake-codex.mjs
@@ -0,0 +1,63 @@
+// A fake Codex app-server for tests: `codex app-server --listen stdio://`
+// dialect, newline JSON-RPC. The turn's first text picks the behavior:
+// "ask" -> an approval request the client must answer
+// otherwise -> an activity item, an agentMessage, turn/completed
+const threads = new Map()
+let nextId = 0
+const requests = new Map()
+
+const send = (message) => process.stdout.write(`${JSON.stringify(message)}\n`)
+const reply = (id, result) => send({ jsonrpc: '2.0', id, result })
+const fail = (id, message) => send({ jsonrpc: '2.0', id, error: { code: -32601, message } })
+const notice = (method, params) => send({ jsonrpc: '2.0', method, params })
+
+function runTurn(thread, turnId, text) {
+ notice('item/started', { threadId: thread.id, item: { id: 'i1', type: 'commandExecution', command: 'ls' } })
+ notice('item/completed', { threadId: thread.id, item: { id: 'i1', type: 'commandExecution', exitCode: 0 } })
+ notice('item/completed', { threadId: thread.id, item: { id: 'i2', type: 'agentMessage', text: `ok: ${text.slice(0, 60)}` } })
+ notice('turn/completed', { threadId: thread.id, turn: { id: turnId, status: 'completed' } })
+}
+
+let rest = ''
+process.stdin.setEncoding('utf8')
+process.stdin.on('data', (chunk) => {
+ rest += chunk
+ let at
+ while ((at = rest.indexOf('\n')) !== -1) {
+ const line = rest.slice(0, at).trim()
+ rest = rest.slice(at + 1)
+ if (line === '') continue
+ let message
+ try { message = JSON.parse(line) } catch { continue }
+ if (message.id !== undefined && (message.result !== undefined || message.error !== undefined)) {
+ requests.get(message.id)?.(message)
+ requests.delete(message.id)
+ continue
+ }
+ const { id, method, params = {} } = message
+ switch (method) {
+ case 'initialize': reply(id, { userAgent: 'fake-codex' }); break
+ case 'initialized': break
+ case 'model/list': reply(id, { data: [{ id: 'gpt-5.1-codex', displayName: 'GPT-5.1 Codex' }] }); break
+ case 'thread/start': {
+ const thread = { id: `thr-${++nextId}` }
+ threads.set(thread.id, thread)
+ reply(id, { thread: { id: thread.id } })
+ break
+ }
+ case 'thread/resume': reply(id, { thread: { id: params.threadId } }); break
+ case 'thread/inject_items': reply(id, {}); break
+ case 'turn/start': {
+ const thread = threads.get(params.threadId)
+ const turnId = `turn-${++nextId}`
+ reply(id, { turn: { id: turnId } })
+ const text = (params.input ?? []).map(item => item.text ?? '').join('\n')
+ setImmediate(() => runTurn(thread ?? { id: params.threadId }, turnId, text))
+ break
+ }
+ case 'turn/interrupt': reply(id, {}); break
+ case 'turn/steer': reply(id, {}); break
+ default: if (id !== undefined) fail(id, `method not found: ${method}`)
+ }
+ }
+})