Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix: enforce routine ownership and preserve busy retries

Chris070c2756bed0
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 7e73c9ea2b..d90ff51029 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -246,7 +246,6 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
logger: createLogger('mcp/cindy_slack'),
},
scheduler: {
- routines: routineTools,
getScheduler: () => getScheduler(),
// 前置检查脚本统一安装服务:落盘路径/协议/自测与 UI「AI 生成」共用同一实现
// (hook-script-generator)。lazy import:该链上有 electron app 依赖,且 maker
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index fce40d1873..5153a1b73b 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -14,7 +14,7 @@ const mock = vi.hoisted(() => ({
]),
},
scheduler: {
- runNow: vi.fn(async () => ({ runId: 'execution' })),
+ runNow: vi.fn(async (): Promise<{ runId: string; deferred?: boolean }> => ({ runId: 'execution' })),
pause: vi.fn(async () => {}),
delete: vi.fn(async () => {}),
},
@@ -103,3 +103,25 @@ it('restarts after a cancelled account transition instead of returning a stopped
mock.boundaryPending = false;
expect(await getRoutineEngine()).not.toBe(first);
});
+
+it('keeps a busy batch queued for 30 seconds and then executes it once', async () => {
+ vi.useFakeTimers();
+ mock.scheduler.runNow.mockResolvedValueOnce({ runId: 'busy', deferred: true });
+ const routine = await routineTools.save('bot', {
+ name: 'Review', prompt: 'Check the PR', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ });
+ await routineTools.runNow('bot', routine.id);
+ await vi.advanceTimersByTimeAsync(0);
+ const pending = (await routineTools.history('bot', routine.id))[0];
+ expect(pending.status).toBe('queued');
+ expect(mock.scheduler.runNow).toHaveBeenCalledWith(`routine-${routine.id}`, { deferToCaller: true });
+ expect(mock.scheduler.pause).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(29000);
+ expect(mock.scheduler.runNow).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mock.scheduler.runNow).toHaveBeenCalledTimes(2);
+ const history = await routineTools.history('bot', routine.id);
+ expect(history).toHaveLength(1);
+ expect(history[0]).toMatchObject({ id: pending.id, status: 'success', resultText: 'Reviewed PR' });
+});
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 5b265dee1e..678bff8657 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -84,16 +84,13 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
};
signal.addEventListener('abort', abort, { once: true });
try {
- const result = await scheduler.runNow(id);
+ const result = await scheduler.runNow(id, { deferToCaller: true });
assertScope(scope);
+ // The routine queue owns this batch and its retry delay, not the backing schedule.
+ if (result.deferred) return { deferred: true };
const rows = await storage.listRuns(id, 10);
const completed = rows.find((row) => row.id === result.runId);
- if (!completed) {
- // The existing runner deferred because the canonical task is busy. Keep retry ownership
- // in the routine queue; never let the backing schedule replay a stale event batch.
- await scheduler.pause(id);
- return { deferred: true };
- }
+ if (!completed) throw new Error('Routine execution record is missing');
return {
scheduleRunId: result.runId,
resultText: completed.resultText,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
index c62f8cfd52..621a8f11b4 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -1251,6 +1251,20 @@ describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
expect(harness.send).not.toHaveBeenCalled();
});
+ it.each([false, true])('manual busy dispatch defers only when the caller owns retries: %s', async (deferToCaller) => {
+ const harness = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true, hasQueued: true });
+ const { runner } = createRunnerHarness(harness.session, queue.deps);
+ const result = runner.fire(
+ heartbeatSchedule({ manual: true, source: 'bot' }),
+ { ...createFireContext(), deferToCaller },
+ );
+ if (deferToCaller) await expect(result).resolves.toMatchObject({ deferred: true });
+ else await expect(result).rejects.toThrow('HEARTBEAT_ALREADY_QUEUED');
+ expect(queue.enqueueCalls).toHaveLength(0);
+ expect(harness.send).not.toHaveBeenCalled();
+ });
+
it('settles the run as aborted-style failure when the queued prompt is discarded', async () => {
const harness = createSessionHarness(async () => ({ accepted: true }));
const queue = createQueueHarness({ busy: true });
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 3fc8f52fe4..1926d1eef8 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -462,7 +462,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
* (review #944 第十九轮 P1;本函数原来的注释已经把 manual 算在排除项里,代码没跟上)。
* 排除后走可见失败:用户知道这次没跑成,可以自己再点一次,不会莫名多出自动运行。
*/
- private canDefer(schedule: Schedule): boolean {
+ private canDefer(schedule: Schedule, ctx: FireContext): boolean {
+ // RoutineEngine explicitly owns retries; no nextFireAt is armed in this mode.
+ if (ctx.deferToCaller) return true;
return schedule.recurring === true && schedule.status === 'active' && schedule.manual !== true;
}
@@ -472,7 +474,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
sessionId: string,
allowDefer: boolean,
): Promise<FireResult> {
- if (allowDefer && this.canDefer(schedule)) {
+ if (allowDefer && this.canDefer(schedule, ctx)) {
return this.deferFire(schedule, sessionId, 'session-running');
}
const sendContext = buildSchedulerSendContext(schedule, ctx, sessionId);
@@ -704,7 +706,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 落点一致,无功能回退,仅 telemetry reason 偏"user-active"。
const recentlyUserDriven =
row?.userSendAt != null && Date.now() - row.userSendAt < ACTIVE_YIELD_WINDOW_MS;
- if (recentlyUserDriven && isSessionInTurn(sessionId) && this.canDefer(schedule)) {
+ if (recentlyUserDriven && isSessionInTurn(sessionId) && this.canDefer(schedule, ctx)) {
holder.releaseAgentSwitchLock?.();
holder.releaseAgentSwitchLock = undefined;
return this.deferFire(schedule, sessionId, 'user-active');
@@ -1572,7 +1574,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// (用户远程控制 / 上轮心跳未完)→ 不记失败,顺延重排。非 heartbeat 是新建
// session,SESSION_RUNNING 属异常,维持原 failed(可见)。先就近摘掉本轮挂
// 的 listener(turnFinished + abort),否则它们持有 session 引用阻止 GC。
- if (isHeartbeat && normalized.reason === 'SESSION_RUNNING' && this.canDefer(schedule)) {
+ if (isHeartbeat && normalized.reason === 'SESSION_RUNNING' && this.canDefer(schedule, ctx)) {
waiter.stopListening();
ctx.signal.removeEventListener('abort', onAbort);
return this.deferFire(schedule, session.id, 'session-running');
@@ -1636,7 +1638,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
ctx: FireContext,
sessionId: string,
): Promise<FireResult> {
- if (this.canDefer(schedule)) {
+ if (this.canDefer(schedule, ctx)) {
return this.deferFire(schedule, sessionId, 'already-queued');
}
const errMsg = formatSchedulerSendError(
@@ -1998,7 +2000,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
if ('retry' in enqueueResult) {
// 崩溃恢复快照尚未成功读回 → 持久化去重做不了,顺延本次 fire(90s 后重试,
// 届时恢复多半已完成);一次性任务无法顺延,按可见失败收口。
- if (this.canDefer(schedule)) {
+ if (this.canDefer(schedule, ctx)) {
return this.deferFire(schedule, sessionId, 'queue-restore-pending');
}
const errMsg = formatSchedulerSendError(
@@ -2135,7 +2137,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 若空闲就直发,槽位届时也可能腾出来)。
// 不能顺延的(一次性 / manual / 已 paused)退回可见失败,否则任务静默消失。
if (err instanceof QueuedDispatchTimeoutError || err instanceof QueuedSlotUnavailableError) {
- if (this.canDefer(schedule)) {
+ if (this.canDefer(schedule, ctx)) {
return this.deferFire(schedule, sessionId, 'queue-wait-timeout');
}
const errMsg = formatSchedulerSendError(
diff --git a/apps/desktop/src/shared/__tests__/ghost.routineEvents.test.ts b/apps/desktop/src/shared/__tests__/ghost.routineEvents.test.ts
index 63507b734c..6b19d7b396 100644
--- a/apps/desktop/src/shared/__tests__/ghost.routineEvents.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.routineEvents.test.ts
@@ -23,6 +23,16 @@ describe.each([
expect(result.ok).toBe(true);
if (result.ok) expect(result.manifest.routineEvents).toBeUndefined();
});
+ it('accepts legacy v2 plugins but rejects their v3-only event capability', () => {
+ const legacy = { ...manifest, schemaVersion: 2, slots: [] };
+ expect(validate(legacy).ok).toBe(true);
+ const rejected = validate({
+ ...legacy,
+ routineEvents: { events: [{ type: 'new', name: 'New', fields: [] }] },
+ });
+ expect(rejected.ok).toBe(false);
+ if (!rejected.ok) expect(rejected.reason).toContain('schemaVersion 3');
+ });
it('roundtrips declared event types and rejects invalid declarations', () => {
const routineEvents = {
events: [{ type: 'message.new', name: 'New Message', fields: ['channel'] }],
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 70f3d9b371..30515dbb4c 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -4820,6 +4820,9 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
// 订阅槽详单(卡槽①):与 slots 含 'subscribe' 成对(有详单必有槽;有槽
// 无详单允许装入但零事件,同 cindy 语义)。硬规则:声明了 hooks(拦截)
// 必须 launch:'resident'——要挡路就得常驻在场,每条消息等冷启动不可接受。
+ if (raw.routineEvents !== undefined && prepared.schemaVersion !== 3) {
+ return { ok: false, reason: 'routineEvents requires schemaVersion 3' };
+ }
const routineEvents = raw.routineEvents === undefined ? undefined : parseGhostRoutineEvents(raw.routineEvents);
if (routineEvents === null) return { ok: false, reason: 'Invalid routineEvents declaration' };
let subscribe: GhostSubscribeNeeds | undefined;
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index f85d73b837..a4be8bf81d 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -15,11 +15,11 @@
- `@cindy/maker-scheduler`:例行任务校验、匹配、去重、串行落盘和运行状态机。纯逻辑,不依赖 Electron。
- Desktop routines service:按当前账号保存本地文件,解析伙伴当前的长期任务,调用现有调度执行器。
- 插件:第三方身份认证、长连接、消息订阅或本地采集。向宿主报告事件,不指定伙伴、指令或执行权限。
-- UI / MCP / 手机资源:共用管理服务,不能冒充事件来源。MCP 管理工具只有宿主注入对应能力时才出现。
+- UI / MCP / 手机资源:共用管理服务,不能冒充事件来源。MCP 管理仅走宿主绑定调用者身份的伙伴必备工具;通用 scheduler MCP 不提供可任意指定 botId 的例行任务入口。
所有执行复用伙伴 canonical task,继承模型、技能和实际权限,包括冷恢复时的权限。合成触发消息不作为用户聊天消息展示;有成果的输出由已有伙伴消息链呈现,空转复用静默策略。每条例行任务最多一个正在执行的运行;等待中的新事件合并为一批。不同规则共享伙伴时,由既有任务队列串行派发。
-伙伴忙碌导致的 deferred 保留同一待执行批次,30 秒后重试;不能由旧 backing schedule 另行重放旧事件。已开始的执行失败不会自动重做,避免重复外部副作用。暂停或删除取消等待项并中止当前运行;修改规则取消旧版本等待项,下一次事件按新规则匹配。
+伙伴忙碌导致的 deferred 保留同一待执行批次,30 秒后重试;宿主通过 runNow 的内部 deferToCaller 选项领取重试责任,底层不设置重试时间,不能由旧 backing schedule 另行重放旧事件。普通手动调度保持原有忙碌失败语义。已开始的执行失败不会自动重做,避免重复外部副作用。暂停或删除取消等待项并中止当前运行;修改规则取消旧版本等待项,下一次事件按新规则匹配。
重启时保留已接收事件的去重记录和等待队列;中断前标记 running 的记录转为 interrupted,不自动重放,因为无法断言模型是否已经产生外部副作用。运行历史保留触发来源、事件标识、版本、状态、结果和错误。去重回执、队列和规则在同一账号文件中原子提交,落盘失败不回复成功。当前历史不按条数自动删除。
diff --git a/packages/lizi-mcps/src/__tests__/botRoutineTools.test.ts b/packages/lizi-mcps/src/__tests__/botRoutineTools.test.ts
index 1bdc6c4919..9ff872f0a9 100644
--- a/packages/lizi-mcps/src/__tests__/botRoutineTools.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botRoutineTools.test.ts
@@ -56,3 +56,24 @@ it('does not access the native service for an unbound caller', async () => {
expect(resolveBotId).not.toHaveBeenCalled();
expect(list).not.toHaveBeenCalled();
});
+
+it('rejects unrelated and background callers before reaching any routine operation', async () => {
+ const registry = new XdtHelperToolRegistry();
+ const operation = vi.fn();
+ const service: BotRoutineCallbacks['service'] = {
+ list: operation, sources: operation, save: operation,
+ history: operation, remove: operation, runNow: operation,
+ };
+ registerBotRoutineTools(registry, {
+ service, resolveBotId: async () => { throw new Error('not canonical'); },
+ }, () => 'ordinary-background-session');
+ for (const name of ['routine_list', 'routine_sources', 'routine_history', 'routine_delete', 'routine_run_now']) {
+ const args = ['routine_list', 'routine_sources'].includes(name) ? {} : { id: 'routine' };
+ expect((await registry.call(name, args)).isError).toBe(true);
+ }
+ expect((await registry.call('routine_save', {
+ name: 'Other', prompt: 'Do work', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ })).isError).toBe(true);
+ expect(operation).not.toHaveBeenCalled();
+});
diff --git a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
index 97fd5c3ccb..dd4006f6e1 100644
--- a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
@@ -261,6 +261,16 @@ describe('cindy_scheduler MCP server (in-process smoke)', () => {
await h.cleanup();
});
+ it('rejects arbitrary-bot routine management on the general scheduler surface', async () => {
+ for (const name of ['routine_list', 'routine_sources', 'routine_save', 'routine_history', 'routine_delete', 'routine_run_now']) {
+ const result = await h.client.callTool({
+ name: 'call_tool', arguments: { name, args: { botId: 'another-bot', id: 'routine' } },
+ });
+ expect(result.isError).toBe(true);
+ }
+ await h.cleanup();
+ });
+
it('call_tool(schedule_create) creates a schedule and call_tool(schedule_list) returns it (same payload as scheduler.list)', async () => {
// schedule_create
const created = await h.client.callTool({
diff --git a/packages/lizi-mcps/src/__tests__/routineTools.test.ts b/packages/lizi-mcps/src/__tests__/routineTools.test.ts
index 68fb79211c..da699fb656 100644
--- a/packages/lizi-mcps/src/__tests__/routineTools.test.ts
+++ b/packages/lizi-mcps/src/__tests__/routineTools.test.ts
@@ -1,17 +1,17 @@
import { expect, it, vi } from "vitest";
import { SchedulerToolRegistry } from "../cindy_schedulerToolRegistry.js";
import { registerRoutineTools } from "../scheduler/routines.js";
-import type { SchedulerMcpDeps } from "../types.js";
+import type { RoutineToolService } from "../types.js";
it("exposes local management only when supported and propagates the host error", async () => {
const registry = new SchedulerToolRegistry();
- registerRoutineTools(registry, {} as SchedulerMcpDeps);
+ registerRoutineTools(registry, {});
expect(registry.list()).toHaveLength(0);
const save = vi.fn(async () => {
throw new Error("Teammate not found");
});
registerRoutineTools(registry, {
routines: { save },
- } as unknown as SchedulerMcpDeps);
+ } as unknown as { routines: RoutineToolService });
expect(registry.list().map((tool) => tool.name)).toEqual([
"routine_list",
"routine_sources",
diff --git a/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts b/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts
index 25b4d0af9e..164521677f 100644
--- a/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts
@@ -1,4 +1,3 @@
-import { registerRoutineTools } from './scheduler/routines.js';
/**
* cindy_schedulerMcpServer.ts
* ---------------------------------------------------------------------------
@@ -180,7 +179,6 @@ export function createSchedulerMcpServer(
// 注册顺序 = list_tools 里的位次。读优先 → 写次之 → 危险写在最后。
registerScheduleListTool(registry, deps);
- registerRoutineTools(registry, deps);
registerScheduleGetTool(registry, deps);
registerScheduleListRunsTool(registry, deps);
// create / update 都注入 ctx:bindToCurrentSession 据 sessionId 自动填 targetSessionId,
diff --git a/packages/lizi-mcps/src/scheduler/routines.ts b/packages/lizi-mcps/src/scheduler/routines.ts
index e24ee11bc4..882fa0346d 100644
--- a/packages/lizi-mcps/src/scheduler/routines.ts
+++ b/packages/lizi-mcps/src/scheduler/routines.ts
@@ -1,11 +1,11 @@
import { z } from "zod";
-import type { SchedulerMcpDeps } from "../types.js";
+import type { RoutineToolService } from "../types.js";
import type { SchedulerToolRegistry } from "../cindy_schedulerToolRegistry.js";
/** Routine tools share the UI's host service and do not expose event-source impersonation. */
export function registerRoutineTools(
registry: SchedulerToolRegistry,
- deps: Pick<SchedulerMcpDeps, "routines">,
+ deps: { routines?: RoutineToolService },
): void {
if (!deps.routines) return;
const service = deps.routines;
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 5f56f1976b..f58876978c 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -203,6 +203,16 @@ export interface SlackHookMcpDeps {
logger?: LiziMcpLogger;
}
+/** Native routine service; only caller-bound companion tools expose it to agents. */
+export interface RoutineToolService {
+ list(botId: string): Promise<import('@cindy/maker-scheduler').Routine[]>;
+ sources(): Promise<import('@cindy/maker-scheduler').RoutineSource[]>;
+ save(botId: string, input: import('@cindy/maker-scheduler').RoutineInput, id?: string): Promise<import('@cindy/maker-scheduler').Routine>;
+ history(botId: string, id: string): Promise<import('@cindy/maker-scheduler').RoutineRun[]>;
+ remove(botId: string, id: string): Promise<void>;
+ runNow(botId: string, id: string): Promise<void>;
+}
+
/**
* Host injects a `getScheduler()` accessor — the cindy_scheduler MCP server
* never holds a long-lived Scheduler reference because the host may
@@ -215,14 +225,6 @@ export interface SlackHookMcpDeps {
* @cindy/maker-scheduler still has zero runtime deps per Phase 1).
*/
export interface SchedulerMcpDeps {
- routines?: {
- list(botId: string): Promise<import('@cindy/maker-scheduler').Routine[]>;
- sources(): Promise<import('@cindy/maker-scheduler').RoutineSource[]>;
- save(botId: string, input: import('@cindy/maker-scheduler').RoutineInput, id?: string): Promise<import('@cindy/maker-scheduler').Routine>;
- history(botId: string, id: string): Promise<import('@cindy/maker-scheduler').RoutineRun[]>;
- remove(botId: string, id: string): Promise<void>;
- runNow(botId: string, id: string): Promise<void>;
- };
getScheduler(): import('@cindy/maker-scheduler').Scheduler;
/**
* 前置检查脚本(preRunHook)统一安装服务(host 注入,desktop 实现为
diff --git a/packages/lizi-mcps/src/xdt-helper/botRoutineTools.ts b/packages/lizi-mcps/src/xdt-helper/botRoutineTools.ts
index 093b9feae3..77c358954b 100644
--- a/packages/lizi-mcps/src/xdt-helper/botRoutineTools.ts
+++ b/packages/lizi-mcps/src/xdt-helper/botRoutineTools.ts
@@ -1,11 +1,11 @@
import { SchedulerToolRegistry } from '../cindy_schedulerToolRegistry.js';
import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
import { registerRoutineTools } from '../scheduler/routines.js';
-import type { SchedulerMcpDeps } from '../types.js';
+import type { RoutineToolService } from '../types.js';
export interface BotRoutineCallbacks {
resolveBotId(callerSessionId: string): Promise<string>;
- service: NonNullable<SchedulerMcpDeps['routines']>;
+ service: RoutineToolService;
}
/** Same native service/schema as automation, scoped to the calling companion. */
diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
index 116a0c2125..92c3f6e4de 100644
--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts
+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
@@ -4421,3 +4421,27 @@ describe('Scheduler: attempt 生命周期状态机(#1016)', () => {
await h.scheduler.stop();
});
});
+
+describe('caller-owned deferred dispatch', () => {
+ it('returns deferred without arming a manual schedule or recording a failure', async () => {
+ const h = makeHarness({ runnerImpl: async (_schedule, ctx) => {
+ expect(ctx.deferToCaller).toBe(true);
+ return { sessionId: 'bot-task', deferred: true, deferRetryMs: 1000 };
+ } });
+ const schedule = await h.scheduler.create({ ...baseInput, manual: true });
+ await h.scheduler.start();
+ const failed = vi.fn();
+ h.scheduler.on('failed', failed);
+ const result = await h.scheduler.runNow(schedule.id, { deferToCaller: true });
+ expect(result.deferred).toBe(true);
+ expect(await h.storage.listRuns(schedule.id)).toEqual([]);
+ expect(await h.storage.get(schedule.id)).toMatchObject({
+ nextFireAt: undefined, lastFiredAt: undefined,
+ });
+ h.clock.advance(120000);
+ await h.scheduler.tick();
+ expect(h.runner.fire).toHaveBeenCalledTimes(1);
+ expect(failed).not.toHaveBeenCalled();
+ await h.scheduler.stop();
+ });
+});
diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.ts
index 98bebaaf68..c45b5e3d25 100644
--- a/packages/maker-scheduler/src/engine/scheduler.ts
+++ b/packages/maker-scheduler/src/engine/scheduler.ts
@@ -1006,7 +1006,9 @@ export class Scheduler extends EventEmitter {
// - 副作用:recurring=false 的任务被手动 runNow 后 lastFiredAt 落地,
// 重启 app 时 computeNextFireAt 会返回 undefined → 不会再被 cron 触发。
// 这反而更贴合"Once"语义:用户手动跑过一次就视作用完。
- async runNow(id: string): Promise<{ runId: string }> {
+ // Internal callers with their own durable queue may own the deferred retry.
+ // This option is not exposed through schedule CRUD or public MCP arguments.
+ async runNow(id: string, options?: { deferToCaller?: boolean }): Promise<{ runId: string; deferred?: boolean }> {
// 手动触发不受并发闸门拦截(用户显式动作要即时响应),但计入 in-flight 占用,
// 会挤压后续自动触发的槽位。
const runId = this.generateId();
@@ -1017,13 +1019,13 @@ export class Scheduler extends EventEmitter {
phase: 'loading',
});
try {
- return await this.runNowInner(id, runId);
+ return await this.runNowInner(id, runId, options);
} finally {
this.finishInflightAttempt(runId);
}
}
- private async runNowInner(id: string, runId: string): Promise<{ runId: string }> {
+ private async runNowInner(id: string, runId: string, options?: { deferToCaller?: boolean }): Promise<{ runId: string; deferred?: boolean }> {
const schedule = await this.storage.get(id);
if (!schedule) throw new Error(`Schedule not found: ${id}`);
this.updateInflightAttempt(runId, 'persisting', schedule);
@@ -1083,6 +1085,7 @@ export class Scheduler extends EventEmitter {
const result = await this.runner.fire(schedule, {
runId,
firedAt,
+ deferToCaller: options?.deferToCaller,
signal: controller.signal,
onSessionBound: this.buildOnSessionBound(schedule.id, runId),
onPreRunHookCompleted: this.buildOnPreRunHookCompleted(runId),
@@ -1119,6 +1122,7 @@ export class Scheduler extends EventEmitter {
// 顺延(手动触发撞忙也礼让,与 cron 路径一致):撤销预插的 running run、不通知。
// runNow 正常路径不动 nextFireAt;但顺延必须把 nextFireAt 前移到短延后,让 cron
// tick 在会话空闲后接力真跑(否则手动触发撞忙就石沉大海)。
+ // deferToCaller 由宿主持久队列接力,保留原 nextFireAt,不建立第二个重试来源。
if (deferred && !wasAborted) {
try {
await this.storage.deleteRun(runId);
@@ -1133,7 +1137,7 @@ export class Scheduler extends EventEmitter {
// ② 对 recurring=false 的 Once 任务,lastFiredAt 一旦落地,重启时
// computeNextFireAt 会因 lastFiredAt 已设而返回 undefined → 顺延的重试被吞掉。
const updated = await this.storage.update(schedule.id, {
- nextFireAt: retryAt,
+ nextFireAt: options?.deferToCaller ? schedule.nextFireAt : retryAt,
lastFiredAt: schedule.lastFiredAt,
});
if (updated && updated.status === 'active') {
@@ -1142,7 +1146,7 @@ export class Scheduler extends EventEmitter {
// 'deferred' 配对先前的 'fired'(清 UI running 态、不留可见 run);'changed' revalidate。
this.emitEvent({ type: 'deferred', scheduleId: schedule.id, runId });
this.emitEvent({ type: 'changed', scheduleId: schedule.id });
- return { runId };
+ return { runId, deferred: true };
}
if (stallAborted) {
diff --git a/packages/maker-scheduler/src/interfaces/schedule-runner.ts b/packages/maker-scheduler/src/interfaces/schedule-runner.ts
index 7d65c1b763..7140b6cb4a 100644
--- a/packages/maker-scheduler/src/interfaces/schedule-runner.ts
+++ b/packages/maker-scheduler/src/interfaces/schedule-runner.ts
@@ -10,6 +10,8 @@ export interface ChildRunInput {
export interface FireContext {
runId: string;
firedAt: number;
+ /** Host caller owns deferred retries; never schedule a cron replay for this attempt. */
+ deferToCaller?: boolean;
/**
* 由 Scheduler 创建并 own 的 AbortSignal。当用户在 UI 上 delete/pause 这条 schedule 时,
* Scheduler 会对所有 in-flight 的 runner.fire() 触发 abort。
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index 0d8bd4412b..70723067e2 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -419,7 +419,8 @@ export class RoutineEngine {
this.retryAfter.set(run.routineId, this.deps.now() + 30_000);
return;
}
- const { deferred: _deferred, ...completed } = result;
+ const completed = { ...result };
+ delete completed.deferred;
Object.assign(run, completed, {
status: controller.signal.aborted
? "cancelled"
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index c6d8c77660..40ec213471 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -1906,6 +1906,9 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
// 订阅槽详单(卡槽①):与 slots 含 'subscribe' 成对(有详单必有槽;有槽
// 无详单允许装入但零事件,同 cindy 语义)。硬规则:声明了 hooks(拦截)
// 必须 launch:'resident'——要挡路就得常驻在场,每条消息等冷启动不可接受。
+ if (raw.routineEvents !== undefined && prepared.schemaVersion !== 3) {
+ return { ok: false, reason: 'routineEvents requires schemaVersion 3' };
+ }
const routineEvents = raw.routineEvents === undefined ? undefined : parseGhostRoutineEvents(raw.routineEvents);
if (routineEvents === null) return { ok: false, reason: 'Invalid routineEvents declaration' };
let subscribe: GhostSubscribeNeeds | undefined;