Skip to content
104 changes: 104 additions & 0 deletions src/adapters/external/ExternalAdapter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { describe, expect, it } from 'vitest'
import type { ExternalBridge, ExternalEvent } from '@shared/externalAgents'
import { AdapterError, type AdapterEvent } from '../types'
import { ExternalAdapter, decodeExternalError } from './ExternalAdapter'
import { setExternalConfirmHandler } from './confirmGate'

function fakeBridge(chat: ExternalBridge['chat']) {
const listeners = new Set<(e: ExternalEvent) => void>()
const cancelled: string[] = []
const bridge: ExternalBridge = {
listAccounts: async () => ['x1'],
config: async () => ({ kind: 'cli', name: 'Claude CLI', command: 'claude', args: ['-p', '{prompt}'], input: 'arg', cwd: '', timeoutMs: 1000, needsConfirm: true }),
configure: async () => { throw new Error('unused') },
confirmCommand: async () => { throw new Error('unused') },
remove: async () => undefined,
chat,
cancel: async (_a, id) => { cancelled.push(id) },
onEvent: (l) => { listeners.add(l); return () => listeners.delete(l) }
}
return { bridge, emit: (e: ExternalEvent) => listeners.forEach((l) => l(e)), cancelled }
}

describe('ExternalAdapter', () => {
it('decodes IPC error codes', () => {
expect(decodeExternalError(new Error("Error invoking remote method 'x': Error: [external:timeout] 超时"))).toEqual({ code: 'timeout', message: '超时' })
expect(decodeExternalError('plain')).toEqual({ code: 'unknown', message: 'plain' })
})

it('relays progress as deltas, then the final message with the session id', async () => {
const fake = fakeBridge(async (req) => {
fake.emit({ type: 'accepted', requestId: req.requestId, accountId: req.accountId, sessionId: 's1' })
fake.emit({ type: 'progress', requestId: req.requestId, accountId: req.accountId, sessionId: 's1', text: 'par' })
expect(req.workspaceScope).toBe('room-1')
return { messageId: 'm1', sessionId: 's1', text: 'partial done', createdAt: 1 }
})
const adapter = new ExternalAdapter(() => fake.bridge)
const seen: AdapterEvent[] = []
adapter.subscribe((e) => seen.push(e))
let acceptedWith: string | undefined
const receipt = await adapter.sendMessage({
conversationId: 'c', accountId: 'x1', text: 'hi', workspaceScope: 'room-1', onAccepted: (sid) => { acceptedWith = sid }
})
expect(receipt.sessionId).toBe('s1')
expect(acceptedWith).toBe('s1')
expect(seen.some((e) => e.type === 'message_delta' && e.text === 'par')).toBe(true)
expect(seen.some((e) => e.type === 'message' && e.message.text === 'partial done')).toBe(true)
expect(adapter.getStatus('x1')).toBe('online')
})

it('a missing confirmation fails before acceptance and flags the account', async () => {
const fake = fakeBridge(async () => { throw new Error('[external:needs-confirm] 首次运行此命令前需要你在界面确认') })
const adapter = new ExternalAdapter(() => fake.bridge)
const err = await adapter.sendMessage({ conversationId: 'c', accountId: 'x1', text: 'hi' }).catch((e) => e)
expect(err).toBeInstanceOf(AdapterError)
expect(err.code).toBe('not-connected')
expect(adapter.getStatus('x1')).toBe('attention')
expect(await adapter.connect('x1')).toBe('attention')
})

it('a failure after acceptance is no-reply; abort cancels the main-side run', async () => {
const controller = new AbortController()
const fake = fakeBridge((req) => new Promise((_resolve, reject) => {
fake.emit({ type: 'accepted', requestId: req.requestId, accountId: req.accountId })
setTimeout(() => reject(new Error('[external:timeout] 外部成员超时')), 20)
}))
const adapter = new ExternalAdapter(() => fake.bridge)
const err = await adapter.sendMessage({ conversationId: 'c', accountId: 'x1', text: 'hi' }).catch((e) => e)
expect(err.code).toBe('no-reply')
expect(adapter.getStatus('x1')).toBe('online')

const hang = fakeBridge(() => new Promise(() => undefined))
const a2 = new ExternalAdapter(() => hang.bridge)
const run = a2.sendMessage({ conversationId: 'c', accountId: 'x1', text: 'hi', signal: controller.signal })
void run.catch(() => undefined)
// The first-run check reads the config first; abort once the run is under way.
await new Promise((r) => setTimeout(r, 0))
controller.abort()
await new Promise((r) => setTimeout(r, 0))
expect(hang.cancelled).toHaveLength(1)
void run.catch(() => undefined)
})

it('asks the UI before a first run: refused skips the turn, allowed runs it', async () => {
let chats = 0
const fake = fakeBridge(async () => { chats++; return { messageId: 'm', text: 'ok', createdAt: 1 } })
const adapter = new ExternalAdapter(() => fake.bridge)
let answer = false
const asked: string[] = []
const off = setExternalConfirmHandler(async (req) => { asked.push(req.config.command); return answer })
try {
const err = await adapter.sendMessage({ conversationId: 'c', accountId: 'x1', text: 'hi' }).catch((e) => e)
expect(err).toBeInstanceOf(AdapterError)
expect(err.code).toBe('not-connected')
expect(chats).toBe(0)
expect(adapter.getStatus('x1')).toBe('attention')
answer = true
await adapter.sendMessage({ conversationId: 'c', accountId: 'x1', text: 'hi' })
expect(chats).toBe(1)
expect(asked).toEqual(['claude', 'claude'])
} finally {
off()
}
})
})
158 changes: 158 additions & 0 deletions src/adapters/external/ExternalAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import type { ExternalBridge, ExternalErrorCode } from '@shared/externalAgents'
import { createId } from '@shared/id'
import { getBotHubBridge } from '../meta-muse/electronBridge'
import { requestExternalConfirm } from './confirmGate'
import { statusAfterSendFailure } from '../sendFailure'
import {
AdapterError, type AdapterErrorCode, type AdapterEvent, type AdapterListener, type ConnectionStatus,
type IncomingMessage, type OutgoingMessage, type PlatformAccount, type PlatformAdapter, type SendReceipt
} from '../types'

/** Main encodes `[external:<code>] message` so the code survives IPC. */
export function decodeExternalError(error: unknown): { code: ExternalErrorCode | 'unknown'; message: string } {
const text = error instanceof Error ? error.message : String(error)
const match = /\[external:([a-z-]+)\]\s*([\s\S]*)$/.exec(text)
return match ? { code: match[1] as ExternalErrorCode, message: match[2] } : { code: 'unknown', message: text }
}

const ADAPTER_CODES: Partial<Record<ExternalErrorCode, AdapterErrorCode>> = {
timeout: 'timeout', network: 'network', http: 'network', process: 'network',
'needs-confirm': 'not-connected', config: 'unsupported'
}

/**
* 外部成员: an OpenAI-compatible API or a local command, run in the main
* process. The adapter only relays; it never sees the API key.
*/
export class ExternalAdapter implements PlatformAdapter {
readonly id = 'external'
readonly name = '外部成员'
private readonly listeners = new Set<AdapterListener>()
private readonly statuses = new Map<string, ConnectionStatus>()
private readonly runs = new Map<string, string>()

constructor(private readonly getApi: () => ExternalBridge | undefined = () => getBotHubBridge()?.external) {}

private api(): ExternalBridge {
const api = this.getApi()
if (!api) throw new AdapterError('not-connected', '外部成员需要桌面版')
return api
}
subscribe(listener: AdapterListener) {
this.listeners.add(listener)
return () => { this.listeners.delete(listener) }
}
onMessage(listener: (message: IncomingMessage) => void) {
return this.subscribe((event) => { if (event.type === 'message') listener(event.message) })
}
private emit(event: AdapterEvent) {
for (const listener of this.listeners) listener(event)
}
private status(accountId: string, status: ConnectionStatus, detail?: string) {
this.statuses.set(accountId, status)
this.emit({ type: 'status', accountId, status, detail })
return status
}
getStatus(accountId: string) { return this.statuses.get(accountId) ?? 'offline' }

async listAccounts(): Promise<PlatformAccount[]> {
const api = this.api()
const ids = await api.listAccounts()
const configs = await Promise.all(ids.map((id) => api.config(id).catch(() => null)))
return ids.map((id, i) => ({
id, platformId: this.id, displayName: configs[i]?.name ?? this.name,
handle: configs[i]?.kind === 'cli' ? configs[i].command : configs[i]?.kind === 'openai' ? configs[i].model : id
}))
}

async connect(accountId: string): Promise<ConnectionStatus> {
const config = await this.api().config(accountId)
if (!config) return this.status(accountId, 'offline')
if (config.kind === 'cli' && config.needsConfirm) return this.status(accountId, 'attention', '首次运行需确认命令')
if (config.kind === 'openai' && !config.hasApiKey && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])/.test(config.baseUrl)) {
return this.status(accountId, 'attention', '缺少 API Key')
}
return this.status(accountId, [...this.runs.values()].includes(accountId) ? 'busy' : 'online')
}

async disconnect(accountId: string) {
this.status(accountId, 'offline')
await Promise.all([...this.runs].filter(([, owner]) => owner === accountId)
.map(([requestId]) => this.api().cancel(accountId, requestId).catch(() => undefined)))
}

/** A CLI member's first run (or a changed command line) waits for the user's 允许 in the UI. */
private async confirmFirstRun(api: ExternalBridge, accountId: string): Promise<void> {
const config = await api.config(accountId).catch(() => null)
if (config?.kind !== 'cli' || !config.needsConfirm) return
const asked = requestExternalConfirm({ accountId, config })
if (!asked) return
if (await asked) return
this.status(accountId, 'attention', '首次运行需确认命令')
throw new AdapterError('not-connected', '你拒绝了运行这个本地命令,这一轮已跳过')
}

async sendMessage(input: OutgoingMessage): Promise<SendReceipt> {
const { accountId, conversationId, signal } = input
signal?.throwIfAborted()
const api = this.api()
await this.confirmFirstRun(api, accountId)
signal?.throwIfAborted()
const requestId = createId('external')
let accepted = false
let acceptedAt = 0
let sessionId = input.sessionId
const accept = (sid?: string) => {
if (sid) sessionId = sid
if (accepted) return
accepted = true
acceptedAt = Date.now()
input.onAccepted?.(sid)
}
const off = api.onEvent((event) => {
if (event.requestId !== requestId || event.accountId !== accountId || signal?.aborted) return
accept(event.sessionId)
if (event.type === 'progress') {
this.emit({ type: 'message_delta', accountId, sessionId, conversationId, messageId: requestId, text: event.text })
}
})
const abort = () => { void api.cancel(accountId, requestId).catch(() => undefined) }
signal?.addEventListener('abort', abort, { once: true })
this.runs.set(requestId, accountId)
this.status(accountId, 'busy')
this.emit({ type: 'typing', accountId, sessionId, conversationId, isTyping: true })
let settled: ConnectionStatus = 'online'
try {
const result = await api.chat({
accountId, requestId, conversationId, sessionId, workspaceScope: input.workspaceScope, text: input.text
})
signal?.throwIfAborted()
accept(result.sessionId)
sessionId = result.sessionId
this.emit({ type: 'message', message: {
accountId, sessionId, conversationId, id: result.messageId, text: result.text, createdAt: result.createdAt
} })
return { messageId: requestId, sessionId, acceptedAt }
} catch (error) {
signal?.throwIfAborted()
const { code, message } = decodeExternalError(error)
const failure = new AdapterError(code === 'unknown' ? 'network' : ADAPTER_CODES[code] ?? 'network', message)
// A timeout or a failed command must not lock the composer; only a missing confirmation asks for attention.
settled = code === 'needs-confirm' ? 'attention' : statusAfterSendFailure(failure)
if (accepted) throw new AdapterError('no-reply', message)
throw failure
} finally {
off()
signal?.removeEventListener('abort', abort)
this.runs.delete(requestId)
this.emit({ type: 'typing', accountId, sessionId, conversationId, isTyping: false })
if (this.getStatus(accountId) !== 'offline') {
this.status(accountId, [...this.runs.values()].includes(accountId) ? 'busy' : settled)
}
}
}
}

export function createExternalAdapter(): ExternalAdapter {
return new ExternalAdapter()
}
33 changes: 33 additions & 0 deletions src/adapters/external/confirmGate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import type { ExternalCliConfig } from '@shared/externalAgents'
import { requestExternalConfirm, setExternalConfirmHandler } from './confirmGate'

const config: ExternalCliConfig = { kind: 'cli', name: 'C', command: 'claude', args: ['-p', '{prompt}'], input: 'arg', cwd: '', timeoutMs: 1000 }

describe('confirmGate', () => {
it('is a no-op without a UI handler (main still refuses)', () => {
expect(requestExternalConfirm({ accountId: 'a', config })).toBeUndefined()
})

it('asks once per account + command line and forgets after settling', async () => {
let asked = 0
let release: (v: boolean) => void = () => undefined
const off = setExternalConfirmHandler(() => { asked++; return new Promise((r) => { release = r }) })
const one = requestExternalConfirm({ accountId: 'a', config })
const two = requestExternalConfirm({ accountId: 'a', config })
expect(one).toBe(two)
expect(asked).toBe(1)
release(true)
expect(await one).toBe(true)
void requestExternalConfirm({ accountId: 'a', config: { ...config, args: ['{prompt}'] } })
expect(asked).toBe(2)
off()
expect(requestExternalConfirm({ accountId: 'a', config })).toBeUndefined()
})

it('a failing handler counts as refused', async () => {
const off = setExternalConfirmHandler(async () => { throw new Error('boom') })
expect(await requestExternalConfirm({ accountId: 'b', config })).toBe(false)
off()
})
})
43 changes: 43 additions & 0 deletions src/adapters/external/confirmGate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { cliFingerprint, type ExternalCliConfig } from '@shared/externalAgents'

/**
* GOXF 外部成员: first-run approval of a local command, asked in the UI.
*
* The renderer mounts one host that registers a handler; the adapter asks
* before running a CLI member whose command line is not yet approved. The
* handler itself records the approval in main (confirmCommand) and resolves
* true; false = the user refused, this turn is skipped. With no handler
* mounted (tests, headless) the gate is a no-op and main still refuses with
* `needs-confirm`, so the safety rule never depends on the UI being there.
*/
export interface ExternalConfirmRequest {
accountId: string
config: ExternalCliConfig
}

export type ExternalConfirmHandler = (request: ExternalConfirmRequest) => Promise<boolean>

let handler: ExternalConfirmHandler | undefined
const pending = new Map<string, Promise<boolean>>()

export function setExternalConfirmHandler(next: ExternalConfirmHandler): () => void {
handler = next
return () => {
if (handler === next) handler = undefined
}
}

/**
* Ask once per account + command line: several room turns that hit the same
* member at once share one prompt. `undefined` = no UI to ask.
*/
export function requestExternalConfirm(request: ExternalConfirmRequest): Promise<boolean> | undefined {
const current = handler
if (!current) return undefined
const key = `${request.accountId}:${cliFingerprint(request.config)}`
const existing = pending.get(key)
if (existing) return existing
const asked = current(request).catch(() => false).finally(() => pending.delete(key))
pending.set(key, asked)
return asked
}
2 changes: 2 additions & 0 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createHermesAdapter } from "./hermes/HermesAdapter"
import { createAntigravityAdapter } from "./antigravity/AntigravityAdapter"
import { createCueAdapter } from "./cue/CueAdapter"
import { createDsBotAdapter } from "./dsbot/DsBotAdapter"
import { createExternalAdapter } from "./external/ExternalAdapter"
import { adapterRegistry, type AdapterRegistry } from "./registry"
import { FakeAdapter, readFakeScript } from "./fake/FakeAdapter"

Expand Down Expand Up @@ -48,4 +49,5 @@ export function registerBuiltInAdapters(registry: AdapterRegistry = adapterRegis
if (!registry.has("antigravity")) registry.register(createAntigravityAdapter())
if (!registry.has("cue")) registry.register(createCueAdapter())
if (!registry.has("ds-bot")) registry.register(createDsBotAdapter())
if (!registry.has("external")) registry.register(createExternalAdapter())
}
8 changes: 8 additions & 0 deletions src/adapters/platforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ export const PLATFORMS: readonly PlatformDescriptor[] = [
availability: 'available',
monogram: 'DS',
homeUrl: 'http://127.0.0.1:8797/mcp'
},
{
// GOXF 外部成员: added from its own group in the add-bot dialog (v33, approved 2026-12-03).
id: 'external',
name: '外部成员',
description: 'OpenAI 兼容 API 或本地命令行工具 · 作为 Bot 进群聊',
availability: 'available',
monogram: 'Ex'
}
]

Expand Down
3 changes: 3 additions & 0 deletions src/adapters/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type PlatformId =
| 'cue'
| 'ds-bot'
| 'gemini'
| 'external'

/** Connection state of a single platform account. */
export type ConnectionStatus = 'online' | 'busy' | 'attention' | 'offline' | 'error'
Expand Down Expand Up @@ -91,6 +92,8 @@ export interface OutgoingMessage {
replyTimeoutMs?: number
/** Optional abort signal (e.g. Collaboration Room Stop) to cancel waiting for the turn. */
signal?: AbortSignal
/** GOXF: room id, so a local-command member runs in that room's workspace directory. */
workspaceScope?: string
}

export interface SendReceipt {
Expand Down
Loading