diff --git a/src/adapters/external/ExternalAdapter.test.ts b/src/adapters/external/ExternalAdapter.test.ts new file mode 100644 index 00000000..a90f4622 --- /dev/null +++ b/src/adapters/external/ExternalAdapter.test.ts @@ -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() + } + }) +}) diff --git a/src/adapters/external/ExternalAdapter.ts b/src/adapters/external/ExternalAdapter.ts new file mode 100644 index 00000000..be7ea5d9 --- /dev/null +++ b/src/adapters/external/ExternalAdapter.ts @@ -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:] 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> = { + 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() + private readonly statuses = new Map() + private readonly runs = new Map() + + 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 { + 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 { + 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 { + 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 { + 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() +} diff --git a/src/adapters/external/confirmGate.test.ts b/src/adapters/external/confirmGate.test.ts new file mode 100644 index 00000000..7095e0d8 --- /dev/null +++ b/src/adapters/external/confirmGate.test.ts @@ -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() + }) +}) diff --git a/src/adapters/external/confirmGate.ts b/src/adapters/external/confirmGate.ts new file mode 100644 index 00000000..90cc8d7d --- /dev/null +++ b/src/adapters/external/confirmGate.ts @@ -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 + +let handler: ExternalConfirmHandler | undefined +const pending = new Map>() + +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 | 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 +} diff --git a/src/adapters/index.ts b/src/adapters/index.ts index b096d91c..9fa11014 100644 --- a/src/adapters/index.ts +++ b/src/adapters/index.ts @@ -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" @@ -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()) } diff --git a/src/adapters/platforms.ts b/src/adapters/platforms.ts index 9d14f36c..6bd65f8a 100644 --- a/src/adapters/platforms.ts +++ b/src/adapters/platforms.ts @@ -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' } ] diff --git a/src/adapters/types.ts b/src/adapters/types.ts index d7b1a57a..581eee04 100644 --- a/src/adapters/types.ts +++ b/src/adapters/types.ts @@ -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' @@ -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 { diff --git a/src/main/external/cliRunner.test.ts b/src/main/external/cliRunner.test.ts new file mode 100644 index 00000000..3d512558 --- /dev/null +++ b/src/main/external/cliRunner.test.ts @@ -0,0 +1,100 @@ +import { mkdtempSync, realpathSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, describe, expect, it } from 'vitest' +import { ExternalRunError } from './externalErrors' +import { MAX_STDERR_CHARS, buildInvocation, runCli, spawnOptions, type SpawnLike } from './cliRunner' +import { spawn } from 'node:child_process' + +const node = process.execPath +const dir = mkdtempSync(join(tmpdir(), 'ext-cli-')) +afterAll(() => rmSync(dir, { recursive: true, force: true })) + +describe('buildInvocation (template → argv, no shell)', () => { + it('substitutes {prompt} inside one argv entry as literal text', () => { + const evil = 'hi"; rm -rf / #$(whoami) `id` $& $1 && echo pwned | cat > x' + const inv = buildInvocation({ command: 'claude', args: ['-p', '{prompt}', '--x={prompt}!'], input: 'arg' }, evil) + expect(inv).toEqual({ file: 'claude', args: ['-p', evil, `--x=${evil}!`], stdin: undefined }) + }) + it('stdin mode leaves the template untouched and pipes the prompt', () => { + const inv = buildInvocation({ command: 'tool', args: ['--read', '{prompt}'], input: 'stdin' }, 'q') + expect(inv).toEqual({ file: 'tool', args: ['--read', '{prompt}'], stdin: 'q' }) + }) + it('rejects arg mode without a {prompt} slot, empty commands and NUL', () => { + expect(() => buildInvocation({ command: 'x', args: ['-p'], input: 'arg' }, 'q')).toThrow(/\{prompt\}/) + expect(() => buildInvocation({ command: ' ', args: [], input: 'stdin' }, 'q')).toThrow(ExternalRunError) + expect(() => buildInvocation({ command: 'x', args: ['{prompt}'], input: 'arg' }, 'a\0b')).toThrow(/空字符/) + }) + it('refuses .cmd/.bat on Windows instead of quoting for cmd.exe', () => { + expect(() => buildInvocation({ command: 'claude.cmd', args: ['{prompt}'], input: 'arg' }, 'q', 'win32')).toThrow(/cmd/) + expect(buildInvocation({ command: 'claude.cmd', args: ['{prompt}'], input: 'arg' }, 'q', 'linux').file).toBe('claude.cmd') + }) + it('spawn options never enable a shell', () => { + expect(spawnOptions('/tmp')).toMatchObject({ shell: false, cwd: '/tmp', windowsHide: true }) + expect(spawnOptions('').cwd).toBeUndefined() + }) + it('passes argv straight to spawn (spied)', async () => { + const calls: Parameters[] = [] + const spy: SpawnLike = (file, args, options) => { calls.push([file, args, options]); return spawn(node, ['-e', ''], options) } + await runCli(buildInvocation({ command: 'mytool', args: ['-p', '{prompt}'], input: 'arg' }, 'a b; c'), { timeoutMs: 5000, spawn: spy }) + expect(calls[0][0]).toBe('mytool') + expect(calls[0][1]).toEqual(['-p', 'a b; c']) + expect(calls[0][2].shell).toBe(false) + }) +}) + +describe('runCli with a fake command (node -e)', () => { + it('returns trimmed stdout and receives shell metacharacters literally', async () => { + const evil = '$(echo pwned); `id` | cat' + const inv = buildInvocation({ command: node, args: ['-e', 'process.stdout.write("got:" + process.argv[1] + "\\n")', '{prompt}'], input: 'arg' }, evil) + expect(await runCli(inv, { timeoutMs: 10_000 })).toBe('got:' + evil) + }) + it('feeds stdin mode and streams output', async () => { + const inv = buildInvocation({ command: node, args: ['-e', 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(s.toUpperCase()))'], input: 'stdin' }, 'hello stdin') + const seen: string[] = [] + expect(await runCli(inv, { timeoutMs: 10_000, onOutput: (t) => seen.push(t) })).toBe('HELLO STDIN') + expect(seen.length).toBeGreaterThan(0) + }) + it('runs in the given working directory', async () => { + const inv = { file: node, args: ['-e', 'console.log(process.cwd())'] } + expect(realpathSync(await runCli(inv, { cwd: dir, timeoutMs: 10_000 }))).toBe(realpathSync(dir)) + }) + it('kills on timeout', async () => { + const started = Date.now() + const err = await runCli({ file: node, args: ['-e', 'setInterval(()=>{},1000)'] }, { timeoutMs: 1000 }).catch((e) => e) + expect(err).toBeInstanceOf(ExternalRunError) + expect(err.code).toBe('timeout') + expect(Date.now() - started).toBeLessThan(5000) + }) + it('escalates to SIGKILL when SIGTERM is ignored', async () => { + if (process.platform === 'win32') return // Windows has no SIGTERM handler semantics + let child: ReturnType | undefined + const spy: SpawnLike = (file, args, options) => (child = spawn(file, args, options)) + const err = await runCli( + { file: node, args: ['-e', 'process.on("SIGTERM",()=>{});setInterval(()=>{},1000)'] }, + { timeoutMs: 800, spawn: spy } + ).catch((e) => e) + expect(err.code).toBe('timeout') + const signal = await new Promise((r) => child!.once('exit', (_code, sig) => r(sig))) + expect(signal).toBe('SIGKILL') + }, 10_000) + it('cancels via the caller signal', async () => { + const controller = new AbortController() + const run = runCli({ file: node, args: ['-e', 'setInterval(()=>{},1000)'] }, { timeoutMs: 10_000, signal: controller.signal }) + setTimeout(() => controller.abort(), 200) + expect((await run.catch((e) => e)).code).toBe('cancelled') + }) + it('reports a non-zero exit with truncated stderr', async () => { + const err = await runCli({ file: node, args: ['-e', `process.stderr.write("E".repeat(${MAX_STDERR_CHARS * 3}));process.exit(3)`] }, { timeoutMs: 10_000 }) + .catch((e) => e) + expect(err.code).toBe('process') + expect(err.message).toMatch(/退出码 3/) + expect(err.message).toMatch(/已截断/) + expect(err.message.length).toBeLessThan(MAX_STDERR_CHARS + 200) + }) + it('reports a missing command', async () => { + const err = await runCli({ file: join(dir, 'definitely-missing-cmd'), args: [] }, { timeoutMs: 5000 }).catch((e) => e) + expect(err.code).toBe('process') + expect(err.message).toMatch(/找不到命令/) + }) +}) diff --git a/src/main/external/cliRunner.ts b/src/main/external/cliRunner.ts new file mode 100644 index 00000000..83ba6942 --- /dev/null +++ b/src/main/external/cliRunner.ts @@ -0,0 +1,142 @@ +import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from 'node:child_process' +import type { ExternalCliConfig } from '@shared/externalAgents' +import { ExternalRunError, truncate, turnSignal } from './externalErrors' + +export const PROMPT_TOKEN = '{prompt}' +/** Reply cap: a runaway command must not fill memory. */ +export const MAX_STDOUT_BYTES = 4 * 1024 * 1024 +export const MAX_STDERR_CHARS = 2000 +/** Grace between SIGTERM and SIGKILL. */ +export const KILL_GRACE_MS = 2000 + +export interface CliInvocation { + file: string + args: string[] + /** Text written to stdin, then stdin is closed. Undefined = stdin closed empty. */ + stdin?: string +} + +/** + * Turn the template into argv. Pure: `{prompt}` is substituted inside each + * array entry as plain text; the prompt can never add, split or quote argv + * entries, and nothing goes through a shell. + */ +export function buildInvocation( + config: Pick, + prompt: string, + platform: NodeJS.Platform = process.platform +): CliInvocation { + const file = config.command.trim() + if (!file) throw new ExternalRunError('config', '本地命令未填写') + if (/[\0\r\n]/.test(file)) throw new ExternalRunError('config', '命令名不能含换行或空字符') + // Windows runs .cmd/.bat through cmd.exe, which re-parses argv (BatBadBut): refuse instead of quoting. + if (platform === 'win32' && /\.(cmd|bat)$/i.test(file)) { + throw new ExternalRunError('config', 'Windows 的 .cmd/.bat 会经 cmd 解析,不安全:请填 node.exe 等可执行文件,脚本路径放进参数') + } + if (prompt.includes('\0')) throw new ExternalRunError('config', '消息含空字符,不能作为命令参数') + const usesArg = config.input === 'arg' + if (usesArg && !config.args.some((arg) => arg.includes(PROMPT_TOKEN))) { + throw new ExternalRunError('config', '参数模板里需要 {prompt},或改为通过 stdin 传入') + } + // Replacer function: `$&`/`$1` in the prompt stay literal. + const args = config.args.map((arg) => (usesArg ? arg.split(PROMPT_TOKEN).join(prompt) : arg)) + return { file, args, stdin: usesArg ? undefined : prompt } +} + +/** Options handed to spawn: never a shell, no window on Windows. */ +export function spawnOptions(cwd: string | undefined, env: NodeJS.ProcessEnv = process.env): SpawnOptions { + return { + cwd: cwd || undefined, + env, + shell: false, + windowsHide: true, + stdio: ['pipe', 'pipe', 'pipe'] + } +} + +export type SpawnLike = (file: string, args: string[], options: SpawnOptions) => ChildProcess + +export interface CliRunOptions { + cwd?: string + timeoutMs: number + signal?: AbortSignal + spawn?: SpawnLike + /** Called with the stdout text so far as it arrives. */ + onOutput?: (text: string) => void +} + +function killTree(child: ChildProcess): void { + if (child.exitCode !== null || child.signalCode !== null) return + child.kill('SIGTERM') + const hard = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') + }, KILL_GRACE_MS) + hard.unref?.() +} + +/** Run the command; resolves with trimmed stdout on exit code 0. */ +export function runCli(invocation: CliInvocation, options: CliRunOptions): Promise { + const turn = turnSignal(options.signal, options.timeoutMs) + return new Promise((resolve, reject) => { + let child: ChildProcess + try { + child = (options.spawn ?? (nodeSpawn as SpawnLike))(invocation.file, invocation.args, spawnOptions(options.cwd)) + } catch { + turn.dispose() + reject(new ExternalRunError('process', `无法启动命令 ${invocation.file}`)) + return + } + const out: Buffer[] = [] + let outBytes = 0 + let overflow = false + let stderr = '' + let settled = false + const finish = (error: ExternalRunError | null, text = '') => { + if (settled) return + settled = true + turn.dispose() + turn.signal.removeEventListener('abort', onAbort) + if (error) reject(error) + else resolve(text) + } + const onAbort = () => { + killTree(child) + finish(turn.reason()) + } + turn.signal.addEventListener('abort', onAbort, { once: true }) + if (turn.signal.aborted) onAbort() + + child.stdout?.on('data', (chunk: Buffer) => { + if (overflow) return + outBytes += chunk.length + if (outBytes > MAX_STDOUT_BYTES) { + overflow = true + killTree(child) + finish(new ExternalRunError('process', `命令输出超过 ${MAX_STDOUT_BYTES / 1024 / 1024} MB,已停止`)) + return + } + out.push(chunk) + options.onOutput?.(Buffer.concat(out).toString('utf8')) + }) + child.stderr?.on('data', (chunk: Buffer) => { + if (stderr.length < MAX_STDERR_CHARS * 2) stderr += chunk.toString('utf8') + }) + child.on('error', (error: NodeJS.ErrnoException) => { + const why = error.code === 'ENOENT' ? '找不到命令' : error.code === 'EACCES' ? '没有执行权限' + : error.code === 'EINVAL' ? '不能直接启动(Windows 的 .cmd/.bat 需改填可执行文件)' : '启动失败' + finish(new ExternalRunError('process', `${why}:${invocation.file}`)) + }) + child.on('close', (code, signal) => { + if (code === 0) { + finish(null, Buffer.concat(out).toString('utf8').trim()) + return + } + const tail = stderr.trim() ? `\n${truncate(stderr.trim(), MAX_STDERR_CHARS)}` : '' + const how = code === null ? `被信号 ${signal ?? '?'} 结束` : `退出码 ${code}` + finish(new ExternalRunError('process', `命令${how}${tail}`)) + }) + child.stdin?.on('error', () => undefined) // EPIPE when the command ignores stdin + if (invocation.stdin !== undefined) child.stdin?.end(invocation.stdin, 'utf8') + else child.stdin?.end() + }) +} diff --git a/src/main/external/externalConfig.ts b/src/main/external/externalConfig.ts new file mode 100644 index 00000000..7d62b8b9 --- /dev/null +++ b/src/main/external/externalConfig.ts @@ -0,0 +1,121 @@ +import { + EXTERNAL_DEFAULT_TIMEOUT_MS, EXTERNAL_MAX_TIMEOUT_MS, cliFingerprint, + type ExternalCliConfig, type ExternalConfig, type ExternalDraft, type ExternalOpenAiConfig, + type ExternalPublicConfig +} from '@shared/externalAgents' +import { ExternalRunError } from './externalErrors' + +/** Stored form: config plus the write-only key (vault only). */ +export type StoredExternal = ExternalConfig & { apiKey?: string } + +export function validAccountId(accountId: unknown): string { + if (typeof accountId !== 'string' || !/^[\w-]{1,100}$/.test(accountId)) { + throw new ExternalRunError('config', '无效的外部成员 ID') + } + return accountId +} + +function timeout(value: number | undefined, fallback: number | undefined): number { + const ms = value ?? fallback ?? EXTERNAL_DEFAULT_TIMEOUT_MS + if (!Number.isFinite(ms) || ms < 1000 || ms > EXTERNAL_MAX_TIMEOUT_MS) { + throw new ExternalRunError('config', '超时需在 1 秒到 30 分钟之间') + } + return Math.round(ms) +} + +function name(value: string | undefined, fallback: string | undefined, kind: string): string { + const text = (value ?? fallback ?? '').trim() || (kind === 'cli' ? '本地命令' : '外部 API') + return text.slice(0, 60) +} + +function resolveOpenAi(current: StoredExternal | null, draft: Extract) { + const prev = current?.kind === 'openai' ? current : undefined + const raw = (draft.baseUrl ?? prev?.baseUrl ?? '').trim() + let url: URL + try { + url = new URL(raw) + } catch { + throw new ExternalRunError('config', '请填写有效的 API 地址') + } + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) + if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || + url.username || url.password || url.search || url.hash) { + throw new ExternalRunError('config', 'API 地址需要 HTTPS,或本机 HTTP(localhost)') + } + const baseUrl = url.href.replace(/\/+$/, '') + const typed = draft.apiKey?.trim() + if (typed && /[^!-~]/.test(typed)) throw new ExternalRunError('config', 'API Key 格式不对') + // A key never follows the config to a different host unless typed again. + const apiKey = typed || (prev && prev.baseUrl === baseUrl ? prev.apiKey : undefined) + if (prev?.apiKey && prev.baseUrl !== baseUrl && !typed) { + throw new ExternalRunError('config', '换了 API 地址,请重新输入 API Key') + } + const model = (draft.model ?? prev?.model ?? '').trim() + if (!model || model.length > 200 || /[\0\r\n]/.test(model)) throw new ExternalRunError('config', '请填写模型名') + const temperature = draft.temperature ?? prev?.temperature + if (temperature !== undefined && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) { + throw new ExternalRunError('config', 'temperature 需在 0 到 2 之间') + } + const config: ExternalOpenAiConfig & { apiKey?: string } = { + kind: 'openai', + name: name(draft.name, prev?.name, 'openai'), + baseUrl, model, temperature, + systemPrompt: (draft.systemPrompt ?? prev?.systemPrompt ?? '').slice(0, 20_000), + stream: draft.stream ?? prev?.stream ?? true, + timeoutMs: timeout(draft.timeoutMs, prev?.timeoutMs), + ...(apiKey ? { apiKey } : {}) + } + return config +} + +function resolveCli(current: StoredExternal | null, draft: Extract) { + const prev = current?.kind === 'cli' ? current : undefined + const command = (draft.command ?? prev?.command ?? '').trim() + if (!command || command.length > 1000 || /[\0\r\n]/.test(command)) throw new ExternalRunError('config', '请填写命令') + const args = draft.args ?? prev?.args ?? [] + if (!Array.isArray(args) || args.length > 64 || args.some((a) => typeof a !== 'string' || a.length > 4000 || a.includes('\0'))) { + throw new ExternalRunError('config', '参数模板格式不对') + } + const input = draft.input ?? prev?.input ?? 'arg' + if (input !== 'arg' && input !== 'stdin') throw new ExternalRunError('config', '输入方式只能是参数或 stdin') + const cwd = (draft.cwd ?? prev?.cwd ?? '').trim() + if (/[\0\r\n]/.test(cwd)) throw new ExternalRunError('config', '工作目录格式不对') + const next: ExternalCliConfig = { + kind: 'cli', + name: name(draft.name, prev?.name, 'cli'), + command, args: [...args], input, cwd, + timeoutMs: timeout(draft.timeoutMs, prev?.timeoutMs) + } + // Keep the approval only while the confirmed command line is unchanged. + if (prev?.confirmedAt && prev.confirmedFingerprint === cliFingerprint(next)) { + next.confirmedAt = prev.confirmedAt + next.confirmedFingerprint = prev.confirmedFingerprint + } + return next +} + +export function resolveDraft(current: StoredExternal | null, draft: ExternalDraft): StoredExternal { + if (!draft || (draft.kind !== 'openai' && draft.kind !== 'cli')) throw new ExternalRunError('config', '未知的外部成员类型') + if (current && current.kind !== draft.kind) throw new ExternalRunError('config', '不能改变外部成员类型,请新建一个') + return draft.kind === 'openai' ? resolveOpenAi(current, draft) : resolveCli(current, draft) +} + +export function needsConfirm(config: ExternalCliConfig): boolean { + return !config.confirmedAt || config.confirmedFingerprint !== cliFingerprint(config) +} + +/** Record approval of exactly the command line the card showed. */ +export function confirmCli(config: StoredExternal, fingerprint: string, now = Date.now()): ExternalCliConfig { + if (config.kind !== 'cli') throw new ExternalRunError('config', '只有本地命令需要确认') + if (fingerprint !== cliFingerprint(config)) throw new ExternalRunError('config', '命令已改动,请重新确认') + return { ...config, confirmedAt: now, confirmedFingerprint: fingerprint } +} + +/** Renderer-safe view: the API key is reduced to a flag. */ +export function publicConfig(stored: StoredExternal): ExternalPublicConfig { + if (stored.kind === 'openai') { + const { apiKey, ...config } = stored + return { ...config, hasApiKey: Boolean(apiKey) } + } + return { ...stored, needsConfirm: needsConfirm(stored) } +} diff --git a/src/main/external/externalErrors.ts b/src/main/external/externalErrors.ts new file mode 100644 index 00000000..eaa4e239 --- /dev/null +++ b/src/main/external/externalErrors.ts @@ -0,0 +1,65 @@ +import type { ExternalErrorCode } from '@shared/externalAgents' + +/** An error whose message is safe to show in the renderer (no secrets, no upstream body). */ +export class ExternalRunError extends Error { + readonly code: ExternalErrorCode + constructor(code: ExternalErrorCode, message: string) { + super(message) + this.name = 'ExternalRunError' + this.code = code + } +} + +/** + * Remove every occurrence of the given secrets (and their Bearer form) from a + * text. Used on every error message that may have touched the key, as a second + * line of defence after never building messages from request data. + */ +export function redactSecrets(text: string, secrets: ReadonlyArray): string { + let out = text + for (const secret of secrets) { + if (!secret || secret.length < 4) continue + out = out.split(secret).join('***') + } + return out.replace(/Bearer\s+[^\s"']+/gi, 'Bearer ***') +} + +/** Keep the tail end readable: first `max` chars plus a marker. */ +export function truncate(text: string, max: number): string { + return text.length <= max ? text : text.slice(0, max) + `…(已截断,共 ${text.length} 字)` +} + +/** + * Combine the caller's cancel signal with a turn timeout. `reason()` tells the + * two apart after an abort so errors read 「超时」 vs 「已取消」. + */ +export function turnSignal(signal: AbortSignal | undefined, timeoutMs: number) { + const controller = new AbortController() + let timedOut = false + const timer = setTimeout(() => { + timedOut = true + controller.abort(new ExternalRunError('timeout', `外部成员超时(${Math.round(timeoutMs / 1000)} 秒)`)) + }, timeoutMs) + const onAbort = () => controller.abort(new ExternalRunError('cancelled', '已取消')) + if (signal?.aborted) onAbort() + else signal?.addEventListener('abort', onAbort, { once: true }) + return { + signal: controller.signal, + timedOut: () => timedOut, + /** The ExternalRunError explaining why the turn stopped. */ + reason: (): ExternalRunError => + controller.signal.reason instanceof ExternalRunError + ? controller.signal.reason + : new ExternalRunError('cancelled', '已取消'), + dispose: () => { + clearTimeout(timer) + signal?.removeEventListener('abort', onAbort) + } + } +} + +/** Error text crossing IPC keeps its code: `[external:] message`. Unknown errors lose their text. */ +export function encodeIpcError(error: unknown): Error { + if (error instanceof ExternalRunError) return new Error(`[external:${error.code}] ${error.message}`) + return new Error('[external:network] 外部成员运行失败') +} diff --git a/src/main/external/externalHistory.ts b/src/main/external/externalHistory.ts new file mode 100644 index 00000000..8e457427 --- /dev/null +++ b/src/main/external/externalHistory.ts @@ -0,0 +1,80 @@ +import { randomUUID } from 'node:crypto' +import type { ChatMessage } from './openaiClient' + +/** + * Per-session chat history for OpenAI-compatible members. The room sends only + * what is new since the member's cursor once a session exists, so main keeps + * the earlier turns here. Pure: persistence is injected. + */ +export interface HistoryThread { + accountId: string + updatedAt: number + messages: ChatMessage[] +} +export type HistorySnapshot = Record + +export const MAX_THREAD_MESSAGES = 60 +export const MAX_THREAD_CHARS = 200_000 +export const MAX_THREADS = 300 + +export class ExternalHistory { + private readonly threads = new Map() + + constructor( + snapshot: HistorySnapshot = {}, + private readonly persist: (snapshot: HistorySnapshot) => void = () => undefined + ) { + for (const [id, thread] of Object.entries(snapshot)) { + if (thread && typeof thread.accountId === 'string' && Array.isArray(thread.messages)) this.threads.set(id, thread) + } + } + + /** Existing thread for this account, or a new id when missing / foreign. */ + open(accountId: string, sessionId: string | undefined): { sessionId: string; messages: ChatMessage[]; fresh: boolean } { + const thread = sessionId ? this.threads.get(sessionId) : undefined + if (sessionId && thread && thread.accountId === accountId) { + return { sessionId, messages: [...thread.messages], fresh: false } + } + return { sessionId: randomUUID(), messages: [], fresh: true } + } + + /** Commit a finished turn (user + assistant together, never a half turn). */ + append(accountId: string, sessionId: string, turn: ChatMessage[], now = Date.now()): void { + const prev = this.threads.get(sessionId) + const messages = trimThread([...(prev?.accountId === accountId ? prev.messages : []), ...turn]) + this.threads.delete(sessionId) + this.threads.set(sessionId, { accountId, updatedAt: now, messages }) + while (this.threads.size > MAX_THREADS) this.threads.delete(this.threads.keys().next().value!) + this.persist(this.snapshot()) + } + + dropAccount(accountId: string): void { + for (const [id, thread] of this.threads) if (accountId === '*' || thread.accountId === accountId) this.threads.delete(id) + this.persist(this.snapshot()) + } + + snapshot(): HistorySnapshot { + return Object.fromEntries(this.threads) + } +} + +/** Drop the oldest messages (in user/assistant pairs) past the caps. */ +export function trimThread(messages: ChatMessage[]): ChatMessage[] { + let out = messages.slice(-MAX_THREAD_MESSAGES) + let chars = out.reduce((n, m) => n + m.content.length, 0) + while (out.length > 2 && chars > MAX_THREAD_CHARS) { + chars -= out[0].content.length + out = out.slice(1) + } + while (out.length && out[0].role === 'assistant') out = out.slice(1) + return out +} + +/** System prompt + history + this turn. */ +export function buildMessages(systemPrompt: string, history: ChatMessage[], text: string): ChatMessage[] { + return [ + ...(systemPrompt.trim() ? [{ role: 'system' as const, content: systemPrompt }] : []), + ...history, + { role: 'user' as const, content: text } + ] +} diff --git a/src/main/external/externalIpc.ts b/src/main/external/externalIpc.ts new file mode 100644 index 00000000..6cdef5cf --- /dev/null +++ b/src/main/external/externalIpc.ts @@ -0,0 +1,78 @@ +import { join } from 'node:path' +import { app, dialog, ipcMain, type BrowserWindow } from 'electron' +import { EXTERNAL_CHANNELS, type ExternalBridge, type ExternalChatRequest } from '@shared/externalAgents' +import { readJsonFile, writeJsonAtomicAsync } from '../jsonFile' +import { resolveWorkspaceRootFor } from '../mcp/hub' +import { loadAccountProxyUrl } from '../muse/accountProxy' +import { proxyFetch } from '../proxyTransport' +import { deleteVaultSecret, getVaultSecret, listVaultKeys, setVaultSecret } from '../securityVault' +import { encodeIpcError } from './externalErrors' +import { ExternalHistory, type HistorySnapshot } from './externalHistory' +import { createExternalService, type ExternalService } from './externalService' + +const HISTORY_FILE = 'external-sessions.json' +let service: ExternalService | undefined + +function createHistory(): ExternalHistory { + const path = join(app.getPath('userData'), HISTORY_FILE) + const snapshot = readJsonFile(path, {}, (raw) => Boolean(raw) && typeof raw === 'object' && !Array.isArray(raw)) + let pending: Promise = Promise.resolve() + return new ExternalHistory(snapshot, (next) => { + pending = pending.then(() => writeJsonAtomicAsync(path, next)).catch(() => undefined) + }) +} + +export function registerExternalIpc(getWindow: () => BrowserWindow | null): void { + const svc = createExternalService({ + vault: { get: getVaultSecret, set: setVaultSecret, delete: deleteVaultSecret, list: listVaultKeys }, + history: createHistory(), + fetchFor: async (accountId) => { + const proxy = await loadAccountProxyUrl(accountId).catch(() => undefined) + return (url, init) => proxyFetch(proxy, url, init) + }, + workspaceDir: async (scope) => (scope ? resolveWorkspaceRootFor(scope) : undefined), + emit: (event) => { + const contents = getWindow()?.webContents + if (contents && !contents.isDestroyed()) contents.send(EXTERNAL_CHANNELS.event, event) + } + }) + service = svc + const methods = { + listAccounts: svc.listAccounts, + config: svc.config, + configure: svc.configure, + confirmCommand: svc.confirmCommand, + remove: svc.remove, + cancel: svc.cancel, + pickDirectory: async () => { + const win = getWindow() + if (!win) return undefined + const pick = await dialog.showOpenDialog(win, { title: '选择本地命令的工作目录', properties: ['openDirectory'] }) + return pick.canceled ? undefined : pick.filePaths[0] + }, + chat: (req: ExternalChatRequest) => { + const contents = getWindow()?.webContents + const stop = () => void svc.cancel(req.accountId, req.requestId) + contents?.once('destroyed', stop) + return svc.chat(req).finally(() => contents?.removeListener('destroyed', stop)) + } + } satisfies { [K in Exclude]-?: + (...args: Parameters>) => ReturnType> | Awaited>> } + for (const name of Object.keys(methods) as (keyof typeof methods)[]) { + ipcMain.handle(EXTERNAL_CHANNELS[name], async (event, ...args) => { + const sender = getWindow()?.webContents + if (!sender || event.sender !== sender || event.senderFrame !== sender.mainFrame) throw new Error('Desktop window required') + try { + return await Reflect.apply(methods[name] as (...a: unknown[]) => unknown, undefined, args) + } catch (error) { + throw encodeIpcError(error) + } + }) + } +} + +export function disposeExternalIpc(): void { + service?.cancelAll() + service = undefined + for (const [name, channel] of Object.entries(EXTERNAL_CHANNELS)) if (name !== 'event') ipcMain.removeHandler(channel) +} diff --git a/src/main/external/externalService.test.ts b/src/main/external/externalService.test.ts new file mode 100644 index 00000000..e91de382 --- /dev/null +++ b/src/main/external/externalService.test.ts @@ -0,0 +1,162 @@ +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { cliFingerprint, type ExternalEvent } from '@shared/externalAgents' +import { ExternalHistory, trimThread, MAX_THREAD_MESSAGES } from './externalHistory' +import { resolveDraft } from './externalConfig' +import { createExternalService, VAULT_PREFIX, type ExternalVault } from './externalService' +import { encodeIpcError } from './externalErrors' + +const KEY = 'sk-live-TOPSECRET-abcdef123456' +const node = process.execPath + +let secrets: Map +let events: ExternalEvent[] +let server: Server | undefined +const vault: ExternalVault = { + get: async (k) => secrets.get(k) ?? null, + set: async (k, v) => secrets.set(k, v), + delete: async (k) => { secrets.delete(k) }, + list: (p) => [...secrets.keys()].filter((k) => k.startsWith(p)) +} +function service(history = new ExternalHistory()) { + return createExternalService({ + vault, history, fetchFor: async () => globalThis.fetch, + workspaceDir: async () => undefined, emit: (e) => events.push(e) + }) +} +beforeEach(() => { secrets = new Map(); events = [] }) +afterEach(() => new Promise((done) => (server ? server.close(() => done()) : done()))) + +async function echoServer(status = 200): Promise<{ url: string; bodies: Array<{ messages: Array<{ role: string; content: string }> }> }> { + const bodies: Array<{ messages: Array<{ role: string; content: string }> }> = [] + server = createServer((req, res) => { + let body = '' + req.on('data', (c) => (body += c)) + req.on('end', () => { + bodies.push(JSON.parse(body)) + if (status !== 200) { + res.writeHead(status) + res.end(`echo ${req.headers.authorization}`) + return + } + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.end(`data: ${JSON.stringify({ choices: [{ delta: { content: `reply#${bodies.length}` } }] })}\n\ndata: [DONE]\n\n`) + }) + }) + await new Promise((r) => server!.listen(0, '127.0.0.1', r)) + return { url: `http://127.0.0.1:${(server!.address() as AddressInfo).port}/v1`, bodies } +} + +describe('config & credentials', () => { + it('keeps the API key in the vault only; public config has a flag', async () => { + const svc = service() + const pub = await svc.configure('a1', { kind: 'openai', baseUrl: 'https://api.example.com/v1', model: 'gpt', apiKey: KEY }) + expect(JSON.stringify(pub)).not.toContain(KEY) + expect(pub).toMatchObject({ kind: 'openai', hasApiKey: true }) + expect(secrets.get(VAULT_PREFIX + 'a1')).toContain(KEY) + expect(JSON.stringify(await svc.config('a1'))).not.toContain(KEY) + expect(await svc.listAccounts()).toEqual(['a1']) + }) + it('keeps the key on an unrelated edit, but not across a host change', async () => { + const svc = service() + await svc.configure('a1', { kind: 'openai', baseUrl: 'https://api.example.com/v1', model: 'gpt', apiKey: KEY }) + expect(await svc.configure('a1', { kind: 'openai', model: 'gpt-2' })).toMatchObject({ hasApiKey: true, model: 'gpt-2' }) + await expect(svc.configure('a1', { kind: 'openai', baseUrl: 'https://evil.example/v1' })).rejects.toThrow(/重新输入/) + }) + it('rejects plain HTTP to a remote host and URL credentials', () => { + expect(() => resolveDraft(null, { kind: 'openai', baseUrl: 'http://api.example.com/v1', model: 'm' })).toThrow(/HTTPS/) + expect(() => resolveDraft(null, { kind: 'openai', baseUrl: 'https://u:p@x.test/v1', model: 'm' })).toThrow(/HTTPS/) + }) + it('clears a CLI confirmation when the command line changes', async () => { + const svc = service() + const draft = { kind: 'cli' as const, command: node, args: ['-e', 'console.log(1)'], input: 'stdin' as const } + const pub = await svc.configure('c1', draft) + expect(pub).toMatchObject({ needsConfirm: true }) + if (pub.kind !== 'cli') throw new Error('kind') + await expect(svc.confirmCommand('c1', 'deadbeef')).rejects.toThrow(/重新确认/) + const ok = await svc.confirmCommand('c1', cliFingerprint(pub)) + expect(ok).toMatchObject({ needsConfirm: false }) + expect(ok.kind === 'cli' && ok.confirmedAt).toBeGreaterThan(0) + expect(await svc.configure('c1', { kind: 'cli', timeoutMs: 5000 })).toMatchObject({ needsConfirm: false }) + expect(await svc.configure('c1', { kind: 'cli', args: ['-e', 'console.log(2)'] })).toMatchObject({ needsConfirm: true }) + }) +}) + +describe('chat', () => { + it('OpenAI: keeps its own history per session; room sends only the increment', async () => { + const { url, bodies } = await echoServer() + const svc = service() + await svc.configure('a1', { kind: 'openai', baseUrl: url, model: 'm', apiKey: KEY, systemPrompt: 'sys' }) + const first = await svc.chat({ accountId: 'a1', requestId: 'r1', conversationId: 'c', text: 'turn one' }) + expect(first.text).toBe('reply#1') + expect(first.sessionId).toBeTruthy() + const second = await svc.chat({ accountId: 'a1', requestId: 'r2', conversationId: 'c', sessionId: first.sessionId, text: 'turn two' }) + expect(second.sessionId).toBe(first.sessionId) + expect(bodies[1].messages).toEqual([ + { role: 'system', content: 'sys' }, + { role: 'user', content: 'turn one' }, + { role: 'assistant', content: 'reply#1' }, + { role: 'user', content: 'turn two' } + ]) + expect(events.some((e) => e.type === 'accepted' && e.requestId === 'r1')).toBe(true) + expect(events.some((e) => e.type === 'progress' && e.text === 'reply#2')).toBe(true) + }) + + it('OpenAI: an upstream body echoing the key never reaches the error (incl. IPC encoding)', async () => { + const { url } = await echoServer(500) + const svc = service() + await svc.configure('a1', { kind: 'openai', baseUrl: url, model: 'm', apiKey: KEY }) + const err = await svc.chat({ accountId: 'a1', requestId: 'r1', conversationId: 'c', text: 'x' }).catch((e) => e) + expect(err.message).toBe('外部 API HTTP 500') + const wire = encodeIpcError(err) + expect(wire.message).toBe('[external:http] 外部 API HTTP 500') + expect(JSON.stringify(events) + wire.message + String(err.stack)).not.toContain(KEY) + }) + + it('CLI: refuses to run before confirmation, then runs once confirmed', async () => { + const svc = service() + const pub = await svc.configure('c1', { kind: 'cli', command: node, args: ['-e', 'console.log("echo:"+process.argv[1])', '{prompt}'], input: 'arg' }) + const err = await svc.chat({ accountId: 'c1', requestId: 'r1', conversationId: 'c', text: 'hi' }).catch((e) => e) + expect(err.code).toBe('needs-confirm') + if (pub.kind !== 'cli') throw new Error('kind') + await svc.confirmCommand('c1', cliFingerprint(pub)) + const ok = await svc.chat({ accountId: 'c1', requestId: 'r2', conversationId: 'c', text: 'hi; ls' }) + expect(ok.text).toBe('echo:hi; ls') + expect(ok.sessionId).toBeUndefined() + }) + + it('CLI: cancel by request id stops the process', async () => { + const svc = service() + const pub = await svc.configure('c1', { kind: 'cli', command: node, args: ['-e', 'setInterval(()=>{},1000)'], input: 'stdin' }) + if (pub.kind !== 'cli') throw new Error('kind') + await svc.confirmCommand('c1', cliFingerprint(pub)) + const run = svc.chat({ accountId: 'c1', requestId: 'r1', conversationId: 'c', text: 'x' }) + await new Promise((r) => setTimeout(r, 200)) + await svc.cancel('c1', 'r1') + expect((await run.catch((e) => e)).code).toBe('cancelled') + }) + + it('remove deletes config, key and history', async () => { + const history = new ExternalHistory() + history.append('a1', 's1', [{ role: 'user', content: 'u' }, { role: 'assistant', content: 'a' }]) + const svc = service(history) + await svc.configure('a1', { kind: 'openai', baseUrl: 'https://x.test/v1', model: 'm', apiKey: KEY }) + await svc.remove('a1') + expect([...secrets.keys()]).toEqual([]) + expect(history.snapshot()).toEqual({}) + }) +}) + +describe('history', () => { + it('never hands a thread to another account and trims to the caps', () => { + const h = new ExternalHistory() + h.append('a', 's', [{ role: 'user', content: 'u' }, { role: 'assistant', content: 'r' }]) + expect(h.open('b', 's').fresh).toBe(true) + expect(h.open('a', 's').messages).toHaveLength(2) + const many = Array.from({ length: MAX_THREAD_MESSAGES + 5 }, (_, i) => ({ role: i % 2 ? 'assistant' as const : 'user' as const, content: String(i) })) + const trimmed = trimThread(many) + expect(trimmed.length).toBeLessThanOrEqual(MAX_THREAD_MESSAGES) + expect(trimmed[0].role).toBe('user') + }) +}) diff --git a/src/main/external/externalService.ts b/src/main/external/externalService.ts new file mode 100644 index 00000000..7a25f9ab --- /dev/null +++ b/src/main/external/externalService.ts @@ -0,0 +1,142 @@ +import { randomUUID } from 'node:crypto' +import type { + ExternalChatRequest, ExternalChatResult, ExternalDraft, ExternalEvent, ExternalPublicConfig +} from '@shared/externalAgents' +import { createMutex } from '@shared/proxyPool' +import { buildInvocation, runCli, type SpawnLike } from './cliRunner' +import { confirmCli, needsConfirm, publicConfig, resolveDraft, validAccountId, type StoredExternal } from './externalConfig' +import { ExternalRunError, redactSecrets } from './externalErrors' +import { buildMessages, type ExternalHistory } from './externalHistory' +import { runOpenAiTurn, type FetchLike } from './openaiClient' + +export const VAULT_PREFIX = 'internal.external.' + +export interface ExternalVault { + get(key: string): Promise + set(key: string, value: string): Promise + delete(key: string): Promise + list(prefix: string): string[] +} + +export interface ExternalServiceDeps { + vault: ExternalVault + history: ExternalHistory + /** fetch for this account (account proxy applied). */ + fetchFor(accountId: string): Promise + /** Room workspace directory for a scope (workspace portal / MCP hub binding). */ + workspaceDir(scope: string | undefined): Promise + emit(event: ExternalEvent): void + spawn?: SpawnLike +} + +/** + * Main-process side of 外部成员: configs in the vault, one AbortController per + * running turn, and the two runners. Every error that leaves here is an + * ExternalRunError with the API key redacted. + */ +export function createExternalService(deps: ExternalServiceDeps) { + const lock = createMutex() + const runs = new Map() + const key = (accountId: string) => VAULT_PREFIX + validAccountId(accountId) + + async function load(accountId: string): Promise { + const raw = await deps.vault.get(key(accountId)) + if (!raw) { + if (deps.vault.list(key(accountId)).includes(key(accountId))) throw new ExternalRunError('config', '无法解密外部成员配置') + return null + } + return JSON.parse(raw) as StoredExternal + } + async function save(accountId: string, stored: StoredExternal): Promise { + await deps.vault.set(key(accountId), JSON.stringify(stored)) + return publicConfig(stored) + } + + async function chatOpenAi(stored: Extract, req: ExternalChatRequest, signal: AbortSignal) { + const thread = deps.history.open(req.accountId, req.sessionId) + deps.emit({ type: 'accepted', requestId: req.requestId, accountId: req.accountId, sessionId: thread.sessionId }) + const text = await runOpenAiTurn({ + config: stored, + apiKey: stored.apiKey ?? '', + messages: buildMessages(stored.systemPrompt, thread.messages, req.text), + fetch: await deps.fetchFor(req.accountId), + signal, + onDelta: (sofar) => deps.emit({ + type: 'progress', requestId: req.requestId, accountId: req.accountId, sessionId: thread.sessionId, text: sofar + }) + }) + deps.history.append(req.accountId, thread.sessionId, [ + { role: 'user', content: req.text }, + { role: 'assistant', content: text } + ]) + return { text, sessionId: thread.sessionId } + } + + async function chatCli(stored: Extract, req: ExternalChatRequest, signal: AbortSignal) { + if (needsConfirm(stored)) throw new ExternalRunError('needs-confirm', '首次运行此命令前需要你在界面确认') + const invocation = buildInvocation(stored, req.text) + const cwd = stored.cwd || (await deps.workspaceDir(req.workspaceScope)) || undefined + deps.emit({ type: 'accepted', requestId: req.requestId, accountId: req.accountId }) + const text = await runCli(invocation, { + cwd, timeoutMs: stored.timeoutMs, signal, spawn: deps.spawn, + onOutput: (sofar) => deps.emit({ type: 'progress', requestId: req.requestId, accountId: req.accountId, text: sofar }) + }) + // Stateless: no sessionId, so the room resends recent context every turn. + return { text, sessionId: undefined } + } + + return { + listAccounts: () => deps.vault.list(VAULT_PREFIX).map((k) => k.slice(VAULT_PREFIX.length)), + config: async (accountId: string) => { + const stored = await load(accountId) + return stored && publicConfig(stored) + }, + configure: (accountId: string, draft: ExternalDraft) => + lock(async () => save(accountId, resolveDraft(await load(accountId), draft))), + confirmCommand: (accountId: string, fingerprint: string) => + lock(async () => { + const stored = await load(accountId) + if (!stored) throw new ExternalRunError('config', '外部成员不存在') + return save(accountId, confirmCli(stored, fingerprint)) + }), + remove: (accountId: string) => + lock(async () => { + for (const run of runs.values()) if (run.accountId === accountId) run.controller.abort() + await deps.vault.delete(key(accountId)) + deps.history.dropAccount(accountId) + }), + cancel: async (accountId: string, requestId: string) => { + const run = runs.get(requestId) + if (run && run.accountId === accountId) run.controller.abort() + }, + cancelAll: () => { + for (const run of runs.values()) run.controller.abort() + }, + async chat(req: ExternalChatRequest): Promise { + validAccountId(req.accountId) + if (typeof req.requestId !== 'string' || !req.requestId || runs.has(req.requestId)) { + throw new ExternalRunError('config', '无效的请求 ID') + } + if (typeof req.text !== 'string') throw new ExternalRunError('config', '消息格式不对') + const controller = new AbortController() + runs.set(req.requestId, { accountId: req.accountId, controller }) + let stored: StoredExternal | null = null + try { + stored = await load(req.accountId) + if (!stored) throw new ExternalRunError('config', '外部成员未配置') + const { text, sessionId } = stored.kind === 'openai' + ? await chatOpenAi(stored, req, controller.signal) + : await chatCli(stored, req, controller.signal) + return { messageId: randomUUID(), sessionId, text, createdAt: Date.now() } + } catch (error) { + const secret = stored?.kind === 'openai' ? stored.apiKey : undefined + if (error instanceof ExternalRunError) throw new ExternalRunError(error.code, redactSecrets(error.message, [secret])) + throw new ExternalRunError('network', '外部成员运行失败') + } finally { + runs.delete(req.requestId) + } + } + } +} + +export type ExternalService = ReturnType diff --git a/src/main/external/openaiClient.test.ts b/src/main/external/openaiClient.test.ts new file mode 100644 index 00000000..d2aabdd8 --- /dev/null +++ b/src/main/external/openaiClient.test.ts @@ -0,0 +1,151 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' +import type { AddressInfo } from 'node:net' +import { afterEach, describe, expect, it } from 'vitest' +import type { ExternalOpenAiConfig } from '@shared/externalAgents' +import { ExternalRunError } from './externalErrors' +import { ChatCompletionStream, completionsUrl, parseCompletionBody, runOpenAiTurn } from './openaiClient' + +const KEY = 'sk-test-SECRET-0123456789' +const frame = (value: unknown) => 'data: ' + JSON.stringify(value) + '\n\n' +const delta = (content: string) => frame({ choices: [{ delta: { content } }] }) + +let server: Server | undefined +afterEach(() => new Promise((done) => (server ? server.close(() => done()) : done()))) + +/** Local fake OpenAI endpoint; `handler` sees each request. */ +async function fake(handler: (req: IncomingMessage, res: ServerResponse, body: string) => void): Promise { + server = createServer((req, res) => { + let body = '' + req.on('data', (c) => (body += c)) + req.on('end', () => handler(req, res, body)) + }) + await new Promise((r) => server!.listen(0, '127.0.0.1', r)) + return `http://127.0.0.1:${(server!.address() as AddressInfo).port}/v1` +} + +function config(baseUrl: string, patch: Partial = {}): ExternalOpenAiConfig { + return { kind: 'openai', name: 't', baseUrl, model: 'm1', systemPrompt: '', stream: true, timeoutMs: 5000, ...patch } +} + +describe('ChatCompletionStream (SSE)', () => { + it('joins deltas across arbitrary chunk boundaries, CRLF and keepalives', () => { + const s = new ChatCompletionStream() + const wire = ': keepalive\r\n\r\n' + delta('Hel') + delta('lo') + frame({ choices: [{ delta: {}, finish_reason: 'stop' }] }) + 'data: [DONE]\n\n' + for (let i = 0; i < wire.length; i += 3) s.feed(wire.slice(i, i + 3)) + s.end() + expect(s.text).toBe('Hello') + expect(s.done).toBe(true) + expect(s.finishReason).toBe('stop') + }) + it('ignores frames after [DONE] and non-JSON payloads', () => { + const s = new ChatCompletionStream() + s.feed('data: not-json\n\n' + delta('a') + 'data: [DONE]\n\n' + delta('b')) + expect(s.text).toBe('a') + }) + it('handles a final frame without a trailing blank line', () => { + const s = new ChatCompletionStream() + s.feed('data: {"choices":[{"delta":{"content":"x"}}]}') + expect(s.text).toBe('') + s.end() + expect(s.text).toBe('x') + }) + it('turns an in-stream error frame into a generic error without its text', () => { + const s = new ChatCompletionStream() + expect(() => s.feed(frame({ error: { message: 'bad key ' + KEY } }))).toThrowError(/流中返回错误/) + try { s.feed('') } catch { /* already thrown */ } + }) +}) + +describe('helpers', () => { + it('builds the completions URL', () => { + expect(completionsUrl('https://x.test/v1/')).toBe('https://x.test/v1/chat/completions') + expect(completionsUrl('https://x.test/v1/chat/completions')).toBe('https://x.test/v1/chat/completions') + }) + it('parses a non-streaming body', () => { + expect(parseCompletionBody({ choices: [{ message: { content: 'hi' } }] })).toBe('hi') + expect(() => parseCompletionBody({})).toThrow(ExternalRunError) + }) +}) + +describe('runOpenAiTurn against a local fake server', () => { + it('streams, sends Bearer + model + messages, and reports deltas', async () => { + let seen: { auth?: string; body?: Record; path?: string } = {} + const base = await fake((req, res, body) => { + seen = { auth: req.headers.authorization, body: JSON.parse(body), path: req.url } + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.write(delta('你')) + setTimeout(() => { res.write(delta('好')); res.end('data: [DONE]\n\n') }, 20) + }) + const deltas: string[] = [] + const text = await runOpenAiTurn({ + config: config(base, { temperature: 0.2 }), apiKey: KEY, fetch: globalThis.fetch, + messages: [{ role: 'user', content: 'q' }], onDelta: (t) => deltas.push(t) + }) + expect(text).toBe('你好') + expect(deltas.at(-1)).toBe('你好') + expect(seen.path).toBe('/v1/chat/completions') + expect(seen.auth).toBe(`Bearer ${KEY}`) + expect(seen.body).toMatchObject({ model: 'm1', stream: true, temperature: 0.2, messages: [{ role: 'user', content: 'q' }] }) + }) + + it('reads a JSON reply when stream is off', async () => { + const base = await fake((_req, res) => { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ choices: [{ message: { content: 'plain' } }] })) + }) + expect(await runOpenAiTurn({ config: config(base, { stream: false }), apiKey: KEY, fetch: globalThis.fetch, messages: [] })) + .toBe('plain') + }) + + it('times out a silent stream', async () => { + const base = await fake((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.write(': open\n\n') // then silence + }) + const started = Date.now() + const err = await runOpenAiTurn({ config: config(base, { timeoutMs: 1000 }), apiKey: KEY, fetch: globalThis.fetch, messages: [] }) + .catch((e) => e) + expect(err).toBeInstanceOf(ExternalRunError) + expect(err.code).toBe('timeout') + expect(Date.now() - started).toBeLessThan(4000) + }) + + it('cancels mid-stream via the caller signal', async () => { + const base = await fake((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.write(delta('partial')) + }) + const controller = new AbortController() + const run = runOpenAiTurn({ + config: config(base), apiKey: KEY, fetch: globalThis.fetch, messages: [], signal: controller.signal, + onDelta: () => controller.abort() + }) + const err = await run.catch((e) => e) + expect(err.code).toBe('cancelled') + }) + + it('never relays an upstream error body (which may echo the key)', async () => { + const base = await fake((req, res) => { + res.writeHead(401, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: { message: `Incorrect API key provided: ${req.headers.authorization}` } })) + }) + const err = await runOpenAiTurn({ config: config(base), apiKey: KEY, fetch: globalThis.fetch, messages: [] }).catch((e) => e) + expect(err.code).toBe('http') + expect(err.message).toBe('外部 API HTTP 401') + expect(String(err.message) + String(err.stack)).not.toContain(KEY) + }) + + it('redacts the key even if a fetch implementation puts it in an error', async () => { + const leaky = async () => { throw new ExternalRunError('network', `boom Authorization: Bearer ${KEY} / ${KEY}`) } + const err = await runOpenAiTurn({ config: config('http://127.0.0.1:1/v1'), apiKey: KEY, fetch: leaky, messages: [] }) + .catch((e) => e) + expect(err.message).not.toContain(KEY) + }) + + it('reports an unreachable host as a network error', async () => { + const err = await runOpenAiTurn({ config: config('http://127.0.0.1:1/v1'), apiKey: KEY, fetch: globalThis.fetch, messages: [] }) + .catch((e) => e) + expect(err.code).toBe('network') + expect(err.message).not.toContain(KEY) + }) +}) diff --git a/src/main/external/openaiClient.ts b/src/main/external/openaiClient.ts new file mode 100644 index 00000000..d2880a10 --- /dev/null +++ b/src/main/external/openaiClient.ts @@ -0,0 +1,148 @@ +import type { ExternalOpenAiConfig } from '@shared/externalAgents' +import { SseParser } from '../sseParser' +import { ExternalRunError, redactSecrets, turnSignal } from './externalErrors' + +export interface ChatMessage { + role: 'system' | 'user' | 'assistant' + content: string +} + +export type FetchLike = (url: string, init: RequestInit) => Promise + +export interface OpenAiTurnOptions { + config: ExternalOpenAiConfig + apiKey: string + messages: ChatMessage[] + fetch: FetchLike + signal?: AbortSignal + /** Called with the full text so far on every streamed delta. */ + onDelta?: (text: string) => void +} + +/** `https://host/v1/` → `https://host/v1/chat/completions` (an explicit endpoint is kept). */ +export function completionsUrl(baseUrl: string): string { + const base = baseUrl.trim().replace(/\/+$/, '') + return /\/chat\/completions$/.test(base) ? base : base + '/chat/completions' +} + +/** + * Accumulates `choices[0].delta.content` from OpenAI-style SSE chunks. + * Handles arbitrary chunk boundaries (via SseParser), keepalive comments, + * `[DONE]`, and in-stream `{"error":…}` frames (message dropped: upstream text + * may echo request data). + */ +export class ChatCompletionStream { + private readonly parser = new SseParser(() => new ExternalRunError('http', '外部 API 返回的流数据过大')) + text = '' + done = false + finishReason?: string + + /** Feed one decoded chunk; returns true when the text grew. */ + feed(chunk: string): boolean { + return this.consume(this.parser.feed(chunk)) + } + + end(): boolean { + return this.consume(this.parser.flush()) + } + + private consume(frames: { data: string }[]): boolean { + let grew = false + for (const { data } of frames) { + if (this.done) break + const payload = data.trim() + if (!payload) continue + if (payload === '[DONE]') { + this.done = true + break + } + let json: { + error?: unknown + choices?: Array<{ delta?: { content?: unknown }; message?: { content?: unknown }; finish_reason?: unknown }> + } + try { + json = JSON.parse(payload) + } catch { + continue // tolerate non-JSON keepalive payloads + } + if (json.error) throw new ExternalRunError('http', '外部 API 在流中返回错误') + const choice = json.choices?.[0] + const piece = choice?.delta?.content ?? choice?.message?.content + if (typeof piece === 'string' && piece) { + this.text += piece + grew = true + } + if (typeof choice?.finish_reason === 'string') this.finishReason = choice.finish_reason + } + return grew + } +} + +/** Pull the reply out of a non-streaming chat completion body. */ +export function parseCompletionBody(body: unknown): string { + const choice = (body as { choices?: Array<{ message?: { content?: unknown } }> })?.choices?.[0] + const content = choice?.message?.content + if (typeof content !== 'string') throw new ExternalRunError('http', '外部 API 返回格式不是 chat completion') + return content +} + +/** Run one chat completion turn. Resolves with the whole reply text. */ +export async function runOpenAiTurn(options: OpenAiTurnOptions): Promise { + const { config, apiKey, messages } = options + const turn = turnSignal(options.signal, config.timeoutMs) + const body: Record = { model: config.model, messages, stream: config.stream } + if (config.temperature !== undefined) body.temperature = config.temperature + try { + let response: Response + try { + response = await options.fetch(completionsUrl(config.baseUrl), { + method: 'POST', + redirect: 'error', + signal: turn.signal, + headers: { + 'Content-Type': 'application/json', + Accept: config.stream ? 'text/event-stream' : 'application/json', + ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) + }, + body: JSON.stringify(body) + }) + } catch { + if (turn.signal.aborted) throw turn.reason() + throw new ExternalRunError('network', '外部 API 网络请求失败,请检查地址与代理') + } + if (!response.ok) { + await response.body?.cancel().catch(() => undefined) + // Never relay the upstream body: custom endpoints can echo headers (the key). + throw new ExternalRunError('http', `外部 API HTTP ${response.status}`) + } + const type = response.headers.get('content-type') ?? '' + if (!config.stream || !type.includes('text/event-stream')) { + return parseCompletionBody(await response.json().catch(() => { + if (turn.signal.aborted) throw turn.reason() + throw new ExternalRunError('http', '外部 API 返回的不是 JSON') + })) + } + const stream = new ChatCompletionStream() + const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader() + try { + for (;;) { + const { value, done } = await reader.read() + if (done) break + if (stream.feed(value)) options.onDelta?.(stream.text) + if (stream.done) break + } + if (stream.end()) options.onDelta?.(stream.text) + } finally { + await reader.cancel().catch(() => undefined) + } + return stream.text + } catch (error) { + if (turn.signal.aborted) throw turn.reason() + if (error instanceof ExternalRunError) { + throw new ExternalRunError(error.code, redactSecrets(error.message, [apiKey])) + } + throw new ExternalRunError('network', '外部 API 读取回复失败') + } finally { + turn.dispose() + } +} diff --git a/src/main/index.ts b/src/main/index.ts index ed460918..1688f46d 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -37,6 +37,7 @@ import { findCueCallbackArg, handleCueDesktopCallbackUrl } from './cue/cueDeskto import { stopCueAccountWatch } from './cue/cueWatchManager' import { registerGeminiIpc, disposeGeminiIpc } from './gemini/geminiIpc' import { registerDsBotIpc } from './dsbot/dsBotIpc' +import { registerExternalIpc, disposeExternalIpc } from './external/externalIpc' import { cancelAllDsBotRuns } from './dsbot/dsBotClient' import { registerMobileSyncIpc, stopMobileSyncServer } from './mobileSync/mobileSyncIpc' import { applyAllStoredProxies } from './muse/accountProxy' @@ -338,6 +339,7 @@ app.on('before-quit', (event) => { cancelAllHermesRuns('*') cancelAllAntigravityRuns('*') disposeGeminiIpc() + disposeExternalIpc() cancelAllDsBotRuns('*') stopCueAccountWatch('*') disposeAllMuseManagers() @@ -398,6 +400,7 @@ app.whenReady().then(async () => { registerCueIpc() registerGeminiIpc(() => mainWindow) registerDsBotIpc() + registerExternalIpc(() => mainWindow) // GOXF 外部成员 registerMobileSyncIpc() registerVaultIpc() registerWorkspaceIpc(() => mainWindow) diff --git a/src/main/securityVault.ts b/src/main/securityVault.ts index cc0a0a0a..a75d056d 100644 --- a/src/main/securityVault.ts +++ b/src/main/securityVault.ts @@ -53,7 +53,7 @@ const AUDITED_STORES: ReadonlyArray<{ id: string; label: string; fileName: strin ] const PLATFORM_SECURITY_SPECS: Record< - 'meta-muse' | 'grok' | 'hark' | 'dot' | 'hermes' | 'antigravity' | 'cue' | 'ds-bot' | 'gemini', + 'meta-muse' | 'grok' | 'hark' | 'dot' | 'hermes' | 'antigravity' | 'cue' | 'ds-bot' | 'gemini' | 'external', { transportProtocol: string; credentialIsolation: string } > = { 'meta-muse': { @@ -91,6 +91,10 @@ const PLATFORM_SECURITY_SPECS: Record< 'ds-bot': { transportProtocol: 'DS Bot Native Channel SSE / Noise_IK 端到端加密中继 / MCP Streamable HTTP', credentialIsolation: '系统钥匙串 SafeStorage 加密存储令牌、Cookie 与 X25519 私钥(渲染层零暴露)' + }, + external: { + transportProtocol: 'OpenAI 兼容 REST + SSE(主进程代发)/ 本地进程 spawn(不经 shell)', + credentialIsolation: '系统钥匙串 SafeStorage 加密 API Key(渲染层零密钥暴露)' } } diff --git a/src/preload/index.ts b/src/preload/index.ts index 57ac1994..00d43cf4 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,5 +1,6 @@ import { DISPLAY_LOCALE_CHANNEL, isDisplayLocale } from '@shared/displayLocale' import type { GeminiEvent } from '@shared/gemini' +import { EXTERNAL_CHANNELS, type ExternalEvent } from '@shared/externalAgents' import { SETTINGS_MENU_CHANNEL } from '@shared/settingsMenu' import { SLACK_CHANNEL, SLACK_INBOUND, type SlackInbound } from '@shared/slack' import { WORKSPACE_CHANNEL } from '@shared/workspace' @@ -351,6 +352,22 @@ const bridge: BotHubBridge = { return () => ipcRenderer.removeListener(GEMINI_CHANNELS.event, handler) } }, + // GOXF 外部成员: the API key only goes in (configure), never comes back. + external: { + listAccounts: () => ipcRenderer.invoke(EXTERNAL_CHANNELS.listAccounts), + config: (accountId) => ipcRenderer.invoke(EXTERNAL_CHANNELS.config, accountId), + configure: (accountId, draft) => ipcRenderer.invoke(EXTERNAL_CHANNELS.configure, accountId, draft), + confirmCommand: (accountId, fingerprint) => ipcRenderer.invoke(EXTERNAL_CHANNELS.confirmCommand, accountId, fingerprint), + remove: (accountId) => ipcRenderer.invoke(EXTERNAL_CHANNELS.remove, accountId), + chat: (request) => ipcRenderer.invoke(EXTERNAL_CHANNELS.chat, request), + cancel: (accountId, requestId) => ipcRenderer.invoke(EXTERNAL_CHANNELS.cancel, accountId, requestId), + pickDirectory: () => ipcRenderer.invoke(EXTERNAL_CHANNELS.pickDirectory), + onEvent: (listener) => { + const handler = (_event: unknown, payload: ExternalEvent) => listener(payload) + ipcRenderer.on(EXTERNAL_CHANNELS.event, handler) + return () => ipcRenderer.removeListener(EXTERNAL_CHANNELS.event, handler) + } + }, dsBot: { configure: (request) => ipcRenderer.invoke(DS_BOT_CHANNELS.configure, request), detectLocal: () => ipcRenderer.invoke(DS_BOT_CHANNELS.detectLocal), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 36d284f3..32f43b2e 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -25,6 +25,7 @@ import { useBotStore } from '@/store/botStore' import { startPrefsSync, usePrefsStore } from '@/store/prefsStore' import { ChatArea } from '@/components/chat/ChatArea' import { usePromptStore } from '@/store/promptStore' +import { ExternalConfirmHost } from '@/components/external/ExternalConfirmHost' const PromptLibraryDialog = lazy(() => import('@/components/chat/PromptLibraryDialog').then(({ PromptLibraryDialog }) => ({ default: PromptLibraryDialog }))) const SettingsView = lazy(() => import('@/components/settings/SettingsView').then(({ SettingsView }) => ({ default: SettingsView }))) @@ -306,6 +307,8 @@ export default function App() { + {/* GOXF 外部成员: first-run approval of a local command, asked whenever a member is called. */} + diff --git a/src/renderer/src/components/add-bot/AddBotDialog.tsx b/src/renderer/src/components/add-bot/AddBotDialog.tsx index 93ac7572..78127803 100644 --- a/src/renderer/src/components/add-bot/AddBotDialog.tsx +++ b/src/renderer/src/components/add-bot/AddBotDialog.tsx @@ -8,6 +8,8 @@ import { createId } from '@shared/id' import { Camera, ChevronLeft, ChevronRight, ExternalLink, ListPlus, Plus, RefreshCw } from 'lucide-react' import { MuseBatchImport } from './MuseBatchImport' import { DsBotConnectForm } from '@/components/dsbot/DsBotConnectForm' +import { EXTERNAL_KIND_TITLES, ExternalConnectStep, ExternalPlatformRows } from '@/components/external/ExternalConnectStep' +import type { ExternalKind } from '@shared/externalAgents' import { ArkRelayOrbSvg } from '@/components/ui/ArkGlyphs' import { BotAvatar } from '@/components/ui/Avatar' import { Button } from '@/components/ui/Button' @@ -102,6 +104,8 @@ function AddBotFlow({ open, wizardId }: { open: boolean; wizardId: number }) { const [hermesConnectOpen, setHermesConnectOpen] = useState(false) const [hermesReady, setHermesReady] = useState<{ handle: string; displayName: string } | null>(null) const [dsBotConnectOpen, setDsBotConnectOpen] = useState(false) + // GOXF 外部成员: its own form step and account id (ExternalConnectStep), not the sign-in hook. + const [externalKind, setExternalKind] = useState(null) const activeGeminiAccount = useRef(null) activeGeminiAccount.current = geminiOpen ? login.accountId : null const { phase } = login @@ -258,6 +262,7 @@ function AddBotFlow({ open, wizardId }: { open: boolean; wizardId: number }) { const platform = phase.kind === 'idle' ? undefined : getPlatform(phase.platformId) const title = batch ? t('Batch import Muse accounts') + : externalKind ? EXTERNAL_KIND_TITLES[externalKind] : geminiOpen ? t('Configure Gemini connection') : hermesReady ? t('Set up your bot') @@ -292,6 +297,10 @@ function AddBotFlow({ open, wizardId }: { open: boolean; wizardId: number }) { > + ) : externalKind ? ( + setExternalKind(null)} className="-ml-1"> + + ) : geminiOpen ? ( { login.discard(); setGeminiOpen(false) }}> @@ -433,7 +442,30 @@ function AddBotFlow({ open, wizardId }: { open: boolean; wizardId: number }) { /> )} - {!batch && phase.kind === 'idle' && !grokAccountChoiceOpen && !geminiOpen && !hermesConnectOpen && !hermesReady && !dsBotConnectOpen && ( + {!batch && phase.kind === 'idle' && externalKind && ( + { + if (!isCurrentWizard()) return + created.current = true + addBot({ + id: botId, + platformId: 'external', + name: freshName(config.name, bots.map((b) => b.name)), + customName: true, + emoji: config.kind === 'cli' ? '🖥️' : '🌐', + accounts: [{ + key: accountId, + accountId, + displayName: config.name, + handle: config.kind === 'cli' ? config.command : config.model + }] + }) + }} + /> + )} + {!batch && phase.kind === 'idle' && !externalKind && !grokAccountChoiceOpen && !geminiOpen && !hermesConnectOpen && !hermesReady && !dsBotConnectOpen && ( setBatch(true)} + onExternal={setExternalKind} onCreateRoom={() => { close() useBotStore.getState().selectBot(NEW_ROOM_ID) @@ -715,6 +748,7 @@ function PlatformStep({ error, onPick, onBatch, + onExternal, onCreateRoom }: { listRef: RefObject @@ -722,10 +756,11 @@ function PlatformStep({ error?: string onPick: (platformId: PlatformId) => void onBatch: () => void + onExternal: (kind: ExternalKind) => void onCreateRoom: () => void }) { useDesktopLocale() - const platforms = adapterRegistry.listPlatforms().filter((p) => p.usable) + const platforms = adapterRegistry.listPlatforms().filter((p) => p.usable && p.id !== 'external') const t = useT() return (
@@ -761,6 +796,7 @@ function PlatformStep({ ) })} +
+ + +
+
+ )} + + ) +} + +export function ConfirmBody({ config, name }: { config: ExternalCliConfig; name: string }) { + return ( +
+
+ +

+ 「{name}」允许后,在群里或单聊被叫到时会直接运行;命令、参数或目录一改就会再问。拒绝 = 这一轮跳过,不运行。 +

+
+
+
+ {commandChips(config).map((chip, i) => ( + {chip.text} + ))} +
+

+ 目录:{config.cwd ? {config.cwd} : '所在群的工作区(默认)'} · 超时 {Math.round(config.timeoutMs / 1000)} 秒 · 不经过命令行解释器 +

+
+
+ ) +} diff --git a/src/renderer/src/components/external/ExternalConnectStep.tsx b/src/renderer/src/components/external/ExternalConnectStep.tsx new file mode 100644 index 00000000..640bf487 --- /dev/null +++ b/src/renderer/src/components/external/ExternalConnectStep.tsx @@ -0,0 +1,140 @@ +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { ChevronRight, Globe, SquareTerminal } from 'lucide-react' +import { decodeExternalError } from '@adapters/external/ExternalAdapter' +import { requestExternalConfirm } from '@adapters/external/confirmGate' +import type { ExternalKind, ExternalPublicConfig } from '@shared/externalAgents' +import { createId } from '@shared/id' +import { getBridge } from '@/lib/bridge' +import { ApiForm, CliForm, type FormStatus } from './ExternalForms' +import { API_DEFAULTS, CLI_DEFAULTS, apiDraft, cliDraft, type ApiFormValues, type CliFormValues } from './externalForm' + +/** GOXF 外部成员 in the add-bot dialog: the two picker rows and the form step. */ + +const TEST_PROMPT = '这是一次连接测试,请只回复「OK」。' + +export const EXTERNAL_KIND_TITLES: Record = { openai: '外部 API', cli: '本地命令' } + +export function errorText(error: unknown): string { + return decodeExternalError(error).message || '出错了' +} + +function ExtGlyph({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} + +function Row({ icon, name, hint, onClick }: { icon: ReactNode; name: string; hint: string; onClick: () => void }) { + return ( +
  • + +
  • + ) +} + +/** The 「外部成员」 group under the platform list (desktop only: it runs in main). */ +export function ExternalPlatformRows({ onPick, available = Boolean(getBridge()?.external) }: { + onPick: (kind: ExternalKind) => void + /** Defaults to "the desktop bridge is there"; the screenshot mock forces it on. */ + available?: boolean +}) { + if (!available) return null + return ( + <> +

    外部成员

    +
      + } name="外部 API" hint="OpenAI 兼容接口 · 填地址、模型和 Key" onClick={() => onPick('openai')} /> + } name="本地命令" hint="本机命令行工具 · 如 claude -p" onClick={() => onPick('cli')} /> +
    + + ) +} + +/** + * Configure a new external member under its own account id. A config saved + * by 测试连接 / 试运行 but never added is removed again when the step closes. + */ +export function ExternalConnectStep({ + kind, onCreated +}: { + kind: ExternalKind + onCreated: (accountId: string, config: ExternalPublicConfig) => void +}) { + const accountId = useRef(createId('ext')).current + const saved = useRef(false) + const kept = useRef(false) + const live = useRef(true) + const running = useRef(null) + const [status, setStatus] = useState({}) + + useEffect(() => () => { + live.current = false + const api = getBridge()?.external + if (running.current) void api?.cancel(accountId, running.current).catch(() => undefined) + if (saved.current && !kept.current) void api?.remove(accountId).catch(() => undefined) + }, [accountId]) + + const save = async (values: ApiFormValues | CliFormValues): Promise => { + const api = getBridge()?.external + if (!api) { setStatus({ error: '外部成员需要桌面版' }); return undefined } + const built = kind === 'openai' + ? apiDraft(values as ApiFormValues) + : cliDraft(values as CliFormValues, getBridge()?.platform) + if (!built.ok) { setStatus({ error: built.error }); return undefined } + const config = await api.configure(accountId, built.draft) + saved.current = true + return config + } + + const submit = async (values: ApiFormValues | CliFormValues) => { + setStatus({ busy: true }) + try { + const config = await save(values) + if (!config || !live.current) return + kept.current = true + onCreated(accountId, config) + } catch (error) { + if (live.current) setStatus({ error: errorText(error) }) + } + } + + const test = async (values: ApiFormValues | CliFormValues) => { + setStatus({ busy: true, note: kind === 'cli' ? '正在试运行…' : '正在测试连接…' }) + try { + const config = await save(values) + const api = getBridge()?.external + if (!config || !api || !live.current) return + if (config.kind === 'cli' && config.needsConfirm) { + const asked = requestExternalConfirm({ accountId, config }) + if (!asked) { setStatus({ error: '无法弹出运行确认,请重开窗口后再试' }); return } + if (!(await asked)) { if (live.current) setStatus({ note: '已取消试运行' }); return } + } + const requestId = createId('external') + running.current = requestId + const result = await api.chat({ accountId, requestId, conversationId: `${accountId}:test`, text: TEST_PROMPT }) + .finally(() => { if (running.current === requestId) running.current = null }) + if (!live.current) return + const reply = result.text.trim().replace(/\s+/g, ' ') + setStatus({ note: `${kind === 'cli' ? '试运行成功' : '连接成功'}:${reply ? reply.slice(0, 80) : '(空回复)'}` }) + } catch (error) { + if (live.current) setStatus({ error: errorText(error) }) + } + } + + return kind === 'openai' + ? void submit(v)} onTest={(v) => void test(v)} /> + : void submit(v)} onTest={(v) => void test(v)} /> +} diff --git a/src/renderer/src/components/external/ExternalForms.tsx b/src/renderer/src/components/external/ExternalForms.tsx new file mode 100644 index 00000000..43af8b19 --- /dev/null +++ b/src/renderer/src/components/external/ExternalForms.tsx @@ -0,0 +1,212 @@ +import { useState, type ReactNode } from 'react' +import { FolderOpen, KeyRound, X } from 'lucide-react' +import { Button } from '@/components/ui/Button' +import { SwitchPill } from '@/components/ui/Controls' +import { Field, TextInput } from '@/components/ui/Field' +import { SegmentedControl } from '@/components/ui/SegmentedControl' +import { getBridge } from '@/lib/bridge' +import { cn } from '@/lib/cn' +import { addArg, removeArg, type ApiFormValues, type CliFormValues } from './externalForm' + +/** GOXF 外部成员 forms (v33 mock ②③). State lives here; saving is the caller's. */ + +export interface FormStatus { + busy?: boolean + error?: string + /** Result line of 测试连接 / 试运行. */ + note?: string +} + +function SettingLine({ title, hint, control }: { title: string; hint: string; control: ReactNode }) { + return ( +
    +
    +

    {title}

    +

    {hint}

    +
    + {control} +
    + ) +} + +function StatusLines({ status }: { status: FormStatus }) { + return ( + <> + {status.note && !status.error &&

    {status.note}

    } + {status.error &&

    {status.error}

    } + + ) +} + +export function ArgChip({ children, prompt, onRemove }: { children: string; prompt?: boolean; onRemove?: () => void }) { + return ( + + {children} + {onRemove && ( + + )} + + ) +} + +export function ApiForm({ + initial, editing, status, onSubmit, onTest +}: { + initial: ApiFormValues + /** Editing a saved member: an empty key field keeps the saved key. */ + editing?: { hasApiKey: boolean } + status: FormStatus + onSubmit: (values: ApiFormValues) => void + onTest?: (values: ApiFormValues) => void +}) { + const [values, setValues] = useState(initial) + const set = (key: K, value: ApiFormValues[K]) => setValues((v) => ({ ...v, [key]: value })) + return ( +
    { event.preventDefault(); if (!status.busy) onSubmit(values) }} + > + + set('name', e.target.value)} /> + + + set('baseUrl', e.target.value)} /> + + + set('model', e.target.value)} /> + + 只保存在本机系统钥匙串,界面和日志都不显示} + > + set('apiKey', e.target.value)} + /> + +
    + set('stream', on)} aria-label="流式回复" />} + /> + set('timeoutSec', e.target.value)} aria-label="超时(秒)" />} + /> +
    + + set('systemPrompt', e.target.value)} /> + + +
    + {onTest && } + +
    + + ) +} + +function ArgsEditor({ args, onChange }: { args: string[]; onChange: (args: string[]) => void }) { + const [typed, setTyped] = useState('') + const commit = () => { + if (!typed) return + onChange(addArg(args, typed)) + setTyped('') + } + return ( +
    + {args.map((arg, i) => ( + onChange(removeArg(args, i))}>{arg} + ))} + setTyped(e.target.value)} + onBlur={commit} + onKeyDown={(e) => { + if (e.key === 'Enter') { e.preventDefault(); commit() } + if (e.key === 'Backspace' && !typed && args.length) onChange(args.slice(0, -1)) + }} + className="h-7 min-w-28 flex-1 bg-transparent px-1.5 font-mono text-[12px] text-ink outline-none placeholder:text-ink-muted" + /> +
    + ) +} + +export function CliForm({ + initial, editing, status, onSubmit, onTest +}: { + initial: CliFormValues + editing?: boolean + status: FormStatus + onSubmit: (values: CliFormValues) => void + onTest?: (values: CliFormValues) => void +}) { + const [values, setValues] = useState(initial) + const set = (key: K, value: CliFormValues[K]) => setValues((v) => ({ ...v, [key]: value })) + const pick = getBridge()?.external?.pickDirectory + const windows = getBridge()?.platform === 'win32' + return ( +
    { event.preventDefault(); if (!status.busy) onSubmit(values) }} + > + + set('name', e.target.value)} /> + + + set('command', e.target.value)} /> + + + set('args', args)} /> + + set('input', v)} + options={[{ value: 'arg', label: '参数' }, { value: 'stdin', label: 'stdin' }]} aria-label="消息怎么传" /> + } + /> + +
    + set('cwd', e.target.value)} /> + {pick && ( + + )} +
    +
    + set('timeoutSec', e.target.value)} aria-label="超时(秒)" />} + /> + +
    + {onTest && } + +
    + + ) +} diff --git a/src/renderer/src/components/external/externalForm.test.ts b/src/renderer/src/components/external/externalForm.test.ts new file mode 100644 index 00000000..7fb16ea6 --- /dev/null +++ b/src/renderer/src/components/external/externalForm.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' +import { cliFingerprint } from '@shared/externalAgents' +import { + API_DEFAULTS, CLI_DEFAULTS, WINDOWS_SCRIPT_ERROR, addArg, apiDraft, apiValuesFrom, cliDraft, cliValuesFrom, + commandChips, isAllowedBaseUrl, parseTimeoutSec, removeArg +} from './externalForm' + +describe('externalForm', () => { + it('parses timeouts in seconds within main limits', () => { + expect(parseTimeoutSec('120')).toBe(120_000) + expect(parseTimeoutSec(' 300 秒 ')).toBe(300_000) + expect(parseTimeoutSec('0')).toBeUndefined() + expect(parseTimeoutSec('1801')).toBeUndefined() + expect(parseTimeoutSec('abc')).toBeUndefined() + }) + + it('accepts https or loopback http only', () => { + expect(isAllowedBaseUrl('https://api.deepseek.com/v1')).toBe(true) + expect(isAllowedBaseUrl('http://127.0.0.1:11434/v1')).toBe(true) + expect(isAllowedBaseUrl('http://api.example.com/v1')).toBe(false) + expect(isAllowedBaseUrl('https://u:p@api.example.com')).toBe(false) + expect(isAllowedBaseUrl('not a url')).toBe(false) + }) + + it('builds an OpenAI draft; the key is sent only when typed', () => { + const ok = apiDraft({ ...API_DEFAULTS, baseUrl: ' https://api.deepseek.com/v1 ', model: 'deepseek-chat', apiKey: ' sk-1 ' }) + expect(ok).toEqual({ ok: true, draft: expect.objectContaining({ + kind: 'openai', name: 'deepseek-chat', baseUrl: 'https://api.deepseek.com/v1', apiKey: 'sk-1', stream: true, timeoutMs: 120_000 + }) }) + const keep = apiDraft({ ...API_DEFAULTS, baseUrl: 'https://x.dev/v1', model: 'm' }) + expect(keep.ok && 'apiKey' in keep.draft).toBe(false) + expect(apiDraft({ ...API_DEFAULTS, model: 'm' })).toEqual({ ok: false, error: '请填写 API 地址' }) + expect(apiDraft({ ...API_DEFAULTS, baseUrl: 'https://x.dev', model: 'm', apiKey: 'sk 中' }).ok).toBe(false) + }) + + it('builds a CLI draft and refuses .cmd/.bat on Windows only', () => { + const base = { ...CLI_DEFAULTS, command: 'claude' } + expect(cliDraft(base, 'linux')).toEqual({ ok: true, draft: { + kind: 'cli', name: 'claude', command: 'claude', args: ['-p', '{prompt}'], input: 'arg', cwd: '', timeoutMs: 300_000 + } }) + expect(cliDraft({ ...base, command: 'C:\\tools\\claude.cmd' }, 'win32')).toEqual({ ok: false, error: WINDOWS_SCRIPT_ERROR }) + expect(cliDraft({ ...base, command: 'run.BAT' }, 'win32').ok).toBe(false) + expect(cliDraft({ ...base, command: 'run.cmd' }, 'darwin').ok).toBe(true) + expect(cliDraft({ ...base, command: 'node.exe', args: ['C:\\x\\cli.js', '{prompt}'] }, 'win32').ok).toBe(true) + }) + + it('rejects a command line with arguments and a prompt that reaches nothing', () => { + expect(cliDraft({ ...CLI_DEFAULTS, command: 'claude -p' }, 'linux').ok).toBe(false) + expect(cliDraft({ ...CLI_DEFAULTS, command: 'claude', args: ['-p'] }, 'linux').ok).toBe(false) + expect(cliDraft({ ...CLI_DEFAULTS, command: 'claude', args: ['-p'], input: 'stdin' }, 'linux').ok).toBe(true) + }) + + it('adds argv entries verbatim, never split', () => { + expect(addArg(['-p'], 'a b; rm -rf ~')).toEqual(['-p', 'a b; rm -rf ~']) + expect(addArg(['-p'], '')).toEqual(['-p']) + expect(removeArg(['a', 'b', 'c'], 1)).toEqual(['a', 'c']) + }) + + it('round-trips saved configs into form values without the key', () => { + const api = apiValuesFrom({ kind: 'openai', name: 'D', baseUrl: 'https://x.dev', model: 'm', systemPrompt: '', stream: false, timeoutMs: 60_000, hasApiKey: true }) + expect(api).toEqual({ ...API_DEFAULTS, name: 'D', baseUrl: 'https://x.dev', model: 'm', stream: false, timeoutSec: '60' }) + const cli = cliValuesFrom({ kind: 'cli', name: 'C', command: 'claude', args: ['-p', '{prompt}'], input: 'arg', cwd: '/w', timeoutMs: 5000, needsConfirm: false }) + expect(cli).toEqual({ name: 'C', command: 'claude', args: ['-p', '{prompt}'], input: 'arg', cwd: '/w', timeoutSec: '5' }) + expect(cliValuesFrom(null).args).not.toBe(CLI_DEFAULTS.args) + }) + + it('shows every argv slot and the stdin route in the confirmation', () => { + expect(commandChips({ command: 'claude', args: ['-p', '{prompt}', '--x={prompt}'], input: 'arg' })).toEqual([ + { text: 'claude' }, { text: '-p' }, { text: '{本轮消息}', prompt: true }, { text: '--x={本轮消息}', prompt: true } + ]) + expect(commandChips({ command: 'cat', args: [], input: 'stdin' }).at(-1)).toEqual({ text: '标准输入 ← 本轮消息', prompt: true }) + // The confirmation hashes the same fields main does. + expect(cliFingerprint({ command: 'a', args: [], input: 'arg', cwd: '' })).toMatch(/^[0-9a-f]{8}$/) + }) +}) diff --git a/src/renderer/src/components/external/externalForm.ts b/src/renderer/src/components/external/externalForm.ts new file mode 100644 index 00000000..c39ddbd4 --- /dev/null +++ b/src/renderer/src/components/external/externalForm.ts @@ -0,0 +1,168 @@ +import { + EXTERNAL_MAX_TIMEOUT_MS, + type ExternalCliConfig, type ExternalCliInput, type ExternalDraft, type ExternalPublicConfig +} from '@shared/externalAgents' + +/** + * GOXF 外部成员: pure helpers behind the add-bot forms (v33 mock) and the + * first-run confirmation. No React, no IPC: the forms call these, then hand + * the draft to main, which re-validates everything (main is the authority). + */ + +export interface ApiFormValues { + name: string + baseUrl: string + model: string + /** Write-only; empty while editing = keep the saved key. */ + apiKey: string + systemPrompt: string + stream: boolean + timeoutSec: string +} + +export interface CliFormValues { + name: string + command: string + args: string[] + input: ExternalCliInput + cwd: string + timeoutSec: string +} + +export type DraftResult = + | { ok: true; draft: Extract } + | { ok: false; error: string } + +export const API_DEFAULTS: ApiFormValues = { + name: '', baseUrl: '', model: '', apiKey: '', systemPrompt: '', stream: true, timeoutSec: '120' +} + +export const CLI_DEFAULTS: CliFormValues = { + name: '', command: '', args: ['-p', '{prompt}'], input: 'arg', cwd: '', timeoutSec: '300' +} + +export const WINDOWS_SCRIPT_ERROR = + 'Windows 的 .cmd/.bat 会经 cmd 解析,不安全:请填 node.exe 等可执行文件,脚本路径放进参数' + +/** Seconds typed in the form (「120」「120 秒」) → ms, within main's limits. */ +export function parseTimeoutSec(raw: string): number | undefined { + const match = /^\s*(\d{1,5})\s*(秒|s)?\s*$/i.exec(raw) + if (!match) return undefined + const ms = Number(match[1]) * 1000 + return ms >= 1000 && ms <= EXTERNAL_MAX_TIMEOUT_MS ? ms : undefined +} + +const TIMEOUT_ERROR = '超时请填 1 到 1800 之间的秒数' + +/** True for https, or plain http only on this machine (mirrors main). */ +export function isAllowedBaseUrl(raw: string): boolean { + try { + const url = new URL(raw.trim()) + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) + return (url.protocol === 'https:' || (url.protocol === 'http:' && loopback)) && + !url.username && !url.password && !url.search && !url.hash + } catch { + return false + } +} + +/** Windows runs .cmd/.bat through cmd.exe, which re-parses argv: refused (user chose this, 2026-12-03). */ +export function isWindowsScript(command: string, platform: string | undefined): boolean { + return platform === 'win32' && /\.(cmd|bat)["']?\s*$/i.test(command.trim()) +} + +export function apiDraft(values: ApiFormValues): DraftResult<'openai'> { + const baseUrl = values.baseUrl.trim() + const model = values.model.trim() + const apiKey = values.apiKey.trim() + if (!baseUrl) return { ok: false, error: '请填写 API 地址' } + if (!isAllowedBaseUrl(baseUrl)) return { ok: false, error: 'API 地址需要 HTTPS,或本机 HTTP(localhost)' } + if (!model) return { ok: false, error: '请填写模型名' } + if (apiKey && /[^!-~]/.test(apiKey)) return { ok: false, error: 'API Key 格式不对' } + const timeoutMs = parseTimeoutSec(values.timeoutSec) + if (!timeoutMs) return { ok: false, error: TIMEOUT_ERROR } + return { + ok: true, + draft: { + kind: 'openai', + name: values.name.trim() || model, + baseUrl, model, + systemPrompt: values.systemPrompt, + stream: values.stream, + timeoutMs, + ...(apiKey ? { apiKey } : {}) + } + } +} + +export function cliDraft(values: CliFormValues, platform: string | undefined): DraftResult<'cli'> { + const command = values.command.trim() + if (!command) return { ok: false, error: '请填写命令' } + if (/\s/.test(command) && !/[\\/]/.test(command)) { + return { ok: false, error: '命令只填程序名或完整路径,参数请逐个加到下面' } + } + if (isWindowsScript(command, platform)) return { ok: false, error: WINDOWS_SCRIPT_ERROR } + if (values.input === 'arg' && !values.args.some((a) => a.includes('{prompt}'))) { + return { ok: false, error: '参数里需要有 {prompt},或把「消息怎么传」改成 stdin' } + } + const timeoutMs = parseTimeoutSec(values.timeoutSec) + if (!timeoutMs) return { ok: false, error: TIMEOUT_ERROR } + return { + ok: true, + draft: { + kind: 'cli', + name: values.name.trim() || command.split(/[\\/]/).pop() || command, + command, + args: [...values.args], + input: values.input, + cwd: values.cwd.trim(), + timeoutMs + } + } +} + +/** Add one argv entry exactly as typed (never split: no shell parsing anywhere). */ +export function addArg(args: readonly string[], typed: string): string[] { + return typed === '' ? [...args] : [...args, typed] +} + +export function removeArg(args: readonly string[], index: number): string[] { + return args.filter((_, i) => i !== index) +} + +export function apiValuesFrom(config: ExternalPublicConfig | null): ApiFormValues { + if (config?.kind !== 'openai') return { ...API_DEFAULTS } + return { + name: config.name, baseUrl: config.baseUrl, model: config.model, apiKey: '', + systemPrompt: config.systemPrompt, stream: config.stream, timeoutSec: String(Math.round(config.timeoutMs / 1000)) + } +} + +export function cliValuesFrom(config: ExternalPublicConfig | null): CliFormValues { + if (config?.kind !== 'cli') return { ...CLI_DEFAULTS, args: [...CLI_DEFAULTS.args] } + return { + name: config.name, command: config.command, args: [...config.args], input: config.input, + cwd: config.cwd, timeoutSec: String(Math.round(config.timeoutMs / 1000)) + } +} + +export interface CommandChip { + text: string + /** The slot the turn's message goes into. */ + prompt?: boolean +} + +/** + * What the confirmation shows: the program, then every argv entry as its own + * chip, `{prompt}` spelled out; stdin input gets a trailing chip. + */ +export function commandChips(config: Pick): CommandChip[] { + const chips: CommandChip[] = [{ text: config.command }] + for (const arg of config.args) { + chips.push(arg.includes('{prompt}') + ? { text: arg.split('{prompt}').join('{本轮消息}'), prompt: true } + : { text: arg }) + } + if (config.input === 'stdin') chips.push({ text: '标准输入 ← 本轮消息', prompt: true }) + return chips +} diff --git a/src/renderer/src/components/info/AccountList.tsx b/src/renderer/src/components/info/AccountList.tsx index 3a67b018..9045cd0c 100644 --- a/src/renderer/src/components/info/AccountList.tsx +++ b/src/renderer/src/components/info/AccountList.tsx @@ -38,7 +38,8 @@ const LOGIN_CTA_LABEL: Record = { hermes: 'Configure Hermes connection', antigravity: 'Sign in with Antigravity', cue: 'Sign in with Cue', - 'ds-bot': 'Configure DS Bot connection' + 'ds-bot': 'Configure DS Bot connection', + external: 'Configure external member' } /** diff --git a/src/renderer/src/components/info/platformInspector.ts b/src/renderer/src/components/info/platformInspector.ts index 41b3151c..e981d8db 100644 --- a/src/renderer/src/components/info/platformInspector.ts +++ b/src/renderer/src/components/info/platformInspector.ts @@ -48,6 +48,14 @@ export const PLATFORM_INSPECTORS: Record = { { id: 'members', label: 'Agents' } ] }, + external: { + platformId: 'external', + displayName: '外部成员', + protocolLabel: 'OpenAI 兼容 API · 本地命令', + supportsWebSession: false, + supportsQuickNewConversation: false, + tabs: [{ id: 'overview', label: 'Overview' }] + }, hark: { platformId: 'hark', displayName: 'Hark', diff --git a/src/renderer/src/components/settings/GeneralSettingsSection.tsx b/src/renderer/src/components/settings/GeneralSettingsSection.tsx index 0e5e7872..eb9b87f2 100644 --- a/src/renderer/src/components/settings/GeneralSettingsSection.tsx +++ b/src/renderer/src/components/settings/GeneralSettingsSection.tsx @@ -79,7 +79,14 @@ async function purgeCredentials() { hermes: bridge?.hermes, antigravity: bridge?.antigravity, cue: bridge?.cue, - 'ds-bot': bridge?.dsBot + 'ds-bot': bridge?.dsBot, + // GOXF 外部成员: removing the member deletes its stored config and API key. + external: bridge?.external && { + clearAuth: async (id: string) => { + await bridge.external!.remove(id) + return { signedIn: false as const } + } + } } const grokSessionIds = listGrokAuthAccountIds() for (const id of grokSessionIds) { diff --git a/src/renderer/src/components/settings/PlatformAccountsSection.tsx b/src/renderer/src/components/settings/PlatformAccountsSection.tsx index 0b4160ae..9d4bb683 100644 --- a/src/renderer/src/components/settings/PlatformAccountsSection.tsx +++ b/src/renderer/src/components/settings/PlatformAccountsSection.tsx @@ -57,7 +57,8 @@ export const PLATFORM_LABELS: Record = { hermes: 'Hermes', antigravity: 'Antigravity', cue: 'Cue (Manus)', - 'ds-bot': 'DS Bot' + 'ds-bot': 'DS Bot', + external: '外部成员' } export function errorMessage(error: unknown): string { diff --git a/src/renderer/src/mock/mocks/v33-external-agents.tsx b/src/renderer/src/mock/mocks/v33-external-agents.tsx new file mode 100644 index 00000000..c2a126ea --- /dev/null +++ b/src/renderer/src/mock/mocks/v33-external-agents.tsx @@ -0,0 +1,261 @@ +import type { ReactNode } from 'react' +import { ChevronRight, FolderOpen, KeyRound, ListPlus, ShieldCheck, SquareTerminal, Globe, X } from 'lucide-react' +import type { PlatformDescriptor } from '@adapters/types' +import { BotAvatar } from '@/components/ui/Avatar' +import { Button } from '@/components/ui/Button' +import { SwitchPill } from '@/components/ui/Controls' +import { Field, TextInput } from '@/components/ui/Field' +import { PlatformGlyph } from '@/components/ui/PlatformGlyph' +import { SegmentedControl } from '@/components/ui/SegmentedControl' +import { cn } from '@/lib/cn' + +/** + * v33:外部成员(PR #56)。添加 Bot 对话框新增「外部 API」「本地命令」两种, + * 各自一张配置表单;本地命令第一次在群里被叫到时,先出一张确认卡,允许后才运行。 + * 逻辑已在主进程(confirmedAt + 指纹),这里只是界面方案。 + */ +const glyph = (id: string, name: string, monogram: string): PlatformDescriptor => + ({ id: id as PlatformDescriptor['id'], name, description: '', availability: 'available', monogram }) +const PLATFORMS = [glyph('meta-muse', 'Meta Muse', 'M'), glyph('hark', 'Hark', 'H'), glyph('gemini', 'Google Gemini', 'Ge'), glyph('hermes', 'Hermes', 'He')] + +function Panel({ title, children, className }: { title: string; children: ReactNode; className?: string }) { + return ( +
    +
    {title}
    +
    {children}
    +
    + ) +} + +function DialogHead({ title, back }: { title: string; back?: boolean }) { + return ( +
    + {back && } +

    {title}

    + +
    + ) +} + +function PlatformRow({ icon, name, hint, highlighted }: { icon: ReactNode; name: string; hint?: string; highlighted?: boolean }) { + return ( +
  • + +
  • + ) +} + +function ExtGlyph({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} + +function PickStep() { + return ( + + +
    +
      + {PLATFORMS.map((p) => ( + } name={p.name} /> + ))} +
    +

    外部成员

    +
      + } name="外部 API" hint="OpenAI 兼容接口 · 填地址、模型和 Key" highlighted /> + } name="本地命令" hint="本机命令行工具 · 如 claude -p" /> +
    +
    + 多 Agent 协作室 + + 批量导入 + +
    +
    +
    + ) +} + +function SettingLine({ title, hint, control }: { title: string; hint: string; control: ReactNode }) { + return ( +
    +
    +

    {title}

    +

    {hint}

    +
    + {control} +
    + ) +} + +function ApiStep() { + return ( + + +
    + + + + + + 只保存在本机系统钥匙串,界面和日志都不显示} + > + + +
    + undefined} aria-label="流式回复" />} /> + } /> +
    + +
    +
    + + +
    +
    + ) +} + +function ArgChip({ children, prompt }: { children: string; prompt?: boolean }) { + return ( + + {children} + + ) +} + +function CliStep() { + return ( + + +
    + + + + + +
    + -p + {'{prompt}'} + --output-format + text + + 添加参数 +
    +
    + undefined} + options={[{ value: 'arg', label: '参数' }, { value: 'stdin', label: 'stdin' }]} aria-label="消息怎么传" /> + } + /> + +
    + + +
    +
    + } /> +
    +
    + + +
    +
    + ) +} + +export function V33ExternalFormsMock() { + return ( +
    + + + +
    + ) +} + +/** First time a local command is called in a room: a card in the transcript, nothing runs until 允许. */ +function ConfirmCard({ state }: { state: 'ask' | 'changed' }) { + return ( +
    + +
    +
    + Claude CLI + 本地命令 · 14:52 +
    +
    +
    + +
    +

    + {state === 'ask' ? '第一次在本机运行这个命令,允许吗?' : '命令改过了,需要重新允许'} +

    +

    允许后,这个成员在群里被叫到时会直接运行;命令、参数或目录一改就会再问。

    +
    +
    +
    +
    + claude + -p + {'{本轮消息}'} + --output-format + {state === 'ask' ? 'text' : 'json'} +
    +

    目录:群工作区 D:\work\botark · 超时 300 秒 · 不经过命令行解释器

    +
    +
    + + + +
    +
    +
    +
    + ) +} + +export function V33ExternalConfirmMock() { + return ( +
    + +
    +
    +
    @Claude CLI 看下 src/main 里有没有没关的定时器
    +
    + +
    +
    + +
    + +

    成员头像上的状态点为「需要处理」(橙色),直到允许或拒绝。拒绝 = 这一轮跳过,不运行。

    +
    +
    +
    + ) +} diff --git a/src/renderer/src/mock/mocks/v33b-external-real.tsx b/src/renderer/src/mock/mocks/v33b-external-real.tsx new file mode 100644 index 00000000..2adeb43b --- /dev/null +++ b/src/renderer/src/mock/mocks/v33b-external-real.tsx @@ -0,0 +1,55 @@ +import type { ReactNode } from 'react' +import { ApiForm, CliForm } from '@/components/external/ExternalForms' +import { ConfirmBody } from '@/components/external/ExternalConfirmHost' +import { ExternalPlatformRows } from '@/components/external/ExternalConnectStep' +import { API_DEFAULTS, CLI_DEFAULTS } from '@/components/external/externalForm' +import { Button } from '@/components/ui/Button' + +/** v33b:PR #56 真实组件截图(非效果图)——添加 Bot 的外部成员两行、两张表单、首次运行确认。 */ +function Panel({ title, children, width }: { title: string; children: ReactNode; width: number }) { + return ( +
    +
    {title}
    +
    {children}
    +
    + ) +} + +export function V33bExternalRealMock() { + return ( +
    +
    + + undefined} /> + + + +
    + + + +
    +
    +
    + + undefined} + onTest={() => undefined} + /> + + + undefined} + onTest={() => undefined} + /> + +
    + ) +} diff --git a/src/renderer/src/mock/registry.ts b/src/renderer/src/mock/registry.ts index b765e4cb..491c4345 100644 --- a/src/renderer/src/mock/registry.ts +++ b/src/renderer/src/mock/registry.ts @@ -15,6 +15,8 @@ import { V29ProxyAssignOpenMock, V29ProxyAssignPageMock, V29ProxyRemoveConfirmMo import { V28ProxyPoolEmptyMock, V28ProxyPoolStepsMock } from './mocks/v28-proxy-pool-steps' import { V30RoomRoutedMock } from './mocks/v30-room-routed' import { V31ProjectRowMock } from './mocks/v31-project-row' +import { V33ExternalConfirmMock, V33ExternalFormsMock } from './mocks/v33-external-agents' +import { V33bExternalRealMock } from './mocks/v33b-external-real' import { V32RoomContextMock } from './mocks/v32-room-context' import { V32bRoomContextLiveMock } from './mocks/v32b-room-context-live' import { V32RoomWorkflowMock } from './mocks/v32-room-workflow' @@ -41,6 +43,9 @@ export const MOCKS: Record = { 'v29-proxy-assign-open': V29ProxyAssignOpenMock, 'v29-proxy-remove-confirm': V29ProxyRemoveConfirmMock, 'v30-room-routed': V30RoomRoutedMock, + 'v33-external-forms': V33ExternalFormsMock, + 'v33-external-confirm': V33ExternalConfirmMock, + 'v33b-external-real': V33bExternalRealMock, 'v32-room-context': V32RoomContextMock, 'v32b-room-context-live': V32bRoomContextLiveMock, 'v32-room-workflow': V32RoomWorkflowMock, diff --git a/src/renderer/src/rooms/roomAttachments.ts b/src/renderer/src/rooms/roomAttachments.ts index 2ab9e225..60b9104e 100644 --- a/src/renderer/src/rooms/roomAttachments.ts +++ b/src/renderer/src/rooms/roomAttachments.ts @@ -20,7 +20,9 @@ const SUPPORT: Record = { gemini: 'gemini', hermes: 'images', 'ds-bot': 'images', - antigravity: 'none' + antigravity: 'none', + // GOXF 外部成员: text only; files reach it by name in the prompt. + external: 'none' } export function attachmentSupport(platform: PlatformId): AttachmentSupport { diff --git a/src/renderer/src/rooms/roomStore.ts b/src/renderer/src/rooms/roomStore.ts index 69bb0223..2ba27238 100644 --- a/src/renderer/src/rooms/roomStore.ts +++ b/src/renderer/src/rooms/roomStore.ts @@ -961,6 +961,7 @@ async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMe accountId: member.accountId, agentId: member.agentId, hermesSessionKey, + workspaceScope: room.id, text: prompt, replyTimeoutMs: member.platform === 'hark' ? HARK_ROOM_REPLY_TIMEOUT_MS : ROOM_REPLY_TIMEOUT_MS, onAccepted: () => { accepted = true }, diff --git a/src/renderer/src/services/mobileSyncBridge.ts b/src/renderer/src/services/mobileSyncBridge.ts index 038d2ede..11bba425 100644 --- a/src/renderer/src/services/mobileSyncBridge.ts +++ b/src/renderer/src/services/mobileSyncBridge.ts @@ -171,7 +171,7 @@ function buildWorkspaceSnapshot(onMediaResolved?: () => void): MobileWorkspaceSn const accounts: Record = {} for (const [id, acc] of Object.entries(s.accounts)) { // Version 1 companion clients decode platform IDs as closed enums. - if (acc.platformId === 'gemini') continue + if (acc.platformId === 'gemini' || acc.platformId === 'external') continue accounts[id] = { id: acc.id, platformId: acc.platformId, @@ -184,7 +184,7 @@ function buildWorkspaceSnapshot(onMediaResolved?: () => void): MobileWorkspaceSn const desktopOnlyBots = new Set() const bots: MobileSyncedBot[] = s.bots.flatMap((b) => { - if (b.platformId === 'gemini') { desktopOnlyBots.add(b.id); return [] } + if (b.platformId === 'gemini' || b.platformId === 'external') { desktopOnlyBots.add(b.id); return [] } const botMsgs = s.messages[b.id] ?? [] const lastMsgAt = botMsgs.length ? botMsgs[botMsgs.length - 1]!.createdAt : b.createdAt return { diff --git a/src/renderer/src/store/botStore.ts b/src/renderer/src/store/botStore.ts index 15becd1c..c0ae9933 100644 --- a/src/renderer/src/store/botStore.ts +++ b/src/renderer/src/store/botStore.ts @@ -683,6 +683,8 @@ export const useBotStore = create()( : platformId === 'cue' ? bridge?.cue : platformId === 'ds-bot' ? bridge?.dsBot : undefined await platformBridge?.clearAuth?.(accountId) + // GOXF 外部成员: deleting the bot drops its stored config and API key. + if (platformId === 'external') await bridge?.external?.remove(accountId) } finally { if (platformId === 'grok') (adapter as { clearAuth?: (id: string) => void })?.clearAuth?.(accountId) if (platformId !== 'hermes' && platformId !== 'ds-bot') { diff --git a/src/shared/bridge.ts b/src/shared/bridge.ts index 712339dd..b00aee9d 100644 --- a/src/shared/bridge.ts +++ b/src/shared/bridge.ts @@ -314,6 +314,8 @@ export interface VaultBridge { export interface BotHubBridge { readonly gemini?: import('./gemini').GeminiBridge + /** GOXF 外部成员 (OpenAI-compatible API / local command). */ + readonly external?: import('./externalAgents').ExternalBridge /** Node-style platform string, e.g. "darwin", "win32", "linux". */ readonly platform: string readonly setDisplayLocale?: (locale: import('./displayLocale').DisplayLocale) => void diff --git a/src/shared/externalAgents.ts b/src/shared/externalAgents.ts new file mode 100644 index 00000000..feddf6c6 --- /dev/null +++ b/src/shared/externalAgents.ts @@ -0,0 +1,139 @@ +/** + * GOXF「外部成员」: an OpenAI-compatible HTTP API or a local CLI command that + * joins rooms as a bot. Shared between main, preload and renderer. + * + * Secrets: the API key only travels renderer → main once (configure) and is + * stored in the main-process vault (safeStorage). Nothing here ever carries it + * back: {@link ExternalPublicConfig} reports `hasApiKey` instead. + */ + +export type ExternalKind = 'openai' | 'cli' + +export interface ExternalOpenAiConfig { + kind: 'openai' + name: string + /** e.g. https://api.openai.com/v1 — `/chat/completions` is appended. */ + baseUrl: string + model: string + systemPrompt: string + temperature?: number + /** Stream with SSE (`stream: true`); off = one JSON response. */ + stream: boolean + /** Whole turn limit in ms. */ + timeoutMs: number +} + +/** How the prompt reaches the command. */ +export type ExternalCliInput = 'arg' | 'stdin' + +export interface ExternalCliConfig { + kind: 'cli' + name: string + /** Executable only (no arguments), e.g. `claude` or an absolute path. */ + command: string + /** + * Argument template, one array entry per argv slot. `{prompt}` inside an + * entry is replaced with the turn text; nothing is ever parsed by a shell. + */ + args: string[] + input: ExternalCliInput + /** Working directory; empty = the room's workspace directory. */ + cwd: string + timeoutMs: number + /** + * First-run confirmation: when the user approved this exact command line. + * Cleared whenever command / args / input / cwd change. + */ + confirmedAt?: number + /** Fingerprint of what was confirmed (see `cliFingerprint`). */ + confirmedFingerprint?: string +} + +export type ExternalConfig = ExternalOpenAiConfig | ExternalCliConfig + +export type ExternalPublicConfig = + | (ExternalOpenAiConfig & { hasApiKey: boolean }) + | (ExternalCliConfig & { needsConfirm: boolean }) + +/** What the renderer may send to configure; `apiKey` is write-only. */ +export type ExternalDraft = + | (Partial> & { kind: 'openai'; apiKey?: string }) + | (Partial> & { kind: 'cli' }) + +export interface ExternalChatRequest { + accountId: string + requestId: string + conversationId: string + /** Main-side history thread (OpenAI). Missing = start a new one. */ + sessionId?: string + /** Room id: picks the default working directory for CLI members. */ + workspaceScope?: string + text: string +} + +export interface ExternalChatResult { + messageId: string + sessionId?: string + text: string + createdAt: number +} + +export type ExternalEvent = + | { type: 'accepted'; requestId: string; accountId: string; sessionId?: string } + | { type: 'progress'; requestId: string; accountId: string; sessionId?: string; text: string } + +export type ExternalErrorCode = + | 'needs-confirm' + | 'timeout' + | 'cancelled' + | 'http' + | 'network' + | 'process' + | 'config' + +export interface ExternalBridge { + listAccounts(): Promise + config(accountId: string): Promise + configure(accountId: string, draft: ExternalDraft): Promise + /** Record the user's first-run approval of the CLI command line shown in the card. */ + confirmCommand(accountId: string, fingerprint: string): Promise + remove(accountId: string): Promise + chat(request: ExternalChatRequest): Promise + cancel(accountId: string, requestId: string): Promise + onEvent(listener: (event: ExternalEvent) => void): () => void + /** Native folder picker for a CLI member's working directory; undefined = cancelled. */ + pickDirectory?(): Promise +} + +export const EXTERNAL_CHANNELS = { + listAccounts: 'bothub:external:listAccounts', + config: 'bothub:external:config', + configure: 'bothub:external:configure', + confirmCommand: 'bothub:external:confirmCommand', + remove: 'bothub:external:remove', + chat: 'bothub:external:chat', + cancel: 'bothub:external:cancel', + pickDirectory: 'bothub:external:pickDirectory', + event: 'bothub:external:event' +} as const + +export const EXTERNAL_DEFAULT_TIMEOUT_MS = 120_000 +export const EXTERNAL_MAX_TIMEOUT_MS = 30 * 60_000 + +/** + * Stable text of what a CLI member will run, shown in the confirm card and + * hashed into `confirmedFingerprint`. Pure and identical in main and renderer. + */ +export function cliCommandLine(config: Pick): string { + return JSON.stringify([config.command, config.args, config.input, config.cwd]) +} + +/** Small non-crypto hash (FNV-1a 32) so the renderer can compute it too. */ +export function cliFingerprint(config: Pick): string { + let hash = 0x811c9dc5 + for (const ch of cliCommandLine(config)) { + hash ^= ch.codePointAt(0)! + hash = Math.imul(hash, 0x01000193) >>> 0 + } + return hash.toString(16).padStart(8, '0') +} diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts index 7a29437a..458bb873 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -1455,7 +1455,7 @@ export interface SecurityStoreAudit { export interface SecurityAccountAudit { accountId: string - platformId?: 'meta-muse' | 'grok' | 'hark' | 'dot' | 'hermes' | 'antigravity' | 'cue' | 'ds-bot' | 'gemini' + platformId?: 'meta-muse' | 'grok' | 'hark' | 'dot' | 'hermes' | 'antigravity' | 'cue' | 'ds-bot' | 'gemini' | 'external' partition: string transportProtocol: string credentialIsolation: string @@ -1482,7 +1482,7 @@ export interface SecurityVaultStatus { export interface VaultStatusRequest { accountId?: string - platformId?: 'meta-muse' | 'grok' | 'hark' | 'dot' | 'hermes' | 'antigravity' | 'cue' | 'ds-bot' | 'gemini' + platformId?: 'meta-muse' | 'grok' | 'hark' | 'dot' | 'hermes' | 'antigravity' | 'cue' | 'ds-bot' | 'gemini' | 'external' } export const CUE_CHANNELS = {