mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-10 01:20:49 +08:00
feat: support per-bot workspace switching
This commit is contained in:
parent
adcace3512
commit
44dd50216a
64 changed files with 3878 additions and 712 deletions
|
|
@ -3,6 +3,12 @@ import { homedir } from 'node:os';
|
|||
import { join, resolve } from 'node:path';
|
||||
|
||||
import { createTokenConnectionSupervisor } from './connection-supervisor.mjs';
|
||||
import {
|
||||
BotWorkspaceStore,
|
||||
createBotWorkspaceScope,
|
||||
createWorkspaceAwareController,
|
||||
observeBotWorkspaceRemovals,
|
||||
} from '../../../../src/channels/shared/bot-workspace-store.mjs';
|
||||
|
||||
export function harnessOrigin(webServer, configured) {
|
||||
if (configured !== undefined) return new URL(configured);
|
||||
|
|
@ -19,6 +25,7 @@ export function pluginPaths(config, channel) {
|
|||
return {
|
||||
config: resolve(config.configPath ?? join(root, 'config.json')),
|
||||
bots: resolve(config.botsDir ?? join(root, 'bots')),
|
||||
workspaces: resolve(config.workspacesPath ?? join(root, 'workspaces.json')),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -37,6 +44,16 @@ export async function createTokenProductionController(ctx, config, internals, de
|
|||
? ctx.logger(`dsh-im:${channel}`) : (ctx.logger ?? console);
|
||||
const paths = pluginPaths(config, channel);
|
||||
const configStore = await new ResolvedConfigStore(paths.config).load();
|
||||
const defaultWorkspace = resolve(config.workspace ?? process.cwd());
|
||||
const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
|
||||
const workspaces = internals.workspaces
|
||||
?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace }).load();
|
||||
const configuredBots = configStore.list();
|
||||
await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
|
||||
await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId)));
|
||||
const observedConfigStore = typeof configStore.remove === 'function'
|
||||
? observeBotWorkspaceRemovals(configStore, { workspaces })
|
||||
: configStore;
|
||||
const stateStores = new Map();
|
||||
const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
|
||||
const stateFor = async (botId) => {
|
||||
|
|
@ -49,41 +66,50 @@ export async function createTokenProductionController(ctx, config, internals, de
|
|||
};
|
||||
const harness = new ResolvedHarness({
|
||||
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
|
||||
workspace: resolve(config.workspace ?? process.cwd()),
|
||||
workspace: defaultWorkspace,
|
||||
agentPreset: config.agentPreset ?? 'standard',
|
||||
autostart: false,
|
||||
dshBin: config.dshBin ?? 'dsh',
|
||||
});
|
||||
const controller = new ResolvedController({
|
||||
const coreController = new ResolvedController({
|
||||
credentials: ctx.credentials,
|
||||
configStore,
|
||||
configStore: observedConfigStore,
|
||||
logger,
|
||||
...(internals.inspectToken ? { inspectToken: internals.inspectToken } : {}),
|
||||
createRuntime: async ({ botId, config: botConfig, token }) => new ResolvedRuntime({
|
||||
config: botConfig,
|
||||
token,
|
||||
harness,
|
||||
state: await stateFor(botId),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
logger: {
|
||||
error: (...args) => logger.error?.(`[${botId}]`, ...args),
|
||||
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
|
||||
info: (...args) => logger.info?.(`[${botId}]`, ...args),
|
||||
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
|
||||
},
|
||||
}),
|
||||
createRuntime: async ({ botId, config: botConfig, token }) => {
|
||||
const state = await stateFor(botId);
|
||||
await workspaces.ensure(botId);
|
||||
const workspaceScope = createBotWorkspaceScope(harness, { botId, workspaces, state });
|
||||
return new ResolvedRuntime({
|
||||
config: botConfig,
|
||||
token,
|
||||
harness: workspaceScope.harness,
|
||||
state: workspaceScope.state,
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
logger: {
|
||||
error: (...args) => logger.error?.(`[${botId}]`, ...args),
|
||||
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
|
||||
info: (...args) => logger.info?.(`[${botId}]`, ...args),
|
||||
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
|
||||
},
|
||||
});
|
||||
},
|
||||
deleteState: async ({ botId }) => {
|
||||
const state = stateStores.get(botId);
|
||||
stateStores.delete(botId);
|
||||
if (state && typeof state.remove === 'function') return state.remove();
|
||||
try {
|
||||
await unlink(statePath(botId));
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
if (state && typeof state.remove === 'function') {
|
||||
await state.remove();
|
||||
} else {
|
||||
try {
|
||||
await unlink(statePath(botId));
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
const controller = createWorkspaceAwareController(coreController, { workspaces, stateFor });
|
||||
const supervisor = createSupervisor({
|
||||
channel,
|
||||
controller,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,16 @@
|
|||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
import {
|
||||
publicWorkspaceError,
|
||||
SET_WORKSPACE_ENDPOINT,
|
||||
validWorkspacePayload,
|
||||
} from './workspace-rpc.mjs';
|
||||
|
||||
export const TOKEN_BOT_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
bindCredentials: 'bot.bind-credentials',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
setWorkspace: SET_WORKSPACE_ENDPOINT,
|
||||
});
|
||||
|
||||
const ENDPOINTS = Object.freeze(Object.values(TOKEN_BOT_ENDPOINTS));
|
||||
|
|
@ -45,6 +51,10 @@ function payloadFailure(endpoint, payload) {
|
|||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
||||
? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.setWorkspace) {
|
||||
return validWorkspacePayload(payload)
|
||||
? null : '请输入工作区绝对路径。';
|
||||
}
|
||||
return 'Unknown bot endpoint.';
|
||||
}
|
||||
|
||||
|
|
@ -59,6 +69,8 @@ function sanitizePublic(value) {
|
|||
}
|
||||
|
||||
function operationError(channel, error) {
|
||||
const workspaceError = publicWorkspaceError(error);
|
||||
if (workspaceError) return workspaceError;
|
||||
if (error?.code === 'webhook-configured') {
|
||||
return { code: 'webhook-configured', message: error.message };
|
||||
}
|
||||
|
|
@ -93,6 +105,9 @@ export function createTokenBotRpcHandler(controller, { channel }) {
|
|||
value = await controller.bindCredentials(payload);
|
||||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.reconnectBot) {
|
||||
value = await controller.reconnectBot(payload.botId);
|
||||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.setWorkspace) {
|
||||
if (typeof controller.updateWorkspace !== 'function') throw new Error('Workspace update is unavailable');
|
||||
value = await controller.updateWorkspace(payload.botId, payload.workspace);
|
||||
} else {
|
||||
value = await controller.deleteBot(payload.botId);
|
||||
}
|
||||
|
|
|
|||
25
plugin-src/host/channels/shared/workspace-rpc.mjs
Normal file
25
plugin-src/host/channels/shared/workspace-rpc.mjs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { isAbsolute } from 'node:path';
|
||||
|
||||
export const SET_WORKSPACE_ENDPOINT = 'bot.workspace.set';
|
||||
|
||||
export function validWorkspacePayload(payload) {
|
||||
return payload !== null
|
||||
&& typeof payload === 'object'
|
||||
&& !Array.isArray(payload)
|
||||
&& Object.keys(payload).every((key) => ['botId', 'workspace'].includes(key))
|
||||
&& typeof payload.botId === 'string'
|
||||
&& /^[A-Za-z0-9_-]{1,128}$/.test(payload.botId)
|
||||
&& typeof payload.workspace === 'string'
|
||||
&& payload.workspace.length <= 4_096
|
||||
&& isAbsolute(payload.workspace.trim());
|
||||
}
|
||||
|
||||
export function publicWorkspaceError(error) {
|
||||
if (![
|
||||
'workspace-not-absolute',
|
||||
'workspace-not-found',
|
||||
'workspace-not-directory',
|
||||
'workspace-bot-not-found',
|
||||
].includes(error?.code)) return null;
|
||||
return { code: error.code, message: error.message };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue