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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
197 changes: 197 additions & 0 deletions packages/services/service-ai/src/__tests__/agent-chat-quota.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { describe, it, expect, vi } from 'vitest';
import type { IDataEngine, Logger } from '@objectstack/spec/contracts';
import { DailyMessageQuota, type AgentChatQuota } from '../quota/agent-chat-quota.js';
import { buildAgentRoutes } from '../routes/agent-routes.js';
import { AIService } from '../ai-service.js';
import { MemoryLLMAdapter } from '../adapters/memory-adapter.js';
import { InMemoryConversationService } from '../conversation/in-memory-conversation-service.js';
import type { AgentRuntime } from '../agent-runtime.js';

const silentLogger: Logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
fatal: vi.fn(),
};

const FIXED_NOW = () => new Date('2026-06-12T10:00:00.000Z');

function mockDataEngine(rows: Record<string, { messages: number }> = {}): IDataEngine & {
inserted: unknown[];
updated: unknown[];
} {
const inserted: unknown[] = [];
const updated: unknown[] = [];
return {
inserted,
updated,
findOne: vi.fn(async (_obj: string, q?: { where?: { id?: string } }) => {
const id = q?.where?.id;
return id && rows[id] ? { id, ...rows[id] } : null;
}),
insert: vi.fn(async (_obj: string, data: unknown) => {
inserted.push(data);
return data;
}),
update: vi.fn(async (_obj: string, data: unknown, opts: unknown) => {
updated.push({ data, opts });
return data;
}),
find: vi.fn(async () => []),
delete: vi.fn(async () => ({})),
count: vi.fn(async () => 0),
aggregate: vi.fn(async () => []),
} as unknown as IDataEngine & { inserted: unknown[]; updated: unknown[] };
}

// ═══════════════════════════════════════════════════════════════════
// DailyMessageQuota
// ═══════════════════════════════════════════════════════════════════

describe('DailyMessageQuota', () => {
const subject = { userId: 'u1', environmentId: 'env1' };
const todayId = '2026-06-12:env1:u1';

it('allows under the limit and reports remaining + resetAt', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 3 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(true);
expect(d.remaining).toBe(26); // 30 - 3 - this turn
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
});

it('refuses at the limit with honest copy (why + when + way out)', async () => {
const quota = new DailyMessageQuota(mockDataEngine({ [todayId]: { messages: 30 } }), 30, FIXED_NOW);
const d = await quota.check(subject);
expect(d.allowed).toBe(false);
expect(d.resetAt).toBe('2026-06-13T00:00:00.000Z');
expect(d.message).toContain('30');
expect(d.message).toContain('恢复');
expect(d.message).toContain('upgrade');
});

it('consume inserts the first turn of the day, then increments', async () => {
const engine = mockDataEngine();
const quota = new DailyMessageQuota(engine, 30, FIXED_NOW);
await quota.consume(subject);
expect(engine.inserted).toEqual([
{ id: todayId, day: '2026-06-12', user_id: 'u1', environment_id: 'env1', messages: 1 },
]);

const engine2 = mockDataEngine({ [todayId]: { messages: 5 } });
const quota2 = new DailyMessageQuota(engine2, 30, FIXED_NOW);
await quota2.consume(subject);
expect(engine2.updated).toEqual([{ data: { messages: 6 }, opts: { where: { id: todayId } } }]);
});

it('fails OPEN when the counter store errors — never blocks chat', async () => {
const engine = mockDataEngine();
(engine.findOne as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db down'));
const quota = new DailyMessageQuota(engine, 1, FIXED_NOW);
await expect(quota.check(subject)).resolves.toMatchObject({ allowed: true });
await expect(quota.consume(subject)).resolves.toBeUndefined();
});

it('scopes the counter per environment and per user', async () => {
const engine = mockDataEngine({ ['2026-06-12:envA:u1']: { messages: 99 } });
const quota = new DailyMessageQuota(engine, 10, FIXED_NOW);
// Same user, different environment → independent counter.
expect((await quota.check({ userId: 'u1', environmentId: 'envB' })).allowed).toBe(true);
// Different user, same environment → independent counter.
expect((await quota.check({ userId: 'u2', environmentId: 'envA' })).allowed).toBe(true);
// The exhausted pair stays refused.
expect((await quota.check({ userId: 'u1', environmentId: 'envA' })).allowed).toBe(false);
});
});

// ═══════════════════════════════════════════════════════════════════
// Agent chat route × quota gate
// ═══════════════════════════════════════════════════════════════════

function mockAgentRuntime(): AgentRuntime {
return {
loadAgent: vi.fn(async () => ({
name: 'data_chat',
label: 'Assistant',
active: true,
})),
resolveActiveSkills: vi.fn(async () => []),
buildSystemMessages: vi.fn(() => [{ role: 'system', content: 'sys' }]),
buildRequestOptions: vi.fn(() => ({})),
listAgents: vi.fn(async () => []),
} as unknown as AgentRuntime;
}

function chatRoute(quota?: AgentChatQuota) {
const aiService = new AIService({
adapter: new MemoryLLMAdapter(),
conversationService: new InMemoryConversationService(),
});
const routes = buildAgentRoutes(aiService, mockAgentRuntime(), silentLogger, { quota });
const route = routes.find((r) => r.path.endsWith('/chat'));
if (!route) throw new Error('chat route not found');
return route;
}

const chatReq = (over: Record<string, unknown> = {}) => ({
params: { agentName: 'data_chat' },
body: { messages: [{ role: 'user', content: 'hi' }], stream: false, ...over },
user: { userId: 'u1' },
});

describe('agent chat route quota gate', () => {
it('passes through and consumes exactly once when allowed', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(200);
expect(quota.check).toHaveBeenCalledTimes(1);
expect(quota.consume).toHaveBeenCalledTimes(1);
});

it('returns 429 + stable code on JSON mode when exhausted (nothing consumed)', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq() as never);
expect(res.status).toBe(429);
expect(res.body).toMatchObject({ code: 'ai_quota_exhausted', error: '额度已用完', resetAt: '2026-06-13T00:00:00.000Z' });
expect(quota.consume).not.toHaveBeenCalled();
});

it('streams the refusal as a normal assistant message in stream mode', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: false, message: '今日额度已用完,明日恢复' })),
consume: vi.fn(async () => {}),
};
const res = await chatRoute(quota).handler(chatReq({ stream: true }) as never);
expect(res.status).toBe(200);
expect(res.stream).toBe(true);
let text = '';
for await (const chunk of res.events as AsyncIterable<string>) text += chunk;
expect(text).toContain('今日额度已用完');
expect(text).toContain('"type":"finish"');
expect(quota.consume).not.toHaveBeenCalled();
});

it('no quota wired → unchanged behavior', async () => {
const res = await chatRoute(undefined).handler(chatReq() as never);
expect(res.status).toBe(200);
});

it('forwards the environmentId from chat context to the quota subject', async () => {
const quota: AgentChatQuota = {
check: vi.fn(async () => ({ allowed: true })),
consume: vi.fn(async () => {}),
};
await chatRoute(quota).handler(chatReq({ context: { environmentId: 'env42' } }) as never);
expect(quota.check).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
expect(quota.consume).toHaveBeenCalledWith({ userId: 'u1', environmentId: 'env42' });
});
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';

/**
* ai_usage_daily — per-user, per-day AI chat usage counters
*
* One row per (UTC day, environment, user). The agent chat route increments
* `messages` once per user turn; {@link DailyMessageQuota} reads it to decide
* whether a daily message limit has been reached.
*
* This is a quota counter, not billing-grade metering: increments are
* last-write-wins and a lost update under concurrency only ever under-counts
* by a message — acceptable for an abuse/entitlement gate, not for invoicing.
*
* @namespace ai
*/
export const AiUsageDailyObject = ObjectSchema.create({
name: 'ai_usage_daily',
label: 'AI Daily Usage',
pluralLabel: 'AI Daily Usage',
icon: 'gauge',
isSystem: true,
description: 'Per-user daily AI chat usage counters (quota enforcement)',

fields: {
id: Field.text({
label: 'Usage ID',
required: true,
readonly: true,
description: 'Deterministic key: <day>:<environment|->:<user>',
}),

day: Field.text({
label: 'Day (UTC)',
required: true,
maxLength: 10,
description: 'UTC calendar day, YYYY-MM-DD',
}),

user_id: Field.text({
label: 'User ID',
required: true,
maxLength: 255,
}),

environment_id: Field.text({
label: 'Environment ID',
required: false,
maxLength: 255,
}),

messages: Field.number({
label: 'Messages',
required: true,
description: 'User chat turns consumed this day',
}),
},
});
1 change: 1 addition & 0 deletions packages/services/service-ai/src/objects/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,3 +12,4 @@ export { AiTraceObject } from './ai-trace.object.js';
export { AiPendingActionObject } from './ai-pending-action.object.js';
export { AiEvalCaseObject } from './ai-eval-case.object.js';
export { AiEvalRunObject } from './ai-eval-run.object.js';
export { AiUsageDailyObject } from './ai-usage-daily.object.js';
26 changes: 23 additions & 3 deletions packages/services/service-ai/src/plugin.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,7 +14,8 @@ import { buildToolRoutes } from './routes/tool-routes.js';
import { buildPendingActionRoutes } from './routes/pending-action-routes.js';
import { buildEvalRoutes } from './routes/eval-routes.js';
import { ObjectQLConversationService } from './conversation/objectql-conversation-service.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject } from './objects/index.js';
import { AiConversationObject, AiMessageObject, AiPendingActionObject, AiTraceObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject } from './objects/index.js';
import { DailyMessageQuota, type AgentChatQuota } from './quota/agent-chat-quota.js';
import { AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView } from './views/index.js';
import { EvalRunner } from './eval/index.js';
import { registerDataTools } from './tools/data-tools.js';
Expand DownExpand Up@@ -593,7 +594,7 @@ export class AIServicePlugin implements Plugin {
type: 'plugin',
scope: 'system',
namespace: 'ai',
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject],
objects: [AiConversationObject, AiMessageObject, AiTraceObject, AiPendingActionObject, AiEvalCaseObject, AiEvalRunObject, AiUsageDailyObject],
views: [AiTraceView, AiMessageView, AiPendingActionView, AiEvalCaseView, AiEvalRunView],
});

Expand DownExpand Up@@ -857,7 +858,26 @@ export class AIServicePlugin implements Plugin {
if (metadataService) {
const skillRegistry = new SkillRegistry(metadataService);
const agentRuntime = new AgentRuntime(metadataService, skillRegistry);
const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger);

// ── Optional per-turn chat quota (ADR-0040 §5, perception rule) ──
// Mechanism only: the deployment opts in by setting
// AI_DAILY_USER_MESSAGES=<N>. Unset/invalid → no quota, unchanged
// behavior. Plan-tier policies (free vs pro) wire a richer
// AgentChatQuota here later; the gate and counter do not change.
let chatQuota: AgentChatQuota | undefined;
const quotaRaw = process.env.AI_DAILY_USER_MESSAGES;
const quotaLimit = quotaRaw ? Number.parseInt(quotaRaw, 10) : NaN;
if (Number.isFinite(quotaLimit) && quotaLimit > 0) {
const quotaDataEngine = ctx.getService<IDataEngine>('data');
if (quotaDataEngine && typeof quotaDataEngine.findOne === 'function') {
chatQuota = new DailyMessageQuota(quotaDataEngine, quotaLimit);
ctx.logger.info(`[AI] Daily chat quota enabled (${quotaLimit} user turns/user/day)`);
} else {
ctx.logger.warn('[AI] AI_DAILY_USER_MESSAGES set but IDataEngine unavailable — quota disabled');
}
}

const agentRoutes = buildAgentRoutes(this.service, agentRuntime, ctx.logger, { quota: chatQuota });
routes.push(...agentRoutes);
ctx.logger.info(`[AI] Agent routes registered (${agentRoutes.length} routes)`);

Expand Down
Loading