Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion packages/app/api/lib/route-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,33 @@ import type { AgentLlmConfig } from './clawscale-agent.js';
import { parseCommand, resolveTarget, resolveAddRemoveArg, formatCommandHelp } from './slash-commands.js';
import type { AiBackendType, AiBackendProviderConfig } from '../../shared/index.js';

// ── Per-user rate limiter (in-memory) ────────────────────────────────────────

interface RateBucket {
count: number;
resetAt: number;
}

/** Key: `${tenantId}:${endUserId}` */
const rateBuckets = new Map<string, RateBucket>();

function isRateLimited(
tenantId: string,
endUserId: string,
limit: { maxMessages: number; windowSeconds: number },
): boolean {
if (limit.maxMessages <= 0) return false; // 0 = unlimited
const key = `${tenantId}:${endUserId}`;
const now = Date.now();
const bucket = rateBuckets.get(key);
if (!bucket || now >= bucket.resetAt) {
rateBuckets.set(key, { count: 1, resetAt: now + limit.windowSeconds * 1000 });
return false;
}
bucket.count++;
return bucket.count > limit.maxMessages;
}

export interface Attachment {
url: string;
filename: string;
Expand Down Expand Up @@ -68,7 +95,7 @@ export async function routeInboundMessage(input: InboundMessage): Promise<RouteR
personaName?: string;
endUserAccess?: 'anonymous' | 'whitelist' | 'blacklist';
allowList?: string[];
clawscale?: { name?: string; answerStyle?: string; isActive?: boolean; llm?: AgentLlmConfig };
clawscale?: { name?: string; answerStyle?: string; isActive?: boolean; rateLimit?: { maxMessages: number; windowSeconds: number }; llm?: AgentLlmConfig };
blockList?: string[];
};

Expand Down Expand Up @@ -130,6 +157,7 @@ export async function routeInboundMessage(input: InboundMessage): Promise<RouteR
const clawscaleStyle = clawscaleCfg.answerStyle;
const clawscaleActive = clawscaleCfg.isActive !== false;
const clawscaleLlm = clawscaleCfg.llm ?? { model: 'openai:gpt-5.4-mini' };
const clawscaleRateLimit = clawscaleCfg.rateLimit;

const allBackends = await db.aiBackend.findMany({
where: { tenantId, isActive: true },
Expand All @@ -145,6 +173,14 @@ export async function routeInboundMessage(input: InboundMessage): Promise<RouteR
* Slash commands are executed via a callback that re-enters routeInboundMessage.
*/
async function runAgent(userText: string, mode: 'select' | 'direct'): Promise<RouteResult> {
// Rate limit check
if (clawscaleRateLimit && isRateLimited(tenantId, endUser!.id, clawscaleRateLimit)) {
const mins = Math.ceil(clawscaleRateLimit.windowSeconds / 60);
return reply(
`⏳ You've reached the message limit (${clawscaleRateLimit.maxMessages} per ${mins === 1 ? 'minute' : `${mins} minutes`}). Please wait a moment before sending another message.`,
);
}

// If attachments are present but multimodal is not enabled, nudge the admin
if (attachments?.length && !clawscaleLlm?.multimodal) {
return reply(
Expand Down
4 changes: 4 additions & 0 deletions packages/app/api/routes/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const updateSettingsSchema = z.object({
name: z.string().min(1).max(80).optional(),
answerStyle: z.string().max(500).optional(),
isActive: z.boolean().optional(),
rateLimit: z.object({
maxMessages: z.number().int().min(0).max(10000),
windowSeconds: z.number().int().min(1).max(86400),
}).nullable().optional(),
llm: z.object({
model: z.string().min(1).max(100),
apiKey: z.string().max(500).optional(),
Expand Down
7 changes: 7 additions & 0 deletions packages/app/shared/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ export interface ClawScaleAgentSettings {
answerStyle?: string;
/** Whether the orchestrator responds at all (default: true) */
isActive?: boolean;
/** Per-user rate limiting for the assistant */
rateLimit?: {
/** Maximum messages allowed per window (0 = unlimited) */
maxMessages: number;
/** Window duration in seconds (default: 60) */
windowSeconds: number;
};
/** LLM configuration for the ClawScale agent */
llm?: {
/** LangChain model string, e.g. "openai:gpt-5.4-mini", "anthropic:claude-haiku-4-5-20251001" */
Expand Down
25 changes: 25 additions & 0 deletions packages/app/web/app/(dashboard)/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export default function Settings() {
const [clawscaleApiKey, setClawscaleApiKey] = useState('');
const [apiKeySet, setApiKeySet] = useState(false);
const [clawscaleMultimodal, setClawscaleMultimodal] = useState(false);
const [rateLimitEnabled, setRateLimitEnabled] = useState(false);
const [rateLimitMax, setRateLimitMax] = useState(20);
const [rateLimitWindow, setRateLimitWindow] = useState(60);

useEffect(() => {
api.get<ApiResponse<Tenant>>('/api/tenant').then((res) => {
Expand All @@ -34,6 +37,8 @@ export default function Settings() {
setClawscaleModel(s.clawscale?.llm?.model ?? 'openai:gpt-5.4-mini');
setApiKeySet(!!s.clawscale?.llm?.apiKey && s.clawscale.llm.apiKey !== '');
setClawscaleMultimodal(s.clawscale?.llm?.multimodal ?? false);
const rl = s.clawscale?.rateLimit;
if (rl) { setRateLimitEnabled(true); setRateLimitMax(rl.maxMessages); setRateLimitWindow(rl.windowSeconds); }
}
setLoading(false);
});
Expand All @@ -52,6 +57,7 @@ export default function Settings() {
...(clawscaleApiKey ? { apiKey: clawscaleApiKey } : {}),
multimodal: clawscaleMultimodal,
},
rateLimit: rateLimitEnabled ? { maxMessages: rateLimitMax, windowSeconds: rateLimitWindow } : null,
},
},
});
Expand Down Expand Up @@ -108,6 +114,25 @@ export default function Settings() {
<span className="text-xs text-gray-500 block">Allow the assistant to process images, files, and audio sent by users. Requires a vision-capable model (e.g. GPT-4o, Claude Sonnet).</span>
</span>
</label>
<label className="flex items-start gap-3 cursor-pointer">
<input type="checkbox" checked={rateLimitEnabled} onChange={(e) => setRateLimitEnabled(e.target.checked)} disabled={!isAdmin} className="mt-0.5" />
<span>
<span className="text-sm font-medium text-gray-900">Rate limit</span>
<span className="text-xs text-gray-500 block">Limit how many messages each end-user can send within a time window.</span>
</span>
</label>
{rateLimitEnabled && (
<div className="flex items-center gap-3 pl-7">
<div className="flex-1">
<label className="label">Max messages</label>
<input type="number" className="input" min={1} max={10000} value={rateLimitMax} onChange={(e) => setRateLimitMax(Number(e.target.value))} disabled={!isAdmin} />
</div>
<div className="flex-1">
<label className="label">Window (seconds)</label>
<input type="number" className="input" min={1} max={86400} value={rateLimitWindow} onChange={(e) => setRateLimitWindow(Number(e.target.value))} disabled={!isAdmin} />
</div>
</div>
)}
</div>
</div>

Expand Down
Loading