Unify typed agent transport and shared state
This commit is contained in:
parent
2059411e85
commit
c4376ee129
23 changed files with 1434 additions and 538 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import "dotenv/config";
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isAbsolute, join, relative, resolve } from "node:path";
|
||||
|
|
@ -23,6 +24,7 @@ import {
|
|||
loadSystemMessageCatalog,
|
||||
resolveRepoFaceStatePath,
|
||||
resolveWeksaArtifactPath,
|
||||
type RepoDiscordIdentity,
|
||||
type SystemMessageCatalog,
|
||||
WeksaSpeechClient,
|
||||
type WeksaMimoReceipt,
|
||||
|
|
@ -71,13 +73,18 @@ import {
|
|||
|
||||
const config = loadConfig();
|
||||
const weksaSpeechClient = new WeksaSpeechClient({
|
||||
baseUrl: config.repoFaceWeksaSpeech.daemonBaseUrl,
|
||||
commandUri: config.repoFaceWeksaSpeech.commandUri,
|
||||
repoRoot: config.repoFaceWeksaSpeech.repoRoot,
|
||||
timeoutMs: config.repoFaceWeksaSpeech.timeoutMs,
|
||||
});
|
||||
const REPO_IDENTITY_PROPOSAL_PR_SENTINEL = "VOIDBOT_REPO_IDENTITY_PROPOSAL_PR:";
|
||||
const REPO_IDENTITY_PR_COMMENT_SENTINEL = "VOIDBOT_REPO_IDENTITY_PR_COMMENT:";
|
||||
const REPO_IDENTITY_UPDATE_REQUEST_SENTINEL = "VOIDBOT_REPO_IDENTITY_UPDATE_REQUEST:";
|
||||
const REPO_IDENTITY_BIFROST_TOPIC_SENTINEL = "VOIDBOT_REPO_IDENTITY_BIFROST_TOPIC:";
|
||||
const BIFROST_DISCORD_POST_COMMAND_DOCUMENT_TYPE = "bifrost.bridge.discord_post_command";
|
||||
const BIFROST_DISCORD_POST_COMMAND_SCHEMA_ID = "bifrost.bridge.discord_post_command.v1";
|
||||
const BIFROST_DISCORD_POST_RECEIPT_DOCUMENT_TYPE = "bifrost.bridge.discord_post_receipt";
|
||||
const BIFROST_DISCORD_POST_RECEIPT_SCHEMA_ID = "bifrost.bridge.discord_post_receipt.v1";
|
||||
const CURRENT_REPO_FACE_IDENTITY_SELECTORS = new Set([
|
||||
"face_id",
|
||||
"faceid",
|
||||
|
|
@ -240,6 +247,7 @@ async function buildProviderRegistry(systemMessagesCatalog: SystemMessageCatalog
|
|||
timeoutMs: config.openAiApi.timeoutMs,
|
||||
authHeader: config.openAiApi.authHeader,
|
||||
maxCompletionTokens: config.openAiApi.maxCompletionTokens,
|
||||
toolbox: buildRetrievalToolbox(),
|
||||
}),
|
||||
new LocalLlmProvider({
|
||||
enabled: config.enabledProviders.includes("local_llm"),
|
||||
|
|
@ -349,6 +357,124 @@ async function buildProviderRegistry(systemMessagesCatalog: SystemMessageCatalog
|
|||
]);
|
||||
}
|
||||
|
||||
function buildRetrievalToolbox() {
|
||||
return {
|
||||
listIndexedRepos: async () => {
|
||||
const repos = await sourceArchiveRepository.listRepoSummaries();
|
||||
|
||||
return {
|
||||
repoCount: repos.length,
|
||||
repos,
|
||||
};
|
||||
},
|
||||
searchHistory: async (input: {
|
||||
query: string;
|
||||
limit: number;
|
||||
guildId?: string;
|
||||
channelId?: string;
|
||||
authorId?: string;
|
||||
}) => {
|
||||
const rawResults = await searchHistoryWithArchiveFallback({
|
||||
retrievalService,
|
||||
archiveRepository,
|
||||
query: input.query,
|
||||
limit: input.limit,
|
||||
guildId: input.guildId,
|
||||
channelId: input.channelId,
|
||||
authorId: input.authorId,
|
||||
preserveOverfetch: true,
|
||||
});
|
||||
const results = filterPromptEchoHistoryResults(rawResults, input.query);
|
||||
|
||||
return {
|
||||
query: input.query,
|
||||
resultCount: results.length,
|
||||
results: formatHistoryResults(results),
|
||||
};
|
||||
},
|
||||
getMessageContext: async (input: {
|
||||
messageId: string;
|
||||
before: number;
|
||||
after: number;
|
||||
}) => {
|
||||
const messages = await archiveRepository.listContextWindow(
|
||||
input.messageId,
|
||||
input.before,
|
||||
input.after,
|
||||
);
|
||||
|
||||
return {
|
||||
found: messages.length > 0,
|
||||
messageId: input.messageId,
|
||||
count: messages.length,
|
||||
messages: messages.map((message) =>
|
||||
formatArchivedMessageContext(message, input.messageId),
|
||||
),
|
||||
};
|
||||
},
|
||||
searchSources: async (input: {
|
||||
query: string;
|
||||
limit: number;
|
||||
repoName?: string;
|
||||
pathPrefix?: string;
|
||||
language?: string;
|
||||
}) => {
|
||||
const results = await retrievalService.searchRepositorySources(input.query, input.limit, {
|
||||
repoName: input.repoName,
|
||||
pathPrefix: input.pathPrefix,
|
||||
language: input.language,
|
||||
});
|
||||
|
||||
return {
|
||||
query: input.query,
|
||||
resultCount: results.length,
|
||||
results: formatSourceResults(results),
|
||||
};
|
||||
},
|
||||
getSourceContext: async (input: {
|
||||
sourceId: string;
|
||||
chunkIndex: number;
|
||||
before: number;
|
||||
after: number;
|
||||
}) => {
|
||||
const document = await sourceArchiveRepository.get(input.sourceId);
|
||||
|
||||
if (!document) {
|
||||
return {
|
||||
found: false,
|
||||
sourceId: input.sourceId,
|
||||
count: 0,
|
||||
chunks: [],
|
||||
};
|
||||
}
|
||||
|
||||
const chunks = sourceDocumentIngester.buildContextWindow(
|
||||
document,
|
||||
input.chunkIndex,
|
||||
input.before,
|
||||
input.after,
|
||||
);
|
||||
|
||||
return {
|
||||
found: true,
|
||||
sourceId: input.sourceId,
|
||||
repoName: document.repoName,
|
||||
path: document.path,
|
||||
language: document.language,
|
||||
count: chunks.length,
|
||||
chunks: chunks.map((chunk) => ({
|
||||
chunkId: chunk.chunkId,
|
||||
chunkIndex: chunk.chunkIndex,
|
||||
lineStart: chunk.lineStart,
|
||||
lineEnd: chunk.lineEnd,
|
||||
isAnchor: chunk.chunkIndex === input.chunkIndex,
|
||||
text: chunk.text,
|
||||
})),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function processJob(job: JobRecord): Promise<void> {
|
||||
const provider = providerRegistry.get(job.provider);
|
||||
|
||||
|
|
@ -595,6 +721,13 @@ async function executeRepoFaceJobWithInterpreter(
|
|||
: await interpretRepoFaceTurnOutput(provider, job, firstText, {
|
||||
attempt: 1,
|
||||
});
|
||||
const firstRouteProblem = firstInterpretation.decision === "route"
|
||||
? validateRepoFaceRoutedOutput(firstInterpretation.routedOutput, job)
|
||||
: undefined;
|
||||
if (firstRouteProblem) {
|
||||
firstInterpretation.decision = "retry";
|
||||
firstInterpretation.reasons = [firstRouteProblem, ...firstInterpretation.reasons].slice(0, 4);
|
||||
}
|
||||
if (firstInterpretation.decision === "route") {
|
||||
return routeRepoFaceInterpretedOutput(firstResponse, firstInterpretation, {
|
||||
job,
|
||||
|
|
@ -648,6 +781,13 @@ async function executeRepoFaceJobWithInterpreter(
|
|||
: await interpretRepoFaceTurnOutput(provider, job, retryText, {
|
||||
attempt: 2,
|
||||
});
|
||||
const retryRouteProblem = retryInterpretation.decision === "route"
|
||||
? validateRepoFaceRoutedOutput(retryInterpretation.routedOutput, job)
|
||||
: undefined;
|
||||
if (retryRouteProblem) {
|
||||
retryInterpretation.decision = "drop";
|
||||
retryInterpretation.reasons = [retryRouteProblem, ...retryInterpretation.reasons].slice(0, 4);
|
||||
}
|
||||
if (retryInterpretation.decision === "route") {
|
||||
return routeRepoFaceInterpretedOutput(retryResponse, retryInterpretation, {
|
||||
job,
|
||||
|
|
@ -971,6 +1111,38 @@ function normalizeInterpretedRepoFaceSpeechDestinations(
|
|||
);
|
||||
}
|
||||
|
||||
function validateRepoFaceRoutedOutput(
|
||||
outputText: string | undefined,
|
||||
job: JobRecord,
|
||||
): string | undefined {
|
||||
if (job.command !== "repo-face-rumination" || !outputText || !repoFaceHasMultipleActiveConversationChannels(job)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const block of parseRepoFaceActionBlocks(outputText)) {
|
||||
if (block.kind !== "say") {
|
||||
continue;
|
||||
}
|
||||
const context = optionalDslString(block.fields.context) ??
|
||||
optionalDslString(block.fields.context_id) ??
|
||||
optionalDslString(block.fields.contextId);
|
||||
const replyTo = optionalDslString(block.fields.reply_to) ??
|
||||
optionalDslString(block.fields.replyToMessageId);
|
||||
const channel = optionalDslString(block.fields.channel) ??
|
||||
optionalDslString(block.fields.channelId);
|
||||
const normalizedChannel = normalizeChannelSelector(channel);
|
||||
const hasConcreteChannel = Boolean(channel) &&
|
||||
normalizedChannel !== "current_room" &&
|
||||
normalizedChannel !== "currentroom";
|
||||
|
||||
if (!context && !replyTo && !hasConcreteChannel) {
|
||||
return "Routed SAY lacks context, reply_to, or a concrete channel id while multiple active conversation contexts are visible.";
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function repoFaceHasMultipleActiveConversationChannels(job: JobRecord): boolean {
|
||||
const activeThreads = job.contextBundle.repoFaceConversationThreads ?? [];
|
||||
const representedChannels = new Set(activeThreads.map((thread) => thread.channelId));
|
||||
|
|
@ -1137,14 +1309,23 @@ function repoFaceHeartbeatCodexOptions(job: JobRecord, role: "face" | "interpret
|
|||
return {};
|
||||
}
|
||||
|
||||
const identityId = parseRepoIdentityIdFromRequestMessageId(job.requestMessageId)
|
||||
?? parseRepoIdentityIdFromPrompt(job.prompt);
|
||||
const faceContext = {
|
||||
repoFaceRole: role,
|
||||
...(identityId ? { repoFaceIdentity: identityId } : {}),
|
||||
};
|
||||
|
||||
if (job.provider === "openai_api") {
|
||||
return {
|
||||
...faceContext,
|
||||
model: config.openAiApi.model,
|
||||
};
|
||||
}
|
||||
|
||||
if (role === "face") {
|
||||
return {
|
||||
...faceContext,
|
||||
model: config.repoFaceHeartbeats.turnCodexModel,
|
||||
...(config.repoFaceHeartbeats.codexModelReasoningEffort
|
||||
? { reasoningEffort: config.repoFaceHeartbeats.codexModelReasoningEffort }
|
||||
|
|
@ -1153,6 +1334,7 @@ function repoFaceHeartbeatCodexOptions(job: JobRecord, role: "face" | "interpret
|
|||
}
|
||||
|
||||
return {
|
||||
...faceContext,
|
||||
...(config.repoFaceHeartbeats.codexModel ? { model: config.repoFaceHeartbeats.codexModel } : {}),
|
||||
...(config.repoFaceHeartbeats.codexModels.length > 0
|
||||
? { models: config.repoFaceHeartbeats.codexModels.join(",") }
|
||||
|
|
@ -1491,18 +1673,13 @@ async function postRepoIdentityIntent(job: JobRecord, intent: RepoIdentityPostIn
|
|||
if (/\S(?:\.\.\.|…)$/.test(content)) {
|
||||
throw new Error(`Repo identity ${identity.id} SAY content appears mechanically truncated.`);
|
||||
}
|
||||
const contentFile = await writeBifrostPayloadFile(job, `${identity.id}-discord-post.md`, content);
|
||||
const posted = runBifrostBridge([
|
||||
"discord-post",
|
||||
"--channel-id",
|
||||
const posted = await postRepoIdentityDiscordViaCultMeshCommand({
|
||||
job,
|
||||
identity,
|
||||
channelId,
|
||||
"--content-file",
|
||||
contentFile,
|
||||
"--persona-name",
|
||||
identity.displayName,
|
||||
...(identity.avatarUrl ? ["--persona-avatar-url", identity.avatarUrl] : []),
|
||||
...(effectiveReplyToMessageId ? ["--reply-to-message-id", effectiveReplyToMessageId] : []),
|
||||
], { retries: 1 });
|
||||
content,
|
||||
replyToMessageId: effectiveReplyToMessageId,
|
||||
});
|
||||
if (!posted.messageId || !posted.transport) {
|
||||
throw new Error(`Bifrost Discord bridge returned no message receipt for job ${job.id}.`);
|
||||
}
|
||||
|
|
@ -1531,6 +1708,282 @@ async function postRepoIdentityIntent(job: JobRecord, intent: RepoIdentityPostIn
|
|||
return true;
|
||||
}
|
||||
|
||||
async function postRepoIdentityDiscordViaCultMeshCommand(input: {
|
||||
job: JobRecord;
|
||||
identity: RepoDiscordIdentity;
|
||||
channelId: string;
|
||||
content: string;
|
||||
replyToMessageId?: string;
|
||||
}): Promise<BifrostBridgeReceipt> {
|
||||
assertBifrostCultMeshCommandUri(config.bifrostCultMesh.commandUri);
|
||||
const commandId = buildBifrostDiscordCommandId(input);
|
||||
const node = await openBifrostCommandNode(config.bifrostCultMesh.storePath);
|
||||
const requestedAt = new Date().toISOString();
|
||||
const command = {
|
||||
schemaName: BIFROST_DISCORD_POST_COMMAND_DOCUMENT_TYPE,
|
||||
schemaVersion: BIFROST_DISCORD_POST_COMMAND_SCHEMA_ID,
|
||||
commandId,
|
||||
command: "discord-post",
|
||||
status: "pending",
|
||||
requestedBy: "voidbot",
|
||||
requestedAt,
|
||||
updatedAt: requestedAt,
|
||||
commandUri: config.bifrostCultMesh.commandUri,
|
||||
source: {
|
||||
kind: "voidbot.repo-face.say",
|
||||
id: input.job.id,
|
||||
jobId: input.job.id,
|
||||
requestMessageId: input.job.requestMessageId,
|
||||
},
|
||||
actor: {
|
||||
id: input.identity.id,
|
||||
displayName: input.identity.displayName,
|
||||
repoName: input.identity.repoName,
|
||||
},
|
||||
payload: {
|
||||
identityId: input.identity.id,
|
||||
channelId: input.channelId,
|
||||
content: input.content,
|
||||
personaName: input.identity.displayName,
|
||||
personaAvatarUrl: input.identity.avatarUrl ?? "",
|
||||
replyToMessageId: input.replyToMessageId ?? "",
|
||||
},
|
||||
};
|
||||
|
||||
await node.put(bifrostDiscordCommandDefinition(), commandId, command);
|
||||
await node.flush?.();
|
||||
|
||||
if (config.bifrostCultMesh.pumpEnabled) {
|
||||
pumpBifrostCultMeshCommand(commandId);
|
||||
}
|
||||
|
||||
const receipt = await waitForBifrostDiscordReceipt(node, commandId, config.bifrostCultMesh.timeoutMs);
|
||||
if (receipt.status !== "completed" || receipt.ok !== true) {
|
||||
throw new Error(
|
||||
`Bifrost CultMesh Discord command ${commandId} failed: ${bifrostString(receipt.error) || "no error detail"}`,
|
||||
);
|
||||
}
|
||||
const messageId = bifrostString(receipt.messageId);
|
||||
const transport = bifrostString(receipt.transport);
|
||||
if (!messageId || !transport) {
|
||||
throw new Error(`Bifrost CultMesh Discord command ${commandId} returned an incomplete receipt.`);
|
||||
}
|
||||
return {
|
||||
action: "discord-post",
|
||||
ok: true,
|
||||
messageId,
|
||||
transport: transport === "bot" || transport === "webhook" ? transport : "webhook",
|
||||
url: bifrostString(receipt.url),
|
||||
};
|
||||
}
|
||||
|
||||
function buildBifrostDiscordCommandId(input: {
|
||||
job: JobRecord;
|
||||
identity: RepoDiscordIdentity;
|
||||
channelId: string;
|
||||
content: string;
|
||||
replyToMessageId?: string;
|
||||
}): string {
|
||||
const hash = createHash("sha1")
|
||||
.update(JSON.stringify({
|
||||
jobId: input.job.id,
|
||||
identityId: input.identity.id,
|
||||
channelId: input.channelId,
|
||||
replyToMessageId: input.replyToMessageId ?? "",
|
||||
content: input.content,
|
||||
}))
|
||||
.digest("hex")
|
||||
.slice(0, 20);
|
||||
return `voidbot-discord-${hash}`;
|
||||
}
|
||||
|
||||
function assertBifrostCultMeshCommandUri(value: string): void {
|
||||
if (!/^cultmesh:\/\/[^/]+\/commands\/discord-post(?:$|[/?#])/.test(value)) {
|
||||
throw new Error(
|
||||
`BIFROST_CULTMESH_COMMAND_URI must be a CultMesh Discord command URI, got "${value}".`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function openBifrostCommandNode(storePath: string): Promise<{
|
||||
put: (definition: unknown, key: string, value: unknown) => Promise<void>;
|
||||
get: (definition: unknown, key: string) => unknown;
|
||||
flush?: () => Promise<void>;
|
||||
cache?: { pullAllBackingStores?: () => Promise<void> };
|
||||
}> {
|
||||
const { CultMesh } = loadBifrostCultMeshRuntime();
|
||||
return CultMesh.createNode(storePath, {
|
||||
documents: [
|
||||
bifrostDiscordCommandDefinition(),
|
||||
bifrostDiscordReceiptDefinition(),
|
||||
bifrostGenericDocumentDefinition("gamecult.eve.provider_advertisement", "gamecult.eve.provider_advertisement.v1", "providerId"),
|
||||
bifrostGenericDocumentDefinition("gamecult.eve.surface_state", "gamecult.eve.surface_state.v1", "providerId"),
|
||||
bifrostGenericDocumentDefinition("gamecult.eve.interface_binding", "gamecult.eve.interface_binding.v1", "bindingId"),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function pumpBifrostCultMeshCommand(commandId: string): void {
|
||||
const processor = resolve(config.bifrostRoot, "tools", "cultmesh-bridge-commands.mjs");
|
||||
const result = spawnSync(process.execPath, [
|
||||
processor,
|
||||
"process",
|
||||
"--store",
|
||||
config.bifrostCultMesh.storePath,
|
||||
"--command-id",
|
||||
commandId,
|
||||
], {
|
||||
cwd: config.bifrostRoot,
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
});
|
||||
if (result.status !== 0 || result.error) {
|
||||
throw new Error(`Bifrost CultMesh command processor failed. ${renderBridgeFailure(result, 1, 1)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForBifrostDiscordReceipt(
|
||||
node: { get: (definition: unknown, key: string) => unknown; cache?: { pullAllBackingStores?: () => Promise<void> } },
|
||||
commandId: string,
|
||||
timeoutMs: number,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt <= timeoutMs) {
|
||||
await node.cache?.pullAllBackingStores?.();
|
||||
const receipt = unwrapBifrostRecord(await node.get(bifrostDiscordReceiptDefinition(), commandId));
|
||||
if (receipt) {
|
||||
return receipt;
|
||||
}
|
||||
await delay(250);
|
||||
}
|
||||
throw new Error(`Timed out waiting for Bifrost CultMesh Discord receipt ${commandId}.`);
|
||||
}
|
||||
|
||||
let bifrostDefinitions: {
|
||||
command?: unknown;
|
||||
receipt?: unknown;
|
||||
generic: Map<string, unknown>;
|
||||
} | undefined;
|
||||
|
||||
function bifrostDiscordCommandDefinition(): unknown {
|
||||
const { defineDocumentType } = loadBifrostCultMeshRuntime();
|
||||
bifrostDefinitions ??= { generic: new Map() };
|
||||
bifrostDefinitions.command ??= defineDocumentType({
|
||||
type: BIFROST_DISCORD_POST_COMMAND_DOCUMENT_TYPE,
|
||||
schemaName: BIFROST_DISCORD_POST_COMMAND_DOCUMENT_TYPE,
|
||||
schemaId: BIFROST_DISCORD_POST_COMMAND_SCHEMA_ID,
|
||||
schemaVersion: BIFROST_DISCORD_POST_COMMAND_SCHEMA_ID,
|
||||
contentHash: BIFROST_DISCORD_POST_COMMAND_SCHEMA_ID,
|
||||
global: false,
|
||||
name: "commandId",
|
||||
schema: parseBifrostObjectDocument("Bifrost Discord post command"),
|
||||
});
|
||||
return bifrostDefinitions.command;
|
||||
}
|
||||
|
||||
function bifrostDiscordReceiptDefinition(): unknown {
|
||||
const { defineDocumentType } = loadBifrostCultMeshRuntime();
|
||||
bifrostDefinitions ??= { generic: new Map() };
|
||||
bifrostDefinitions.receipt ??= defineDocumentType({
|
||||
type: BIFROST_DISCORD_POST_RECEIPT_DOCUMENT_TYPE,
|
||||
schemaName: BIFROST_DISCORD_POST_RECEIPT_DOCUMENT_TYPE,
|
||||
schemaId: BIFROST_DISCORD_POST_RECEIPT_SCHEMA_ID,
|
||||
schemaVersion: BIFROST_DISCORD_POST_RECEIPT_SCHEMA_ID,
|
||||
contentHash: BIFROST_DISCORD_POST_RECEIPT_SCHEMA_ID,
|
||||
global: false,
|
||||
name: "commandId",
|
||||
schema: parseBifrostObjectDocument("Bifrost Discord post receipt"),
|
||||
});
|
||||
return bifrostDefinitions.receipt;
|
||||
}
|
||||
|
||||
function bifrostGenericDocumentDefinition(type: string, schemaId: string, name: string): unknown {
|
||||
const { defineDocumentType } = loadBifrostCultMeshRuntime();
|
||||
bifrostDefinitions ??= { generic: new Map() };
|
||||
const key = `${type}:${schemaId}:${name}`;
|
||||
let definition = bifrostDefinitions.generic.get(key);
|
||||
if (!definition) {
|
||||
definition = defineDocumentType({
|
||||
type,
|
||||
schemaName: type,
|
||||
schemaId,
|
||||
schemaVersion: schemaId,
|
||||
contentHash: schemaId,
|
||||
global: false,
|
||||
name,
|
||||
schema: parseBifrostObjectDocument(type),
|
||||
});
|
||||
bifrostDefinitions.generic.set(key, definition);
|
||||
}
|
||||
return definition;
|
||||
}
|
||||
|
||||
function loadBifrostCultMeshRuntime(): {
|
||||
CultMesh: { createNode: (storePath: string, options: unknown) => Promise<{
|
||||
put: (definition: unknown, key: string, value: unknown) => Promise<void>;
|
||||
get: (definition: unknown, key: string) => unknown;
|
||||
flush?: () => Promise<void>;
|
||||
cache?: { pullAllBackingStores?: () => Promise<void> };
|
||||
}> };
|
||||
defineDocumentType: (definition: Record<string, unknown>) => unknown;
|
||||
} {
|
||||
const candidates = [
|
||||
resolve(config.bifrostRoot, "..", "CultLib", "packages", "cultmesh-ts", "package.json"),
|
||||
resolve(config.bifrostRoot, "..", "CultMeshTS", "package.json"),
|
||||
];
|
||||
|
||||
for (const packageJson of candidates) {
|
||||
try {
|
||||
const requireCult = createRequire(packageJson);
|
||||
const { CultMesh } = requireCult("cultmesh-ts") as {
|
||||
CultMesh?: { createNode: (storePath: string, options: unknown) => Promise<{
|
||||
put: (definition: unknown, key: string, value: unknown) => Promise<void>;
|
||||
get: (definition: unknown, key: string) => unknown;
|
||||
flush?: () => Promise<void>;
|
||||
cache?: { pullAllBackingStores?: () => Promise<void> };
|
||||
}> };
|
||||
};
|
||||
const { defineDocumentType } = requireCult("cultcache-ts") as {
|
||||
defineDocumentType?: (definition: Record<string, unknown>) => unknown;
|
||||
};
|
||||
if (CultMesh && defineDocumentType) {
|
||||
return { CultMesh, defineDocumentType };
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
throw new Error("CultMesh/CultCache packages are unavailable; cannot write Bifrost command documents.");
|
||||
}
|
||||
|
||||
function parseBifrostObjectDocument(label: string): { parse: (value: unknown) => unknown } {
|
||||
return {
|
||||
parse(value: unknown): unknown {
|
||||
if (!value || typeof value !== "object") {
|
||||
throw new Error(`${label} must be an object.`);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function unwrapBifrostRecord(record: unknown): Record<string, unknown> | undefined {
|
||||
const candidate = Array.isArray(record) && record.length === 1 ? record[0] : record;
|
||||
const value = isBifrostRecord(candidate) && isBifrostRecord(candidate.value) ? candidate.value : candidate;
|
||||
return isBifrostRecord(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function isBifrostRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function bifrostString(value: unknown): string {
|
||||
return typeof value === "string" ? value.trim() : value === undefined || value === null ? "" : String(value).trim();
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
|
||||
}
|
||||
|
||||
async function resolveRepoIdentityForJobIntent(
|
||||
job: JobRecord,
|
||||
identitySelector?: string,
|
||||
|
|
|
|||
|
|
@ -48,31 +48,46 @@ export const applyRepoFaceStateOperationInputSchema = {
|
|||
operation: z.record(z.unknown()),
|
||||
};
|
||||
|
||||
export const readSharedDocumentInputSchema = {
|
||||
documentId: z.string().min(1).max(120).optional(),
|
||||
};
|
||||
|
||||
export const createSharedDocumentInputSchema = {
|
||||
documentId: z.string().min(1).max(120),
|
||||
title: z.string().min(1).max(240),
|
||||
body: z.string().max(20_000),
|
||||
};
|
||||
|
||||
export const updateSharedDocumentInputSchema = {
|
||||
documentId: z.string().min(1).max(120),
|
||||
title: z.string().min(1).max(240).optional(),
|
||||
body: z.string().max(20_000),
|
||||
expectedVersion: z.number().int().positive(),
|
||||
};
|
||||
|
||||
export const runtimeInfoInputSchema = {};
|
||||
|
||||
export const odinEndpointInputSchema = {
|
||||
odinBaseUrl: z.string().url().optional(),
|
||||
odinStorePath: z.string().min(1).optional(),
|
||||
};
|
||||
|
||||
export const odinSurfaceInputSchema = {
|
||||
odinBaseUrl: z.string().url().optional(),
|
||||
odinStorePath: z.string().min(1).optional(),
|
||||
providerId: z.string().min(1).optional(),
|
||||
};
|
||||
|
||||
export const odinInterfaceContextInputSchema = {
|
||||
odinBaseUrl: z.string().url().optional(),
|
||||
odinStorePath: z.string().min(1).optional(),
|
||||
providerId: z.string().min(1),
|
||||
maxTextItems: z.number().int().min(1).max(80).optional(),
|
||||
maxTreeItems: z.number().int().min(1).max(160).optional(),
|
||||
};
|
||||
|
||||
export const odinInterfaceCommandInputSchema = {
|
||||
odinBaseUrl: z.string().url().optional(),
|
||||
odinStorePath: z.string().min(1).optional(),
|
||||
providerId: z.string().min(1),
|
||||
command: z.string().min(1),
|
||||
payload: z.record(z.unknown()).optional(),
|
||||
frame: z.record(z.unknown()).optional(),
|
||||
expectReceiptMs: z.number().int().min(0).max(15000).optional(),
|
||||
};
|
||||
|
||||
export const searchSourcesInputSchema = {
|
||||
|
|
@ -132,33 +147,48 @@ export interface ApplyRepoFaceStateOperationArgs {
|
|||
operation: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ReadSharedDocumentArgs {
|
||||
documentId?: string;
|
||||
}
|
||||
|
||||
export interface CreateSharedDocumentArgs {
|
||||
documentId: string;
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface UpdateSharedDocumentArgs {
|
||||
documentId: string;
|
||||
title?: string;
|
||||
body: string;
|
||||
expectedVersion: number;
|
||||
}
|
||||
|
||||
export interface RuntimeInfoArgs {
|
||||
[key: string]: never;
|
||||
}
|
||||
|
||||
export interface OdinEndpointArgs {
|
||||
odinBaseUrl?: string;
|
||||
odinStorePath?: string;
|
||||
}
|
||||
|
||||
export interface OdinSurfaceArgs {
|
||||
odinBaseUrl?: string;
|
||||
odinStorePath?: string;
|
||||
providerId?: string;
|
||||
}
|
||||
|
||||
export interface OdinInterfaceContextArgs {
|
||||
odinBaseUrl?: string;
|
||||
odinStorePath?: string;
|
||||
providerId: string;
|
||||
maxTextItems?: number;
|
||||
maxTreeItems?: number;
|
||||
}
|
||||
|
||||
export interface OdinInterfaceCommandArgs {
|
||||
odinBaseUrl?: string;
|
||||
odinStorePath?: string;
|
||||
providerId: string;
|
||||
command: string;
|
||||
payload?: Record<string, unknown>;
|
||||
frame?: Record<string, unknown>;
|
||||
expectReceiptMs?: number;
|
||||
}
|
||||
|
||||
export interface ListIndexedReposArgs {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { type CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import crypto from "node:crypto";
|
||||
import net from "node:net";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
|
||||
import { DEFAULT_RETRIEVAL_RESULT_LIMIT } from "@voidbot/shared";
|
||||
import { searchHistoryWithArchiveFallback } from "@voidbot/rag";
|
||||
import {
|
||||
applyRepoFacePostFatigueAfterSpeech,
|
||||
createRepoFaceSharedDocument,
|
||||
applyVoidSelfStateOperation,
|
||||
buildVoidSelfStateContext,
|
||||
faceRegistryAsRepoDiscordRegistry,
|
||||
|
|
@ -14,9 +16,12 @@ import {
|
|||
isRepoDiscordIdentityAllowedInChannel,
|
||||
loadFaceIdentityRegistry,
|
||||
loadVoidSelfStateTypedDocuments,
|
||||
listRepoFaceSharedDocuments,
|
||||
renderFaceIdentityDoctrine,
|
||||
resolveFaceStatePath,
|
||||
resolveRepoFaceStatePath,
|
||||
resolveRepoFaceSharedDocumentsPath,
|
||||
updateRepoFaceSharedDocument,
|
||||
VOID_SELF_STATE_SCHEMA_DOCUMENT_TYPES,
|
||||
VOID_SELF_STATE_SCHEMA_FINGERPRINT,
|
||||
} from "@voidbot/core";
|
||||
|
|
@ -32,17 +37,21 @@ import {
|
|||
type OdinInterfaceContextArgs,
|
||||
type OdinSurfaceArgs,
|
||||
type ApplyRepoFaceStateOperationArgs,
|
||||
type CreateSharedDocumentArgs,
|
||||
type PostDiscordMessageArgs,
|
||||
type PostRepoIdentityMessageArgs,
|
||||
type RepoFaceStateArgs,
|
||||
type ReadSharedDocumentArgs,
|
||||
type RuntimeInfoArgs,
|
||||
type SearchHistoryArgs,
|
||||
type SearchSourcesArgs,
|
||||
type SourceContextArgs,
|
||||
type UpdateSharedDocumentArgs,
|
||||
formatArchivedMessage,
|
||||
formatHistoryResults,
|
||||
formatSourceResults,
|
||||
applyRepoFaceStateOperationInputSchema,
|
||||
createSharedDocumentInputSchema,
|
||||
messageContextInputSchema,
|
||||
notifyOwnerInputSchema,
|
||||
odinEndpointInputSchema,
|
||||
|
|
@ -52,11 +61,13 @@ import {
|
|||
postDiscordMessageInputSchema,
|
||||
postRepoIdentityMessageInputSchema,
|
||||
repoFaceStateInputSchema,
|
||||
readSharedDocumentInputSchema,
|
||||
renderJsonBlock,
|
||||
runtimeInfoInputSchema,
|
||||
searchHistoryInputSchema,
|
||||
searchSourcesInputSchema,
|
||||
sourceContextInputSchema,
|
||||
updateSharedDocumentInputSchema,
|
||||
} from "./mcp-server-shared";
|
||||
|
||||
const READ_ONLY_ANNOTATIONS = {
|
||||
|
|
@ -66,7 +77,8 @@ const READ_ONLY_ANNOTATIONS = {
|
|||
openWorldHint: false,
|
||||
} as const;
|
||||
|
||||
const DEFAULT_ODIN_BASE_URL = "http://127.0.0.1:8797";
|
||||
const DEFAULT_ODIN_STORE_PATH = path.resolve(process.cwd(), "..", "Odin", "scratch", "odin", "odin.ccmp");
|
||||
const ODIN_SURFACE_KEY = "surface:gamecult.network.status";
|
||||
|
||||
function isMcpToolAllowed(name: string): boolean {
|
||||
const raw = process.env.VOIDBOT_MCP_TOOL_ALLOWLIST?.trim();
|
||||
|
|
@ -136,22 +148,22 @@ export function registerVoidbotTools(
|
|||
annotations: READ_ONLY_ANNOTATIONS,
|
||||
},
|
||||
async (input: OdinEndpointArgs): Promise<CallToolResult> => {
|
||||
const odinBaseUrl = normalizeOdinBaseUrl(input.odinBaseUrl);
|
||||
const catalog = await fetchOdinProviderCatalog(odinBaseUrl);
|
||||
const odinStorePath = resolveOdinStorePath(input.odinStorePath);
|
||||
const catalog = await fetchOdinProviderCatalog(odinStorePath);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
providerCount: catalog.providers.length,
|
||||
providers: catalog.providers,
|
||||
}),
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
providerCount: catalog.providers.length,
|
||||
providers: catalog.providers,
|
||||
},
|
||||
|
|
@ -169,8 +181,8 @@ export function registerVoidbotTools(
|
|||
annotations: READ_ONLY_ANNOTATIONS,
|
||||
},
|
||||
async (input: OdinEndpointArgs): Promise<CallToolResult> => {
|
||||
const odinBaseUrl = normalizeOdinBaseUrl(input.odinBaseUrl);
|
||||
const snapshot = await fetchOdinDeckSnapshot(odinBaseUrl);
|
||||
const odinStorePath = resolveOdinStorePath(input.odinStorePath);
|
||||
const snapshot = await fetchOdinSnapshot(odinStorePath);
|
||||
const verses = summarizeOdinVerses(snapshot);
|
||||
|
||||
return {
|
||||
|
|
@ -178,7 +190,7 @@ export function registerVoidbotTools(
|
|||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
providerId: snapshot.providerId,
|
||||
title: snapshot.title,
|
||||
version: snapshot.version,
|
||||
|
|
@ -189,7 +201,7 @@ export function registerVoidbotTools(
|
|||
},
|
||||
],
|
||||
structuredContent: {
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
providerId: snapshot.providerId,
|
||||
title: snapshot.title,
|
||||
version: snapshot.version,
|
||||
|
|
@ -211,8 +223,8 @@ export function registerVoidbotTools(
|
|||
annotations: READ_ONLY_ANNOTATIONS,
|
||||
},
|
||||
async (input: OdinSurfaceArgs): Promise<CallToolResult> => {
|
||||
const odinBaseUrl = normalizeOdinBaseUrl(input.odinBaseUrl);
|
||||
const snapshot = await fetchOdinDeckSnapshot(odinBaseUrl, input.providerId);
|
||||
const odinStorePath = resolveOdinStorePath(input.odinStorePath);
|
||||
const snapshot = await fetchOdinSnapshot(odinStorePath, input.providerId);
|
||||
const surfaceSummary = summarizeOdinSurface(snapshot);
|
||||
|
||||
return {
|
||||
|
|
@ -220,7 +232,7 @@ export function registerVoidbotTools(
|
|||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
providerId: snapshot.providerId,
|
||||
title: snapshot.title,
|
||||
version: snapshot.version,
|
||||
|
|
@ -231,7 +243,7 @@ export function registerVoidbotTools(
|
|||
},
|
||||
],
|
||||
structuredContent: {
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
providerId: snapshot.providerId,
|
||||
title: snapshot.title,
|
||||
version: snapshot.version,
|
||||
|
|
@ -253,8 +265,8 @@ export function registerVoidbotTools(
|
|||
annotations: READ_ONLY_ANNOTATIONS,
|
||||
},
|
||||
async (input: OdinInterfaceContextArgs): Promise<CallToolResult> => {
|
||||
const odinBaseUrl = normalizeOdinBaseUrl(input.odinBaseUrl);
|
||||
const loaded = await loadOdinProviderInterface(odinBaseUrl, input.providerId);
|
||||
const odinStorePath = resolveOdinStorePath(input.odinStorePath);
|
||||
const loaded = await loadOdinProviderInterface(odinStorePath, input.providerId);
|
||||
const contextSummary = summarizeProviderInterface(loaded, {
|
||||
maxTextItems: input.maxTextItems ?? 32,
|
||||
maxTreeItems: input.maxTreeItems ?? 80,
|
||||
|
|
@ -265,13 +277,13 @@ export function registerVoidbotTools(
|
|||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
...contextSummary,
|
||||
}),
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
odinBaseUrl,
|
||||
odinStorePath,
|
||||
...contextSummary,
|
||||
},
|
||||
};
|
||||
|
|
@ -283,7 +295,7 @@ export function registerVoidbotTools(
|
|||
{
|
||||
title: "Invoke Odin Interface Command",
|
||||
description:
|
||||
"Send an explicit command through a provider-owned Eve/CultUI command boundary discovered via Odin. The command must be advertised by the provider interface. Odin is not the side-effect owner; this relays to the provider endpoint when the interface exposes a WebSocket command transport.",
|
||||
"Inspect a provider-owned Eve/CultUI command boundary discovered via Odin. The command must be advertised by the provider interface; execution requires a CultMesh command document path and no longer tunnels through provider WebSockets.",
|
||||
inputSchema: odinInterfaceCommandInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
|
|
@ -293,8 +305,8 @@ export function registerVoidbotTools(
|
|||
},
|
||||
},
|
||||
async (input: OdinInterfaceCommandArgs): Promise<CallToolResult> => {
|
||||
const odinBaseUrl = normalizeOdinBaseUrl(input.odinBaseUrl);
|
||||
const loaded = await loadOdinProviderInterface(odinBaseUrl, input.providerId);
|
||||
const odinStorePath = resolveOdinStorePath(input.odinStorePath);
|
||||
const loaded = await loadOdinProviderInterface(odinStorePath, input.providerId);
|
||||
const command = findAdvertisedCommand(loaded, input.command);
|
||||
|
||||
if (!command) {
|
||||
|
|
@ -316,50 +328,28 @@ export function registerVoidbotTools(
|
|||
};
|
||||
}
|
||||
|
||||
if (!loaded.source.startsWith("ws://")) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Provider ${input.providerId} is visible through ${loaded.source || "an unknown source"}, but this MCP relay only supports provider WebSocket command endpoints right now.`,
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
sent: false,
|
||||
reason: "unsupported_command_transport",
|
||||
providerId: input.providerId,
|
||||
command: input.command,
|
||||
source: loaded.source,
|
||||
},
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
const frame = input.frame ?? buildCommandFrame(input.providerId, command, input.payload ?? {});
|
||||
const receipt = await sendProviderCommandFrame(loaded.source, frame, input.expectReceiptMs ?? 5000);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: renderJsonBlock({
|
||||
sent: true,
|
||||
sent: false,
|
||||
reason: "cultmesh_command_transport_required",
|
||||
providerId: input.providerId,
|
||||
source: loaded.source,
|
||||
command: input.command,
|
||||
frame,
|
||||
receipt,
|
||||
advertisedCommand: command,
|
||||
}),
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
sent: true,
|
||||
sent: false,
|
||||
reason: "cultmesh_command_transport_required",
|
||||
providerId: input.providerId,
|
||||
source: loaded.source,
|
||||
command: input.command,
|
||||
frame,
|
||||
receipt,
|
||||
},
|
||||
isError: true,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
|
@ -995,6 +985,106 @@ export function registerVoidbotTools(
|
|||
},
|
||||
);
|
||||
|
||||
registerIfAllowed(
|
||||
"read_shared_document",
|
||||
{
|
||||
title: "Read Shared Document",
|
||||
description:
|
||||
"List shared typed documents, or read one by documentId. These documents are visible to every repo Face and carry revision and author provenance.",
|
||||
inputSchema: readSharedDocumentInputSchema,
|
||||
annotations: READ_ONLY_ANNOTATIONS,
|
||||
},
|
||||
async (input: ReadSharedDocumentArgs): Promise<CallToolResult> => {
|
||||
const storePath = resolveRepoFaceSharedDocumentsPath(context.config.storageRoot);
|
||||
const documents = await listRepoFaceSharedDocuments(storePath);
|
||||
const requestedDocumentId = input.documentId?.trim().toLowerCase();
|
||||
const selected = requestedDocumentId
|
||||
? documents.find((document) => document.documentId === requestedDocumentId)
|
||||
: undefined;
|
||||
if (input.documentId && !selected) {
|
||||
return {
|
||||
content: [{ type: "text", text: `Shared document "${input.documentId}" was not found.` }],
|
||||
structuredContent: { found: false, documentId: input.documentId },
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
const result = input.documentId ? { storePath, document: selected } : { storePath, documents };
|
||||
return {
|
||||
content: [{ type: "text", text: renderJsonBlock(result) }],
|
||||
structuredContent: result,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
registerIfAllowed(
|
||||
"create_shared_document",
|
||||
{
|
||||
title: "Create Shared Document",
|
||||
description:
|
||||
"Create one shared typed document visible to every repo Face. The active Face identity is stamped by the server; arbitrary filesystem writes are not exposed.",
|
||||
inputSchema: createSharedDocumentInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
},
|
||||
},
|
||||
async (input: CreateSharedDocumentArgs): Promise<CallToolResult> => {
|
||||
const actor = await resolveActiveRepoFaceForSharedTool(context);
|
||||
if (!actor.identity) {
|
||||
return actor.error;
|
||||
}
|
||||
const storePath = resolveRepoFaceSharedDocumentsPath(context.config.storageRoot);
|
||||
const document = await createRepoFaceSharedDocument({
|
||||
canonicalPath: storePath,
|
||||
documentId: input.documentId,
|
||||
title: input.title,
|
||||
body: input.body,
|
||||
actorId: actor.identity.id,
|
||||
});
|
||||
return {
|
||||
content: [{ type: "text", text: renderJsonBlock({ created: true, storePath, document }) }],
|
||||
structuredContent: { created: true, storePath, document },
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
registerIfAllowed(
|
||||
"update_shared_document",
|
||||
{
|
||||
title: "Update Shared Document",
|
||||
description:
|
||||
"Replace one shared typed document body using its expected revision. Stale writes fail instead of overwriting another Face's update.",
|
||||
inputSchema: updateSharedDocumentInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
},
|
||||
},
|
||||
async (input: UpdateSharedDocumentArgs): Promise<CallToolResult> => {
|
||||
const actor = await resolveActiveRepoFaceForSharedTool(context);
|
||||
if (!actor.identity) {
|
||||
return actor.error;
|
||||
}
|
||||
const storePath = resolveRepoFaceSharedDocumentsPath(context.config.storageRoot);
|
||||
const document = await updateRepoFaceSharedDocument({
|
||||
canonicalPath: storePath,
|
||||
documentId: input.documentId,
|
||||
title: input.title,
|
||||
body: input.body,
|
||||
expectedVersion: input.expectedVersion,
|
||||
actorId: actor.identity.id,
|
||||
});
|
||||
return {
|
||||
content: [{ type: "text", text: renderJsonBlock({ updated: true, storePath, document }) }],
|
||||
structuredContent: { updated: true, storePath, document },
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
registerIfAllowed(
|
||||
"notify_owner",
|
||||
{
|
||||
|
|
@ -1091,6 +1181,20 @@ async function resolveRepoIdentityForTool(
|
|||
};
|
||||
}
|
||||
|
||||
async function resolveActiveRepoFaceForSharedTool(context: VoidbotMcpContext) {
|
||||
const identity = process.env.VOIDBOT_REPO_FACE_IDENTITY?.trim();
|
||||
if (!identity) {
|
||||
return {
|
||||
error: {
|
||||
content: [{ type: "text" as const, text: "Shared document mutation requires an active repo Face identity." }],
|
||||
structuredContent: { applied: false, reason: "missing_active_face_identity" },
|
||||
isError: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
return resolveRepoIdentityForTool(context, identity);
|
||||
}
|
||||
|
||||
async function recordRepoIdentityDeliveryReceipt(input: {
|
||||
context: VoidbotMcpContext;
|
||||
identity: NonNullable<ReturnType<typeof findRepoDiscordIdentity>>;
|
||||
|
|
@ -1157,55 +1261,115 @@ function identityForToolResult(
|
|||
};
|
||||
}
|
||||
|
||||
function normalizeOdinBaseUrl(value: string | undefined): string {
|
||||
return (value ?? process.env.ODIN_BASE_URL ?? DEFAULT_ODIN_BASE_URL).replace(/\/+$/, "");
|
||||
function resolveOdinStorePath(value: string | undefined): string {
|
||||
return path.resolve(value ?? process.env.ODIN_CULTMESH_STORE ?? DEFAULT_ODIN_STORE_PATH);
|
||||
}
|
||||
|
||||
async function fetchOdinProviderCatalog(odinBaseUrl: string): Promise<{ providers: Array<Record<string, unknown>> }> {
|
||||
const response = await fetch(`${odinBaseUrl}/eve/deck/providers`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Odin provider catalog failed: HTTP ${response.status}`);
|
||||
}
|
||||
const payload = await response.json() as { providers?: unknown };
|
||||
const providers = Array.isArray(payload.providers)
|
||||
? payload.providers.filter(isRecord)
|
||||
: [];
|
||||
async function fetchOdinProviderCatalog(odinStorePath: string): Promise<{ providers: Array<Record<string, unknown>> }> {
|
||||
const snapshot = await fetchOdinSnapshot(odinStorePath);
|
||||
const providers = summarizeOdinSurface(snapshot).interfaces.map((entry) => ({
|
||||
id: entry.providerId,
|
||||
title: entry.title,
|
||||
status: entry.status,
|
||||
detail: entry.detail,
|
||||
source: entry.source,
|
||||
updatedAt: entry.updatedAt,
|
||||
}));
|
||||
return { providers };
|
||||
}
|
||||
|
||||
async function fetchOdinDeckSnapshot(
|
||||
odinBaseUrl: string,
|
||||
async function fetchOdinSnapshot(
|
||||
odinStorePath: string,
|
||||
providerId?: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const deckUrl = new URL(odinBaseUrl);
|
||||
deckUrl.protocol = deckUrl.protocol === "https:" ? "wss:" : "ws:";
|
||||
deckUrl.pathname = "/eve/deck";
|
||||
deckUrl.search = "";
|
||||
const connection = await openWebSocketSnapshotSocket(deckUrl);
|
||||
const { socket } = connection;
|
||||
let pendingBuffer = connection.initialBuffer;
|
||||
try {
|
||||
if (providerId) {
|
||||
sendClientWebSocketText(socket, JSON.stringify({ type: "open-provider", providerId }));
|
||||
}
|
||||
for (let attempt = 0; attempt < 8; attempt += 1) {
|
||||
const frame = await readServerWebSocketText(socket, 3000, pendingBuffer);
|
||||
pendingBuffer = frame.remaining;
|
||||
const message = frame.text;
|
||||
const parsed = JSON.parse(message) as unknown;
|
||||
if (!isRecord(parsed)) {
|
||||
continue;
|
||||
}
|
||||
if (!providerId || parsed.providerId === providerId) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
throw new Error(providerId
|
||||
? `Odin did not publish provider ${providerId} in the snapshot window.`
|
||||
: "Odin did not publish a deck snapshot.");
|
||||
} finally {
|
||||
socket.destroy();
|
||||
const allSeer = await readOdinAllSeerSurface(odinStorePath);
|
||||
if (!providerId) {
|
||||
return allSeer;
|
||||
}
|
||||
const provider = providerStateFromOdinSurface(allSeer, providerId);
|
||||
if (!provider) {
|
||||
throw new Error(`Odin CultMesh store does not currently expose provider interface ${providerId}.`);
|
||||
}
|
||||
return provider;
|
||||
}
|
||||
|
||||
async function readOdinAllSeerSurface(odinStorePath: string): Promise<Record<string, unknown>> {
|
||||
if (!existsSync(odinStorePath)) {
|
||||
throw new Error(`Odin CultMesh store is missing: ${odinStorePath}`);
|
||||
}
|
||||
const { inspectCultCacheBytes } = loadCultCacheInspector();
|
||||
const inspection = inspectCultCacheBytes(odinStorePath, readFileSync(odinStorePath));
|
||||
const surfaceRecord = inspection.records.find((entry) =>
|
||||
entry.schemaId === "gamecult.eve.surface_state.v1"
|
||||
&& entry.key === ODIN_SURFACE_KEY
|
||||
);
|
||||
const record = isRecord(surfaceRecord?.payloadPreview) ? surfaceRecord.payloadPreview : null;
|
||||
if (!record) {
|
||||
throw new Error(`Odin CultMesh store does not contain ${ODIN_SURFACE_KEY}.`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
function loadCultCacheInspector(): {
|
||||
inspectCultCacheBytes: (
|
||||
filePath: string,
|
||||
bytes: Uint8Array,
|
||||
) => { records: Array<{ key: string; schemaId: string; payloadPreview: unknown }> };
|
||||
} {
|
||||
const packageJsonCandidates = [
|
||||
path.resolve(process.cwd(), "vendor", "cultcache-ts", "package.json"),
|
||||
path.resolve(process.cwd(), "node_modules", "cultcache-ts", "package.json"),
|
||||
path.resolve(process.cwd(), "..", "CultLib", "packages", "cultcache-ts", "package.json"),
|
||||
];
|
||||
|
||||
for (const packageJson of packageJsonCandidates) {
|
||||
try {
|
||||
const requireFromCandidate = createRequire(packageJson);
|
||||
const loaded = requireFromCandidate("./dist/cult-cache-inspector.js") as {
|
||||
inspectCultCacheBytes?: (
|
||||
filePath: string,
|
||||
bytes: Uint8Array,
|
||||
) => { records: Array<{ key: string; schemaId: string; payloadPreview: unknown }> };
|
||||
};
|
||||
if (loaded.inspectCultCacheBytes) {
|
||||
return { inspectCultCacheBytes: loaded.inspectCultCacheBytes };
|
||||
}
|
||||
} catch {
|
||||
// Try the next known CultCache runtime root.
|
||||
}
|
||||
}
|
||||
throw new Error("CultCache inspector is unavailable; cannot read Odin provider state.");
|
||||
}
|
||||
|
||||
function providerStateFromOdinSurface(
|
||||
allSeer: Record<string, unknown>,
|
||||
providerId: string,
|
||||
): Record<string, unknown> | null {
|
||||
const interfaceNode = findOdinInterfaceNode(allSeer, providerId);
|
||||
if (!interfaceNode) {
|
||||
return null;
|
||||
}
|
||||
const props = isRecord(interfaceNode.props) ? interfaceNode.props : {};
|
||||
const embeddedRoot = embeddedInterfaceRoot(interfaceNode);
|
||||
return {
|
||||
schema: "gamecult.eve.surface_state.v1",
|
||||
providerId,
|
||||
title: stringValue(props.title) || providerId,
|
||||
version: props.version ?? allSeer.version ?? 0,
|
||||
updatedAt: stringValue(props.updatedAt) || stringValue(allSeer.updatedAt),
|
||||
selectedNodeId: stringValue(allSeer.selectedNodeId),
|
||||
source: stringValue(props.source),
|
||||
manifest: isRecord(props.manifest) ? props.manifest : null,
|
||||
surface: {
|
||||
schema: "gamecult.eve.surface.v1",
|
||||
root: embeddedRoot ?? {
|
||||
id: `${providerId}.unavailable`,
|
||||
kind: "text",
|
||||
props: { text: `Provider ${providerId} has no embedded Odin interface root.` },
|
||||
children: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeOdinVerses(snapshot: Record<string, unknown>) {
|
||||
|
|
@ -1297,13 +1461,13 @@ interface LoadedOdinInterface {
|
|||
manifest: Record<string, unknown> | null;
|
||||
snapshot: Record<string, unknown>;
|
||||
root?: Record<string, unknown>;
|
||||
loadedFrom: "provider-websocket" | "odin-embedded-interface";
|
||||
loadedFrom: "odin-embedded-interface";
|
||||
}
|
||||
|
||||
interface InterfaceCommandSummary {
|
||||
command: string;
|
||||
label: string;
|
||||
source: "surface.commands" | "node.action" | "node.command";
|
||||
source: "surface.commands" | "manifest.commands" | "node.action" | "node.command";
|
||||
nodeId?: string;
|
||||
transport?: string;
|
||||
frameTemplate?: unknown;
|
||||
|
|
@ -1312,10 +1476,10 @@ interface InterfaceCommandSummary {
|
|||
}
|
||||
|
||||
async function loadOdinProviderInterface(
|
||||
odinBaseUrl: string,
|
||||
odinStorePath: string,
|
||||
providerId: string,
|
||||
): Promise<LoadedOdinInterface> {
|
||||
const odinSnapshot = await fetchOdinDeckSnapshot(odinBaseUrl);
|
||||
const odinSnapshot = await fetchOdinSnapshot(odinStorePath);
|
||||
const interfaceNode = findOdinInterfaceNode(odinSnapshot, providerId);
|
||||
if (!interfaceNode) {
|
||||
throw new Error(`Odin does not currently expose provider interface ${providerId}.`);
|
||||
|
|
@ -1323,38 +1487,6 @@ async function loadOdinProviderInterface(
|
|||
|
||||
const props = isRecord(interfaceNode.props) ? interfaceNode.props : {};
|
||||
const source = stringValue(props.source);
|
||||
if (source.startsWith("ws://")) {
|
||||
try {
|
||||
const providerSnapshot = await fetchProviderDeckSnapshot(source, providerId);
|
||||
return {
|
||||
providerId,
|
||||
title: stringValue(providerSnapshot.title) || stringValue(props.title) || providerId,
|
||||
source,
|
||||
status: stringValue(props.status),
|
||||
detail: stringValue(props.detail),
|
||||
manifest: isRecord(props.manifest) ? props.manifest : null,
|
||||
snapshot: providerSnapshot,
|
||||
root: getSurfaceRoot(providerSnapshot),
|
||||
loadedFrom: "provider-websocket",
|
||||
};
|
||||
} catch (error) {
|
||||
const embedded = embeddedInterfaceRoot(interfaceNode);
|
||||
if (!embedded) {
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
providerId,
|
||||
title: stringValue(props.title) || providerId,
|
||||
source,
|
||||
status: stringValue(props.status),
|
||||
detail: `provider websocket failed; using Odin embedded root: ${error instanceof Error ? error.message : String(error)}`,
|
||||
manifest: isRecord(props.manifest) ? props.manifest : null,
|
||||
snapshot: odinSnapshot,
|
||||
root: embedded,
|
||||
loadedFrom: "odin-embedded-interface",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
providerId,
|
||||
|
|
@ -1369,30 +1501,6 @@ async function loadOdinProviderInterface(
|
|||
};
|
||||
}
|
||||
|
||||
async function fetchProviderDeckSnapshot(
|
||||
deckUrlText: string,
|
||||
providerId: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const deckUrl = new URL(deckUrlText);
|
||||
const connection = await openWebSocketSnapshotSocket(deckUrl);
|
||||
const { socket } = connection;
|
||||
let pendingBuffer = connection.initialBuffer;
|
||||
try {
|
||||
sendClientWebSocketText(socket, JSON.stringify({ type: "open-provider", providerId }));
|
||||
for (let attempt = 0; attempt < 8; attempt += 1) {
|
||||
const frame = await readServerWebSocketText(socket, 3000, pendingBuffer);
|
||||
pendingBuffer = frame.remaining;
|
||||
const parsed = JSON.parse(frame.text) as unknown;
|
||||
if (isRecord(parsed) && parsed.providerId === providerId) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
throw new Error(`Provider deck did not publish ${providerId}.`);
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function findOdinInterfaceNode(
|
||||
odinSnapshot: Record<string, unknown>,
|
||||
providerId: string,
|
||||
|
|
@ -1495,8 +1603,11 @@ function extractProviderCommands(loaded: LoadedOdinInterface): InterfaceCommandS
|
|||
: Array.isArray(loaded.snapshot.commands)
|
||||
? loaded.snapshot.commands.filter(isRecord)
|
||||
: [];
|
||||
const manifestCommands = Array.isArray(loaded.manifest?.commands)
|
||||
? loaded.manifest.commands.filter(isRecord)
|
||||
: [];
|
||||
|
||||
for (const command of surfaceCommands) {
|
||||
for (const command of [...surfaceCommands, ...manifestCommands]) {
|
||||
const commandName = stringValue(command.command) || stringValue(command.id);
|
||||
if (!commandName) {
|
||||
continue;
|
||||
|
|
@ -1504,7 +1615,7 @@ function extractProviderCommands(loaded: LoadedOdinInterface): InterfaceCommandS
|
|||
commands.push({
|
||||
command: commandName,
|
||||
label: stringValue(command.label) || commandName,
|
||||
source: "surface.commands",
|
||||
source: surfaceCommands.includes(command) ? "surface.commands" : "manifest.commands",
|
||||
transport: stringValue(command.transport),
|
||||
frameTemplate: command.frameTemplate,
|
||||
payloadSchema: command.payloadSchema,
|
||||
|
|
@ -1558,98 +1669,6 @@ function findAdvertisedCommand(
|
|||
return extractProviderCommands(loaded).find((entry) => entry.command === command);
|
||||
}
|
||||
|
||||
function buildCommandFrame(
|
||||
providerId: string,
|
||||
command: InterfaceCommandSummary,
|
||||
payload: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
if (isRecord(command.frameTemplate)) {
|
||||
return materializeFrameTemplate(command.frameTemplate, payload);
|
||||
}
|
||||
|
||||
return {
|
||||
type: "surface-command",
|
||||
schema: "gamecult.eve.command.v1",
|
||||
providerId,
|
||||
command: command.command,
|
||||
payload,
|
||||
nodeId: command.nodeId,
|
||||
};
|
||||
}
|
||||
|
||||
function materializeFrameTemplate(
|
||||
template: Record<string, unknown>,
|
||||
payload: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const materialized: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(template)) {
|
||||
materialized[key] = materializeTemplateValue(value, payload);
|
||||
}
|
||||
return materialized;
|
||||
}
|
||||
|
||||
function materializeTemplateValue(value: unknown, payload: Record<string, unknown>): unknown {
|
||||
if (typeof value === "string") {
|
||||
const exact = value.match(/^\$\{([A-Za-z0-9_.-]+)\??\}$/);
|
||||
if (exact) {
|
||||
return payload[exact[1]] ?? "";
|
||||
}
|
||||
return value.replace(/\$\{([A-Za-z0-9_.-]+)\??\}/g, (_match, key: string) =>
|
||||
payload[key] === undefined || payload[key] === null ? "" : String(payload[key]),
|
||||
);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) => materializeTemplateValue(entry, payload));
|
||||
}
|
||||
if (isRecord(value)) {
|
||||
return materializeFrameTemplate(value, payload);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
async function sendProviderCommandFrame(
|
||||
deckUrlText: string,
|
||||
frame: Record<string, unknown>,
|
||||
expectReceiptMs: number,
|
||||
) {
|
||||
const deckUrl = new URL(deckUrlText);
|
||||
const connection = await openWebSocketSnapshotSocket(deckUrl);
|
||||
const { socket } = connection;
|
||||
let pendingBuffer = connection.initialBuffer;
|
||||
try {
|
||||
try {
|
||||
const initial = await readServerWebSocketText(socket, 1000, pendingBuffer);
|
||||
pendingBuffer = initial.remaining;
|
||||
} catch {
|
||||
// Some providers do not send an initial deck frame before commands.
|
||||
}
|
||||
sendClientWebSocketText(socket, JSON.stringify(frame));
|
||||
if (expectReceiptMs <= 0) {
|
||||
return {
|
||||
received: false,
|
||||
detail: "Command frame sent; receipt wait disabled.",
|
||||
};
|
||||
}
|
||||
try {
|
||||
const response = await readServerWebSocketText(socket, expectReceiptMs, pendingBuffer);
|
||||
pendingBuffer = response.remaining;
|
||||
const parsed = JSON.parse(response.text) as unknown;
|
||||
return {
|
||||
received: true,
|
||||
frame: isRecord(parsed) ? parsed : response.text,
|
||||
remainingBytes: pendingBuffer.length,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
received: false,
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function getSurfaceRoot(snapshot: Record<string, unknown>): Record<string, unknown> | undefined {
|
||||
const surface = isRecord(snapshot.surface) ? snapshot.surface : undefined;
|
||||
return isRecord(surface?.root) ? surface.root : undefined;
|
||||
|
|
@ -1662,146 +1681,3 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|||
function stringValue(value: unknown): string {
|
||||
return typeof value === "string" ? value : value === null || value === undefined ? "" : String(value);
|
||||
}
|
||||
|
||||
function openWebSocketSnapshotSocket(url: URL): Promise<{ socket: net.Socket; initialBuffer: Buffer }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (url.protocol === "wss:") {
|
||||
reject(new Error("Odin WSS is not supported by this lightweight MCP snapshot client yet."));
|
||||
return;
|
||||
}
|
||||
const port = Number(url.port || 80);
|
||||
const socket = net.createConnection({ host: url.hostname, port, timeout: 3000 });
|
||||
const key = crypto.randomBytes(16).toString("base64");
|
||||
let buffer = Buffer.alloc(0);
|
||||
socket.on("connect", () => {
|
||||
socket.write([
|
||||
`GET ${url.pathname || "/eve/deck"} HTTP/1.1`,
|
||||
`Host: ${url.hostname}:${port}`,
|
||||
"Upgrade: websocket",
|
||||
"Connection: Upgrade",
|
||||
`Sec-WebSocket-Key: ${key}`,
|
||||
"Sec-WebSocket-Version: 13",
|
||||
"",
|
||||
"",
|
||||
].join("\r\n"));
|
||||
});
|
||||
socket.on("data", function onHandshake(chunk) {
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
const marker = buffer.indexOf("\r\n\r\n");
|
||||
if (marker < 0) {
|
||||
return;
|
||||
}
|
||||
const header = buffer.subarray(0, marker).toString("latin1");
|
||||
if (!header.startsWith("HTTP/1.1 101")) {
|
||||
reject(new Error(header.split(/\r?\n/)[0] || "Odin websocket handshake failed"));
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
socket.off("data", onHandshake);
|
||||
resolve({ socket, initialBuffer: buffer.subarray(marker + 4) });
|
||||
});
|
||||
socket.on("timeout", () => {
|
||||
reject(new Error("Odin websocket connection timed out"));
|
||||
socket.destroy();
|
||||
});
|
||||
socket.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function sendClientWebSocketText(socket: net.Socket, text: string): void {
|
||||
const payload = Buffer.from(text, "utf8");
|
||||
const mask = crypto.randomBytes(4);
|
||||
const header = [0x81];
|
||||
if (payload.length < 126) {
|
||||
header.push(0x80 | payload.length);
|
||||
} else if (payload.length <= 0xffff) {
|
||||
header.push(0x80 | 126, payload.length >> 8, payload.length & 0xff);
|
||||
} else {
|
||||
const length = Buffer.alloc(8);
|
||||
length.writeBigUInt64BE(BigInt(payload.length));
|
||||
header.push(0x80 | 127, ...length);
|
||||
}
|
||||
const masked = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4]));
|
||||
socket.write(Buffer.concat([Buffer.from(header), mask, masked]));
|
||||
}
|
||||
|
||||
function readServerWebSocketText(
|
||||
socket: net.Socket,
|
||||
timeoutMs: number,
|
||||
initialBuffer: Buffer<ArrayBufferLike> = Buffer.alloc(0),
|
||||
): Promise<{ text: string; remaining: Buffer<ArrayBufferLike> }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let buffer = initialBuffer;
|
||||
const timer = setTimeout(() => cleanup(new Error("Timed out waiting for Odin deck frame")), timeoutMs);
|
||||
function cleanup(error?: Error, value?: { text: string; remaining: Buffer<ArrayBufferLike> }) {
|
||||
clearTimeout(timer);
|
||||
socket.off("data", onData);
|
||||
socket.off("error", onError);
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(value ?? { text: "", remaining: Buffer.alloc(0) });
|
||||
}
|
||||
}
|
||||
function onError(error: Error) {
|
||||
cleanup(error);
|
||||
}
|
||||
function onData(chunk: Buffer) {
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
readBufferedFrame();
|
||||
}
|
||||
function readBufferedFrame() {
|
||||
const frame = tryReadWebSocketFrame(buffer);
|
||||
if (!frame) {
|
||||
return;
|
||||
}
|
||||
buffer = buffer.subarray(frame.consumed);
|
||||
if (frame.opcode === 0x1) {
|
||||
cleanup(undefined, {
|
||||
text: frame.payload.toString("utf8"),
|
||||
remaining: buffer,
|
||||
});
|
||||
} else if (frame.opcode === 0x8) {
|
||||
cleanup(new Error("Odin websocket closed"));
|
||||
}
|
||||
}
|
||||
socket.on("data", onData);
|
||||
socket.on("error", onError);
|
||||
readBufferedFrame();
|
||||
});
|
||||
}
|
||||
|
||||
function tryReadWebSocketFrame(buffer: Buffer): { opcode: number; payload: Buffer; consumed: number } | null {
|
||||
if (buffer.length < 2) {
|
||||
return null;
|
||||
}
|
||||
const opcode = buffer[0] & 0x0f;
|
||||
const masked = Boolean(buffer[1] & 0x80);
|
||||
let length = buffer[1] & 0x7f;
|
||||
let offset = 2;
|
||||
if (length === 126) {
|
||||
if (buffer.length < offset + 2) {
|
||||
return null;
|
||||
}
|
||||
length = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
} else if (length === 127) {
|
||||
if (buffer.length < offset + 8) {
|
||||
return null;
|
||||
}
|
||||
length = Number(buffer.readBigUInt64BE(offset));
|
||||
offset += 8;
|
||||
}
|
||||
const mask = masked ? buffer.subarray(offset, offset + 4) : null;
|
||||
if (masked) {
|
||||
offset += 4;
|
||||
}
|
||||
if (buffer.length < offset + length) {
|
||||
return null;
|
||||
}
|
||||
let payload = buffer.subarray(offset, offset + length);
|
||||
if (mask) {
|
||||
payload = Buffer.from(payload.map((byte, index) => byte ^ mask[index % 4]));
|
||||
}
|
||||
return { opcode, payload, consumed: offset + length };
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue