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。

feat(bots): isolate routine sessions and model configuration

Chris1d87da051bbf
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index ff84acb352..2d7556f27e 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1176,7 +1176,7 @@ import {
} from './scheduler-host/index.js';
import { configureRoutineHost } from './routines/service.js';
import { configureBotAutonomyHost, initBotAutonomy } from './bot-autonomy/service.js';
-import { getBotRemoteResourceSource } from './localDb/ipc/bots.js';
+import { getBotRemoteResourceSource, ensureBotRoutineLaneSession } from './localDb/ipc/bots.js';
import {
registerScheduleHandlers,
attachSchedulerEventListeners,
@@ -1234,6 +1234,7 @@ async function waitForCurrentAccountProviderModelsReady(): Promise<void> {
configureRoutineHost({
assertImportedAutomationReady: ensureImportedAutomationReady, prepareImportedAutomation, finishImportedAutomation, recoverImports: recoverCompanionImports,
getBot: getBotRemoteResourceSource,
+ ensureRoutineSession: ensureBotRoutineLaneSession,
getScheduler: getSchedulerIfInitialized,
getScheduleStorage,
});
diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
index 182e379cb1..cf52367945 100644
--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts
+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
@@ -59,7 +59,7 @@ const USER_SOURCES = new Set(['desktop', 'feishu', 'slack', 'telegram', 'x', 'di
* 伙伴的历史 / 私聊话题 / 群 / IM 渠道专线不是「任务」,不进表。主任务(canonical)进表:总调度是另一个伙伴时要能
* 发现它坏了;但它永远不是主任务所属伙伴自己的事件对象(见 followerFor),也不进它自己的工作台。
*/
-const BOT_LANE_ROLES = new Set(['history', 'thread', 'group', 'channel']);
+const BOT_LANE_ROLES = new Set(['history', 'thread', 'group', 'channel', 'routine']);
export interface LocalSessionMeta {
id: string;
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index c31d15c2d1..0b01f7a3ac 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -60,6 +60,7 @@ export type DbTxName =
| 'bots.persistSessionPermission'
| 'bots.createGroupLane'
| 'bots.createChannelLane'
+ | 'bots.createRoutineLane'
| 'bots.createThreadLane'
| 'bots.archiveChannelLanes'
| 'botGroups.create'
@@ -1444,6 +1445,7 @@ export type DbTxArgsByName = {
'bots.persistSessionPermission': { sessionId: string; mode: string };
'bots.createGroupLane': BotGroupsCreateLaneArgs;
'bots.createChannelLane': BotsCreateChannelLaneArgs;
+ 'bots.createRoutineLane': BotsCreateChannelLaneArgs;
'bots.createThreadLane': BotsCreateThreadLaneArgs;
'bots.archiveChannelLanes': BotsArchiveChannelLanesArgs;
'botGroups.create': BotGroupsCreateArgs;
@@ -1544,6 +1546,7 @@ export type DbTxResultByName = {
'bots.persistSessionPermission': { updated: boolean };
'bots.createGroupLane': BotGroupsCreateLaneResult;
'bots.createChannelLane': BotGroupsCreateLaneResult;
+ 'bots.createRoutineLane': BotGroupsCreateLaneResult;
'bots.createThreadLane': BotGroupsCreateLaneResult;
'bots.archiveChannelLanes': { archivedSessionIds: string[] };
'botGroups.create': undefined;
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts
index d5892c2ef8..4ecf512be9 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSettingsOps.ts
@@ -234,6 +234,10 @@ export function createBotRemoteSettingsOps(deps: BotSettingsOpsDeps): Partial<Re
const id = call.args.id === undefined ? undefined : text(call.args.id, 'id', 128);
return deps.routines.save(botOf(call), parseRoutineInput(call.args.input), id);
}),
+ 'routines.saveWithModel': call => routineCall(() => {
+ const id = call.args.id === undefined ? undefined : text(call.args.id, 'id', 128);
+ return deps.routines.save(botOf(call), parseRoutineInput(call.args.input), id);
+ }),
'routines.runNow': call => routineCall(() => deps.routines.runNow(botOf(call), text(call.args.id, 'id', 128))),
'routines.remove': call => routineCall(async () => {
await deps.routines.remove(botOf(call), text(call.args.id, 'id', 128));
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 3adf0502db..30f8ef9536 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -1,3 +1,4 @@
+import type { RoutineModel } from '@cindy/maker-scheduler';
import { todoAccess } from '../../maker-ipc/botTodoAccess.js';
import { botLinkedProjectAccess } from '../../maker-ipc/botLinkedProjects.js';
import type { TodoPatch } from '@cindy/maker-shared/teammate-todo';
@@ -444,13 +445,17 @@ export type EnsureBotChannelLaneResult =
/** Read-only lookup of an active IM channel lane (`role = 'channel'`). */
export async function findBotChannelLaneSession(botId: string, routeKey: string): Promise<string | null> {
+ return findBotOwnedLaneSession(botId, routeKey, 'channel');
+}
+
+async function findBotOwnedLaneSession(botId: string, routeKey: string, role: 'channel' | 'routine'): Promise<string | null> {
const [existing] = await getDbClient()
.drizzle.select({ sessionId: botSessionLinks.sessionId })
.from(botSessionLinks)
.innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
.where(and(
eq(botSessionLinks.botId, botId),
- eq(botSessionLinks.role, 'channel'),
+ eq(botSessionLinks.role, role),
eq(botSessionLinks.routeKey, routeKey),
isNull(botSessionLinks.archivedAt),
eq(sessions.source, 'bot'),
@@ -472,10 +477,19 @@ export async function ensureBotChannelLaneSession(input: {
routeKey: string;
title: string;
}): Promise<EnsureBotChannelLaneResult> {
+ return ensureBotOwnedLaneSession(input, 'channel');
+}
+
+/** A persistent execution context for one standing instruction, sharing its companion's Home. */
+export async function ensureBotRoutineLaneSession(input: { botId: string; routineId: string; title: string; modelOverride?: RoutineModel | null }): Promise<EnsureBotChannelLaneResult> {
+ return ensureBotOwnedLaneSession({ ...input, routeKey: `routine:${input.routineId}` }, 'routine');
+}
+
+async function ensureBotOwnedLaneSession(input: { botId: string; routeKey: string; title: string; modelOverride?: RoutineModel | null }, role: 'channel' | 'routine'): Promise<EnsureBotChannelLaneResult> {
const owner = captureBotOperationOwner();
const client = getDbClient();
const db = client.drizzle;
- const existing = await findBotChannelLaneSession(input.botId, input.routeKey);
+ const existing = await findBotOwnedLaneSession(input.botId, input.routeKey, role);
if (existing) {
await syncBotLanePermission(existing);
owner.assertCurrent();
@@ -495,7 +509,11 @@ export async function ensureBotChannelLaneSession(input: {
.limit(1);
if (!profileVersion) return { ok: false, errorCode: 'BOT_UNAVAILABLE', message: '伙伴资料版本不存在' };
const config = parseJson(profileVersion.capabilitiesJson);
- const primaryRoute = (await readEffectiveBotModelChain(config))[0] ?? null;
+ const override = input.modelOverride;
+ const primaryRoute = override ? { harness: override.agentKind === 'claude-code' ? 'claude' as const : override.agentKind,
+ model: override.model, providerId: override.providerId ?? null, effort: override.effort ?? '',
+ fastMode: override.fastMode ?? false, agentDeviceId: override.agentDeviceId ?? null }
+ : (await readEffectiveBotModelChain(config))[0] ?? null;
if (!primaryRoute) return { ok: false, errorCode: 'NO_MODEL', message: '伙伴还没有可用模型' };
const workspaceKind = 'dialogue' as const;
const workingDir = await ensureBotWorkspaceDir(owner.userDataDir, input.botId, app.getPath('userData'));
@@ -507,7 +525,7 @@ export async function ensureBotChannelLaneSession(input: {
{
workspaceKind,
workingDir,
- ...botSessionRouteFields(config, primaryRoute),
+ ...botSessionRouteFields(override ? { ...config, providerId: null, effort: undefined } : config, primaryRoute),
remoteHostId: undefined,
source: 'bot',
},
@@ -528,7 +546,7 @@ export async function ensureBotChannelLaneSession(input: {
owner.assertCurrent();
let result: BotGroupsCreateLaneResult;
try {
- result = await client.tx<BotGroupsCreateLaneResult>('bots.createChannelLane', {
+ result = await client.tx<BotGroupsCreateLaneResult>(role === 'routine' ? 'bots.createRoutineLane' : 'bots.createChannelLane', {
botId: input.botId,
routeKey: input.routeKey,
session: {
@@ -1325,9 +1343,11 @@ async function readProfile(
? 'group'
: link.role === 'channel'
? 'channel'
- : link.role === 'thread'
- ? 'thread'
- : 'history',
+ : link.role === 'routine'
+ ? 'routine'
+ : link.role === 'thread'
+ ? 'thread'
+ : 'history',
updatedAt: row.updatedAt,
status: row.status,
role: link.role,
@@ -2104,7 +2124,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,
&& Object.prototype.hasOwnProperty.call(body.capabilities, 'permissions');
const modelFollowers = modelSelectionChanged ? await db.select({ sessionId: botSessionLinks.sessionId })
.from(botSessionLinks).where(and(eq(botSessionLinks.botId, id),
- inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread', 'routine']),
isNull(botSessionLinks.archivedAt))) : [];
const commitProfile = async () => {
await coordinateBotModelSelection(modelFollowers.map((link) => link.sessionId), async () => {
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index c9ee3aa88e..7cb3e9cf3a 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -428,7 +428,7 @@ export const botSessionLinks = sqliteTable(
profileVersion: integer('profile_version').notNull().default(1),
// TS-only enum (SQLite `text`, no CHECK): `channel` = 伙伴接管的个人 IM 群 / 话题专线;
// `thread` = 主人私聊里的话题(route_key = dm-thread:<根消息 Session>:<根消息 clientId>)。
- role: text('role', { enum: ['canonical', 'history', 'delegation', 'group', 'channel', 'thread'] }).notNull(),
+ role: text('role', { enum: ['canonical', 'history', 'delegation', 'group', 'channel', 'thread', 'routine'] }).notNull(),
routeKey: text('route_key'),
createdAt: integer('created_at').notNull(),
archivedAt: integer('archived_at'),
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts
index 9aa5642856..54737a2075 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/botTx.test.ts
@@ -516,6 +516,14 @@ describe('Bot named worker transactions', () => {
botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1, session: session('main'), now: 1,
} });
tx(db, { name: 'bots.createChannelLane', args: { botId: 'bot-1', routeKey: 'im:feishu:g:1', session: session('feishu') } });
+ // Routine context is keyed by the standing instruction, never the main task.
+ expect(tx(db, { name: 'bots.createRoutineLane', args: { botId: 'bot-1', routeKey: 'routine:r1', session: session('routine') } }))
+ .toMatchObject({ sessionId: 'routine', created: true });
+ expect(tx(db, { name: 'bots.createRoutineLane', args: { botId: 'bot-1', routeKey: 'routine:r1', session: session('duplicate') } }))
+ .toMatchObject({ sessionId: 'routine', created: false });
+ expect(tx(db, { name: 'bots.createRoutineLane', args: { botId: 'bot-1', routeKey: 'routine:r2', session: session('second-routine') } }))
+ .toMatchObject({ sessionId: 'second-routine', created: true });
+ expect(db.prepare("SELECT canonical_session_id FROM bot_profiles WHERE id = 'bot-1'").pluck().get()).toBe('main');
for (const role of ['group', 'thread', 'delegation', 'history']) {
db.prepare(`INSERT INTO sessions SELECT ?, title, working_dir, workspace_kind, model, effort, permission_mode, status,
scheduled_model_baseline, sdk_session_id, total_token_usage, total_cost_usd, context_tokens, context_window, fast_mode,
@@ -527,7 +535,7 @@ describe('Bot named worker transactions', () => {
const mode = (id: string) => db.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get(id);
for (const next of ['bypassPermissions', 'auto', 'ask']) {
tx(db, { name: 'bots.persistSessionPermission', args: { sessionId: 'main', mode: next } });
- expect(['main', 'feishu', 'group', 'thread'].map(mode)).toEqual([next, next, next, next]);
+ expect(['main', 'feishu', 'group', 'thread', 'routine', 'second-routine'].map(mode)).toEqual(Array(6).fill(next));
expect(['delegation', 'history'].map(mode)).toEqual(['ask', 'ask']);
}
// A stale preflight must not mint a lane with authority older than the Profile.
@@ -537,18 +545,22 @@ describe('Bot named worker transactions', () => {
db.prepare("UPDATE bot_profile_versions SET capabilities_json = ? WHERE bot_id = 'bot-1'").run(JSON.stringify({ permissions: 'ask' }));
expect(tx(db, { name: 'bots.reconcileLanePermission', args: { sessionId: 'feishu' } }))
.toMatchObject({ mode: 'bypassPermissions', canonicalSessionId: 'main' });
- expect(['main', 'feishu', 'group', 'thread', 'new'].map(mode))
- .toEqual(Array(5).fill('bypassPermissions'));
+ expect(['main', 'feishu', 'group', 'thread', 'new', 'routine', 'second-routine'].map(mode))
+ .toEqual(Array(7).fill('bypassPermissions'));
expect(JSON.parse(db.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE bot_id = ?').pluck().get('bot-1') as string).permissions)
.toBe('trusted');
// Main is authoritative in both directions; never choose the widest snapshot.
db.prepare("UPDATE sessions SET permission_mode = 'ask' WHERE id = 'main'").run();
expect(tx(db, { name: 'bots.reconcileLanePermission', args: { sessionId: 'main' } }))
.toMatchObject({ mode: 'ask', canonicalSessionId: 'main' });
- expect(['main', 'feishu', 'group', 'thread', 'new'].map(mode)).toEqual(Array(5).fill('ask'));
+ expect(['main', 'feishu', 'group', 'thread', 'new', 'routine', 'second-routine'].map(mode)).toEqual(Array(7).fill('ask'));
expect(['delegation', 'history'].map(mode)).toEqual(['ask', 'ask']);
+ // A lone stale routine must also be repaired when the Profile already matches main.
+ db.prepare("UPDATE sessions SET permission_mode = 'bypassPermissions' WHERE id = 'routine'").run();
+ expect(tx(db, { name: 'bots.reconcileLanePermission', args: { sessionId: 'routine' } })).toMatchObject({ mode: 'ask', changed: true });
+ expect(mode('routine')).toBe('ask');
expect(tx(db, { name: 'bots.reconcileLanePermission', args: { sessionId: 'history' } })).toMatchObject({ mode: null });
- expect(db.prepare('SELECT COUNT(*) FROM sessions').pluck().get()).toBe(7);
+ expect(db.prepare('SELECT COUNT(*) FROM sessions').pluck().get()).toBe(9);
});
it('does not insert a losing canonical CAS session', () => {
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 1c492d5430..17b05507ce 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -184,6 +184,8 @@ function dispatchTransaction(db: Database.Database, args: unknown): unknown {
return botsPersistSessionPermission(db, txArgs);
case 'bots.createGroupLane':
return botsCreateGroupLane(db, txArgs as BotGroupsCreateLaneArgs);
+ case 'bots.createRoutineLane':
+ return botsCreateChannelLane(db, txArgs as BotsCreateChannelLaneArgs, 'routine');
case 'bots.createChannelLane':
return botsCreateChannelLane(db, txArgs as BotsCreateChannelLaneArgs);
case 'bots.createThreadLane':
@@ -486,7 +488,7 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersi
agent_kind AS agentKind, model, provider_id AS providerId, effort, fast_mode AS fastMode
FROM sessions WHERE id IN
(SELECT session_id FROM bot_session_links WHERE bot_id = ?
- AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL)`)
+ AND role IN ('canonical', 'group', 'channel', 'thread', 'routine') AND archived_at IS NULL)`)
.all(id) as Array<{ id: string; baseline: string | null; agentKind: string; model: string;
providerId: string | null; effort: string; fastMode: number | string }>;
@@ -508,7 +510,7 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersi
// their next runtime bootstrap. Route/worker links remain pinned to their
// creation version.
db.prepare(`UPDATE bot_session_links SET profile_version = ?
- WHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL`)
+ WHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread', 'routine') AND archived_at IS NULL`)
.run(nextVersion, id);
}
if (permissionMode !== undefined) {
@@ -516,7 +518,7 @@ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersi
// Group and IM channel lanes run under the same permission profile as the
// Bot's canonical Chat (per-turn group policies still apply on top).
db.prepare(`UPDATE sessions SET permission_mode = ? WHERE id IN
- (SELECT session_id FROM bot_session_links WHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL)`)
+ (SELECT session_id FROM bot_session_links WHERE bot_id = ? AND role IN ('canonical', 'group', 'channel', 'thread', 'routine') AND archived_at IS NULL)`)
.run(mode, id);
}
return { currentVersion: nextVersion };
@@ -884,11 +886,11 @@ function botsCreateGroupLane(db: Database.Database, args: BotGroupsCreateLaneArg
* of creating a second. Unlike group lanes there is no member table: the
* connection binding (owner-scoped setting) is the authority, checked by Main.
*/
-function botsCreateChannelLane(db: Database.Database, args: BotsCreateChannelLaneArgs): BotGroupsCreateLaneResult {
+function botsCreateChannelLane(db: Database.Database, args: BotsCreateChannelLaneArgs, role: 'channel' | 'routine' = 'channel'): BotGroupsCreateLaneResult {
const p = asRecord(args, 'bots.createChannelLane args');
const botId = expectString(p.botId, 'botId');
const routeKey = expectString(p.routeKey, 'routeKey');
- if (!routeKey.startsWith('im:')) throw new Error('Channel lane route key must start with im:');
+ if (!routeKey.startsWith(role === 'routine' ? 'routine:' : 'im:')) throw new Error('Invalid companion lane route key');
const s = asRecord(p.session, 'session');
const sessionId = expectString(s.id, 'session.id');
const createdAt = expectNumber(s.createdAt, 'session.createdAt');
@@ -901,15 +903,15 @@ function botsCreateChannelLane(db: Database.Database, args: BotsCreateChannelLan
}
const existing = db.prepare(`SELECT l.session_id AS sessionId FROM bot_session_links l
INNER JOIN sessions s ON s.id = l.session_id
- WHERE l.bot_id = ? AND l.role = 'channel' AND l.route_key = ? AND l.archived_at IS NULL
+ WHERE l.bot_id = ? AND l.role = ? AND l.route_key = ? AND l.archived_at IS NULL
AND s.source = 'bot' AND s.status = 'active'
- LIMIT 1`).get(botId, routeKey) as { sessionId: string } | undefined;
+ LIMIT 1`).get(botId, role, routeKey) as { sessionId: string } | undefined;
if (existing) return { sessionId: existing.sessionId, created: false };
insertBotSession(db, s);
db.prepare(`INSERT INTO bot_session_links
(id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)
- VALUES (?, ?, ?, ?, 'channel', ?, ?, NULL)`)
- .run(`${botId}:${sessionId}`, botId, sessionId, profile.version, routeKey, createdAt);
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`)
+ .run(`${botId}:${sessionId}`, botId, sessionId, profile.version, role, routeKey, createdAt);
const permission = botsReconcileLanePermission(db, { sessionId });
return { sessionId, created: true,
...(permission.canonicalSessionId ? { permissionRepairCanonicalSessionId: permission.canonicalSessionId } : {}) };
@@ -1303,7 +1305,7 @@ function botsPersistSessionPermission(
return { updated: true };
}
const link = db.prepare(`SELECT bot_id AS botId FROM bot_session_links
- WHERE session_id = ? AND role IN ('canonical', 'channel', 'group', 'thread')
+ WHERE session_id = ? AND role IN ('canonical', 'channel', 'group', 'thread', 'routine')
AND archived_at IS NULL`).get(sessionId) as { botId: string } | undefined;
if (link) {
const profile = db.prepare('SELECT current_version AS version FROM bot_profiles WHERE id = ?')
@@ -1335,7 +1337,7 @@ function botsPersistSessionPermission(
if (link) {
db.prepare(`UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE source = 'bot' AND status = 'active' AND id IN
(SELECT session_id FROM bot_session_links WHERE bot_id = ?
- AND role IN ('canonical', 'group', 'channel', 'thread') AND archived_at IS NULL)`)
+ AND role IN ('canonical', 'group', 'channel', 'thread', 'routine') AND archived_at IS NULL)`)
.run(mode, Date.now(), link.botId);
} else {
db.prepare('UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE id = ?')
@@ -1354,7 +1356,7 @@ function botsReconcileLanePermission(db: Database.Database, args: unknown): { mo
JOIN sessions s ON s.id = l.session_id
JOIN bot_profiles p ON p.id = l.bot_id
LEFT JOIN bot_profile_versions v ON v.bot_id = p.id AND v.version = p.current_version
- WHERE l.session_id = ? AND l.role IN ('canonical', 'channel', 'group', 'thread') AND l.archived_at IS NULL
+ WHERE l.session_id = ? AND l.role IN ('canonical', 'channel', 'group', 'thread', 'routine') AND l.archived_at IS NULL
AND s.source = 'bot' AND s.status = 'active' AND p.status = 'active'`).get(sessionId) as
{ json: string | null; botId: string; role: string; previousMode: string } | undefined;
if (!row) return { mode: null, changed: false };
@@ -1372,7 +1374,7 @@ function botsReconcileLanePermission(db: Database.Database, args: unknown): { mo
if (canonical && ['ask', 'auto', 'bypassPermissions'].includes(canonical.mode)) {
const permission = canonical.mode === 'bypassPermissions' ? 'trusted' : canonical.mode;
const staleLane = db.prepare(`SELECT 1 FROM bot_session_links l JOIN sessions s ON s.id = l.session_id
- WHERE l.bot_id = ? AND l.role IN ('channel', 'group', 'thread') AND l.archived_at IS NULL
+ WHERE l.bot_id = ? AND l.role IN ('channel', 'group', 'thread', 'routine') AND l.archived_at IS NULL
AND s.source = 'bot' AND s.status = 'active' AND s.permission_mode != ? LIMIT 1`)
.get(row.botId, canonical.mode);
if (config.permissions !== permission || staleLane) {
diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
index f0320f1eea..be4c2d3abc 100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
@@ -54,7 +54,7 @@ export async function isBotAuthorizationSession(sessionId: string): Promise<bool
and(
eq(botSessionLinks.sessionId, sessionId),
// The owner's Bot Chat: the permanent Chat and its private-chat topics.
- inArray(botSessionLinks.role, ['canonical', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'thread', 'routine']),
isNull(botSessionLinks.archivedAt),
ne(sessions.status, 'deleted'),
ne(sessions.status, 'archived'),
diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
index 571ec0c630..5fbb73369f 100644
--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
@@ -91,7 +91,7 @@ async function context(callerSessionId: string, opts?: { allowPaused?: boolean;
!row ||
row.source !== 'bot' ||
// The owner's Bot Chat: the current main Chat or one of its private-chat topics.
- (!groupAuthority && row.role !== 'thread' && (row.role !== 'canonical' || row.canonicalSessionId !== callerSessionId)) ||
+ (!groupAuthority && row.role !== 'thread' && row.role !== 'routine' && (row.role !== 'canonical' || row.canonicalSessionId !== callerSessionId)) ||
row.archivedAt !== null ||
row.sessionStatus !== 'active' ||
!profileAllowed
diff --git a/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts b/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts
index 863f869fb2..59051978b5 100644
--- a/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts
+++ b/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts
@@ -179,7 +179,7 @@ export async function prepareBotCapabilityEpochBeforeSend<T extends {
coordinator: BotCompactRuntimeRefreshCoordinator;
}): Promise<BotCompactRuntimeRefreshOutcome> {
const row = await deps.readSession();
- if (!row || (row.role !== 'canonical' && row.role !== 'group' && row.role !== 'channel' && row.role !== 'thread')
+ if (!row || (row.role !== 'canonical' && row.role !== 'group' && row.role !== 'channel' && row.role !== 'thread' && row.role !== 'routine')
|| row.source !== 'bot' || row.status !== 'active' || !row.workingDir) {
return 'not-bot';
}
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 1163ca6cb2..da542776a2 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1389,7 +1389,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
// A group lane is a live requester only for the task it started (bot-group-chat.md §10);
// the lane is never woken by this service, its group gets the messages instead.
// A private-chat topic gets the results of the tasks started in it (cindy-bots-runtime.md).
- && (parent.role === 'canonical' || parent.role === 'thread' || parent.role === 'delegation' || parent.role === 'group')
+ && (parent.role === 'canonical' || parent.role === 'thread' || parent.role === 'routine' || parent.role === 'delegation' || parent.role === 'group')
);
};
if (parentSessionId && (await liveRequesterTask(parentSessionId))) return parentSessionId;
@@ -1604,7 +1604,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
|| link.sessionSource !== 'bot'
|| link.profileStatus !== 'active'
|| link.linkArchivedAt !== null
- || !['canonical', 'thread', 'delegation', 'group'].includes(link.role)
+ || !['canonical', 'thread', 'routine', 'delegation', 'group'].includes(link.role)
) return null;
// Delegating full independent work is an owner action, not a guest tool grant.
const group = link.role === 'group' && !ownerUi
@@ -2812,7 +2812,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
|| caller.sessionSource !== 'bot'
|| (caller.sessionStatus !== 'active' && caller.sessionStatus !== 'archived')
|| caller.profileStatus === 'deleting'
- || !['canonical', 'history', 'thread', 'delegation', 'group'].includes(caller.role)) {
+ || !['canonical', 'history', 'thread', 'routine', 'delegation', 'group'].includes(caller.role)) {
return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };
}
const db = getDbClient().drizzle;
diff --git a/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts b/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts
index f543688144..4d03c3ea07 100644
--- a/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts
+++ b/apps/desktop/src/main/maker-ipc/botPermissionDispatch.ts
@@ -49,7 +49,7 @@ export async function withBotPermissionChange<T>(
const owner = getCurrentDbClientSnapshot();
if (!owner) return change();
const [link] = await owner.client.query<{ botId: string }>(`SELECT bot_id AS botId FROM bot_session_links
- WHERE session_id = ? AND role IN ('canonical', 'channel', 'group', 'thread') AND archived_at IS NULL`, [sessionId]);
+ WHERE session_id = ? AND role IN ('canonical', 'channel', 'group', 'thread', 'routine') AND archived_at IS NULL`, [sessionId]);
if (owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed during permission update');
return link ? withBotPermissionChangeForBot(link.botId, change) : change();
}
@@ -60,7 +60,7 @@ export async function prepareBotPermissionDispatch(session: Session): Promise<()
if (!owner) return () => {};
const [link] = await owner.client.query<{ botId: string }>(`SELECT l.bot_id AS botId FROM bot_session_links l
JOIN sessions s ON s.id = l.session_id WHERE l.session_id = ?
- AND l.role IN ('canonical', 'channel', 'group', 'thread') AND l.archived_at IS NULL
+ AND l.role IN ('canonical', 'channel', 'group', 'thread', 'routine') AND l.archived_at IS NULL
AND s.source = 'bot' AND s.status = 'active'`, [session.id]);
if (owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed before dispatch');
if (!link) return () => {};
diff --git a/apps/desktop/src/main/maker-ipc/botPermissionSync.ts b/apps/desktop/src/main/maker-ipc/botPermissionSync.ts
index cde2a3550a..0a8906048e 100644
--- a/apps/desktop/src/main/maker-ipc/botPermissionSync.ts
+++ b/apps/desktop/src/main/maker-ipc/botPermissionSync.ts
@@ -61,8 +61,8 @@ export async function syncBotLinkedLanePermissions(canonicalSessionId: string):
if (!owner) return;
const rows = await owner.client.query<{ sessionId: string }>(`SELECT l.session_id AS sessionId
FROM bot_session_links l JOIN bot_session_links c ON c.bot_id = l.bot_id
- WHERE c.session_id = ? AND c.role IN ('canonical', 'channel', 'group', 'thread') AND c.archived_at IS NULL
- AND l.role IN ('canonical', 'channel', 'group', 'thread') AND l.archived_at IS NULL
+ WHERE c.session_id = ? AND c.role IN ('canonical', 'channel', 'group', 'thread', 'routine') AND c.archived_at IS NULL
+ AND l.role IN ('canonical', 'channel', 'group', 'thread', 'routine') AND l.archived_at IS NULL
AND l.session_id != c.session_id`, [canonicalSessionId]);
if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during lane permission update');
await syncBotPermissionRows(rows.map(row => row.sessionId));
@@ -73,7 +73,7 @@ export async function syncBotPermissionsByBotId(botId: string, excludedSessionId
const owner = getCurrentDbClientSnapshot();
if (!owner) return;
const rows = await owner.client.query<{ sessionId: string }>(`SELECT session_id AS sessionId
- FROM bot_session_links WHERE bot_id = ? AND role IN ('canonical', 'channel', 'group', 'thread')
+ FROM bot_session_links WHERE bot_id = ? AND role IN ('canonical', 'channel', 'group', 'thread', 'routine')
AND archived_at IS NULL AND session_id != ?`, [botId, excludedSessionId]);
if (getCurrentDbClientSnapshot() !== owner) throw new Error('Account changed during lane permission update');
await syncBotPermissionRows(rows.map(row => row.sessionId));
diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
index d95a13f3f4..7ca9d57dfd 100644
--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
@@ -508,10 +508,10 @@ export async function hydrateBotProfileRuntime(
// Group lanes, IM channel lanes and private-chat topics are long-lived like the
// canonical Chat and share its Profile/Home. Channel lanes and topics are
// full-profile lanes (not chat-only).
- if (!row || !['canonical', 'delegation', 'group', 'channel', 'thread'].includes(row.role)) return null;
+ if (!row || !['canonical', 'delegation', 'group', 'channel', 'thread', 'routine'].includes(row.role)) return null;
// A private-chat topic is the owner's own conversation, so it carries the main
// Chat's owner-private abilities (cindy-bots-runtime.md「私聊话题」).
- const ownerChat = row.role === 'canonical' || row.role === 'thread';
+ const ownerChat = row.role === 'canonical' || row.role === 'thread' || row.role === 'routine';
const [profile] = await db
.select()
.from(botProfiles)
@@ -1126,7 +1126,7 @@ export async function hydrateBotProfileRuntime(
: null;
// Canonical Chats, private-chat topics, group lanes and IM channel lanes follow
// Profile updates; delegation children stay frozen.
- const followsProfile = row.role === 'canonical' || row.role === 'thread' || row.role === 'group' || row.role === 'channel';
+ const followsProfile = row.role === 'canonical' || row.role === 'thread' || row.role === 'routine' || row.role === 'group' || row.role === 'channel';
const runtimeEpochChanged = followsProfile && previousSnapshot !== undefined
? previousSnapshot.profileVersion !== row.profileVersion
|| previousRuntimeEpoch?.sha256 !== runtimeEpochSha256
diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.ts
index 4ac167e08c..4b8250c4c6 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts
@@ -187,7 +187,7 @@ async function defaultResolveBotId(
readOnly,
);
if (!laneAccess.ok) return laneAccess;
- } else if (row.role !== 'canonical' && row.role !== 'thread' && row.role !== 'delegation' && !authority) {
+ } else if (row.role !== 'canonical' && row.role !== 'thread' && row.role !== 'routine' && row.role !== 'delegation' && !authority) {
return { ok: false, errorCode: 'BOT_SESSION_READ_ONLY', message: '当前 Bot 历史任务为只读状态' };
}
// Runtime hydration cannot mount the local personal shelf on an SSH host.
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
index 3ef2daad8e..436b2a99ea 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
@@ -54,7 +54,7 @@ export async function resolveWorkbenchCaller(callerSessionId: string): Promise<W
if (row.sessionStatus !== 'active' || row.profileStatus !== 'active' || row.linkArchivedAt !== null) {
return { ok: false, errorCode: 'BOT_SESSION_INACTIVE', message: '伙伴或它的主任务已停用' };
}
- if (row.role !== 'canonical' && row.role !== 'thread') {
+ if (row.role !== 'canonical' && row.role !== 'thread' && row.role !== 'routine') {
return {
ok: false,
errorCode: 'BOT_MAIN_TASK_REQUIRED',
@@ -181,7 +181,7 @@ async function resolveBotTaskCreator(callerSessionId: string): Promise<string |
.innerJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
.where(and(
eq(botSessionLinks.sessionId, callerSessionId),
- inArray(botSessionLinks.role, ['canonical', 'thread', 'channel', 'group']),
+ inArray(botSessionLinks.role, ['canonical', 'thread', 'channel', 'group', 'routine']),
isNull(botSessionLinks.archivedAt),
eq(sessions.source, 'bot'),
eq(sessions.status, 'active'),
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 181f95fa14..7a1f8b40c6 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -532,7 +532,7 @@ export type ContextRebuildReason =
export function isBotChatContext(row: { source?: string | null; botRole?: string | null }): boolean {
return (
row.source === 'bot' &&
- (row.botRole === 'canonical' || row.botRole === 'thread' || row.botRole === 'channel' || row.botRole === 'group')
+ (row.botRole === 'canonical' || row.botRole === 'thread' || row.botRole === 'routine' || row.botRole === 'channel' || row.botRole === 'group')
);
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index f57db17e03..963163895c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -661,7 +661,7 @@ import { registerBotLifecycleHandlers } from './botLifecycleService.js';
import { isSessionPermissionMode, persistPermissionModeWithoutRuntime } from './sessionPermissionPersistence.js';
import { withSessionPermissionChange } from './sessionPermissionChange.js';
import { withBotPermissionChange } from './botPermissionDispatch.js';
-import { updateBotRoutineLifecycle } from '../routines/service.js';
+import { updateBotRoutineLifecycle, readRoutineLaneModel } from '../routines/service.js';
import {
createBotCompactRuntimeRefreshCoordinator,
prepareBotCapabilityEpochBeforeSend,
@@ -9197,7 +9197,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
row.source !== 'bot' ||
row.status !== 'active' ||
(row.role !== 'canonical' && row.role !== 'delegation' && row.role !== 'group'
- && row.role !== 'channel' && row.role !== 'thread')
+ && row.role !== 'channel' && row.role !== 'thread' && row.role !== 'routine')
) {
return 'not-bot';
}
@@ -11401,7 +11401,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
status: sessions.status, botId: botProfiles.id, profileVersion: botProfiles.currentVersion,
}).from(sessions)
.leftJoin(botSessionLinks, and(eq(botSessionLinks.sessionId, sessions.id),
- isNull(botSessionLinks.archivedAt), inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread'])))
+ isNull(botSessionLinks.archivedAt), inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread', 'routine'])))
.leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
.where(eq(sessions.id, sessionId)).limit(1);
return row?.status === 'active' ? { baseline: row.baseline,
@@ -16586,6 +16586,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
read: async (sessionId, purpose) => {
const [row] = await getDbClient().drizzle.select({
capabilitiesJson: botProfileVersions.capabilitiesJson,
+ botId: botSessionLinks.botId,
+ role: botSessionLinks.role,
+ routeKey: botSessionLinks.routeKey,
agentKind: sessions.agentKind,
agentDeviceId: sessions.agentDeviceId,
model: sessions.model,
@@ -16603,7 +16606,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.where(and(
eq(botSessionLinks.sessionId, sessionId),
// Group / IM channel lanes and private-chat topics follow the Bot's current model chain exactly like its canonical Chat.
- inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'group', 'channel', 'thread', 'routine']),
isNull(botSessionLinks.archivedAt),
// Paused settings may preview grants; sending still requires an active Bot.
purpose === 'preview'
@@ -16614,6 +16617,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
)).limit(1);
if (!row) return null;
const selection = await readEffectiveBotModelSelection(JSON.parse(row.capabilitiesJson));
+ const routineModel = row.role === 'routine'
+ ? await readRoutineLaneModel(row.botId, row.routeKey) : null;
+ if (routineModel) {
+ selection.chain = [{ harness: routineModel.agentKind === 'claude-code' ? 'claude' : routineModel.agentKind,
+ model: routineModel.model, providerId: routineModel.providerId ?? null,
+ agentDeviceId: routineModel.agentDeviceId ?? null,
+ effort: routineModel.effort ?? '', fastMode: routineModel.fastMode ?? false }];
+ selection.followsCindyDefault = false;
+ }
const control = getSessionRuntimeControlSnapshot(sessionId);
const intent = agentSwitchPending.get(sessionId);
const live = maker.getSession(sessionId);
@@ -16630,7 +16642,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort: (live ? getSessionEffort(sessionId) : row.effort) ?? null,
fastMode: live ? getSessionFastMode(sessionId) : (row.fastMode ?? false),
},
- hasRuntimeOverride: control.effectiveOverride !== null || control.pending !== null || !!intent,
+ hasRuntimeOverride: row.role !== 'routine' && (control.effectiveOverride !== null || control.pending !== null || !!intent),
next: intent ? { agentDeviceId: intent.targetAgentDeviceId === undefined ? row.agentDeviceId : intent.targetAgentDeviceId, agentKind: intent.targetAgentKind, model: intent.model,
providerId: intent.providerId ?? null, effort: intent.effort ?? null, fastMode: intent.fastMode ?? false }
: control.pending?.profile ?? control.effectiveOverride ?? undefined,
@@ -16748,6 +16760,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const [row] = await getDbClient()
.drizzle.select({
capabilitiesJson: botProfileVersions.capabilitiesJson,
+ botId: botSessionLinks.botId,
+ role: botSessionLinks.role,
+ routeKey: botSessionLinks.routeKey,
remoteHostId: sessions.remoteHostId,
})
.from(botSessionLinks)
@@ -16763,7 +16778,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
and(
eq(botSessionLinks.sessionId, sessionId),
isNull(botSessionLinks.archivedAt),
- inArray(botSessionLinks.role, ['canonical', 'delegation', 'group', 'channel', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'delegation', 'group', 'channel', 'thread', 'routine']),
),
)
.limit(1);
@@ -16777,6 +16792,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} catch {
return { isBot: true, candidate: null };
}
+ const routineModel = row.role === 'routine'
+ ? await readRoutineLaneModel(row.botId, row.routeKey) : null;
+ // An explicit routine choice never falls back to its companion's expensive primary model.
+ if (routineModel) return { isBot: true, candidate: null };
const chain = await readEffectiveBotModelChain(config);
const toAgentKind = (harness: string): AgentKind =>
harness === 'codex' ? 'codex' : harness === 'pi' ? 'pi' : 'claude-code';
@@ -18293,7 +18312,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('PRECONDITION_FAILED', SHADOWED_COMPANION_INPUT_MESSAGE);
}
if (args[2] && typeof args[2] === 'object') {
- if (botInput?.source === 'bot' && ['canonical', 'delegation', 'group', 'channel', 'thread'].includes(botInput.role ?? '')) {
+ if (botInput?.source === 'bot' && ['canonical', 'delegation', 'group', 'channel', 'thread', 'routine'].includes(botInput.role ?? '')) {
botFallbackInputs.add(args[2]);
} else {
botFallbackInputs.delete(args[2]);
diff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
index caeddd4a0d..7fc2fc4d0d 100644
--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
@@ -105,7 +105,7 @@ export async function writeScheduledModelBaselineIfProfileCurrent(
AND (SELECT json_array(p.id, p.current_version)
FROM bot_session_links l JOIN bot_profiles p ON p.id = l.bot_id
WHERE l.session_id = sessions.id AND l.archived_at IS NULL
- AND l.role IN ('canonical', 'group', 'channel', 'thread') LIMIT 1) IS ?`,
+ AND l.role IN ('canonical', 'group', 'channel', 'thread', 'routine') LIMIT 1) IS ?`,
[JSON.stringify(baseline), sessionId, expectedBaseline, profileRevision]);
return result.changes === 1;
}
diff --git a/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts b/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts
index 553cd6bc0e..3b5f4d702e 100644
--- a/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts
+++ b/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts
@@ -58,7 +58,7 @@ export function createFeishuTransportResolver(deps: {
eq(botSessionLinks.sessionId, session.sessionId),
eq(sessions.source, 'bot'),
// The owner's Bot Chat: the main Chat or one of its private-chat topics.
- inArray(botSessionLinks.role, ['canonical', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'thread', 'routine']),
))
.limit(1)
.get();
diff --git a/apps/desktop/src/main/mcp-integrations/helperSurface.ts b/apps/desktop/src/main/mcp-integrations/helperSurface.ts
index e04bfaef61..1c4a361ccc 100644
--- a/apps/desktop/src/main/mcp-integrations/helperSurface.ts
+++ b/apps/desktop/src/main/mcp-integrations/helperSurface.ts
@@ -11,7 +11,7 @@ export function classifyHelperSurface(
): 'bot' | 'bot-main' | 'default' {
if (source !== 'bot' && !hasBotLink) return 'default';
// A private-chat topic is the owner's own Bot Chat, so it gets the main Chat's surface.
- return source === 'bot' && hasBotLink && (main?.role === 'canonical' || main?.role === 'thread')
+ return source === 'bot' && hasBotLink && (main?.role === 'canonical' || main?.role === 'thread' || main?.role === 'routine')
&& main.status === 'active' && !main.remoteHostId
? 'bot-main'
: 'bot';
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 9366675040..1166d6591b 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -1039,7 +1039,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
eq(botSessionLinks.sessionId, callerSessionId),
eq(sessions.source, 'bot'),
// The owner's Bot Chat: the main Chat or one of its private-chat topics.
- inArray(botSessionLinks.role, ['canonical', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'thread', 'routine']),
))
.limit(1);
if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scope) {
@@ -1082,7 +1082,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
and(
eq(botSessionLinks.sessionId, callerSessionId),
eq(sessions.source, 'bot'),
- inArray(botSessionLinks.role, ['canonical', 'thread']),
+ inArray(botSessionLinks.role, ['canonical', 'thread', 'routine']),
),
)
.limit(1);
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index ecffd4a1c6..ee86ac4f5b 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -11,6 +11,7 @@ const mock = vi.hoisted(() => ({
load: vi.fn<() => Promise<RoutineState | null>>(async () => null),
profiles: [] as Array<{ id: string; status: string }>,
save: vi.fn<(state: RoutineState) => Promise<void>>(async () => {}),
+ ensureRoutineSession: vi.fn(async ({ routineId }: { routineId: string }) => ({ ok: true as const, sessionId: `lane-${routineId}`, created: false })),
getBot: vi.fn(async () => ({ status: 'active', canonicalSessionId: 'canonical-task' })),
storage: {
get: vi.fn<(id: string) => Promise<Schedule | null>>(async () => null),
@@ -67,7 +68,7 @@ import { companionHomes } from '../../companion-cloud/homes.js';
import { admitTaskAction, assertTaskActionCurrent, hasTaskActionAuthorization } from '../../maker-ipc/taskActionAuthorization.js';
beforeEach(() => { mock.readProfiles.mockImplementation(async () => mock.profiles); });
beforeEach(() => configureRoutineHost({
- getBot: mock.getBot,
+ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession,
getScheduler: () => mock.schedulerReady ? mock.scheduler : null,
getScheduleStorage: () => mock.storage,
}));
@@ -85,7 +86,7 @@ afterEach(async () => {
mock.profiles = [];
vi.useRealTimers();
});
-it('dispatches into the current canonical task through the existing silent runner', async () => {
+it('dispatches into the routine lane and records its task for inspection', async () => {
const routine = await routineTools.save('bot', {
name: 'Review',
prompt: 'Check the PR',
@@ -100,13 +101,14 @@ it('dispatches into the current canonical task through the existing silent runne
expect(mock.storage.insert).toHaveBeenCalledWith(
expect.objectContaining({
source: 'bot',
- targetSessionId: 'canonical-task',
+ targetSessionId: `lane-${routine.id}`,
manual: true,
silentWhenIdle: true,
prompt: expect.stringContaining('Check the PR'),
}),
);
- expect((await routineTools.history('bot', routine.id))[0].resultText).toBe('Reviewed PR');
+ expect((await routineTools.history('bot', routine.id))[0]).toMatchObject({ resultText: 'Reviewed PR', sessionId: `lane-${routine.id}` });
+ expect(mock.ensureRoutineSession).toHaveBeenCalledWith(expect.objectContaining({ botId: 'bot', routineId: routine.id }));
});
it('turns the teammate\'s weekday todo check on and off as one built-in routine', async () => {
@@ -167,7 +169,7 @@ it.skipIf(process.platform === 'win32')('rejects saving a pre-run hook command w
it('blocks enabling and manual runs until imported handover is ready while retaining disabled edits', async () => {
let ready = false;
configureRoutineHost({
- getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
+ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
assertImportedAutomationReady: async (_root, _botId, id) => { if (id === 'imported-routine-id' && !ready) throw new Error('AUTOMATION_HANDOVER_REQUIRED'); },
});
const input = { name: 'Imported', prompt: 'Read data', enabled: false, triggers: [{ id: 'tick', kind: 'interval' as const, intervalMs: 60000 }] };
@@ -188,7 +190,7 @@ it('blocks enabling and manual runs until imported handover is ready while retai
it('uses the revision committed by an explicit handover retry when saving or manually running a routine', async () => {
const engine = await getRoutineEngine();
configureRoutineHost({
- getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
+ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
assertImportedAutomationReady: async (_root, botId, id) => {
const current = engine.list(botId).find(routine => routine.id === id);
if (!current || current.enabled) return;
@@ -205,7 +207,7 @@ it('uses the revision committed by an explicit handover retry when saving or man
it('defers a queued imported run during an unacknowledged handover without dispatching', async () => {
configureRoutineHost({
- getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
+ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
prepareImportedAutomation: async (_root, _routine, runId) => ({ runId, prompt: '', deferred: true }),
});
const routine = await routineTools.save('bot', { name: 'Imported', prompt: 'Read data', enabled: true, triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }] });
@@ -218,7 +220,7 @@ it('defers a queued imported run during an unacknowledged handover without dispa
it.each(['direct', 'model'] as const)('disables an exhausted imported %s routine after recording its final success', async mode => {
const finish = vi.fn(async () => true);
configureRoutineHost({
- getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
+ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
prepareImportedAutomation: async (_root, _routine, runId) => ({ runId, prompt: 'Imported', ...(mode === 'direct' ? { direct: 'Report' } : {}) }),
finishImportedAutomation: finish,
});
@@ -234,7 +236,7 @@ it.each(['direct', 'model'] as const)('disables an exhausted imported %s routine
it('disables a previously exhausted import without dispatching, while ordinary monitor skips stay enabled', async () => {
let exhausted = false;
configureRoutineHost({
- getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
+ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage,
prepareImportedAutomation: async (_root, _routine, runId) => ({ runId, prompt: '', skipped: true, exhausted }),
});
const routine = await routineTools.save('bot', { name: 'Limited', prompt: 'Report', enabled: true, triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }] });
@@ -743,14 +745,14 @@ it('passes the saved reminder choice and check into the shared runner and return
});
await routineTools.runNow('bot', routine.id);
await vi.waitFor(async () => expect((await routineTools.history('bot', routine.id))[0].status).toBe('skipped'));
- expect(mock.storage.insert).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: 'canonical-task', silentWhenIdle: false, preRunHook }));
+ expect(mock.storage.insert).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: `lane-${routine.id}`, silentWhenIdle: false, preRunHook }));
});
it('persists all imported paused routines before tool-policy setup and never dispatches them', async () => {
const { indexAutomationDependencies, normalizeAutomation } = await import('../../bot-import/sourceAutomations.js');
const dependencies = indexAutomationDependencies([]);
const guard = vi.fn(async () => { throw new Error('SOURCE_TOOL_POLICY_NEEDS_MAPPING'); });
- configureRoutineHost({ getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage, assertImportedAutomationReady: guard });
+ configureRoutineHost({ getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage, assertImportedAutomationReady: guard });
for (let index = 0; index < 11; index++) {
const item = normalizeAutomation({ agentId: 'source', kind: 'openclaw', name: 'Source', root: '/fixture', workspace: '/fixture', configFile: '/fixture/openclaw.json' }, {
id: `report-${index}`, name: `Report ${index}`, enabled: false,
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index b7abddd117..68a596c286 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -9,6 +9,7 @@ import {
type Routine,
type RoutineRun,
type RoutineInput,
+ type RoutineModel,
type Schedule,
type ScheduleStorage,
type Scheduler,
@@ -52,6 +53,7 @@ export interface RoutineHostDeps {
finishImportedAutomation?: typeof import('../bot-import/automationRuntime.js').finishImportedAutomation;
recoverImports?: () => Promise<void>;
getBot(botId: string): Promise<{ status: string; canonicalSessionId?: string | null }>;
+ ensureRoutineSession(input: { botId: string; routineId: string; title: string; modelOverride?: RoutineModel | null }): Promise<{ ok: true; sessionId: string; created: boolean } | { ok: false; message: string }>;
getScheduler(): Pick<Scheduler, 'runNow' | 'pause' | 'delete'> | null;
getScheduleStorage(): Pick<ScheduleStorage, 'get' | 'insert' | 'update' | 'listRuns'>;
}
@@ -142,7 +144,7 @@ async function waitForStartupDependency<T>(
}
}
-/** Resolve the current canonical task at dispatch time, preserving its actual model and permissions. */
+/** Each standing instruction owns one persistent companion lane. */
async function execute(scope: string, routine: Routine, run: RoutineRun, signal: AbortSignal, canDispatch: () => boolean) {
assertScope(scope);
const scheduler = getRoutineHost().getScheduler();
@@ -192,6 +194,11 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
const exhausted = await getRoutineHost().finishImportedAutomation?.(root, routine, bot.canonicalSessionId, run.id, imported.direct, true, signal, () => assertScope(scope));
return { resultText: imported.direct, ...(exhausted ? { disableRoutine: true } : {}) };
}
+ const lane = await getRoutineHost().ensureRoutineSession({ botId: routine.botId, routineId: routine.id, title: routine.name, modelOverride: routine.modelOverride });
+ assertScope(scope);
+ if (!lane.ok) throw new Error(lane.message);
+ if (signal.aborted) throw new Error('Routine cancelled');
+ if (!canDispatch()) return { deferred: true };
const storage = getRoutineHost().getScheduleStorage();
const id = `routine-${routine.id}`;
const now = Date.now();
@@ -208,7 +215,7 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
agentKind: 'pi',
workspaceKind: 'dialogue',
useWorktree: false,
- targetSessionId: bot.canonicalSessionId,
+ targetSessionId: lane.sessionId,
// Rules saved before this preference existed were quiet; only new omissions
// are persisted as false by RoutineEngine.
silentWhenIdle: routine.silentWhenIdle ?? true,
@@ -240,10 +247,11 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
const completed = rows.find((row) => row.id === result.runId);
if (!completed) throw new Error('Routine execution record is missing');
const exhausted = imported && completed.status === 'success'
- ? await getRoutineHost().finishImportedAutomation?.(root, routine, bot.canonicalSessionId, run.id, completed.resultText ?? '', false, signal, () => assertScope(scope)) : false;
+ ? await getRoutineHost().finishImportedAutomation?.(root, routine, lane.sessionId, run.id, completed.resultText ?? '', false, signal, () => assertScope(scope)) : false;
return {
...(exhausted ? { disableRoutine: true } : {}),
scheduleRunId: result.runId,
+ sessionId: lane.sessionId,
skipped: completed.status === 'skipped',
resultText: completed.resultText,
...(completed?.status === 'success' || completed?.status === 'skipped'
@@ -646,7 +654,8 @@ export async function listCompanionRoutines(botId: string, selfDeviceId: string
id: routine.id,
input: { name: routine.name, prompt: routine.prompt, enabled: routine.enabled, triggers: routine.triggers,
...(routine.silentWhenIdle !== undefined ? { silentWhenIdle: routine.silentWhenIdle } : {}),
- ...(routine.preRunHook !== undefined ? { preRunHook: routine.preRunHook } : {}) },
+ ...(routine.preRunHook !== undefined ? { preRunHook: routine.preRunHook } : {}),
+ ...(routine.modelOverride !== undefined ? { modelOverride: routine.modelOverride } : {}) },
originDeviceId: selfDeviceId,
}));
}
@@ -675,3 +684,14 @@ export async function importCompanionRoutines(botId: string, routines: Companion
}
for (const id of remove) if (existing.has(id) && !builtinIds.has(id)) await routineTools.remove(botId, id);
}
+
+/** Read without starting the scheduler: previews and manual sends may precede engine startup. */
+export async function readRoutineLaneModel(botId: string, routeKey: string | null): Promise<RoutineModel | null> {
+ if (!routeKey?.startsWith('routine:')) return null;
+ const scope = activeOwnerScopeKey();
+ assertScope(scope);
+ const routines = current?.scope === scope ? current.engine.list(botId)
+ : (await new RoutineFileStore(ownerScopedUserDataPath()).load())?.routines ?? [];
+ assertScope(scope);
+ return routines.find((routine) => routine.botId === botId && `routine:${routine.id}` === routeKey)?.modelOverride ?? null;
+}
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 dd7deb9e2a..50f0f04a9c 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
@@ -254,11 +254,11 @@ describe('MakerScheduleRunner background subagent task tracking', () => {
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);
+ vi.mocked(maker.getSessionMeta).mockResolvedValue({ id: 'bot-session', agentKind: 'claude-code', model: 'claude-sonnet-4-6', effort: 'low', 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(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({ permissionMode: mode, planMode: true, effort: 'low', 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');
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
index 4a3984a9da..5e0a9817d6 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
@@ -218,16 +218,18 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
expect(mocks.createMessage.mock.calls[0][1].content).toBe('check the PR status');
});
- it.each([true, false])(
- 'keeps ordinary task events visible without duplicating the final report (silenced=%s)',
- async (silenced) => {
+ // Independent routines must retain the same inspectable transcript as ordinary tasks.
+ it.each([true, false].flatMap(silenced => ['ordinary', 'routine'].map(kind => ({ silenced, kind }))))(
+ 'keeps $kind events visible without duplicating the final report (silenced=$silenced)',
+ async ({ silenced, kind }) => {
const h = createSessionHarness(acceptingSend());
const { runner, notifier } = createRunnerHarness(h.session, { silenced });
- const promise = runner.fire(baseSchedule({ silentWhenIdle: true }), createFireContext());
+ const id = kind === 'routine' ? 'routine-check' : 'schedule-1';
+ const promise = runner.fire(baseSchedule({ id, source: kind === 'routine' ? 'bot' : 'user', silentWhenIdle: true }), createFireContext());
await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalled());
const origin = {
kind: 'scheduler' as const,
- scheduleId: 'schedule-1',
+ scheduleId: id,
scheduleName: 'pr follow-up',
runId: 'run-1',
};
@@ -252,7 +254,7 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
h.emit({ type: 'text', turnOrigin: origin, data: { text: 'Review fixed', isFinal: true } });
h.emit(done);
await promise;
- expect(mocks.createMessage.mock.calls[0][1].content).toBe('check the PR status');
+ expect(mocks.createMessage.mock.calls[0][1].content).toBe(kind === 'routine' ? '[UI_ACTION_TRIGGER]check the PR status' : 'check the PR status');
expect(
mocks.createMessage.mock.calls.filter(([, body]) => body.role === 'assistant'),
).toHaveLength(0);
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 6ff7604934..c334583fd1 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -1328,7 +1328,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
let reconciledEffort = resolvedSelection
? (resolvedSelection.effort ?? undefined)
- : this.reconcileEffortForModel(effectiveAgentKind, model, schedule.effort, schedule.id);
+ : this.reconcileEffortForModel(effectiveAgentKind, model, schedule.effort || heartbeatEffort, schedule.id);
// 隐式改道后的来源级 reconcile(PR #744 review 第二十七轮):上面的 clamp 用的是
// merged capability,分辨不出来源差异 —— 改道后的落地拷贝 effort 支持可能更窄、
// 可能不支持 Fast,原样透传会被上游拒。按 (verdict.providerId, model) 的拷贝重查:
diff --git a/apps/desktop/src/main/scheduler-host/silent-output.ts b/apps/desktop/src/main/scheduler-host/silent-output.ts
index 1a2aad400d..1b6acf255f 100644
--- a/apps/desktop/src/main/scheduler-host/silent-output.ts
+++ b/apps/desktop/src/main/scheduler-host/silent-output.ts
@@ -23,9 +23,11 @@ export function isSilencedSchedulerTurn(origin: SendOrigin | undefined): boolean
/** Ordinary tasks keep their transcript even when completion notifications are silent. */
export function hidesScheduledTranscript(
- schedule: Pick<Schedule, 'source' | 'silentWhenIdle'>,
+ schedule: Pick<Schedule, 'source' | 'silentWhenIdle'> & Partial<Pick<Schedule, 'id'>>,
): boolean {
- return schedule.source === 'bot' && schedule.silentWhenIdle === true;
+ // Routine backing schedules now run in independent lanes: keep their full inspectable transcript.
+ // Legacy non-routine Bot schedules may still target the main timeline.
+ return schedule.source === 'bot' && schedule.silentWhenIdle === true && !schedule.id?.startsWith('routine-');
}
/** Run-scoped presentation gate. Raw provider events still reach the scheduler and usage ledger. */
diff --git a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
index a88000e904..42cdd54c16 100644
--- a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
@@ -1,3 +1,8 @@
+import { useBotProfiles } from './botStore';
+import type { BotModelRoute } from '../../../shared/botModelChain';
+import { useNavigate } from 'react-router-dom';
+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';
+import { BotTaskModelEditor } from './BotTaskModelEditor';
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { Clock3, Check, ChevronRight, CircleAlert, Pause, Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -39,8 +44,10 @@ export function BotRoutines({
backRef,
embedded = false,
header,
+ inheritedRoute,
}: {
embedded?: boolean;
+ inheritedRoute?: BotModelRoute;
/** Settings shown above the list (not inside the editor), e.g. the teammate's follow-up switches. */
header?: ReactNode;
botId: string;
@@ -50,7 +57,12 @@ export function BotRoutines({
}) {
const { confirm } = useConfirmDialog();
const settingsTarget = useBotSettingsTarget();
+ const localBots = useBotProfiles();
+ const primaryRoute = inheritedRoute ?? (settingsTarget.kind === 'local'
+ ? localBots.find((bot) => bot.id === botId)?.capabilities.modelChain[0] : undefined);
const routinesApi = settingsTarget.routines;
+ const navigate = useNavigate();
+ const supportsModels = settingsTarget.kind === 'local' || settingsTarget.routineModels === true;
const inFlight = useRef(false);
const [loading, setLoading] = useState(true);
const [reload, setReload] = useState(0);
@@ -139,6 +151,7 @@ export function BotRoutines({
triggers: value.triggers,
silentWhenIdle: value.silentWhenIdle ?? true,
preRunHook: value.preRunHook ?? null,
+ modelOverride: value.modelOverride ?? null,
});
const saved = routines.find((item) => item.id === selected);
const dirty =
@@ -298,6 +311,10 @@ export function BotRoutines({
key={routine.id}
routine={routine}
disabled={busy}
+ onOpen={supportsModels && routine.builtin !== 'nightly-learning' ? () => {
+ setSelected(routine.id);
+ setDraft(structuredClone(routine));
+ } : undefined}
hint={routine.builtin === 'nightly-learning' && nightly.view?.frequency === 'weekly'
? t('routines.builtinNightlyLearning.hintWeekly') : undefined}
extra={routine.builtin === 'nightly-learning' && nightlyLocal
@@ -381,6 +398,7 @@ export function BotRoutines({
<label className="block space-y-2">
<span className="text-[var(--text-secondary)]">{t('routines.name')}</span>
<Input
+ disabled={!!saved?.builtin}
autoFocus={selected === 'new'}
value={draft.name}
onChange={(name) => setDraft({ ...draft, name })}
@@ -389,11 +407,27 @@ export function BotRoutines({
<label className="block space-y-2">
<span className="text-[var(--text-secondary)]">{t('routines.instructions')}</span>
<Textarea
+ disabled={!!saved?.builtin}
rows={8}
value={draft.prompt}
onChange={(prompt) => setDraft({ ...draft, prompt })}
/>
</label>
+ {supportsModels && <BotTaskModelEditor inheritedRoute={primaryRoute} inheritanceHint={t('bots.model.inheritPrimary')}
+ value={draft.modelOverride ? {
+ harness: draft.modelOverride.agentKind === 'claude-code' ? 'claude' : draft.modelOverride.agentKind,
+ model: draft.modelOverride.model, providerId: draft.modelOverride.providerId ?? null,
+ effort: draft.modelOverride.effort ?? '', fastMode: draft.modelOverride.fastMode ?? false,
+ agentDeviceId: draft.modelOverride.agentDeviceId ?? null,
+ } : null}
+ disabled={busy} deviceId={settingsTarget.deviceId}
+ onChange={(route) => setDraft({ ...draft, modelOverride: route ? {
+ agentKind: route.harness === 'claude' ? 'claude-code' : route.harness,
+ model: route.model, providerId: route.providerId, effort: route.effort,
+ fastMode: route.fastMode, agentDeviceId: route.agentDeviceId ?? null,
+ } : null })}
+ />}
+ <fieldset disabled={!!saved?.builtin} className="min-w-0 space-y-5">
<details className="space-y-3">
<summary className="min-h-8 cursor-pointer rounded-full py-2 focus-visible:outline focus-visible:outline-[var(--focus-ring)]">{t('routines.advancedSettings')}</summary>
<label className="flex min-h-8 items-center gap-2">
@@ -523,8 +557,9 @@ export function BotRoutines({
</DropdownMenu>
</div>
</div>
+ </fieldset>
<div className="flex flex-wrap justify-end gap-2">
- {selected !== 'new' && (
+ {selected !== 'new' && !saved?.builtin && (
<Button variant="secondary" disabled={busy} onClick={() => setDeletePending(true)}>
{t('routines.delete')}
</Button>
@@ -597,6 +632,9 @@ export function BotRoutines({
{t(`routines.status.${run.status}`)}
</span>
</summary>
+ {run.sessionId && <Button variant="secondary" size="sm" onClick={() => navigate(standardSessionRoute(run.sessionId!, settingsTarget.deviceId))}>
+ {t('routines.openTask')}
+ </Button>}
{run.resultText && (
<p className="whitespace-pre-wrap break-words text-[var(--text-secondary)]">
{run.resultText}
@@ -896,11 +934,12 @@ function routineInput(routine: Routine): RoutineInput {
triggers: routine.triggers,
...(routine.silentWhenIdle !== undefined ? { silentWhenIdle: routine.silentWhenIdle } : {}),
...(routine.preRunHook !== undefined ? { preRunHook: routine.preRunHook } : {}),
+ ...(routine.modelOverride !== undefined ? { modelOverride: routine.modelOverride } : {}),
};
}
/**
- * 宿主内置的「跟进」:指令与触发条件由宿主维护,这里不进编辑器、不能删,只能暂停或恢复。
+ * 宿主内置规则保留指令与触发条件;普通 Agent 规则允许暂停或单独配置模型。
*/
/** 内置例行任务(跟进、每天查待办、夜间学习)的文案键;名称与说明随界面语言,不用宿主存的名字。 */
const BUILTIN_COPY = {
@@ -968,12 +1007,14 @@ function BuiltinRoutineRow({
routine,
disabled,
onEnabledChange,
+ onOpen,
hint,
extra,
}: {
routine: Routine;
disabled: boolean;
onEnabledChange: (enabled: boolean) => void;
+ onOpen?: () => void;
hint?: string;
extra?: ReactNode;
}) {
@@ -983,7 +1024,10 @@ function BuiltinRoutineRow({
return (
<div className="flex w-full items-start gap-3 border-b border-[var(--border-default)] py-4 last:border-b-0">
<div className="min-w-0 flex-1">
- <p className="break-words text-13 font-medium leading-5">{name}</p>
+ {onOpen ? <button type="button" disabled={disabled} onClick={onOpen}
+ className="flex min-h-6 items-start gap-2 rounded-lg text-left text-13 font-medium leading-5 outline-none hover:text-[var(--text-secondary)] focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
+ <span className="break-words">{name}</span><ChevronRight size={14} className="mt-1 shrink-0" aria-hidden="true" />
+ </button> : <p className="break-words text-13 font-medium leading-5">{name}</p>}
<RoutineState routine={routine} />
<p className="mt-1 text-12 leading-5 text-[var(--text-secondary)]">{hint ?? t(`${copy}.hint`)}</p>
{extra}
diff --git a/apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx b/apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx
index 89e3647da4..9b7191c5eb 100644
--- a/apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx
@@ -5,9 +5,10 @@ import { BotModelChainEditor } from './BotModelChainEditor';
import { useBotTranslation } from './botPronounContext';
/** A purpose-specific override using the same complete-route picker as the primary model. */
-export function BotTaskModelEditor({ value, inheritedRoute, onChange, disabled, hiddenVendors, deviceId }: {
+export function BotTaskModelEditor({ value, inheritedRoute, onChange, disabled, hiddenVendors, deviceId, inheritanceHint }: {
value: BotModelRoute | null;
inheritedRoute?: BotModelRoute;
+ inheritanceHint?: string;
onChange(value: BotModelRoute | null): void;
disabled?: boolean;
hiddenVendors?: MakerVendor[];
@@ -21,6 +22,6 @@ export function BotTaskModelEditor({ value, inheritedRoute, onChange, disabled,
onChange={routes => { if (routes[0]) onChange(routes[0]); }} />
{value ? <Button variant="secondary" tone="quiet" size="sm" compact disabled={disabled}
onClick={() => onChange(null)}>{t('bots.model.inheritPrimary')}</Button>
- : <p className="mt-1 text-12 leading-5 text-[var(--text-secondary)]">{t('bots.model.inheritingPrimary')}</p>}
+ : <p className="mt-1 text-12 leading-5 text-[var(--text-secondary)]">{inheritanceHint ?? t('bots.model.inheritingPrimary')}</p>}
</div>;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
index 78afa8d37f..6beac79ebe 100644
--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx
@@ -781,6 +781,7 @@ export function BotSettings({
<BotRoutines
embedded
botId={bot.id}
+ inheritedRoute={displayedModelChain[0]}
beforeLeaveRef={routineLeaveRef}
backRef={routineBackRef}
header={
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
index 790fd3787b..fc3ec3927a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
@@ -1,6 +1,10 @@
// @vitest-environment jsdom
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render as testingRender, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router-dom';
+import type { ReactElement } from 'react';
+const render = (ui: ReactElement) => testingRender(<MemoryRouter>{ui}</MemoryRouter>);
+vi.mock('../BotTaskModelEditor', () => ({ BotTaskModelEditor: ({ onChange }: { onChange: (value: unknown) => void }) => <button onClick={() => onChange({ harness: 'codex', model: 'budget', providerId: 'subscription', effort: 'medium', fastMode: false })}>Choose routine model</button> }));
import type { Routine } from '@cindy/maker-scheduler';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
@@ -252,8 +256,8 @@ it('hands the editor back step to the host back button and focuses a new routine
expect(document.activeElement).toBe(screen.getByLabelText('routines.name'));
});
-it('shows the host-owned follow-up as a pause-only built-in row that never opens the editor', async () => {
- // 宿主内置的「跟进」:引擎只接受 enabled 变化(BUILTIN_ROUTINE),界面不给改指令、触发条件或删除的入口。
+it('allows an independent follow-up model while keeping its instructions and triggers fixed', async () => {
+ // 宿主内置的「跟进」:引擎只接受 enabled 与模型配置变化(BUILTIN_ROUTINE),界面不给改指令、触发条件或删除的入口。
const builtin: Routine = {
...existing, id: 'builtin-follow-up-bot', name: 'follow-up', prompt: 'host template', builtin: 'follow-up',
};
@@ -267,9 +271,6 @@ it('shows the host-owned follow-up as a pause-only built-in row that never opens
const row = toggle.parentElement!;
expect(row.textContent).toContain('routines.builtinFollowUp.hint');
expect(row.textContent).not.toContain('routines.everyMinutes');
- fireEvent.click(screen.getByText('routines.builtinFollowUp.name'));
- expect(screen.queryByLabelText('routines.instructions')).toBeNull();
-
fireEvent.click(toggle);
await waitFor(() => expect(api.save).toHaveBeenCalledTimes(1));
expect(api.save).toHaveBeenCalledWith(
@@ -279,6 +280,16 @@ it('shows the host-owned follow-up as a pause-only built-in row that never opens
);
expect(api.remove).not.toHaveBeenCalled();
expect(screen.getByText('Daily report')).toBeTruthy();
+ fireEvent.click(screen.getByText('routines.builtinFollowUp.name'));
+ expect((screen.getByLabelText('routines.instructions') as HTMLTextAreaElement).disabled).toBe(true);
+ expect(screen.queryByRole('button', { name: 'routines.delete' })).toBeNull();
+ fireEvent.click(screen.getByText('Choose routine model'));
+ fireEvent.click(screen.getByRole('button', { name: 'routines.save' }));
+ await waitFor(() => expect(api.save).toHaveBeenCalledWith('bot', expect.objectContaining({
+ prompt: 'host template', triggers: builtin.triggers,
+ modelOverride: { agentKind: 'codex', model: 'budget', providerId: 'subscription', effort: 'medium', fastMode: false, agentDeviceId: null },
+ }), builtin.id));
+
});
// Production list switches: previously only built-ins could pause without opening
diff --git a/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts
index ec0890cac7..445593947d 100644
--- a/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts
+++ b/apps/desktop/src/renderer/features/bots/botSettingsTarget.ts
@@ -82,6 +82,8 @@ export interface BotSettingsTarget {
};
/** Routines of the teammate's computer (`onChanged` fires when they change there). */
routines: BotRoutinesApi;
+ /** Host accepts a persistent independent model selection for each routine. */
+ routineModels?: boolean;
autonomy: {
useSettings(): BotAutonomySettingsView | null;
setSchedulerBotId(botId: string | null): Promise<void>;
diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.ts
index 38ca263f29..1bf2ff86c3 100644
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@ -156,10 +156,10 @@ export interface BotSessionProjection {
* Telegram / Feishu group handed to the Bot); see botGroupLane.ts before
* counting sessions.
*/
- kind: 'chat' | 'worker' | 'history' | 'group' | 'channel' | 'thread';
+ kind: 'chat' | 'worker' | 'history' | 'group' | 'channel' | 'thread' | 'routine';
updatedAt: number;
status?: 'active' | 'archived' | 'deleted';
- role?: 'canonical' | 'delegation' | 'history' | 'group' | 'channel' | 'thread';
+ role?: 'canonical' | 'delegation' | 'history' | 'group' | 'channel' | 'thread' | 'routine';
/** Group-lane only: the group whose chat owns this hidden Session. */
groupId?: string;
/** Private-chat topic only: the main-chat message the topic was opened on. */
diff --git a/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts b/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts
index bb273afd32..67cb2468e5 100644
--- a/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts
+++ b/apps/desktop/src/renderer/features/bots/remoteBotSettingsTarget.ts
@@ -355,9 +355,10 @@ export function createRemoteBotSettingsTarget(input: RemoteBotSettingsInput) {
...(sentencePlayback !== undefined ? { sentencePlayback } : {}),
}),
},
+ routineModels: input.ops.has('routines.saveWithModel'),
routines: {
list: (id) => invokeBotSettings(deviceId, 'routines.list', id),
- save: (id, routine, routineId) => invokeBotSettings(deviceId, 'routines.save', id, { input: routine, ...(routineId ? { id: routineId } : {}) }),
+ save: (id, routine, routineId) => invokeBotSettings(deviceId, input.ops.has('routines.saveWithModel') ? 'routines.saveWithModel' : 'routines.save', id, { input: routine, ...(routineId ? { id: routineId } : {}) }),
async remove(id, routineId) {
await invokeBotSettings(deviceId, 'routines.remove', id, { id: routineId });
},
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3c738a88a3..b8212cfd69 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -16256,6 +16256,7 @@
"save": "Save Routine",
"deleteConfirm": "Delete this routine and cancel its pending runs?",
"keep": "Keep Routine",
+ "openTask": "Open Session",
"history": "Run History",
"noRuns": "This routine has not run yet.",
"field": "Field",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 16e46c6a5f..69c28e86b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -16200,6 +16200,7 @@
"save": "ルーティンを保存",
"deleteConfirm": "このルーティンを削除し、待機中の実行をキャンセルしますか?",
"keep": "ルーティンを残す",
+ "openTask": "セッションを開く",
"history": "実行履歴",
"noRuns": "このルーティンはまだ実行されていません。",
"field": "フィールド",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7a3da69507..e4a4ff88e6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -16200,6 +16200,7 @@
"save": "루틴 저장",
"deleteConfirm": "이 루틴을 삭제하고 대기 중인 실행을 취소할까요?",
"keep": "루틴 유지",
+ "openTask": "세션 열기",
"history": "실행 기록",
"noRuns": "이 루틴은 아직 실행되지 않았습니다.",
"field": "필드",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index cd9abe6c41..4b6720f92b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -16200,6 +16200,7 @@
"save": "保存例行任务",
"deleteConfirm": "删除这条例行任务,并取消等待中的运行?",
"keep": "保留例行任务",
+ "openTask": "查看任务",
"history": "运行历史",
"noRuns": "这条例行任务还未运行",
"field": "字段",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 88743b15b0..d9c5c2ab52 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -16200,6 +16200,7 @@
"save": "儲存例行任務",
"deleteConfirm": "刪除這條例行任務,並取消等待中的執行?",
"keep": "保留例行任務",
+ "openTask": "查看任務",
"history": "執行歷史",
"noRuns": "這條例行任務尚未執行",
"field": "欄位",
diff --git a/apps/desktop/src/shared/botRemoteSettings.ts b/apps/desktop/src/shared/botRemoteSettings.ts
index 1028a69383..12c3970b49 100644
--- a/apps/desktop/src/shared/botRemoteSettings.ts
+++ b/apps/desktop/src/shared/botRemoteSettings.ts
@@ -38,6 +38,7 @@ export const BOT_SETTINGS_OPS = [
'routines.sources',
'routines.history',
'routines.save',
+ 'routines.saveWithModel',
'routines.runNow',
'routines.remove',
'voice.models',
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index bf84a93254..ece0c59353 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -155,3 +155,5 @@ Host 不因当前输入缺少主人标记再追加行动同意判定。只认运
当前调用的委托、权限撤销和延迟交付检查继续保留;不恢复过期授权,不自动重发。
实现见 `maker-ipc/taskActionAuthorization.ts`、`taskActionHost.ts` 与
`mcp-integrations/codexHttpBridge.ts`;回归见各自授权及 HTTP 桥接测试。
+
+伙伴例行任务(2026-10-26):桌面与 `routine_save` 共用每条规则的 `modelOverride`,可选引擎、来源、型号、执行位置、推理强度与 Fast;null 恢复跟随伙伴,省略保留选择。执行记录返回独立 `sessionId`。内置跟进/每天查待办也可选模型,指令与触发条件仍由宿主维护。跨电脑桌面设置通过 `routines.saveWithModel` 能力声明协商;手机仍按现有合同不提供例行任务管理。
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 046fda2f10..2459b80d3f 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -19,14 +19,20 @@
Bot Market 原生包的例行任务只通过原导入服务保存停用定义,不接管来源 cron,不建立私有授权迁移绑定。邀请加入与工作执行分开;安装和欢迎不会启用或立即运行规则。用户随后在原伙伴例行任务编辑器明确选择时间、时区并保存启用,继续使用本页既有服务、版本校验与生命周期。
- `@cindy/maker-scheduler`:例行任务校验、匹配、去重、串行落盘和运行状态机。纯逻辑,不依赖 Electron。
-- Desktop routines service:按当前账号保存本地文件,解析伙伴当前的长期任务,调用现有调度执行器。
+- Desktop routines service:按当前账号保存本地文件,为每条规则创建或复用独立的伙伴任务,调用现有调度执行器。
- 插件:第三方身份认证、长连接、消息订阅或本地采集。向宿主报告事件,不指定伙伴、指令或执行权限。
- 桌面远程控制(2026-10-22):控制另一台电脑上的伙伴时,桌面伙伴设置里的「例行任务」页就是本机同一个页面,列表、保存、立即运行、删除和运行历史由伙伴所在电脑的同一个管理服务执行(`management:settings` 的 `routines.*` 操作,见 [伙伴设置动作](../dev-rules/protocol-compatibility.md#伙伴设置动作-managementsettingsremote-resource2026-10-22));那台电脑上的例行任务变化会推送到打开着的页面重读。这是桌面入口,手机仍不提供管理。
- 桌面 UI / MCP / Remote Resources:共用管理服务,不能冒充事件来源。宿主保留 Remote Resources,当前手机端过滤 `routines` 集合及动作。MCP 管理仅走宿主绑定调用者身份的伙伴必备工具;通用 scheduler MCP 不提供可任意指定 botId 的例行任务入口。
-所有执行复用伙伴 canonical task,继承模型、技能和实际权限,包括冷恢复时的权限。合成触发消息不作为用户聊天消息展示;有成果的输出由已有伙伴消息链呈现,空转复用静默策略。每条例行任务最多一个正在执行的运行;等待中的新事件合并为一批。不同规则共享伙伴时,由既有任务队列串行派发。
+每条需要 Agent 执行的例行任务对应一个持久独立 Session(`bot_session_links.role = 'routine'`,`route_key = 'routine:<routineId>'`),重复触发复用,不向伙伴主任务追加执行上下文。它与原伙伴共享 Profile、Home、记忆、技能和实际权限,权限与资料更新同样同步到专线;行动身份仍按本轮来源判定,内置跟进不会因独立任务变成主人授权。
-事件、时间与立即运行触发的批次都以独立宿主作用域执行,不继承发布事件或发起调用的 Agent 轮次行动凭证;当前账号、伙伴状态、规则版本及目标任务的权限检查仍然生效。发布方轮次结束不使已接收批次失效,目标主任务忙碌时沿用下述延期与重试规则。实现与回归见 [service.ts](../../apps/desktop/src/main/routines/service.ts)、[service.test.ts](../../apps/desktop/src/main/routines/__tests__/service.test.ts)(#7044)。
+`modelOverride` 可单独选择完整模型路由(引擎、来源、型号、执行位置、推理强度、Fast);缺失或 null 跟随伙伴模型,显式配置不套用伙伴主模型的备用链。旧客户端省略字段时保留已存选择,null 才清除。保存后下一轮通过普通模型切换与交接入口应用;独立任务内继续交流也使用这份配置。每条例行任务最多一个正在执行的运行;等待事件合成一批,各条规则通过各自任务队列派发。
+
+独立任务保留完整执行记录,历史里的「查看任务」打开原有普通任务页面;静默只控制通知,不隐藏执行正文。它不进入自动跟进的观察列表,避免跟进自己的执行。合成触发输入沿用原有来源说明。夜间学习已有专门宿主流程,不改为这类任务。
+
+远程桌面沿用同一设置页,通过 `routines.saveWithModel` 能力协商展示选模;旧主机不显示选模,新主机接受旧客户端保存时保留覆盖。手机当前仍无例行任务管理入口。模型配置随普通规则的伙伴迁移资料保留,执行任务与运行历史留在执行电脑。
+
+事件、时间与立即运行触发的批次都以独立宿主作用域执行,不继承发布事件或发起调用的 Agent 轮次行动凭证;当前账号、伙伴状态、规则版本及目标任务的权限检查仍然生效。发布方轮次结束不使已接收批次失效,目标独立任务忙碌时沿用下述延期与重试规则。实现与回归见 [service.ts](../../apps/desktop/src/main/routines/service.ts)、[service.test.ts](../../apps/desktop/src/main/routines/__tests__/service.test.ts)(#7044)。
直接执行路径必须取得完整的持久权限/计划模式快照;已有 live Session 还必须提供稳定权限状态,并与持久权限一致。缺失、切换中或不一致时保留原批次延期,不回退到旧权限或把未知计划模式当作关闭。异步准备后在创建 Session 和直接发送前再次读取;冷恢复沿用已保存的有效权限和计划模式。运行信息回写跳过伙伴权限字段,不以普通自动化的默认完全访问覆盖用户选择或并发修改。
@@ -146,8 +152,8 @@ const receipt = await cindy.routines.request({
正本见 [伙伴代表谁](teammate-authority.md)。
- 宿主在例行任务引擎每次启动、伙伴新建(资料广播后立即重读归属)与恢复时幂等 ensure,事件发布前也先确认跟进者的规则已落地
(否则首次安装时的早期事件会被记下回执却没人接收):不存在就建;指令、触发条件或模板版本(`builtinVersion`,随
- `FOLLOW_UP_PROMPT_VERSION` 递增)与模板不同就重写;保留主人的暂停选择。暂停中的伙伴不建。
-- 主人只能暂停 / 恢复:删除(含 `routine_delete`)与修改内容一律以 `BUILTIN_ROUTINE` 拒绝。暂停后该伙伴不再被事件叫醒,
+ `FOLLOW_UP_PROMPT_VERSION` 递增)与模板不同就重写;保留主人的暂停与模型选择。暂停中的伙伴不建。
+- 主人可暂停 / 恢复和配置执行模型;删除(含 `routine_delete`)与修改指令、触发条件一律以 `BUILTIN_ROUTINE` 拒绝。暂停后该伙伴不再被事件叫醒,
本机「等你」改由宿主直接提醒主人。伙伴暂停 / 归档时随伙伴的其它规则一起停摆,删除伙伴时一起清理。
- 云端伙伴的规则同步(companion cloud)不包含内置规则:每台电脑各自 ensure,执行只在主力电脑上发生。
@@ -160,7 +166,7 @@ const receipt = await cindy.routines.request({
- 只在主人打开开关时由 `ensureBuiltin` 建立,之后关掉只暂停、再打开复用同一条,不在启动或伙伴新建时自动建;默认不存在即为关。
- 触发条件:cron `0 9 * * 1-5`(宿主所在时区,建立时取一次),`silentWhenIdle` 开启,没有新待办不打扰主人。
- 指令由宿主模板生成(`TODO_CHECK_PROMPT_VERSION`),要求只用已授权的来源、没连接的不说查过,结果按待办规则记录;
- 主人与伙伴都不能编辑,删除与改内容同样以 `BUILTIN_ROUTINE` 拒绝,桌面例行任务列表里只能暂停或恢复。
+ 主人与伙伴都不能编辑,删除与改内容同样以 `BUILTIN_ROUTINE` 拒绝,桌面例行任务列表可暂停或恢复,详情可单独配置模型。
- 不随云端伙伴同步;执行只在主力电脑上发生,与其它例行任务一致。
## 内置夜间学习例行任务
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 7e6ea66f1b..746f65280e 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -64,6 +64,14 @@ Cindy Session,以父任务关系回到发起伙伴,但不冒充该伙伴或
不进入主时间线;群里分工时的每一步由同为 `role = 'group'` 的分工 Session 完成(工作目录见下文例外)。
规则见 [伙伴群聊](bot-group-chat.md)。
+### 例行任务执行(2026-10-26)
+
+每条例行任务使用自己的持久任务(`role = 'routine'`),不再复用主任务上下文。
+它共享伙伴资料、记忆、技能和权限,可独立设置完整模型路由;显式模型不使用主模型备用链。
+内置跟进与每天查待办同样支持,夜间学习保留宿主专用流程。
+完整执行记录从规则历史打开,复用普通任务页面;静默不隐藏这条独立任务的正文。
+仍按来源判定主人、受托或自主身份,独立任务不是新的权限授权。详情见 [例行任务](bot-routines.md)。
+
### 私聊话题(2026-10-21)
Chris:「私聊话题和群聊话题,要真的能把独立事件隔离到独立 session,像 Slack 一样……开了 pr,它开启独立的 session
diff --git a/packages/lizi-mcps/src/scheduler/routines.ts b/packages/lizi-mcps/src/scheduler/routines.ts
index 47b39c7dbb..4eb9d78860 100644
--- a/packages/lizi-mcps/src/scheduler/routines.ts
+++ b/packages/lizi-mcps/src/scheduler/routines.ts
@@ -41,7 +41,7 @@ export function registerRoutineTools(
name: "routine_list",
category: "scheduler",
description:
- "列出伙伴的例行任务。它们复用伙伴的长期任务与权限,可同时由时间和本地事件触发。",
+ "列出伙伴的例行任务。每项使用独立的持久任务和可选模型配置,共享伙伴身份与权限,可同时由时间和本地事件触发。",
inputShape: { botId: z.string().min(1) },
handler: ({ botId }) => result(() => service.list(botId)),
});
@@ -64,6 +64,14 @@ export function registerRoutineTools(
name: z.string().min(1),
prompt: z.string().min(1),
enabled: z.boolean(),
+ modelOverride: z.object({
+ agentKind: z.enum(['claude-code', 'codex', 'pi']),
+ agentDeviceId: z.string().min(1).max(512).nullable().optional(),
+ model: z.string().min(1).max(512),
+ providerId: z.string().min(1).max(512).nullable().optional(),
+ effort: z.enum(['', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).optional(),
+ fastMode: z.union([z.boolean(), z.literal('ultrafast')]).optional(),
+ }).nullable().optional().describe('Model for this routine only. Use an available model/provider pair. null follows the companion; omission preserves the saved choice. Also configurable for built-in follow-up and todo checks.'),
silentWhenIdle: z.boolean().optional().describe('Set true for checks: no routine chatter, report only when needed via schedule_notify_current_run. Reminders and scheduled delivery default to false. Preserve existing user choices.'),
preRunHook: z.object({
command: z.string().min(1).max(32000),
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index d55de4f10e..29dc7939f6 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -813,15 +813,20 @@ describe('routine check configuration', () => {
expect((await f.engine.ensureBuiltin('bot', 'follow-up', input, id))?.revision).toBe(created?.revision);
await expect(f.engine.remove('bot', id)).rejects.toThrow('BUILTIN_ROUTINE');
await expect(f.engine.put('bot', { ...input, prompt: 'edited' }, id)).rejects.toThrow('BUILTIN_ROUTINE');
- const paused = await f.engine.put('bot', { ...input, enabled: false }, id);
+ const modelOverride = { agentKind: 'codex' as const, model: 'budget-model', providerId: 'subscription', effort: 'medium' };
+ const paused = await f.engine.put('bot', { ...input, enabled: false, modelOverride }, id);
+ // Older clients and template refreshes preserve the explicit choice.
+ expect((await f.engine.put('bot', { ...input, enabled: false }, id)).modelOverride).toEqual(modelOverride);
expect(paused).toMatchObject({ builtin: 'follow-up', enabled: false });
expect(await f.engine.publish('github', event('while-paused'))).toEqual({ accepted: 0, duplicate: false });
const realigned = await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 1);
+ expect(realigned?.modelOverride).toEqual(modelOverride);
expect(realigned).toMatchObject({ prompt: 'v2', enabled: false, builtin: 'follow-up', builtinVersion: 1 });
// 模板版本递增:正文相同也重写并记下新版本;同版本再 ensure 不产生新 revision。主人暂停后的选择保留。
const bumped = await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 2);
expect(bumped).toMatchObject({ builtinVersion: 2, enabled: false, revision: realigned!.revision + 1 });
expect((await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 2))?.revision).toBe(bumped?.revision);
+ expect((await f.engine.put('bot', { ...input, prompt: 'v2', enabled: false, modelOverride: null }, id)).modelOverride).toBeNull();
await f.engine.setBotPaused('bot', true);
expect(await f.engine.ensureBuiltin('bot', 'follow-up', input, id)).toBeNull();
} finally { await f.engine.stop(); }
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index 7901b0d4af..9f94b220a7 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -27,6 +27,7 @@ export interface RoutineRun {
finishedAt?: number;
error?: string;
scheduleRunId?: string;
+ sessionId?: string;
resultText?: string;
}
@@ -95,6 +96,7 @@ export interface RoutineEngineDeps {
canDispatch: () => boolean,
): Promise<{
scheduleRunId?: string;
+ sessionId?: string;
error?: string;
resultText?: string;
deferred?: boolean;
@@ -306,14 +308,15 @@ export class RoutineEngine {
// A newly created, unclassified reminder must retain delivery.
...(!existing && parsed.silentWhenIdle === undefined ? { silentWhenIdle: false } : {}),
// Host realign of a built-in rule keeps the owner's latest pause choice.
- ...(options.builtin && existing ? { enabled: existing.enabled } : {}),
+ ...(options.builtin && existing ? { enabled: existing.enabled, modelOverride: existing.modelOverride } : {}),
});
if (id && !existing && !creationId && !options.builtin) throw new Error("Routine not found");
if ((creationId || options.builtin) && state.routines.some(row => row.id === id && row.botId !== botId)) throw new Error("Routine creation ID already used");
- // Host-owned rules: callers other than ensureBuiltin may only pause/resume them.
+ // Host-owned instructions and triggers stay fixed; callers may pause or choose the execution model.
if (existing?.builtin && !options.builtin &&
- JSON.stringify(parseRoutineInput({ ...existing, enabled: input.enabled })) !== JSON.stringify(input))
- throw new Error(`${BUILTIN_ROUTINE_ERROR}: built-in routines can only be paused or resumed`);
+ JSON.stringify(parseRoutineInput({ ...existing, enabled: input.enabled,
+ ...(existing.builtin !== 'nightly-learning' ? { modelOverride: input.modelOverride } : {}) })) !== JSON.stringify(input))
+ throw new Error(`${BUILTIN_ROUTINE_ERROR}: built-in instructions and triggers cannot be edited`);
const builtin = options.builtin ?? existing?.builtin;
const builtinVersion = options.builtinVersion ?? existing?.builtinVersion;
if (creationId && existing && JSON.stringify(parseRoutineInput(existing)) !== JSON.stringify(input)) throw new Error("Routine already created; refresh before editing");
diff --git a/packages/maker-scheduler/src/routines.ts b/packages/maker-scheduler/src/routines.ts
index 44359ef155..fd8a63b037 100644
--- a/packages/maker-scheduler/src/routines.ts
+++ b/packages/maker-scheduler/src/routines.ts
@@ -1,4 +1,4 @@
-import type { PreRunHookConfig } from "./types.js";
+import type { AgentKind, PreRunHookConfig, Schedule } from "./types.js";
import { nextRun } from "./engine/cron.js";
/** Sources describe events, independently of the connector transporting them. */
@@ -42,6 +42,16 @@ export type RoutineBuiltin = "follow-up" | "todo-check" | "nightly-learning";
/** Stable error prefix for attempts to delete or rewrite a host-owned routine. */
export const BUILTIN_ROUTINE_ERROR = "BUILTIN_ROUTINE";
+/** A routine's explicit choice; null/absence follows its companion's choice. */
+export interface RoutineModel {
+ agentKind: AgentKind;
+ agentDeviceId?: string | null;
+ model: string;
+ providerId?: string | null;
+ effort?: Schedule['effort'];
+ fastMode?: Schedule['fastMode'];
+}
+
/** A single standing instruction, with OR-combined time and event triggers. */
export interface Routine {
/** Derived by the engine, never accepted as configuration. */
@@ -56,9 +66,11 @@ export interface Routine {
silentWhenIdle?: boolean;
/** null explicitly removes the check; omission preserves it on older clients. */
preRunHook?: PreRunHookConfig | null;
+ /** Omission preserves saved settings when an older client edits a rule. */
+ modelOverride?: RoutineModel | null;
/**
* 宿主内置规则(每个伙伴一条的「跟进」与「夜间学习」,以及主人在近况里打开的「每天查待办」)。由宿主模板生成,不接受用户/模型
- * 改写指令与触发条件、不能删除,只能暂停(enabled)。可选字段:旧数据与旧客户端缺省即普通规则,
+ * 改写指令与触发条件、不能删除;可暂停(enabled),普通 Agent 规则可单独选模型。可选字段:旧数据与旧客户端缺省即普通规则,
* state 版本不变。
*/
builtin?: RoutineBuiltin;
@@ -74,7 +86,7 @@ export interface Routine {
export type RoutineInput = Pick<
Routine,
- "name" | "prompt" | "enabled" | "triggers" | "silentWhenIdle" | "preRunHook"
+ "name" | "prompt" | "enabled" | "triggers" | "silentWhenIdle" | "preRunHook" | "modelOverride"
>;
function record(value: unknown): Record<string, unknown> {
@@ -171,7 +183,24 @@ export function parseRoutineInput(value: unknown): RoutineInput {
preRunHook = { command: string(hook.command, 32_000),
...(hook.timeoutMs === undefined ? {} : { timeoutMs: Number(hook.timeoutMs) }) };
}
+ let modelOverride: RoutineModel | null | undefined;
+ if (input.modelOverride === null) modelOverride = null;
+ else if (input.modelOverride !== undefined) {
+ const model = record(input.modelOverride);
+ if (!['claude-code', 'codex', 'pi'].includes(String(model.agentKind))) throw new Error('Invalid routine agent');
+ if (model.effort !== undefined && !['', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(String(model.effort))) throw new Error('Invalid routine effort');
+ if (model.fastMode !== undefined && typeof model.fastMode !== 'boolean' && model.fastMode !== 'ultrafast') throw new Error('Invalid routine fast mode');
+ modelOverride = {
+ agentKind: model.agentKind as AgentKind,
+ model: string(model.model, 512),
+ ...(model.agentDeviceId === undefined ? {} : { agentDeviceId: model.agentDeviceId === null ? null : string(model.agentDeviceId, 512) }),
+ ...(model.providerId === undefined ? {} : { providerId: model.providerId === null ? null : string(model.providerId, 512) }),
+ ...(model.effort === undefined ? {} : { effort: model.effort as RoutineModel['effort'] }),
+ ...(model.fastMode === undefined ? {} : { fastMode: model.fastMode as RoutineModel['fastMode'] }),
+ };
+ }
return {
+ ...(modelOverride === undefined ? {} : { modelOverride }),
...(input.silentWhenIdle === undefined ? {} : { silentWhenIdle: input.silentWhenIdle as boolean }),
...(preRunHook === undefined ? {} : { preRunHook }),
name: string(input.name, 200),