Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): bound routine requests before engine readiness
Chriseec2a494ea2f
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.tsindex a3e5bd4c7a..b3ba2753b9 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts@@ -195,3 +195,129 @@ it('keeps fixed validation and retry guidance without logging repeated expectedexpect(warn).not.toHaveBeenCalled();await f.engine.stop();});++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+}++const listening = { action: 'status', status: 'listening' };+const publish = { action: 'publish', event: { id: 'startup-event', type: 'new', occurredAt: 1, data: {} } };+const busy = { ok: false, message: 'Routine request intake is busy; retry later' };++it('bounds mixed status/publish requests before startup and cannot bypass a plugin quota by self-reporting identity', async () => {+ const f = await statusFixture();+ const ready = deferred<RoutineEngine>();+ const getEngine = vi.fn(() => ready.promise);+ const request = (payload: unknown, plugin = ghost) => handleRoutineRequest(plugin, payload, getEngine, () => true);+ const pending = Array.from({ length: 8 }, (_, i) => request(i % 2 ? publish : listening));+ try {+ for (let i = 0; i < 20; i++) {+ expect(await request({ ...listening, sourceId: `forged-${i}` })).toEqual(busy);+ expect(await request({ ...publish, botId: `forged-${i}` })).toEqual(busy);+ }+ expect(getEngine).toHaveBeenCalledTimes(8);+ const other = { ...ghost, manifest: { ...ghost.manifest, id: 'other' } };+ pending.push(request(listening, other));+ expect(getEngine).toHaveBeenCalledTimes(9);+ } finally {+ ready.resolve(f.engine);+ expect((await Promise.all(pending)).every((reply) => reply.ok)).toBe(true);+ await f.engine.stop();+ }+});++it('caps all plugin startup requests at 32 and returns every slot after success', async () => {+ const f = await statusFixture();+ const ready = deferred<RoutineEngine>();+ const getEngine = vi.fn(() => ready.promise);+ const plugin = (i: number) => ({ ...ghost, manifest: { ...ghost.manifest, id: `startup-${i}` } });+ const pending = Array.from({ length: 32 }, (_, i) =>+ handleRoutineRequest(plugin(Math.floor(i / 8)), listening, getEngine, () => true));+ try {+ expect(await handleRoutineRequest(plugin(4), publish, getEngine, () => true)).toEqual(busy);+ expect(getEngine).toHaveBeenCalledTimes(32);+ ready.resolve(f.engine);+ expect((await Promise.all(pending)).every((reply) => reply.ok)).toBe(true);+ // Refill all slots, not just one, to catch counter leaks after settled requests.+ const retry = Array.from({ length: 32 }, (_, i) =>+ handleRoutineRequest(plugin(Math.floor(i / 8)), listening, getEngine, () => true));+ expect((await Promise.all(retry)).every((reply) => reply.ok)).toBe(true);+ } finally {+ ready.resolve(f.engine);+ await Promise.all(pending);+ await f.engine.stop();+ }+});++it.each(['startup failure', 'owner changed', 'publisher failure'])('releases all reserved slots after %s', async (failure) => {+ const f = await statusFixture();+ const ready = deferred<RoutineEngine>();+ let current = true;+ const pending = Array.from({ length: 8 }, () => handleRoutineRequest(+ ghost, failure === 'publisher failure' ? publish : listening, () => ready.promise, () => current,+ ));+ try {+ if (failure === 'startup failure') ready.reject(new Error('startup failed'));+ else {+ if (failure === 'owner changed') current = false;+ // Publish fails because this engine has no listening source.+ ready.resolve(f.engine);+ }+ expect((await Promise.all(pending)).every((reply) => !reply.ok)).toBe(true);+ const retry = Array.from({ length: 8 }, () => f.request(listening));+ expect((await Promise.all(retry)).every((reply) => reply.ok)).toBe(true);+ } finally {+ ready.resolve(f.engine);+ await Promise.all(pending);+ await f.engine.stop();+ }+});++it('rejects invalid operations and oversized events without waiting for startup or leaking slots', async () => {+ const getEngine = vi.fn();+ const invalid = [+ { action: 'unknown' },+ { action: 'status', status: 'unknown' },+ { action: 'publish', event: { ...publish.event, data: { oversized: 'x'.repeat(8001) } } },+ { action: 'publish', event: { ...publish.event, data: Object.fromEntries(Array.from({ length: 5 }, (_, i) => [`field${i}`, 'x'.repeat(8000)])) } },+ ];+ for (let i = 0; i < 12; i++) {+ for (const payload of invalid) {+ const reply = await handleRoutineRequest(ghost, payload, getEngine, () => true);+ expect(reply.ok).toBe(false);+ expect(reply).not.toEqual(busy);+ }+ }+ expect(getEngine).not.toHaveBeenCalled();+});++it('keeps slots reserved until publish finishes, not only until the engine is ready', async () => {+ const saved = deferred<void>();+ const save = vi.fn(async () => {});+ const engine = new RoutineEngine({+ load: async () => null, save, execute: vi.fn(async () => ({})),+ id: () => 'id', now: () => 1, changed: vi.fn(), onError: vi.fn(),+ });+ await engine.start();+ const getEngine = vi.fn(async () => engine);+ const request = (payload: unknown) => handleRoutineRequest(ghost, payload, getEngine, () => true);+ await request(listening);+ save.mockClear();+ save.mockImplementationOnce(() => saved.promise);+ const pending = Array.from({ length: 8 }, (_, i) => request({ ...publish, event: { ...publish.event, id: `slow-${i}` } }));+ try {+ await vi.waitFor(() => expect(save).toHaveBeenCalled());+ expect(await request(listening)).toEqual(busy);+ expect(getEngine).toHaveBeenCalledTimes(9);+ saved.resolve();+ expect((await Promise.all(pending)).every((reply) => reply.ok)).toBe(true);+ expect(await request(listening)).toEqual({ ok: true });+ } finally {+ saved.resolve();+ await Promise.all(pending);+ await engine.stop();+ }+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 4751fec879..72c501be48 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1478,6 +1478,7 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册返回 {ok:true,accepted,duplicate} 表示事件已持久接收(accepted 是匹配例行任务数),不代表模型已运行或业务已成功。ok:false 时保留投递 ID,按退避重试;不可假报已处理。多条件 OR 命中只入队一次;运行期间的新事件可合并进下一轮。重启不自动重放已经开始、结果未知的执行,以免重复外部副作用。时间与事件共用运行历史。去重针对投递身份,业务对象已完成与否仍由任务指令和工具记录判断。宿主硬上限:单插件每 60 秒最多 60 次发布,全账号最多 240 次;待处理发布请求分别最多 8 和 32。+管子入口在等待引擎或数据库就绪前预留并发额度:状态与事件请求合计单插件最多 8 个、整个宿主最多 32 个,跨引擎重建保留计数,直到请求完成或失败才归还。无效操作、状态和超大事件在等待前拒绝;超额请求立即返回可重试错误,不进入等待队列。去重窗口为 24 小时,回执按 UTF-8 JSON 限制为单插件 256 KiB、账号 2 MiB;超限返回 ok:false,应保留原 event.id 稍后重试,不要改 ID 或紧密循环重试。容量满时不会驱逐窗口内回执;旧版过量回执在启动时保留最新的有界部分。事件运行历史不受回执清理影响。diff --git a/apps/desktop/src/main/cindy-brain/routineSlot.ts b/apps/desktop/src/main/cindy-brain/routineSlot.tsindex 7e15b03ba0..d8874a5139 100644--- a/apps/desktop/src/main/cindy-brain/routineSlot.ts+++ b/apps/desktop/src/main/cindy-brain/routineSlot.ts@@ -1,9 +1,28 @@import type { InstalledGhost } from '../../shared/ghost.js';-import type { RoutineEngine } from '@cindy/maker-scheduler';+import { parseRoutineEvent, type RoutineEngine } from '@cindy/maker-scheduler';import { createLogger } from '../logger.js';const log = createLogger('routines:plugin');+// Host-wide, across engine startup/replacement: status and publish share these slots.+// Engine-local rate and persistence quotas remain independent of this outer concurrency bound.+const pendingByPlugin = new Map<string, number>();+let totalPending = 0;++function reserveRequest(pluginId: string): () => void {+ const pending = pendingByPlugin.get(pluginId) ?? 0;+ if (pending >= 8 || totalPending >= 32)+ throw new Error('Routine request intake is busy; retry later');+ pendingByPlugin.set(pluginId, pending + 1);+ totalPending += 1;+ return () => {+ const remaining = pendingByPlugin.get(pluginId)! - 1;+ if (remaining) pendingByPlugin.set(pluginId, remaining);+ else pendingByPlugin.delete(pluginId);+ totalPending -= 1;+ };+}+// Exact host-authored rejections only. Never echo arbitrary storage errors across the plugin boundary.const PUBLIC_REJECTIONS = ['Routine request rate limit reached; retry after 60 seconds',@@ -38,13 +57,19 @@ export async function handleRoutineRequest(if (!payload || typeof payload !== 'object' || Array.isArray(payload))return { ok: false, message: 'Invalid routine request' };const request = payload as Record<string, unknown>;+ let release: (() => void) | undefined;try {+ release = reserveRequest(ghost.manifest.id);+ if (request.action !== 'status' && request.action !== 'publish')+ return { ok: false, message: 'Unknown routine operation' };+ if (request.action === 'status' && !['listening', 'disconnected', 'error'].includes(String(request.status)))+ return { ok: false, message: 'Invalid source status' };+ // Reject malformed/oversized events before any startup wait, using the engine's validator.+ const event = request.action === 'publish' ? parseRoutineEvent(request.event) : undefined;const engine = await getEngine();if (!isCurrent()) return { ok: false, message: 'Plugin owner or installation changed' };const sourceId = `plugin:${ghost.manifest.id}`;if (request.action === 'status') {- if (!['listening', 'disconnected', 'error'].includes(String(request.status)))- return { ok: false, message: 'Invalid source status' };engine.registerSource({id: sourceId,name: ghost.manifest.name,@@ -53,8 +78,7 @@ export async function handleRoutineRequest(});return { ok: true };}- if (request.action !== 'publish') return { ok: false, message: 'Unknown routine operation' };- return { ok: true, ...(await engine.publish(sourceId, request.event, isCurrent)) };+ return { ok: true, ...(await engine.publish(sourceId, event, isCurrent)) };} catch (error) {const publicMessage = error instanceof Error? PUBLIC_REJECTIONS.find((message) => message === error.message)@@ -68,5 +92,7 @@ export async function handleRoutineRequest(ok: false,message: 'Routine request failed; please retry later',};+ } finally {+ release?.();}}diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.mdindex 9bbdbb138c..e8158b2bec 100644--- a/docs/product-rules/bot-routines.md+++ b/docs/product-rules/bot-routines.md@@ -90,6 +90,8 @@ const receipt = await cindy.routines.request({事件源状态上报使用独立限额:单来源每 60 秒最多 60 次、全账号最多 240 次,重复状态也计入频率。名称、状态及事件声明均未变时直接返回,不广播或清空最近事件时间;真实变化才通知界面。宿主发现插件断开不受插件上报额度限制,重复断开也不广播。+插件管子在等待引擎/数据库就绪前同步预留并发额度:状态和事件请求合计单插件最多 8 个、整个宿主最多 32 个;计数跨引擎重建保留,覆盖启动等待及实际发布,直到成功、失败或取消返回后归还。超额请求立即拒绝,不保留额外等待队列。操作、状态和事件体量沿用现有校验,在等待前拒绝无效请求;引擎内部的频率与落盘限额继续独立生效。+插件失败回执只返回固定公开文案:校验和容量/频率拒绝按精确白名单保留提示;未知异常统一回复通用重试提示,详细异常只进入 Main 日志,不携带文件路径或事件数据返回插件。写盘失败后的原事件 ID 仍可重试,成功持久化后才进入去重窗口。本协议不要求第三方连接器的固定组合:飞书长连接、Gmail 本地采集和 GitHub 事件适配器都可报告相同形态的事件。本次交付的是宿主接入与执行能力,不会自动给现有飞书/Gmail 插件增加第三方订阅;适配器需按上述协议接入。