Add !ai Matrix command for querying other models via OpenRouter
build-agent / build-and-push (push) Successful in 7s

This commit is contained in:
2026-08-23 14:40:46 +00:00
parent 58bce828bf
commit 77ce4a7334
5 changed files with 82 additions and 5 deletions
+39 -5
View File
@@ -1,19 +1,42 @@
import { MatrixClient, SimpleFsStorageProvider, AutojoinRoomsMixin } from "matrix-bot-sdk";
import { runChatTask } from "./runner.js";
import { askOpenRouter, DEFAULT_MODEL } from "./openrouter.js";
const HOMESERVER_URL = process.env.MATRIX_HOMESERVER_URL;
const ACCESS_TOKEN = process.env.MATRIX_BOT_TOKEN;
const CONTROL_ROOM_ID = process.env.MATRIX_CONTROL_ROOM_ID;
const GITEA_URL = process.env.GITEA_URL;
const MAX_REPLY_LENGTH = 4000;
// "!claude owner/repo do the thing" — everything after the repo slug is the instruction.
function parseCommand(text) {
function parseClaudeCommand(text) {
const match = text.match(/^!claude\s+([^\s/]+\/[^\s/]+)\s+(.+)$/s);
if (!match) return null;
const [, repoFullName, instruction] = match;
return { repoFullName, instruction: instruction.trim() };
}
// "!ai <prompt>" uses the default model. "!ai provider/model <prompt>" (first token
// contains a "/") picks a specific OpenRouter model, e.g. "!ai google/gemini-2.0-flash-001
// summarize this repo's README".
function parseAiCommand(text) {
const match = text.match(/^!ai\s+(.+)$/s);
if (!match) return null;
const rest = match[1].trim();
const firstSpace = rest.search(/\s/);
const firstToken = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
if (firstToken.includes("/") && firstSpace !== -1) {
return { model: firstToken, prompt: rest.slice(firstSpace + 1).trim() };
}
return { model: DEFAULT_MODEL, prompt: rest };
}
function truncate(text) {
if (text.length <= MAX_REPLY_LENGTH) return text;
return `${text.slice(0, MAX_REPLY_LENGTH)}\n\n[truncated]`;
}
export async function startMatrixBot() {
if (!HOMESERVER_URL || !ACCESS_TOKEN || !CONTROL_ROOM_ID) {
console.warn("Matrix env vars not set — skipping bot startup");
@@ -27,14 +50,25 @@ export async function startMatrixBot() {
client.on("room.message", async (roomId, event) => {
// Invite-only control room enforces who can reach the bot at all; this just scopes
// command handling to that one room. No need to fetch/compare the bot's own user ID
// to filter out its own messages — its replies ("Working on it...", "Opened PR:...",
// "Failed:...") never match the !claude command pattern below, so they're ignored
// by parseCommand() returning null, same as any other non-command message.
// to filter out its own messages — its replies never match either command pattern
// below, so they're ignored the same as any other non-command message.
if (roomId !== CONTROL_ROOM_ID) return;
const body = event.content?.body;
if (!body) return;
const cmd = parseCommand(body);
const aiCmd = parseAiCommand(body);
if (aiCmd) {
try {
const reply = await askOpenRouter(aiCmd.model, aiCmd.prompt);
await client.sendText(roomId, `[${aiCmd.model}] ${truncate(reply)}`);
} catch (err) {
console.error("openrouter query failed", err);
await client.sendText(roomId, `Failed: ${err.message}`);
}
return;
}
const cmd = parseClaudeCommand(body);
if (!cmd) return;
const [owner, repo] = cmd.repoFullName.split("/");
+33
View File
@@ -0,0 +1,33 @@
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
const DEFAULT_MODEL = process.env.OPENROUTER_DEFAULT_MODEL || "openai/gpt-4o-mini";
export async function askOpenRouter(model, prompt) {
if (!OPENROUTER_API_KEY) {
throw new Error("OPENROUTER_API_KEY is not set");
}
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${OPENROUTER_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: model || DEFAULT_MODEL,
messages: [{ role: "user", content: prompt }],
}),
});
if (!res.ok) {
throw new Error(`OpenRouter request failed: ${res.status} ${await res.text()}`);
}
const data = await res.json();
const content = data.choices?.[0]?.message?.content;
if (!content) {
throw new Error(`OpenRouter returned no content: ${JSON.stringify(data)}`);
}
return content;
}
export { DEFAULT_MODEL };