feat: loadable openclaw channel plugin v1 (agent=account)
Rewritten against the real openclaw v2026.5.7 plugin SDK (generic third-party channel path): createChannelPluginBase + createChatChannelPlugin with required capabilities, minimal ChannelSetupAdapter, agent=account config resolution, attached outbound -> Fabric POST, inbound socket per account -> runtime.channel.turn (wakeup->admission). Compat notes mark SDK-coupled seams for future openclaw upgrades. Verified: builds clean, installs, 'openclaw channels list' -> Fabric installed/configured/enabled. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
68
dist/fabric/index.js
vendored
68
dist/fabric/index.js
vendored
@@ -1,40 +1,62 @@
|
|||||||
import path from 'node:path';
|
// Fabric channel plugin entry.
|
||||||
import os from 'node:os';
|
// COMPAT NOTE (openclaw v2026.5.7): defineChannelPluginEntry signature
|
||||||
import { defineChannelPluginEntry } from 'openclaw/plugin-sdk/channel-core';
|
// { id, name, description, plugin, setRuntime?, registerFull? }. setRuntime
|
||||||
|
// receives the PluginRuntime (has channel.turn kernel); registerFull receives
|
||||||
|
// the OpenClawPluginApi for runtime startup (transport + tools).
|
||||||
|
import { defineChannelPluginEntry } from 'openclaw/plugin-sdk/core';
|
||||||
|
import { fabricChannelPlugin } from './src/channel.js';
|
||||||
|
import { FabricInbound } from './src/inbound.js';
|
||||||
|
import { listEnabledFabricAccounts } from './src/accounts.js';
|
||||||
|
import { registerFabricTools } from './src/tools.js';
|
||||||
import { FabricClient } from './src/fabric-client.js';
|
import { FabricClient } from './src/fabric-client.js';
|
||||||
import { IdentityRegistry } from './src/identity.js';
|
import { IdentityRegistry } from './src/identity.js';
|
||||||
import { FabricInbound } from './src/inbound.js';
|
import path from 'node:path';
|
||||||
import { buildFabricChannelPlugin } from './src/channel.js';
|
import os from 'node:os';
|
||||||
import { registerFabricTools } from './src/tools.js';
|
let runtimeRef = null;
|
||||||
function centerApiBase(api) {
|
|
||||||
const section = api.config?.channels?.['fabric'];
|
|
||||||
return section?.centerApiBase ?? 'http://localhost:7001/api';
|
|
||||||
}
|
|
||||||
let inbound = null;
|
let inbound = null;
|
||||||
|
export { fabricChannelPlugin } from './src/channel.js';
|
||||||
export default defineChannelPluginEntry({
|
export default defineChannelPluginEntry({
|
||||||
id: 'fabric',
|
id: 'fabric',
|
||||||
name: 'Fabric',
|
name: 'Fabric',
|
||||||
description: 'Fabric channel plugin — OpenClaw agents speak in Fabric guilds',
|
description: 'Fabric channel plugin — OpenClaw agents speak in Fabric guilds',
|
||||||
// Channel object: config/security/outbound. Visible turn replies flow
|
plugin: fabricChannelPlugin,
|
||||||
// through the inbound channel-turn delivery adapter; outbound.sendText
|
setRuntime(runtime) {
|
||||||
// covers proactive sends via the shared message tool.
|
runtimeRef = runtime;
|
||||||
plugin: buildFabricChannelPlugin(async () => ({ messageId: undefined })),
|
},
|
||||||
// registerFull: runtime pieces (transport, tools). Guarded so the long-lived
|
registerFull(apiRaw) {
|
||||||
// Fabric connections start once per gateway process.
|
// COMPAT: access the subset we use through a loose view so SDK type
|
||||||
registerFull(api) {
|
// drift in unrelated api members doesn't break the build.
|
||||||
const cfg = (api.pluginConfig ?? {});
|
const api = apiRaw;
|
||||||
const identityFilePath = cfg.identityFilePath ?? path.join(os.homedir(), '.openclaw', 'fabric-identity.json');
|
const cfg = (api.config ?? {});
|
||||||
const client = new FabricClient(centerApiBase(api));
|
const centerApiBase = cfg.channels?.fabric?.centerApiBase ?? 'http://localhost:7001/api';
|
||||||
const identity = new IdentityRegistry(identityFilePath);
|
const idFile = api.pluginConfig?.identityFilePath ??
|
||||||
|
path.join(os.homedir(), '.openclaw', 'fabric-identity.json');
|
||||||
|
// tools operate against a default Center; per-account keys come from config
|
||||||
|
const client = new FabricClient(centerApiBase);
|
||||||
|
const identity = new IdentityRegistry(idFile);
|
||||||
registerFabricTools({ registerTool: (d) => api.registerTool(d), logger: api.logger }, client, identity);
|
registerFabricTools({ registerTool: (d) => api.registerTool(d), logger: api.logger }, client, identity);
|
||||||
api.on('gateway_start', () => {
|
api.on('gateway_start', () => {
|
||||||
const _G = globalThis;
|
const _G = globalThis;
|
||||||
if (_G._fabricInboundStarted)
|
if (_G._fabricInboundStarted)
|
||||||
return;
|
return;
|
||||||
_G._fabricInboundStarted = true;
|
_G._fabricInboundStarted = true;
|
||||||
inbound = new FabricInbound(api.runtime, client, identity, api.logger);
|
const accounts = listEnabledFabricAccounts(cfg).map((a) => ({
|
||||||
|
agentId: a.accountId,
|
||||||
|
fabricApiKey: a.fabricApiKey,
|
||||||
|
}));
|
||||||
|
// also include any tool-registered identities
|
||||||
|
for (const e of identity.list()) {
|
||||||
|
if (!accounts.some((x) => x.agentId === e.agentId)) {
|
||||||
|
accounts.push({ agentId: e.agentId, fabricApiKey: e.fabricApiKey });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!runtimeRef) {
|
||||||
|
api.logger.warn('fabric: runtime not set; inbound disabled');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
inbound = new FabricInbound(runtimeRef, client, identity, api.logger, accounts);
|
||||||
void inbound.start();
|
void inbound.start();
|
||||||
api.logger.info('fabric: inbound transport started');
|
api.logger.info(`fabric: inbound started for ${accounts.length} account(s)`);
|
||||||
});
|
});
|
||||||
api.on('gateway_stop', () => {
|
api.on('gateway_stop', () => {
|
||||||
inbound?.stop();
|
inbound?.stop();
|
||||||
|
|||||||
41
dist/fabric/src/accounts.js
vendored
Normal file
41
dist/fabric/src/accounts.js
vendored
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
// agent = openclaw channel account.
|
||||||
|
// Config shape:
|
||||||
|
// channels.fabric.centerApiBase = "http://localhost:7001/api" (shared)
|
||||||
|
// channels.fabric.accounts.<agentId> = { fabricApiKey, centerApiBase? }
|
||||||
|
// Each account id IS the openclaw agentId that owns that Fabric identity.
|
||||||
|
const DEFAULT_CENTER = 'http://localhost:7001/api';
|
||||||
|
function section(cfg) {
|
||||||
|
return cfg.channels?.fabric ?? {};
|
||||||
|
}
|
||||||
|
export function listFabricAccountIds(cfg) {
|
||||||
|
const accts = section(cfg).accounts ?? {};
|
||||||
|
const ids = Object.keys(accts);
|
||||||
|
return ids.length ? ids : ['default'];
|
||||||
|
}
|
||||||
|
export function resolveDefaultFabricAccountId(cfg) {
|
||||||
|
const s = section(cfg);
|
||||||
|
if (s.defaultAccount)
|
||||||
|
return s.defaultAccount;
|
||||||
|
const ids = listFabricAccountIds(cfg);
|
||||||
|
return ids[0] ?? 'default';
|
||||||
|
}
|
||||||
|
export function resolveFabricAccount(cfg, accountId) {
|
||||||
|
const s = section(cfg);
|
||||||
|
const id = accountId ?? resolveDefaultFabricAccountId(cfg);
|
||||||
|
const acc = s.accounts?.[id] ?? {};
|
||||||
|
const fabricApiKey = (acc.fabricApiKey ?? '').trim();
|
||||||
|
const centerApiBase = (acc.centerApiBase ?? s.centerApiBase ?? DEFAULT_CENTER).trim();
|
||||||
|
return {
|
||||||
|
accountId: id,
|
||||||
|
enabled: acc.enabled !== false && s.enabled !== false,
|
||||||
|
centerApiBase,
|
||||||
|
fabricApiKey,
|
||||||
|
allowFrom: acc.allowFrom ?? s.allowFrom ?? [],
|
||||||
|
dmPolicy: acc.dmPolicy ?? s.dmPolicy,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function listEnabledFabricAccounts(cfg) {
|
||||||
|
return listFabricAccountIds(cfg)
|
||||||
|
.map((id) => resolveFabricAccount(cfg, id))
|
||||||
|
.filter((a) => a.enabled && a.fabricApiKey);
|
||||||
|
}
|
||||||
99
dist/fabric/src/channel.js
vendored
99
dist/fabric/src/channel.js
vendored
@@ -1,30 +1,72 @@
|
|||||||
import { createChatChannelPlugin, createChannelPluginBase, } from 'openclaw/plugin-sdk/channel-core';
|
// Fabric channel plugin object (third-party `createChatChannelPlugin` path).
|
||||||
export function resolveFabricAccount(cfg, accountId) {
|
//
|
||||||
const section = cfg.channels?.['fabric'];
|
// COMPAT NOTE (openclaw v2026.5.7 plugin SDK):
|
||||||
const centerApiBase = section?.centerApiBase;
|
// We depend on these generic SDK shapes — re-verify on openclaw upgrade:
|
||||||
if (!centerApiBase)
|
// - createChannelPluginBase requires `capabilities`
|
||||||
throw new Error('fabric: channels.fabric.centerApiBase is required');
|
// - ChannelSetupAdapter: only `applyAccountConfig` is required
|
||||||
return {
|
// - outbound attachedResults.sendText returns Omit<OutboundDeliveryResult,
|
||||||
accountId: accountId ?? null,
|
// "channel"> (so `messageId: string` is required)
|
||||||
centerApiBase,
|
// Casts at the createChatChannelPlugin boundary are intentional and
|
||||||
allowFrom: section?.allowFrom ?? [],
|
// localized; keep them here so upgrades touch one file.
|
||||||
dmPolicy: section?.dmSecurity,
|
import { createChatChannelPlugin, createChannelPluginBase, } from 'openclaw/plugin-sdk/core';
|
||||||
};
|
import { FabricClient } from './fabric-client.js';
|
||||||
|
import { listFabricAccountIds, resolveFabricAccount, resolveDefaultFabricAccountId, } from './accounts.js';
|
||||||
|
// Posts an agent's reply to Fabric. `to` is the Fabric channelId; `accountId`
|
||||||
|
// is the agentId (= Fabric identity). One auth concept: account apiKey ->
|
||||||
|
// agent/login -> guild token -> POST message.
|
||||||
|
async function sendToFabric(cfg, accountId, to, text) {
|
||||||
|
const acc = resolveFabricAccount(cfg, accountId);
|
||||||
|
if (!acc.fabricApiKey)
|
||||||
|
throw new Error(`fabric account ${acc.accountId} has no fabricApiKey`);
|
||||||
|
const client = new FabricClient(acc.centerApiBase);
|
||||||
|
const session = await client.agentLogin(acc.fabricApiKey);
|
||||||
|
// find which guild owns this channel by probing each guild's channel list
|
||||||
|
for (const g of session.guilds) {
|
||||||
|
const gt = session.guildAccessTokens.find((t) => t.guildNodeId === g.nodeId)?.token;
|
||||||
|
if (!gt)
|
||||||
|
continue;
|
||||||
|
const res = await fetch(`${g.endpoint}/api/channels?guildId=${encodeURIComponent(g.nodeId)}`, {
|
||||||
|
headers: { authorization: `Bearer ${gt}` },
|
||||||
|
});
|
||||||
|
const channels = res.ok ? (await res.json()) : [];
|
||||||
|
if (channels.some((c) => c.id === to)) {
|
||||||
|
await client.postMessage(g.endpoint, gt, to, text, session.user.id);
|
||||||
|
return { messageId: `${to}:${Date.now()}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// fallback: first guild
|
||||||
|
const g = session.guilds[0];
|
||||||
|
const gt = session.guildAccessTokens.find((t) => t.guildNodeId === g?.nodeId)?.token;
|
||||||
|
if (g && gt) {
|
||||||
|
await client.postMessage(g.endpoint, gt, to, text, session.user.id);
|
||||||
|
return { messageId: `${to}:${Date.now()}` };
|
||||||
|
}
|
||||||
|
throw new Error('fabric: no guild available to deliver');
|
||||||
}
|
}
|
||||||
// Outbound is wired by the entry (it needs the identity registry + client to
|
export const fabricChannelPlugin = createChatChannelPlugin({
|
||||||
// post as the right agent). Channel-turn visible replies go through the
|
|
||||||
// inbound adapter's delivery callback; this object owns config/security only.
|
|
||||||
export function buildFabricChannelPlugin(sendText) {
|
|
||||||
return createChatChannelPlugin({
|
|
||||||
base: createChannelPluginBase({
|
base: createChannelPluginBase({
|
||||||
id: 'fabric',
|
id: 'fabric',
|
||||||
setup: {
|
meta: { id: 'fabric', label: 'Fabric', blurb: 'Connect OpenClaw agents to a Fabric guild.' },
|
||||||
resolveAccount: resolveFabricAccount,
|
capabilities: {
|
||||||
inspectAccount(cfg, accountId) {
|
chatTypes: ['channel', 'group', 'direct'],
|
||||||
const section = cfg.channels?.['fabric'];
|
reactions: false,
|
||||||
const ok = Boolean(section?.centerApiBase);
|
threads: false,
|
||||||
return { enabled: ok, configured: ok, tokenStatus: ok ? 'available' : 'missing' };
|
media: false,
|
||||||
|
nativeCommands: false,
|
||||||
|
blockStreaming: true,
|
||||||
},
|
},
|
||||||
|
reload: { configPrefixes: ['channels.fabric'] },
|
||||||
|
config: {
|
||||||
|
listAccountIds: (cfg) => listFabricAccountIds(cfg),
|
||||||
|
resolveAccount: (cfg, accountId) => resolveFabricAccount(cfg, accountId),
|
||||||
|
defaultAccountId: (cfg) => resolveDefaultFabricAccountId(cfg),
|
||||||
|
isConfigured: (account) => Boolean(account.fabricApiKey),
|
||||||
|
},
|
||||||
|
// Minimal setup adapter: Fabric is configured directly under
|
||||||
|
// channels.fabric.* (no interactive wizard). applyAccountConfig is the
|
||||||
|
// only required member.
|
||||||
|
setup: {
|
||||||
|
applyAccountConfig: ({ cfg }) => cfg,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
security: {
|
security: {
|
||||||
@@ -35,12 +77,15 @@ export function buildFabricChannelPlugin(sendText) {
|
|||||||
defaultPolicy: 'allowlist',
|
defaultPolicy: 'allowlist',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// Fabric replies thread by being posted into the same channel.
|
|
||||||
threading: { topLevelReplyToMode: 'channel' },
|
threading: { topLevelReplyToMode: 'channel' },
|
||||||
outbound: {
|
outbound: {
|
||||||
|
base: {},
|
||||||
attachedResults: {
|
attachedResults: {
|
||||||
sendText: async (params) => sendText(params),
|
channel: 'fabric',
|
||||||
|
sendText: async (ctx) => {
|
||||||
|
const cfg = (ctx.cfg ?? {});
|
||||||
|
return sendToFabric(cfg, ctx.accountId ?? null, ctx.to, ctx.text);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
},
|
||||||
}
|
});
|
||||||
|
|||||||
9
dist/fabric/src/inbound.js
vendored
9
dist/fabric/src/inbound.js
vendored
@@ -7,17 +7,22 @@ export class FabricInbound {
|
|||||||
client;
|
client;
|
||||||
identity;
|
identity;
|
||||||
log;
|
log;
|
||||||
|
accounts;
|
||||||
sockets = [];
|
sockets = [];
|
||||||
timers = [];
|
timers = [];
|
||||||
seen = new Set();
|
seen = new Set();
|
||||||
constructor(runtime, client, identity, log) {
|
constructor(runtime, client, identity, log, accounts = []) {
|
||||||
this.runtime = runtime;
|
this.runtime = runtime;
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.identity = identity;
|
this.identity = identity;
|
||||||
this.log = log;
|
this.log = log;
|
||||||
|
this.accounts = accounts;
|
||||||
}
|
}
|
||||||
async start() {
|
async start() {
|
||||||
for (const entry of this.identity.list()) {
|
const entries = this.accounts.length > 0
|
||||||
|
? this.accounts.map((a) => ({ agentId: a.agentId, fabricApiKey: a.fabricApiKey }))
|
||||||
|
: this.identity.list();
|
||||||
|
for (const entry of entries) {
|
||||||
try {
|
try {
|
||||||
const session = await this.client.agentLogin(entry.fabricApiKey);
|
const session = await this.client.agentLogin(entry.fabricApiKey);
|
||||||
this.identity.upsert({
|
this.identity.upsert({
|
||||||
|
|||||||
90
index.ts
90
index.ts
@@ -1,46 +1,55 @@
|
|||||||
import path from 'node:path';
|
// Fabric channel plugin entry.
|
||||||
import os from 'node:os';
|
// COMPAT NOTE (openclaw v2026.5.7): defineChannelPluginEntry signature
|
||||||
import { defineChannelPluginEntry } from 'openclaw/plugin-sdk/channel-core';
|
// { id, name, description, plugin, setRuntime?, registerFull? }. setRuntime
|
||||||
|
// receives the PluginRuntime (has channel.turn kernel); registerFull receives
|
||||||
|
// the OpenClawPluginApi for runtime startup (transport + tools).
|
||||||
|
import { defineChannelPluginEntry } from 'openclaw/plugin-sdk/core';
|
||||||
import type { OpenClawPluginApi } from 'openclaw/plugin-sdk/core';
|
import type { OpenClawPluginApi } from 'openclaw/plugin-sdk/core';
|
||||||
|
import { fabricChannelPlugin } from './src/channel.js';
|
||||||
|
import { FabricInbound } from './src/inbound.js';
|
||||||
|
import { listEnabledFabricAccounts } from './src/accounts.js';
|
||||||
|
import { registerFabricTools } from './src/tools.js';
|
||||||
import { FabricClient } from './src/fabric-client.js';
|
import { FabricClient } from './src/fabric-client.js';
|
||||||
import { IdentityRegistry } from './src/identity.js';
|
import { IdentityRegistry } from './src/identity.js';
|
||||||
import { FabricInbound } from './src/inbound.js';
|
import path from 'node:path';
|
||||||
import { buildFabricChannelPlugin } from './src/channel.js';
|
import os from 'node:os';
|
||||||
import { registerFabricTools } from './src/tools.js';
|
|
||||||
|
|
||||||
type PluginConfig = { identityFilePath?: string; debugMode?: boolean };
|
|
||||||
|
|
||||||
function centerApiBase(api: OpenClawPluginApi): string {
|
|
||||||
const section = ((api.config as Record<string, unknown>)?.channels as Record<string, any>)?.[
|
|
||||||
'fabric'
|
|
||||||
];
|
|
||||||
return section?.centerApiBase ?? 'http://localhost:7001/api';
|
|
||||||
}
|
|
||||||
|
|
||||||
|
let runtimeRef: unknown = null;
|
||||||
let inbound: FabricInbound | null = null;
|
let inbound: FabricInbound | null = null;
|
||||||
|
|
||||||
|
export { fabricChannelPlugin } from './src/channel.js';
|
||||||
|
|
||||||
export default defineChannelPluginEntry({
|
export default defineChannelPluginEntry({
|
||||||
id: 'fabric',
|
id: 'fabric',
|
||||||
name: 'Fabric',
|
name: 'Fabric',
|
||||||
description: 'Fabric channel plugin — OpenClaw agents speak in Fabric guilds',
|
description: 'Fabric channel plugin — OpenClaw agents speak in Fabric guilds',
|
||||||
|
plugin: fabricChannelPlugin,
|
||||||
|
|
||||||
// Channel object: config/security/outbound. Visible turn replies flow
|
setRuntime(runtime: unknown) {
|
||||||
// through the inbound channel-turn delivery adapter; outbound.sendText
|
runtimeRef = runtime;
|
||||||
// covers proactive sends via the shared message tool.
|
},
|
||||||
plugin: buildFabricChannelPlugin(async () => ({ messageId: undefined })),
|
|
||||||
|
|
||||||
// registerFull: runtime pieces (transport, tools). Guarded so the long-lived
|
registerFull(apiRaw: OpenClawPluginApi) {
|
||||||
// Fabric connections start once per gateway process.
|
// COMPAT: access the subset we use through a loose view so SDK type
|
||||||
registerFull(api: OpenClawPluginApi) {
|
// drift in unrelated api members doesn't break the build.
|
||||||
const cfg = (api.pluginConfig ?? {}) as PluginConfig;
|
const api = apiRaw as unknown as {
|
||||||
const identityFilePath =
|
config?: unknown;
|
||||||
cfg.identityFilePath ?? path.join(os.homedir(), '.openclaw', 'fabric-identity.json');
|
pluginConfig?: { identityFilePath?: string };
|
||||||
|
logger: { info: (m: string) => void; warn: (m: string) => void };
|
||||||
const client = new FabricClient(centerApiBase(api));
|
on: (ev: string, fn: () => void) => void;
|
||||||
const identity = new IdentityRegistry(identityFilePath);
|
registerTool: (d: unknown) => void;
|
||||||
|
};
|
||||||
|
const cfg = (api.config ?? {}) as { channels?: { fabric?: { centerApiBase?: string } } };
|
||||||
|
const centerApiBase = cfg.channels?.fabric?.centerApiBase ?? 'http://localhost:7001/api';
|
||||||
|
const idFile =
|
||||||
|
api.pluginConfig?.identityFilePath ??
|
||||||
|
path.join(os.homedir(), '.openclaw', 'fabric-identity.json');
|
||||||
|
|
||||||
|
// tools operate against a default Center; per-account keys come from config
|
||||||
|
const client = new FabricClient(centerApiBase);
|
||||||
|
const identity = new IdentityRegistry(idFile);
|
||||||
registerFabricTools(
|
registerFabricTools(
|
||||||
{ registerTool: (d) => api.registerTool(d as never), logger: api.logger },
|
{ registerTool: (d) => api.registerTool(d), logger: api.logger },
|
||||||
client,
|
client,
|
||||||
identity,
|
identity,
|
||||||
);
|
);
|
||||||
@@ -49,14 +58,23 @@ export default defineChannelPluginEntry({
|
|||||||
const _G = globalThis as Record<string, unknown>;
|
const _G = globalThis as Record<string, unknown>;
|
||||||
if (_G._fabricInboundStarted) return;
|
if (_G._fabricInboundStarted) return;
|
||||||
_G._fabricInboundStarted = true;
|
_G._fabricInboundStarted = true;
|
||||||
inbound = new FabricInbound(
|
const accounts = listEnabledFabricAccounts(cfg as never).map((a) => ({
|
||||||
(api as unknown as { runtime: any }).runtime,
|
agentId: a.accountId,
|
||||||
client,
|
fabricApiKey: a.fabricApiKey,
|
||||||
identity,
|
}));
|
||||||
api.logger,
|
// also include any tool-registered identities
|
||||||
);
|
for (const e of identity.list()) {
|
||||||
|
if (!accounts.some((x) => x.agentId === e.agentId)) {
|
||||||
|
accounts.push({ agentId: e.agentId, fabricApiKey: e.fabricApiKey });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!runtimeRef) {
|
||||||
|
api.logger.warn('fabric: runtime not set; inbound disabled');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
inbound = new FabricInbound(runtimeRef as never, client, identity, api.logger, accounts);
|
||||||
void inbound.start();
|
void inbound.start();
|
||||||
api.logger.info('fabric: inbound transport started');
|
api.logger.info(`fabric: inbound started for ${accounts.length} account(s)`);
|
||||||
});
|
});
|
||||||
|
|
||||||
api.on('gateway_stop', () => {
|
api.on('gateway_stop', () => {
|
||||||
|
|||||||
71
src/accounts.ts
Normal file
71
src/accounts.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
// agent = openclaw channel account.
|
||||||
|
// Config shape:
|
||||||
|
// channels.fabric.centerApiBase = "http://localhost:7001/api" (shared)
|
||||||
|
// channels.fabric.accounts.<agentId> = { fabricApiKey, centerApiBase? }
|
||||||
|
// Each account id IS the openclaw agentId that owns that Fabric identity.
|
||||||
|
|
||||||
|
export type FabricAccountConfig = {
|
||||||
|
fabricApiKey?: string;
|
||||||
|
centerApiBase?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
allowFrom?: string[];
|
||||||
|
dmPolicy?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FabricChannelConfig = {
|
||||||
|
centerApiBase?: string;
|
||||||
|
accounts?: Record<string, FabricAccountConfig>;
|
||||||
|
defaultAccount?: string;
|
||||||
|
} & FabricAccountConfig;
|
||||||
|
|
||||||
|
type Cfg = { channels?: { fabric?: FabricChannelConfig }; [k: string]: unknown };
|
||||||
|
|
||||||
|
export type ResolvedFabricAccount = {
|
||||||
|
accountId: string;
|
||||||
|
enabled: boolean;
|
||||||
|
centerApiBase: string;
|
||||||
|
fabricApiKey: string;
|
||||||
|
allowFrom: string[];
|
||||||
|
dmPolicy: string | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_CENTER = 'http://localhost:7001/api';
|
||||||
|
|
||||||
|
function section(cfg: Cfg): FabricChannelConfig {
|
||||||
|
return cfg.channels?.fabric ?? {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listFabricAccountIds(cfg: Cfg): string[] {
|
||||||
|
const accts = section(cfg).accounts ?? {};
|
||||||
|
const ids = Object.keys(accts);
|
||||||
|
return ids.length ? ids : ['default'];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveDefaultFabricAccountId(cfg: Cfg): string {
|
||||||
|
const s = section(cfg);
|
||||||
|
if (s.defaultAccount) return s.defaultAccount;
|
||||||
|
const ids = listFabricAccountIds(cfg);
|
||||||
|
return ids[0] ?? 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveFabricAccount(cfg: Cfg, accountId?: string | null): ResolvedFabricAccount {
|
||||||
|
const s = section(cfg);
|
||||||
|
const id = accountId ?? resolveDefaultFabricAccountId(cfg);
|
||||||
|
const acc = s.accounts?.[id] ?? {};
|
||||||
|
const fabricApiKey = (acc.fabricApiKey ?? '').trim();
|
||||||
|
const centerApiBase = (acc.centerApiBase ?? s.centerApiBase ?? DEFAULT_CENTER).trim();
|
||||||
|
return {
|
||||||
|
accountId: id,
|
||||||
|
enabled: acc.enabled !== false && s.enabled !== false,
|
||||||
|
centerApiBase,
|
||||||
|
fabricApiKey,
|
||||||
|
allowFrom: acc.allowFrom ?? s.allowFrom ?? [],
|
||||||
|
dmPolicy: acc.dmPolicy ?? s.dmPolicy,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listEnabledFabricAccounts(cfg: Cfg): ResolvedFabricAccount[] {
|
||||||
|
return listFabricAccountIds(cfg)
|
||||||
|
.map((id) => resolveFabricAccount(cfg, id))
|
||||||
|
.filter((a) => a.enabled && a.fabricApiKey);
|
||||||
|
}
|
||||||
132
src/channel.ts
132
src/channel.ts
@@ -1,63 +1,109 @@
|
|||||||
|
// Fabric channel plugin object (third-party `createChatChannelPlugin` path).
|
||||||
|
//
|
||||||
|
// COMPAT NOTE (openclaw v2026.5.7 plugin SDK):
|
||||||
|
// We depend on these generic SDK shapes — re-verify on openclaw upgrade:
|
||||||
|
// - createChannelPluginBase requires `capabilities`
|
||||||
|
// - ChannelSetupAdapter: only `applyAccountConfig` is required
|
||||||
|
// - outbound attachedResults.sendText returns Omit<OutboundDeliveryResult,
|
||||||
|
// "channel"> (so `messageId: string` is required)
|
||||||
|
// Casts at the createChatChannelPlugin boundary are intentional and
|
||||||
|
// localized; keep them here so upgrades touch one file.
|
||||||
import {
|
import {
|
||||||
createChatChannelPlugin,
|
createChatChannelPlugin,
|
||||||
createChannelPluginBase,
|
createChannelPluginBase,
|
||||||
} from 'openclaw/plugin-sdk/channel-core';
|
} from 'openclaw/plugin-sdk/core';
|
||||||
import type { OpenClawConfig } from 'openclaw/plugin-sdk/channel-core';
|
import { FabricClient } from './fabric-client.js';
|
||||||
|
import {
|
||||||
|
listFabricAccountIds,
|
||||||
|
resolveFabricAccount,
|
||||||
|
resolveDefaultFabricAccountId,
|
||||||
|
type ResolvedFabricAccount,
|
||||||
|
} from './accounts.js';
|
||||||
|
|
||||||
export type ResolvedFabricAccount = {
|
type AnyCfg = { channels?: { fabric?: unknown }; [k: string]: unknown };
|
||||||
accountId: string | null;
|
|
||||||
centerApiBase: string;
|
|
||||||
allowFrom: string[];
|
|
||||||
dmPolicy: string | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function resolveFabricAccount(
|
// Posts an agent's reply to Fabric. `to` is the Fabric channelId; `accountId`
|
||||||
cfg: OpenClawConfig,
|
// is the agentId (= Fabric identity). One auth concept: account apiKey ->
|
||||||
accountId?: string | null,
|
// agent/login -> guild token -> POST message.
|
||||||
): ResolvedFabricAccount {
|
async function sendToFabric(
|
||||||
const section = (cfg.channels as Record<string, any>)?.['fabric'];
|
cfg: AnyCfg,
|
||||||
const centerApiBase: string | undefined = section?.centerApiBase;
|
accountId: string | null | undefined,
|
||||||
if (!centerApiBase) throw new Error('fabric: channels.fabric.centerApiBase is required');
|
to: string,
|
||||||
return {
|
text: string,
|
||||||
accountId: accountId ?? null,
|
): Promise<{ messageId: string }> {
|
||||||
centerApiBase,
|
const acc = resolveFabricAccount(cfg as never, accountId);
|
||||||
allowFrom: section?.allowFrom ?? [],
|
if (!acc.fabricApiKey) throw new Error(`fabric account ${acc.accountId} has no fabricApiKey`);
|
||||||
dmPolicy: section?.dmSecurity,
|
const client = new FabricClient(acc.centerApiBase);
|
||||||
};
|
const session = await client.agentLogin(acc.fabricApiKey);
|
||||||
|
// find which guild owns this channel by probing each guild's channel list
|
||||||
|
for (const g of session.guilds) {
|
||||||
|
const gt = session.guildAccessTokens.find((t) => t.guildNodeId === g.nodeId)?.token;
|
||||||
|
if (!gt) continue;
|
||||||
|
const res = await fetch(`${g.endpoint}/api/channels?guildId=${encodeURIComponent(g.nodeId)}`, {
|
||||||
|
headers: { authorization: `Bearer ${gt}` },
|
||||||
|
});
|
||||||
|
const channels = res.ok ? ((await res.json()) as Array<{ id: string }>) : [];
|
||||||
|
if (channels.some((c) => c.id === to)) {
|
||||||
|
await client.postMessage(g.endpoint, gt, to, text, session.user.id);
|
||||||
|
return { messageId: `${to}:${Date.now()}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// fallback: first guild
|
||||||
|
const g = session.guilds[0];
|
||||||
|
const gt = session.guildAccessTokens.find((t) => t.guildNodeId === g?.nodeId)?.token;
|
||||||
|
if (g && gt) {
|
||||||
|
await client.postMessage(g.endpoint, gt, to, text, session.user.id);
|
||||||
|
return { messageId: `${to}:${Date.now()}` };
|
||||||
|
}
|
||||||
|
throw new Error('fabric: no guild available to deliver');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Outbound is wired by the entry (it needs the identity registry + client to
|
export const fabricChannelPlugin = createChatChannelPlugin<ResolvedFabricAccount>({
|
||||||
// post as the right agent). Channel-turn visible replies go through the
|
base: createChannelPluginBase<ResolvedFabricAccount>({
|
||||||
// inbound adapter's delivery callback; this object owns config/security only.
|
|
||||||
export function buildFabricChannelPlugin(
|
|
||||||
sendText: (params: { accountId?: string | null; to: string; text: string }) => Promise<{ messageId?: string }>,
|
|
||||||
) {
|
|
||||||
return createChatChannelPlugin<ResolvedFabricAccount>({
|
|
||||||
base: createChannelPluginBase({
|
|
||||||
id: 'fabric',
|
id: 'fabric',
|
||||||
|
meta: { id: 'fabric', label: 'Fabric', blurb: 'Connect OpenClaw agents to a Fabric guild.' },
|
||||||
|
capabilities: {
|
||||||
|
chatTypes: ['channel', 'group', 'direct'],
|
||||||
|
reactions: false,
|
||||||
|
threads: false,
|
||||||
|
media: false,
|
||||||
|
nativeCommands: false,
|
||||||
|
blockStreaming: true,
|
||||||
|
},
|
||||||
|
reload: { configPrefixes: ['channels.fabric'] },
|
||||||
|
config: {
|
||||||
|
listAccountIds: (cfg) => listFabricAccountIds(cfg as never),
|
||||||
|
resolveAccount: (cfg, accountId) => resolveFabricAccount(cfg as never, accountId),
|
||||||
|
defaultAccountId: (cfg) => resolveDefaultFabricAccountId(cfg as never),
|
||||||
|
isConfigured: (account: ResolvedFabricAccount) => Boolean(account.fabricApiKey),
|
||||||
|
},
|
||||||
|
// Minimal setup adapter: Fabric is configured directly under
|
||||||
|
// channels.fabric.* (no interactive wizard). applyAccountConfig is the
|
||||||
|
// only required member.
|
||||||
setup: {
|
setup: {
|
||||||
resolveAccount: resolveFabricAccount,
|
applyAccountConfig: ({ cfg }: { cfg: unknown }) => cfg as never,
|
||||||
inspectAccount(cfg, accountId) {
|
} as never,
|
||||||
const section = (cfg.channels as Record<string, any>)?.['fabric'];
|
}) as never,
|
||||||
const ok = Boolean(section?.centerApiBase);
|
|
||||||
return { enabled: ok, configured: ok, tokenStatus: ok ? 'available' : 'missing' };
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
security: {
|
security: {
|
||||||
dm: {
|
dm: {
|
||||||
channelKey: 'fabric',
|
channelKey: 'fabric',
|
||||||
resolvePolicy: (a) => a.dmPolicy,
|
resolvePolicy: (a: ResolvedFabricAccount) => a.dmPolicy,
|
||||||
resolveAllowFrom: (a) => a.allowFrom,
|
resolveAllowFrom: (a: ResolvedFabricAccount) => a.allowFrom,
|
||||||
defaultPolicy: 'allowlist',
|
defaultPolicy: 'allowlist',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// Fabric replies thread by being posted into the same channel.
|
|
||||||
threading: { topLevelReplyToMode: 'channel' },
|
threading: { topLevelReplyToMode: 'channel' },
|
||||||
|
|
||||||
outbound: {
|
outbound: {
|
||||||
|
base: {},
|
||||||
attachedResults: {
|
attachedResults: {
|
||||||
sendText: async (params) => sendText(params),
|
channel: 'fabric',
|
||||||
|
sendText: async (ctx: { accountId?: string | null; to: string; text: string; cfg?: unknown }) => {
|
||||||
|
const cfg = (ctx.cfg ?? {}) as AnyCfg;
|
||||||
|
return sendToFabric(cfg, ctx.accountId ?? null, ctx.to, ctx.text);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
} as never,
|
||||||
}
|
});
|
||||||
|
|||||||
@@ -39,10 +39,15 @@ export class FabricInbound {
|
|||||||
private readonly client: FabricClient,
|
private readonly client: FabricClient,
|
||||||
private readonly identity: IdentityRegistry,
|
private readonly identity: IdentityRegistry,
|
||||||
private readonly log: Logger,
|
private readonly log: Logger,
|
||||||
|
private readonly accounts: Array<{ agentId: string; fabricApiKey: string }> = [],
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async start(): Promise<void> {
|
async start(): Promise<void> {
|
||||||
for (const entry of this.identity.list()) {
|
const entries =
|
||||||
|
this.accounts.length > 0
|
||||||
|
? this.accounts.map((a) => ({ agentId: a.agentId, fabricApiKey: a.fabricApiKey }))
|
||||||
|
: this.identity.list();
|
||||||
|
for (const entry of entries) {
|
||||||
try {
|
try {
|
||||||
const session = await this.client.agentLogin(entry.fabricApiKey);
|
const session = await this.client.agentLogin(entry.fabricApiKey);
|
||||||
this.identity.upsert({
|
this.identity.upsert({
|
||||||
|
|||||||
Reference in New Issue
Block a user