build: PaddedCell-style install.mjs + SDK-aligned packaging

install.mjs (--install/--build-only/--uninstall/--openclaw-profile-path),
tsconfig outDir dist/fabric, package.json openclaw file dep + main.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
h z
2026-05-15 17:30:37 +01:00
parent 9221664428
commit 7fed6d07f6
537 changed files with 536836 additions and 3 deletions

46
dist/fabric/src/channel.js vendored Normal file
View File

@@ -0,0 +1,46 @@
import { createChatChannelPlugin, createChannelPluginBase, } from 'openclaw/plugin-sdk/channel-core';
export function resolveFabricAccount(cfg, accountId) {
const section = cfg.channels?.['fabric'];
const centerApiBase = section?.centerApiBase;
if (!centerApiBase)
throw new Error('fabric: channels.fabric.centerApiBase is required');
return {
accountId: accountId ?? null,
centerApiBase,
allowFrom: section?.allowFrom ?? [],
dmPolicy: section?.dmSecurity,
};
}
// Outbound is wired by the entry (it needs the identity registry + client to
// 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({
id: 'fabric',
setup: {
resolveAccount: resolveFabricAccount,
inspectAccount(cfg, accountId) {
const section = cfg.channels?.['fabric'];
const ok = Boolean(section?.centerApiBase);
return { enabled: ok, configured: ok, tokenStatus: ok ? 'available' : 'missing' };
},
},
}),
security: {
dm: {
channelKey: 'fabric',
resolvePolicy: (a) => a.dmPolicy,
resolveAllowFrom: (a) => a.allowFrom,
defaultPolicy: 'allowlist',
},
},
// Fabric replies thread by being posted into the same channel.
threading: { topLevelReplyToMode: 'channel' },
outbound: {
attachedResults: {
sendText: async (params) => sendText(params),
},
},
});
}

53
dist/fabric/src/fabric-client.js vendored Normal file
View File

@@ -0,0 +1,53 @@
// Thin Fabric REST client. One auth concept: an agent's Center API key is
// exchanged for a normal user session (POST /auth/agent/login); the returned
// guild access tokens are used to post messages and call channel APIs.
export class FabricClient {
centerApiBase;
constructor(centerApiBase) {
this.centerApiBase = centerApiBase;
}
async post(url, body, auth) {
const res = await fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
...(auth ? { authorization: `Bearer ${auth}` } : {}),
},
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`POST ${url} -> ${res.status} ${text}`);
}
return (await res.json());
}
// Exchange an agent API key for a Fabric user session (+ guild tokens).
agentLogin(apiKey) {
return this.post(`${this.centerApiBase}/auth/agent/login`, { apiKey });
}
// Refresh the center access token (guild tokens are re-fetched via /auth/me/guilds).
async refresh(refreshToken) {
return this.post(`${this.centerApiBase}/auth/refresh`, { refreshToken });
}
async meGuilds(accessToken) {
const res = await fetch(`${this.centerApiBase}/auth/me/guilds`, {
headers: { authorization: `Bearer ${accessToken}` },
});
if (!res.ok)
throw new Error(`me/guilds -> ${res.status}`);
return (await res.json());
}
// ---- guild-scoped (use the per-guild access token) ----
postMessage(guildEndpoint, guildToken, channelId, content, authorUserId) {
return this.post(`${guildEndpoint}/api/channels/${channelId}/messages`, { content, authorUserId }, guildToken);
}
createChannel(guildEndpoint, guildToken, body) {
return this.post(`${guildEndpoint}/api/channels`, body, guildToken);
}
closeChannel(guildEndpoint, guildToken, channelId) {
return this.post(`${guildEndpoint}/api/channels/${channelId}/close`, {}, guildToken);
}
joinChannel(guildEndpoint, guildToken, channelId) {
return this.post(`${guildEndpoint}/api/channels/${channelId}/join`, {}, guildToken);
}
}

40
dist/fabric/src/identity.js vendored Normal file
View File

@@ -0,0 +1,40 @@
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
export class IdentityRegistry {
filePath;
entries = new Map();
constructor(filePath) {
this.filePath = filePath;
this.load();
}
load() {
if (!existsSync(this.filePath))
return;
try {
const data = JSON.parse(readFileSync(this.filePath, 'utf8'));
for (const e of data.entries ?? []) {
if (e.agentId && e.fabricApiKey)
this.entries.set(e.agentId, e);
}
}
catch {
// corrupt file -> start empty; upsert will rewrite
}
}
persist() {
mkdirSync(dirname(this.filePath), { recursive: true });
const data = { entries: [...this.entries.values()] };
writeFileSync(this.filePath, JSON.stringify(data, null, 2));
}
list() {
return [...this.entries.values()];
}
findByAgentId(agentId) {
return this.entries.get(agentId);
}
upsert(entry) {
const prev = this.entries.get(entry.agentId);
this.entries.set(entry.agentId, { ...prev, ...entry });
this.persist();
}
}

146
dist/fabric/src/inbound.js vendored Normal file
View File

@@ -0,0 +1,146 @@
import { io } from 'socket.io-client';
// One live Fabric connection per agent identity (Phase 1 = B1). Lives in the
// channel-plugin runtime (no separate sidecar). Firehose (B2) would replace
// this class behind the same dispatch() call.
export class FabricInbound {
runtime;
client;
identity;
log;
sockets = [];
timers = [];
seen = new Set();
constructor(runtime, client, identity, log) {
this.runtime = runtime;
this.client = client;
this.identity = identity;
this.log = log;
}
async start() {
for (const entry of this.identity.list()) {
try {
const session = await this.client.agentLogin(entry.fabricApiKey);
this.identity.upsert({
agentId: entry.agentId,
fabricApiKey: entry.fabricApiKey,
fabricUserId: session.user.id,
displayName: session.user.name,
});
await this.connectAgent(entry.agentId, session);
this.log.info(`fabric: agent ${entry.agentId} connected as ${session.user.email}`);
}
catch (err) {
this.log.warn(`fabric: agent ${entry.agentId} connect failed: ${String(err)}`);
}
}
}
stop() {
for (const t of this.timers)
clearInterval(t);
for (const s of this.sockets)
s.disconnect();
this.sockets = [];
this.timers = [];
}
async connectAgent(agentId, session) {
const selfUserId = session.user.id;
for (const g of session.guilds) {
const tok = session.guildAccessTokens.find((t) => t.guildNodeId === g.nodeId)?.token;
if (!tok)
continue;
const socket = io(`${g.endpoint}/realtime`, {
transports: ['websocket'],
auth: { token: tok },
autoConnect: false,
});
const joinAll = async () => {
try {
const res = await fetch(`${g.endpoint}/api/channels?guildId=${encodeURIComponent(g.nodeId)}`, {
headers: { authorization: `Bearer ${tok}` },
});
const channels = res.ok ? (await res.json()) : [];
for (const c of channels)
socket.emit('join_channel', { channelId: c.id });
}
catch {
/* best effort */
}
};
socket.on('connect', () => void joinAll());
socket.on('message.created', (m) => {
const channelId = m.channelId ?? '';
if (!channelId)
return;
// self-echo guard + dedupe
if (m.authorUserId && m.authorUserId === selfUserId)
return;
const key = `${agentId}:${m.messageId}`;
if (this.seen.has(key))
return;
this.seen.add(key);
if (this.seen.size > 5000)
this.seen.clear();
void this.dispatch(agentId, g, channelId, m);
});
socket.connect();
this.sockets.push(socket);
}
}
// Hand the inbound Fabric message to OpenClaw's channel-turn kernel.
// wakeup === true -> dispatch (agent runs, may reply)
// wakeup !== true -> drop but keep as group history/context
async dispatch(agentId, guild, channelId, m) {
const admit = m.wakeup === true;
try {
await this.runtime.channel.turn.run({
channel: 'fabric',
accountId: agentId,
raw: m,
adapter: {
ingest: (raw) => ({
id: raw.messageId,
timestamp: raw.createdAt ? Date.parse(raw.createdAt) : Date.now(),
rawText: raw.content,
textForAgent: raw.content,
}),
classify: () => ({ kind: 'message', canStartAgentTurn: admit }),
preflight: () => admit ? {} : { admission: { kind: 'drop', reason: 'no-wakeup', recordHistory: true } },
resolveTurn: (input) => ({
route: {
agentId,
routeSessionKey: `agent:${agentId}:fabric:channel:${channelId}`,
createIfMissing: true,
},
conversation: { kind: 'channel', id: channelId, label: `fabric:${guild.nodeId}` },
reply: { to: channelId, nativeChannelId: channelId },
message: {
body: m.content,
rawBody: m.content,
bodyForAgent: m.content,
envelopeFrom: m.authorUserId ?? 'fabric',
},
delivery: {
deliver: async (payload) => {
const text = typeof payload?.text === 'string' ? payload.text : '';
if (!text.trim())
return { visibleReplySent: false };
const entry = this.identity.findByAgentId(agentId);
const session = entry ? await this.client.agentLogin(entry.fabricApiKey) : null;
const gt = session?.guildAccessTokens.find((t) => t.guildNodeId === guild.nodeId)?.token;
if (!session || !gt)
return { visibleReplySent: false };
await this.client.postMessage(guild.endpoint, gt, channelId, text, session.user.id);
return { visibleReplySent: true };
},
},
meta: { admission: admit ? { kind: 'dispatch' } : { kind: 'drop', recordHistory: true } },
}),
},
log: (e) => this.runtime.log?.debug?.(`fabric.turn.${e?.stage}`),
});
}
catch (err) {
this.log.warn(`fabric: turn.run failed agent=${agentId} channel=${channelId}: ${String(err)}`);
}
}
}

14
dist/fabric/src/setup-entry.js vendored Normal file
View File

@@ -0,0 +1,14 @@
// Setup-safe entry: returns channel metadata for read-only command paths
// (status, channels list) before the plugin runtime starts. Must NOT start
// clients, listeners, or transports.
export default {
channel: {
id: 'fabric',
label: 'Fabric',
blurb: 'Connect OpenClaw agents to a Fabric guild.',
},
inspect(cfg) {
const ok = Boolean(cfg?.channels?.['fabric']?.centerApiBase);
return { enabled: ok, configured: ok };
},
};

112
dist/fabric/src/tools.js vendored Normal file
View File

@@ -0,0 +1,112 @@
const X_BY_KIND = {
chat: 'general',
work: 'work',
report: 'report',
discussion: 'discuss',
};
export function registerFabricTools(api, client, identity) {
// Resolve the calling agent's Fabric session + a guild's token/endpoint.
const ctxGuild = async (agentId, guildNodeId) => {
const entry = identity.findByAgentId(agentId);
if (!entry)
throw new Error(`agent ${agentId} not registered (call fabric-register)`);
const session = await client.agentLogin(entry.fabricApiKey);
const guild = session.guilds.find((g) => g.nodeId === guildNodeId);
const token = session.guildAccessTokens.find((t) => t.guildNodeId === guildNodeId)?.token;
if (!guild || !token)
throw new Error(`agent not a member of guild ${guildNodeId}`);
return { session, guild, token };
};
// fabric-register: bind this agent to a Fabric API key.
api.registerTool((ctx) => ({
name: 'fabric-register',
description: "Register this agent's Fabric API key (minted via Center CLI `user apikey`).",
inputSchema: {
type: 'object',
additionalProperties: false,
required: ['fabricApiKey'],
properties: {
fabricApiKey: { type: 'string', description: 'Fabric Center API key (fak_…)' },
},
},
handler: async (params) => {
const agentId = ctx.agentId;
if (!agentId)
return { ok: false, error: 'no agent context' };
const session = await client.agentLogin(params.fabricApiKey);
identity.upsert({
agentId,
fabricApiKey: params.fabricApiKey,
fabricUserId: session.user.id,
displayName: session.user.name,
});
return { ok: true, user: session.user };
},
}));
const makeCreate = (kind) => api.registerTool((ctx) => ({
name: `create-${kind}-channel`,
description: `Create a Fabric ${kind} channel (x_type=${X_BY_KIND[kind]}).`,
inputSchema: {
type: 'object',
additionalProperties: false,
required: ['guildNodeId', 'name'],
properties: {
guildNodeId: { type: 'string' },
name: { type: 'string' },
isPublic: { type: 'boolean' },
memberUserIds: { type: 'array', items: { type: 'string' } },
onDuty: { type: 'string', description: 'required for triage-like flows (unused for these kinds)' },
listeners: { type: 'array', items: { type: 'string' } },
},
},
handler: async (p) => {
const agentId = ctx.agentId;
if (!agentId)
return { ok: false, error: 'no agent context' };
const { guild, token } = await ctxGuild(agentId, p.guildNodeId);
const ch = await client.createChannel(guild.endpoint, token, {
guildId: p.guildNodeId,
name: p.name,
xType: X_BY_KIND[kind],
isPublic: p.isPublic ?? false,
memberUserIds: p.memberUserIds ?? [],
});
return { ok: true, channelId: ch.id };
},
}));
makeCreate('chat');
makeCreate('work');
makeCreate('report');
makeCreate('discussion');
// discussion-complete: post a summary then close the channel (Guild
// /channels/:id/close — history stays readable, new posts -> 409).
api.registerTool((ctx) => ({
name: 'discussion-complete',
description: 'Conclude a discussion: post a summary then close the channel.',
inputSchema: {
type: 'object',
additionalProperties: false,
required: ['guildNodeId', 'channelId', 'summary'],
properties: {
guildNodeId: { type: 'string' },
channelId: { type: 'string' },
summary: { type: 'string' },
callbackChannelId: { type: 'string', description: 'optional channel to also post the summary to' },
},
},
handler: async (p) => {
const agentId = ctx.agentId;
if (!agentId)
return { ok: false, error: 'no agent context' };
const { session, guild, token } = await ctxGuild(agentId, p.guildNodeId);
await client.postMessage(guild.endpoint, token, p.channelId, p.summary, session.user.id);
if (p.callbackChannelId) {
await client
.postMessage(guild.endpoint, token, p.callbackChannelId, p.summary, session.user.id)
.catch(() => undefined);
}
await client.closeChannel(guild.endpoint, token, p.channelId);
return { ok: true, closed: true };
},
}));
}