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(bots): bound routine envelopes and require stable permissions

Chrisaeaa88595d17
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts
index b3ba2753b9..583609014d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts
@@ -207,6 +207,38 @@ 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 the entire request including ignored fields before waiting, with UTF-8 accounting', async () => {
+ const getEngine = vi.fn();
+ const invalid: unknown[] = [
+ { ...listening, extra: 'x'.repeat(128 * 1024) },
+ { ...publish, event: { ...publish.event, extra: 'x'.repeat(128 * 1024) } },
+ { ...listening, extra: { nested: '字'.repeat(45_000) } },
+ { ...listening, extra: { ['x'.repeat(128 * 1024)]: true } },
+ { ...listening, extra: new Uint8Array(128 * 1024) },
+ { ...listening, extra: Array(5000).fill(null) },
+ { ...listening, extra: Object.assign([], { hiddenFromJson: 'x'.repeat(128 * 1024) }) },
+ ];
+ const cycle: Record<string, unknown> = { ...listening };
+ cycle.extra = cycle;
+ invalid.push(cycle);
+ for (const payload of invalid) {
+ expect(await handleRoutineRequest(ghost, payload, getEngine, () => true))
+ .toEqual({ ok: false, message: 'Routine request is too large or invalid' });
+ }
+ expect(getEngine).not.toHaveBeenCalled();
+ expect(warn).not.toHaveBeenCalled();
+ const f = await statusFixture();
+ try {
+ // Small ignored fields remain compatible, and rejected payloads did not consume slots.
+ const pending = Array.from({ length: 8 }, () => f.request({ ...listening, extra: { label: '字'.repeat(10_000) } }));
+ expect((await Promise.all(pending)).every((reply) => reply.ok)).toBe(true);
+ const data = Object.fromEntries(Array.from({ length: 4 }, (_, i) => [`field${i}`, '字'.repeat(7900)]));
+ expect(await f.request({ ...publish, event: { ...publish.event, data } })).toMatchObject({ ok: true });
+ } finally {
+ await f.engine.stop();
+ }
+});
+
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>();
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 72c501be48..7f35a11390 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1479,6 +1479,7 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册
宿主硬上限:单插件每 60 秒最多 60 次发布,全账号最多 240 次;待处理发布请求分别最多 8 和 32。
管子入口在等待引擎或数据库就绪前预留并发额度:状态与事件请求合计单插件最多 8 个、整个宿主最多 32 个,跨引擎重建保留计数,直到请求完成或失败才归还。无效操作、状态和超大事件在等待前拒绝;超额请求立即返回可重试错误,不进入等待队列。
+整个请求(含未知字段、字段名和数组附加属性)在等待前受 128 KiB UTF-8 保守预算、4096 个值和 16 层嵌套限制;循环引用、二进制对象等非普通 JSON 数据会被拒绝。小型未知字段仍忽略,data 的 32000 字符限制保持不变。超限返回固定文案 Routine request is too large or invalid,应精简请求后再投递。
去重窗口为 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.ts
index d8874a5139..555d970e40 100644
--- a/apps/desktop/src/main/cindy-brain/routineSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/routineSlot.ts
@@ -1,6 +1,7 @@
import type { InstalledGhost } from '../../shared/ghost.js';
import { parseRoutineEvent, type RoutineEngine } from '@cindy/maker-scheduler';
import { createLogger } from '../logger.js';
+import { Buffer } from 'node:buffer';
const log = createLogger('routines:plugin');
@@ -9,6 +10,45 @@ const log = createLogger('routines:plugin');
const pendingByPlugin = new Map<string, number>();
let totalPending = 0;
+/** Bound the whole JSON envelope, including ignored fields, without serializing a huge value. */
+function validateRequestSize(payload: unknown): void {
+ let remaining = 128 * 1024;
+ let nodes = 4096;
+ const ancestors = new Set<object>();
+ const invalid = () => { throw new Error('Routine request is too large or invalid'); };
+ const spend = (bytes: number) => { remaining -= bytes; if (remaining < 0) invalid(); };
+ const text = (value: string) => {
+ if (value.length > remaining) invalid();
+ spend(Buffer.byteLength(JSON.stringify(value), 'utf8'));
+ };
+ const visit = (value: unknown, depth: number): void => {
+ if (--nodes < 0 || depth > 16) invalid();
+ if (typeof value === 'string') { text(value); return; }
+ if (value == null) { spend(4); return; }
+ if (typeof value === 'boolean') { spend(5); return; }
+ if (typeof value === 'number' && Number.isFinite(value)) { spend(String(value).length); return; }
+ if (typeof value !== 'object' || value === null) return invalid();
+ if (ancestors.has(value)) invalid();
+ ancestors.add(value);
+ spend(2);
+ if (Array.isArray(value)) {
+ if (value.length > nodes) invalid();
+ } else {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) invalid();
+ }
+ // Include enumerable array properties too: structured clone retains them even though JSON ignores them.
+ for (const key in value) {
+ if (!Object.hasOwn(value, key)) continue;
+ text(key);
+ spend(2);
+ visit((value as Record<string, unknown>)[key], depth + 1);
+ }
+ ancestors.delete(value);
+ };
+ visit(payload, 0);
+}
+
function reserveRequest(pluginId: string): () => void {
const pending = pendingByPlugin.get(pluginId) ?? 0;
if (pending >= 8 || totalPending >= 32)
@@ -25,6 +65,7 @@ function reserveRequest(pluginId: string): () => void {
// Exact host-authored rejections only. Never echo arbitrary storage errors across the plugin boundary.
const PUBLIC_REJECTIONS = [
+ 'Routine request is too large or invalid',
'Routine request rate limit reached; retry after 60 seconds',
'Routine request intake is busy; retry later',
'Routine receipt storage is full; retry after receipts expire (24 hours)',
@@ -60,9 +101,10 @@ export async function handleRoutineRequest(
let release: (() => void) | undefined;
try {
release = reserveRequest(ghost.manifest.id);
+ validateRequestSize(request);
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)))
+ if (request.action === 'status' && (typeof request.status !== 'string' || !['listening', 'disconnected', 'error'].includes(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;
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
index 4e27d85266..1c5e4c0979 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
@@ -176,7 +176,7 @@ function createFireContext(): FireContext {
};
}
-function createRunnerHarness(session: Session) {
+function createRunnerHarness(session: Session, overrides: Partial<ConstructorParameters<typeof MakerScheduleRunner>[0]> = {}) {
const notifier: Notifier & { notify: ReturnType<typeof vi.fn> } = {
notify: vi.fn(async () => undefined),
};
@@ -193,6 +193,7 @@ function createRunnerHarness(session: Session) {
getDb: () => ({}) as never,
notifier,
logger,
+ ...overrides,
});
return { runner, notifier, logger, maker };
}
@@ -245,12 +246,14 @@ describe('MakerScheduleRunner background subagent task tracking', () => {
it.each(['ask', 'auto', 'bypassPermissions'])('routine cold resume preserves teammate permission %s and hides the synthetic wake', async (mode) => {
const h = createSessionHarness(acceptingSend());
+ Object.assign(h.session, { stablePermissionModeState: { mode, generation: 0 } });
const { runner, maker } = createRunnerHarness(h.session);
vi.mocked(maker.getSessionMeta).mockResolvedValue({ id: 'bot-session', agentKind: 'claude-code', model: 'claude-sonnet-4-6', workDir: '/repo/project' } as never);
mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: mode, planModeEnabled: true });
const fire = runner.fire(baseSchedule({ source: 'bot', targetSessionId: 'bot-session' }), createFireContext());
await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalled());
expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({ permissionMode: mode, planMode: true, id: 'bot-session' }));
+ expect(mocks.backfillSessionMeta).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.objectContaining({ permissionMode: null }), expect.anything());
expect(h.session.send).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ planMode: true }));
expect(mocks.createMessage.mock.calls[0][1].content).not.toBe('review pending PRs');
expect(mocks.createMessage.mock.calls[0][1].content).toContain('review pending PRs');
@@ -258,6 +261,59 @@ describe('MakerScheduleRunner background subagent task tracking', () => {
await fire;
});
+ it.each(['switching', 'missing snapshot', 'missing plan mode', 'invalid mode', 'durable mismatch'])('defers a routine with %s before creating or sending', async (state) => {
+ const h = createSessionHarness(acceptingSend());
+ Object.assign(h.session, {
+ permissionModeState: { mode: 'bypassPermissions', generation: 0 },
+ stablePermissionModeState: state === 'switching' ? null : { mode: 'bypassPermissions', generation: 0 },
+ });
+ const { runner, maker, notifier } = createRunnerHarness(h.session);
+ vi.mocked(maker.getSession).mockReturnValue(h.session);
+ vi.mocked(maker.getSessionMeta).mockResolvedValue({ id: 'bot-session', agentKind: 'claude-code', model: 'claude-sonnet-4-6', workDir: '/repo/project' } as never);
+ mocks.getSessionFsSnapshot.mockResolvedValue(state === 'missing snapshot' ? null : {
+ permissionMode: state === 'invalid mode' ? 'unknown' : state === 'durable mismatch' ? 'ask' : 'bypassPermissions',
+ ...(state === 'missing plan mode' ? {} : { planModeEnabled: true }),
+ });
+ const result = await runner.fire(baseSchedule({ source: 'bot', manual: true, targetSessionId: 'bot-session' }), { ...createFireContext(), deferToCaller: true });
+ expect(result).toMatchObject({ deferred: true });
+ expect(maker.createSession).not.toHaveBeenCalled();
+ expect(h.session.send).not.toHaveBeenCalled();
+ expect(mocks.createMessage).not.toHaveBeenCalled();
+ expect(notifier.notify).not.toHaveBeenCalled();
+ });
+
+ it.each(['before create', 'before send'])('rechecks routine permission changes %s after async preparation', async (stage) => {
+ const h = createSessionHarness(acceptingSend());
+ Object.assign(h.session, { stablePermissionModeState: { mode: 'bypassPermissions', generation: 0 } });
+ let checks = 0;
+ const { runner, maker, notifier } = createRunnerHarness(h.session, {
+ checkModelRoute: vi.fn(async () => {
+ if (++checks === (stage === 'before create' ? 1 : 2)) {
+ Object.assign(h.session, { stablePermissionModeState: null });
+ vi.mocked(maker.getSession).mockReturnValue(h.session);
+ }
+ return { kind: 'pass' as const };
+ }),
+ });
+ vi.mocked(maker.getSessionMeta).mockResolvedValue({ id: 'bot-session', agentKind: 'claude-code', model: 'claude-sonnet-4-6', workDir: '/repo/project' } as never);
+ mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: 'bypassPermissions', planModeEnabled: true });
+ const result = await runner.fire(baseSchedule({ source: 'bot', targetSessionId: 'bot-session' }), { ...createFireContext(), deferToCaller: true });
+ expect(result).toMatchObject({ deferred: true });
+ expect(maker.createSession).toHaveBeenCalledTimes(stage === 'before create' ? 0 : 1);
+ expect(h.session.send).not.toHaveBeenCalled();
+ expect(mocks.createMessage).not.toHaveBeenCalled();
+ expect(notifier.notify).not.toHaveBeenCalled();
+ // The same routine can run after the new permissions have settled; no failed run is emitted.
+ Object.assign(h.session, { stablePermissionModeState: { mode: 'ask', generation: 1 } });
+ vi.mocked(maker.getSession).mockReturnValue(undefined);
+ mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: 'ask', planModeEnabled: true });
+ const retry = runner.fire(baseSchedule({ source: 'bot', targetSessionId: 'bot-session' }), createFireContext());
+ await vi.waitFor(() => expect(h.session.send).toHaveBeenCalled());
+ expect(maker.createSession).toHaveBeenLastCalledWith(expect.objectContaining({ permissionMode: 'ask', planMode: true }));
+ h.emit({ type: 'done', data: {} });
+ await retry;
+ });
+
it('无后台任务:首个 done 照常收尾,resultText 为本轮最终文本', async () => {
const h = createSessionHarness(acceptingSend());
const { runner, notifier } = createRunnerHarness(h.session);
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts
index 8d4a03a888..9c614446ae 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts
@@ -55,6 +55,14 @@ function createSessionHarness() {
}
describe('backfillSessionMeta', () => {
+ it('preserves teammate permissions while updating routine runtime metadata', async () => {
+ const { db, set } = createUpdateDb();
+ const { logger } = createLogger();
+ await backfillSessionMeta(db, 'bot-session', { permissionMode: null, effort: 'high' }, logger);
+ expect(set).toHaveBeenCalledWith({ effort: 'high', updatedAt: expect.any(Number) });
+ expect(set.mock.calls[0][0]).not.toHaveProperty('permissionMode');
+ });
+
it('writes unattended metadata for newly created scheduler sessions', async () => {
const { db, update, set, where } = createUpdateDb();
const { logger, warn } = createLogger();
diff --git a/apps/desktop/src/main/scheduler-host/routinePermission.ts b/apps/desktop/src/main/scheduler-host/routinePermission.ts
index 1a18176ea4..25fe4011fe 100644
--- a/apps/desktop/src/main/scheduler-host/routinePermission.ts
+++ b/apps/desktop/src/main/scheduler-host/routinePermission.ts
@@ -1,8 +1,6 @@
-import type { PermissionMode } from '@cindy/maker-core';
+import type { PermissionMode, Session } from '@cindy/maker-core';
-/** Background triggers inherit the teammate's permission choice, never grant Full Access. */
-export function routinePermissionMode(live: unknown, stored: unknown): PermissionMode {
- const mode = live ?? stored;
+function permissionMode(mode: unknown): PermissionMode | null {
if (
mode === 'ask' ||
mode === 'default' ||
@@ -12,5 +10,21 @@ export function routinePermissionMode(live: unknown, stored: unknown): Permissio
mode === 'bypassPermissions'
)
return mode;
- throw new Error('The teammate permission setting is unavailable');
+ return null;
+}
+
+/** Never fall back from an unstable live session or a missing/incomplete durable snapshot. */
+export function routinePermissionSnapshot(
+ live: Pick<Session, 'stablePermissionModeState'> | undefined,
+ stored: { permissionMode: unknown; planModeEnabled: unknown } | null,
+): { permissionMode: PermissionMode; planMode: boolean } | null {
+ if (!stored || typeof stored.planModeEnabled !== 'boolean') return null;
+ const mode = permissionMode(stored.permissionMode);
+ if (!mode) return null;
+ if (live) {
+ const stable = live.stablePermissionModeState;
+ // A persistence/runtime mismatch may be a partially applied user change; wait for it to settle.
+ if (!stable || stable.mode !== mode) return null;
+ }
+ return { permissionMode: mode, planMode: stored.planModeEnabled };
}
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 1926d1eef8..0612063375 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -1,5 +1,5 @@
import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';
-import { routinePermissionMode } from './routinePermission.js';
+import { routinePermissionSnapshot } from './routinePermission.js';
/**
* Phase 3: MakerScheduleRunner
*
@@ -440,6 +440,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
| 'session-running'
| 'already-queued'
| 'queue-restore-pending'
+ | 'routine-permission-unavailable'
| 'queue-wait-timeout',
): FireResult {
this.deps.logger.info?.(
@@ -468,6 +469,11 @@ export class MakerScheduleRunner implements ScheduleRunner {
return schedule.recurring === true && schedule.status === 'active' && schedule.manual !== true;
}
+ private async readRoutinePermissions(sessionId: string, live?: Session) {
+ const stored = await getSessionFsSnapshot(sessionId);
+ return routinePermissionSnapshot(live ?? this.deps.maker.getSession(sessionId), stored);
+ }
+
private async failOrDeferSessionRunning(
schedule: Schedule,
ctx: FireContext,
@@ -871,10 +877,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
const materializedDefaultProviderId = shouldMaterializeFreshClaudeProvider
? (dynamicDefaultRoute?.providerId ?? null)
: null;
- const routineSnapshot = schedule.source === 'bot' && isHeartbeat ? await getSessionFsSnapshot(sessionId) : null;
- const permissionMode = schedule.source === 'bot' && isHeartbeat
- ? routinePermissionMode(this.deps.maker.getSession(sessionId)?.permissionModeState.mode, routineSnapshot?.permissionMode)
- : defaultPermissionModeForSchedule();
+ let routinePermissions = schedule.source === 'bot' ? await this.readRoutinePermissions(sessionId) : null;
+ if (schedule.source === 'bot' && !routinePermissions)
+ return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
// fastMode 对 Codex / Pi 生效(claude-code agent 忽略此字段);Claude 恒不传,
// 确保「不影响 Claude」。heartbeat 沿用 session meta 里的 fast 态,非 heartbeat 取 schedule。
let fastMode =
@@ -1080,6 +1085,11 @@ export class MakerScheduleRunner implements ScheduleRunner {
// The worktree path can also await filesystem work, so cancellation may
// have arrived after the preceding guard. Never create a late session.
throwIfFireAborted(ctx.signal, 'session creation');
+ if (schedule.source === 'bot') {
+ routinePermissions = await this.readRoutinePermissions(sessionId);
+ if (!routinePermissions) return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
+ throwIfFireAborted(ctx.signal, 'session creation');
+ }
let session: Awaited<ReturnType<Maker['createSession']>>;
try {
session = await this.deps.maker.createSession({
@@ -1089,8 +1099,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
model,
effort: reconciledEffort,
fastMode,
- permissionMode,
- ...(schedule.source === 'bot' ? { planMode: !!routineSnapshot?.planModeEnabled } : {}),
+ permissionMode: routinePermissions?.permissionMode ?? defaultPermissionModeForSchedule(),
+ ...(routinePermissions ? { planMode: routinePermissions.planMode } : {}),
title: isHeartbeat ? undefined : `[Schedule] ${schedule.name}`,
resumeSessionId,
// Pi distinguishes an explicit null (Cindy default route) from undefined
@@ -1265,6 +1275,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
this.deps.getDb(),
session.id,
{
+ // The routine owns no permission choice; never overwrite the teammate (including a concurrent edit).
+ ...(schedule.source === 'bot' ? { permissionMode: null } : {}),
// 复用路径 setEffort 失败时跳过落库 —— 保留旧 meta.effort, 下次 fire
// heartbeatEffortChanged 仍为 true 会重试同步(4.4.1 注释的固化问题)。
// 落 runtimeReconciledEffort(按实际运行模型 clamp 后的值),session 行 effort 反映真跑的档,
@@ -1471,9 +1483,18 @@ export class MakerScheduleRunner implements ScheduleRunner {
setSessionProvider(session.id, verdict.providerId);
}
}
+ if (schedule.source === 'bot') {
+ routinePermissions = await this.readRoutinePermissions(session.id, session);
+ if (!routinePermissions) {
+ waiter.stopListening();
+ ctx.signal.removeEventListener('abort', onAbort);
+ return this.deferFire(schedule, session.id, 'routine-permission-unavailable');
+ }
+ throwIfFireAborted(ctx.signal, 'agent turn dispatch');
+ }
const sendResult = await session.send(outgoingMessage as never, {
origin,
- planMode: schedule.source === 'bot' ? !!routineSnapshot?.planModeEnabled : false,
+ planMode: routinePermissions?.planMode ?? false,
onAccepted: async () => {
// createSession 之后到真正 dispatch 之间仍会 await 模型切换、baseline
// 等准备工作。复用 desktop session 时不能在这些准备阶段把用户正在跑的
diff --git a/apps/desktop/src/main/scheduler-host/runners/_shared.ts b/apps/desktop/src/main/scheduler-host/runners/_shared.ts
index 48e51693bd..01c73e8f11 100644
--- a/apps/desktop/src/main/scheduler-host/runners/_shared.ts
+++ b/apps/desktop/src/main/scheduler-host/runners/_shared.ts
@@ -47,9 +47,9 @@ export interface BackfillSessionMetaPatch {
* 落库的权限模式。缺省 'bypassPermissions'(scheduler unattended 语义不变);
* learn-host 传 'acceptEdits' —— 蒸馏会话建会话时已降权,若这里放任默认值
* 写回 bypass,app 重启后 lazy-resume 会按 sessions 行重建 createOpts,修订
- * 回合就逃出了降权约束(Codex review)。
+ * 回合就逃出了降权约束(Codex review)。null 保留目标已有权限,伙伴例行任务使用此语义。
*/
- permissionMode?: string;
+ permissionMode?: string | null;
}
export async function backfillSessionMeta(
@@ -60,9 +60,9 @@ export async function backfillSessionMeta(
): Promise<void> {
try {
const patch: Record<string, unknown> = {
- permissionMode: meta.permissionMode ?? 'bypassPermissions',
updatedAt: Date.now(),
};
+ if (meta.permissionMode !== null) patch.permissionMode = meta.permissionMode ?? 'bypassPermissions';
if (meta.effort) patch.effort = meta.effort;
if (meta.model) patch.model = meta.model;
if (meta.providerId) patch.providerId = meta.providerId;
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index e8158b2bec..023fd07d6a 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -19,6 +19,8 @@
所有执行复用伙伴 canonical task,继承模型、技能和实际权限,包括冷恢复时的权限。合成触发消息不作为用户聊天消息展示;有成果的输出由已有伙伴消息链呈现,空转复用静默策略。每条例行任务最多一个正在执行的运行;等待中的新事件合并为一批。不同规则共享伙伴时,由既有任务队列串行派发。
+直接执行路径必须取得完整的持久权限/计划模式快照;已有 live Session 还必须提供稳定权限状态,并与持久权限一致。缺失、切换中或不一致时保留原批次延期,不回退到旧权限或把未知计划模式当作关闭。异步准备后在创建 Session 和直接发送前再次读取;冷恢复沿用已保存的有效权限和计划模式。运行信息回写跳过伙伴权限字段,不以普通自动化的默认完全访问覆盖用户选择或并发修改。
+
启动恢复时若调度器尚未就绪,同样保留原 queued 批次并在 30 秒后重试,不标记为失败。
伙伴忙碌导致的 deferred 保留同一待执行批次,30 秒后重试;宿主通过 runNow 的内部 deferToCaller 选项领取重试责任,底层不设置重试时间,不能由旧 backing schedule 另行重放旧事件。普通手动调度保持原有忙碌失败语义。已开始的执行失败不会自动重做,避免重复外部副作用。暂停或删除取消等待项并中止当前运行;修改规则取消旧版本等待项,下一次事件按新规则匹配。
@@ -92,6 +94,8 @@ const receipt = await cindy.routines.request({
插件管子在等待引擎/数据库就绪前同步预留并发额度:状态和事件请求合计单插件最多 8 个、整个宿主最多 32 个;计数跨引擎重建保留,覆盖启动等待及实际发布,直到成功、失败或取消返回后归还。超额请求立即拒绝,不保留额外等待队列。操作、状态和事件体量沿用现有校验,在等待前拒绝无效请求;引擎内部的频率与落盘限额继续独立生效。
+整个请求(包含忽略的未知字段、字段名和数组附加属性)还受 128 KiB UTF-8 保守预算、4096 个值和 16 层嵌套限制。等待前逐项检查,超大字符串先按长度拒绝,不先把整个请求序列化;循环引用、非普通 JSON 对象和非有限数字直接拒绝。小型未知字段仍按兼容规则忽略,合法事件 data 的既有 32000 字符上限不变。
+
插件失败回执只返回固定公开文案:校验和容量/频率拒绝按精确白名单保留提示;未知异常统一回复通用重试提示,详细异常只进入 Main 日志,不携带文件路径或事件数据返回插件。写盘失败后的原事件 ID 仍可重试,成功持久化后才进入去重窗口。
本协议不要求第三方连接器的固定组合:飞书长连接、Gmail 本地采集和 GitHub 事件适配器都可报告相同形态的事件。本次交付的是宿主接入与执行能力,不会自动给现有飞书/Gmail 插件增加第三方订阅;适配器需按上述协议接入。