Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): let teammates choose configured task recovery routes (#5035)
Chris Zhang75e352b085ed
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex ea33a4e059..cd595cb714 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -3451,6 +3451,7 @@ describe('Bot Session task end-to-end runtime', () => {withTransferredWorktree?: Parameters<typeof createBotDelegationService>[0]['withTransferredWorktree'];prepareWorktree?: Parameters<typeof createBotDelegationService>[0]['prepareWorktree'];taskQueue?: Parameters<typeof createBotDelegationService>[0]['taskQueue'];+ taskRoute?: Parameters<typeof createBotDelegationService>[0]['taskRoute'];taskControl?: boolean;queueSnapshots?: Map<string, AgentInputQueuedMessage[]>;onNativeStarted?: (sessionId: string) => void;@@ -3696,6 +3697,7 @@ describe('Bot Session task end-to-end runtime', () => {reconcileWorktree: options.reconcileWorktree,withTransferredWorktree: options.withTransferredWorktree,taskQueue: options.taskQueue,+ taskRoute: options.taskRoute,...(options.taskControl ? { taskControl: {steer, stop: stopTurn,isActive: (id: string) => pendingTurns.some((turn) => turn.sessionId === id && !turn.queued),@@ -6890,6 +6892,45 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it('lets the requesting teammate choose a configured route only after execution ends', async () => {+ await seedPair();+ const current = { agentKind: 'codex' as const, model: 'same-model', providerId: 'subscription', effort: null, fastMode: false };+ const next = { ...current, providerId: 'paid' };+ const inspect = vi.fn(async () => ({ ok: true as const, generation: 7, current, next }));+ const advance = vi.fn(async () => ({ ok: true as const, status: 'applied' as const, generation: 8 }));+ const runtime = createDelegationRuntime({ taskRoute: { inspect, advance } });+ try {+ const started = await runtime.delegation.startSessionTask({+ callerSessionId: 'session-1', objective: '尝试当前已配置的路线。',+ });+ if (!started.ok) throw new Error('Session task did not start');+ await expect(runtime.delegation.advanceSessionTaskRoute('session-1', started.delegationId, 7, 'old'))+ .resolves.toMatchObject({ ok: false, errorCode: 'TASK_ACTIVE' });+ expect(advance).not.toHaveBeenCalled();+ await runtime.delegation.settleSession({ childSessionId: started.childSessionId, outcome: 'error', error: 'Quota exhausted' });+ const turnsBeforeSwitch = runtime.started.length;+ const preview = await runtime.delegation.inspectSessionTaskRoute('session-1', started.delegationId);+ expect(preview).toMatchObject({ ok: true, current: { providerId: 'subscription' }, next: { providerId: 'paid' } });+ if (!preview.ok) throw new Error('Expected route preview');+ await expect(runtime.delegation.advanceSessionTaskRoute('session-1', started.delegationId, 6, preview.selectionToken!))+ .resolves.toMatchObject({ ok: false, errorCode: 'CONFLICT' });+ await expect(runtime.delegation.advanceSessionTaskRoute('session-1', started.delegationId, 7, 'old'))+ .resolves.toMatchObject({ ok: false, errorCode: 'CONFLICT' });+ await expect(runtime.delegation.advanceSessionTaskRoute('session-1', started.delegationId, 7, preview.selectionToken!))+ .resolves.toMatchObject({ ok: true, status: 'applied', generation: 8 });+ expect(advance).toHaveBeenCalledWith(started.childSessionId, 7, next);+ expect(runtime.started).toHaveLength(turnsBeforeSwitch); // Switching never replays the task.+ await expect(runtime.delegation.advanceSessionTaskRoute('unowned-session', started.delegationId, 7, preview.selectionToken!))+ .resolves.toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run(started.childSessionId);+ await expect(runtime.delegation.inspectSessionTaskRoute('session-1', started.delegationId))+ .resolves.toMatchObject({ ok: false, errorCode: 'CHILD_SESSION_INVALID' });+ expect(inspect).toHaveBeenCalledTimes(4); // No new candidate is shown for an archived child.+ } finally {+ runtime.dispose();+ }+ });+it('lets only the requesting Bot control its Session task', async () => {await seedPair();const runtime = createDelegationRuntime();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.tsindex e695f1dfee..bf00e91e5f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts@@ -1,4 +1,6 @@import { describe, expect, it, vi } from 'vitest';+import { nextBotModelRoute } from '../../../shared/botModelChain';+import { createBotSessionTaskRouteBridge } from '../botSessionTaskRouteBridge';import {applyPendingAgentSwitchIfIdle,createPendingAgentSwitchRegistry,@@ -11,6 +13,7 @@ import {type HarnessRuntimeSelectionDeps,} from '../sessionRuntimeHarnessSelection';import type { SessionRuntimeProfile } from '../sessionRuntimeControl';+import type { SessionRuntimeResult } from '../sessionControlService';function setup(running = false) {let generation = 4;@@ -87,6 +90,76 @@ const request = {};describe('runtime harness selection', () => {+ it('routes a configured cross-harness task choice through the runtime controller', async () => {+ const h = setup();+ const bridge = createBotSessionTaskRouteBridge({+ getSessionRuntime: async ({ targetSessionId }) => {+ expect(targetSessionId).toBe('s1');+ return {+ ok: true,+ runtime: {+ runtimeGeneration: h.deps.generation(targetSessionId),+ effectiveProfile: h.effective,+ },+ } as SessionRuntimeResult;+ },+ setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch }) => {+ expect(patch.harness).toBe('codex');+ return setSessionRuntimeHarness(h.deps, {+ targetSessionId,+ expectedGeneration,+ patch: { ...patch, harness: patch.harness! },+ });+ },+ readConfiguredCandidate: async (callerSessionId, current, childSessionId) => {+ expect([callerSessionId, childSessionId]).toEqual(['bot-main', 's1']);+ const route = nextBotModelRoute([+ { harness: 'claude', model: 'claude-fable-5', providerId: 'old-provider', effort: 'high', fastMode: false },+ { harness: 'codex', model: 'gpt-6-astra', providerId: 'openai', effort: '', fastMode: false },+ ], { harness: current.agentKind === 'claude-code' ? 'claude' : current.agentKind,+ model: current.model, providerId: current.providerId });+ return { candidate: route ? {+ agentKind: route.harness === 'claude' ? 'claude-code' : route.harness,+ model: route.model,+ providerId: route.providerId,+ effort: null,+ fastMode: route.fastMode,+ } satisfies SessionRuntimeProfile : null };+ },+ });+ const preview = await bridge.inspect('bot-main', 's1');+ expect(preview).toMatchObject({+ ok: true, generation: 4,+ next: { agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' },+ });+ if (!preview.ok || !preview.next) throw new Error('Expected configured cross-harness route');+ expect(await bridge.advance('s1', preview.generation, preview.next)).toMatchObject({+ ok: true, status: 'deferred', generation: 5,+ });+ expect(h.pending.get('s1')).toMatchObject({+ targetAgentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',+ });+ expect(pendingHarnessRuntimeMutation(h.pending.get('s1'), 5))+ .toMatchObject({ profile: { effort: null } });+ expect(h.close).not.toHaveBeenCalled();+ await expect(bridge.advance('s1', preview.generation, preview.next))+ .resolves.toMatchObject({ ok: false, errorCode: 'CONFLICT' });+ });++ it('keeps a configured default effort instead of inheriting the previous harness effort', async () => {+ const h = setup();+ const result = await setSessionRuntimeHarness(h.deps, {+ ...request, patch: { ...request.patch, effort: null },+ });+ expect(result).toMatchObject({+ ok: true,+ pendingMutation: { profile: { effort: null } },+ });+ expect(h.deps.resolve).toHaveBeenCalledWith(expect.objectContaining({ effort: null }), {+ effort: true, fast: false,+ });+ });+it('blocks sending on the old harness when the accepted target becomes unavailable', async () => {const h = setup();await setSessionRuntimeHarness(h.deps, request);diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex f79899188a..f50f11c919 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -48,6 +48,7 @@ import { BOT_DELEGATION_CLIENT_ID } from '../../shared/botCollaboration.js';import { ensureBotWorkspaceDir } from './botProfileFolder.js';import type { SessionQueuedMessageControlResult, SessionSteerResult, SessionStopResult } from './sessionControlService.js';import { ownerScopedUserDataPath } from '../appSessionState.js';+import type { SessionRuntimeProfile } from './sessionRuntimeControl.js';const ACTIVE_DELEGATION_STATUSES = ['queued', 'running', 'waiting'] as const;/** 一条补充消息的正文上限:够写清「先别做 X,改做 Y」,又不至于变成另一项任务。 */@@ -178,6 +179,17 @@ export interface BotDelegationServiceDeps {> & { effort?: (typeof sessions.$inferSelect)['effort'] }) | null;/** null means the live permission is changing or the caller is closing. */readCallerPermission?: (sessionId: string) => string | { mode: string; generation: number } | null;+ /** Narrow, owner-checked bridge to the ordinary Session runtime controller. */+ taskRoute?: {+ inspect(callerSessionId: string, childSessionId: string): Promise<+ | { ok: true; generation: number; current: SessionRuntimeProfile; next: SessionRuntimeProfile | null }+ | { ok: false; errorCode: string; message: string }+ >;+ advance(childSessionId: string, expectedGeneration: number, route: SessionRuntimeProfile): Promise<+ | { ok: true; status: 'applied' | 'deferred'; generation: number }+ | { ok: false; errorCode: string; message: string }+ >;+ };now?: () => number;createId?: () => string;maxActiveChildren?: number;@@ -3034,6 +3046,62 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};});+ const inspectSessionTaskRoute = (callerSessionId: string, taskId: string) =>+ withTaskOperation(taskId, async () => {+ const found = await findOwnedSessionTask(callerSessionId, taskId);+ if (!found.ok) return found;+ if (!found.row.childSessionId || !deps.taskRoute) {+ return { ok: false as const, errorCode: 'UNSUPPORTED_CAPABILITY', message: 'Task model control is unavailable' };+ }+ const [child] = await getDbClient().drizzle.select({ status: sessions.status })+ .from(sessions).where(eq(sessions.id, found.row.childSessionId)).limit(1);+ if (child?.status !== 'active') {+ return { ok: false as const, errorCode: 'CHILD_SESSION_INVALID', message: 'Task Session is no longer active' };+ }+ if (isActiveDelegation(found.row.status as DelegationStatus) || deps.taskControl?.isActive(found.row.childSessionId)) {+ return { ok: false as const, errorCode: 'TASK_ACTIVE', message: 'Finish or stop the current execution before changing its model' };+ }+ const inspected = await deps.taskRoute.inspect(callerSessionId, found.row.childSessionId);+ return inspected.ok ? { ...inspected, selectionToken: inspected.next+ ? createHash('sha256').update(JSON.stringify([inspected.generation, inspected.next])).digest('hex')+ : null } : inspected;+ });++ const advanceSessionTaskRoute = (callerSessionId: string, taskId: string, expectedGeneration: number, selectionToken: string) =>+ withTaskOperation(taskId, async () => {+ const found = await findOwnedSessionTask(callerSessionId, taskId);+ if (!found.ok) return found;+ const row = found.row;+ if (!row.childSessionId || !deps.taskRoute) {+ return { ok: false as const, errorCode: 'UNSUPPORTED_CAPABILITY', message: 'Task model control is unavailable' };+ }+ const [child] = await getDbClient().drizzle.select({ status: sessions.status })+ .from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1);+ if (child?.status !== 'active') {+ return { ok: false as const, errorCode: 'CHILD_SESSION_INVALID', message: 'Task Session is no longer active' };+ }+ if (isActiveDelegation(row.status as DelegationStatus) || deps.taskControl?.isActive(row.childSessionId)) {+ return { ok: false as const, errorCode: 'TASK_ACTIVE', message: 'Finish or stop the current execution before changing its model' };+ }+ const inspected = await deps.taskRoute.inspect(callerSessionId, row.childSessionId);+ if (!inspected.ok) return inspected;+ if (inspected.generation !== expectedGeneration) {+ return { ok: false as const, errorCode: 'CONFLICT', message: 'Task model changed; inspect it again before retrying' };+ }+ if (!inspected.next) {+ return { ok: false as const, errorCode: 'NO_CONFIGURED_ROUTE', message: 'No further configured model route is available' };+ }+ const currentToken = createHash('sha256')+ .update(JSON.stringify([inspected.generation, inspected.next])).digest('hex');+ if (currentToken !== selectionToken) {+ return { ok: false as const, errorCode: 'CONFLICT', message: 'Configured route changed; inspect it again before retrying' };+ }+ if (deps.taskControl?.isActive(row.childSessionId)) {+ return { ok: false as const, errorCode: 'TASK_ACTIVE', message: 'Task execution restarted before its model could change' };+ }+ return deps.taskRoute.advance(row.childSessionId, expectedGeneration, inspected.next);+ });+const taskControlView = (row: DelegationRow) => {const pause = isActiveDelegation(row.status as DelegationStatus) ? readTaskPause(row) : null;const cancelling = isActiveDelegation(row.status as DelegationStatus) && parseRecord(row.permissionSnapshotJson).taskCancelRequested === true;@@ -3759,6 +3827,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {},listDelegations,getSessionTask,+ inspectSessionTaskRoute,+ advanceSessionTaskRoute,restorePauseForSession,messageSessionTask,stopSessionTask,diff --git a/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.ts b/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.tsnew file mode 100644index 0000000000..a27fc06ac9--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.ts@@ -0,0 +1,65 @@+import type { BotDelegationServiceDeps } from './botDelegationService.js';+import type { SessionRuntimeResult, SessionRuntimeSetResult } from './sessionControlService.js';+import type { SessionRuntimeProfile } from './sessionRuntimeControl.js';++interface TaskRouteBridgeDeps {+ getSessionRuntime(params: { targetSessionId: string }): Promise<SessionRuntimeResult>;+ setSessionRuntime(params: {+ targetSessionId: string;+ expectedGeneration: number;+ patch: {+ harness?: SessionRuntimeProfile['agentKind'];+ model: string;+ providerId: string | null;+ effort: SessionRuntimeProfile['effort'];+ fastMode: boolean;+ };+ }): Promise<SessionRuntimeSetResult>;+ readConfiguredCandidate(+ callerSessionId: string,+ current: SessionRuntimeProfile,+ childSessionId: string,+ ): Promise<{ candidate: SessionRuntimeProfile | null }>;+}++/** Keep Bot task ownership in delegation; this bridge only uses public Session runtime control. */+export function createBotSessionTaskRouteBridge(+ deps: TaskRouteBridgeDeps,+): NonNullable<BotDelegationServiceDeps['taskRoute']> {+ return {+ inspect: async (callerSessionId, childSessionId) => {+ const runtime = await deps.getSessionRuntime({ targetSessionId: childSessionId });+ if (!runtime.ok) return runtime;+ const next = await deps.readConfiguredCandidate(+ callerSessionId, runtime.runtime.effectiveProfile, childSessionId,+ );+ return {+ ok: true,+ generation: runtime.runtime.runtimeGeneration,+ current: runtime.runtime.effectiveProfile,+ next: next.candidate,+ };+ },+ advance: async (childSessionId, expectedGeneration, route) => {+ const current = await deps.getSessionRuntime({ targetSessionId: childSessionId });+ if (!current.ok) return current;+ if (current.runtime.runtimeGeneration !== expectedGeneration) {+ return { ok: false, errorCode: 'CONFLICT', message: 'Task runtime changed before model selection' };+ }+ const result = await deps.setSessionRuntime({+ targetSessionId: childSessionId,+ expectedGeneration,+ patch: {+ ...(current.runtime.effectiveProfile.agentKind === route.agentKind ? {} : { harness: route.agentKind }),+ model: route.model,+ providerId: route.providerId,+ effort: route.effort,+ fastMode: route.fastMode,+ },+ });+ return result.ok+ ? { ok: true, status: result.status, generation: result.generation }+ : result;+ },+ };+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4acd2b8fbd..d8ba668aeb 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -442,6 +442,7 @@ import {discardDelegationQueuedInputs,type BotDelegationService,} from './botDelegationService.js';+import { createBotSessionTaskRouteBridge } from './botSessionTaskRouteBridge.js';import {createBotDirectMessageService,type BotDirectMessageService,@@ -9741,6 +9742,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)fastMode: getSessionFastMode(sessionId),} : null;},+ taskRoute: createBotSessionTaskRouteBridge({+ getSessionRuntime: params => sessionControlService.getSessionRuntime(params),+ setSessionRuntime: params => sessionControlService.setSessionRuntime(params),+ readConfiguredCandidate: (callerSessionId, current, childSessionId) =>+ readBotFallbackCandidate(callerSessionId, current, childSessionId),+ }),dispatch: ({ targetSessionId, message, persistedContent, clientId, onAccepted, dispatcherSessionId }) =>dispatchBotSessionMessage({targetSessionId,@@ -11513,6 +11520,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const readBotFallbackCandidate = async (sessionId: string,current: SessionRuntimeProfile,+ controlSessionId = sessionId,): Promise<{ isBot: boolean; candidate: SessionRuntimeProfile | null }> => {const [row] = await getDbClient().drizzle.select({@@ -11554,12 +11562,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): current.agentKind === 'pi'? 'pi': 'claude';- const control = getSessionRuntimeControlSnapshot(sessionId);+ const control = getSessionRuntimeControlSnapshot(controlSessionId);+ const [controlSession] = controlSessionId === sessionId ? [{ remoteHostId: row.remoteHostId }]+ : await getDbClient().drizzle.select({ remoteHostId: sessions.remoteHostId })+ .from(sessions).where(eq(sessions.id, controlSessionId)).limit(1);const route = nextBotModelRoute(chain,{ harness: currentHarness, model: current.model, providerId: current.providerId },control.visitedRoutes,- (candidate) => !row.remoteHostId || candidate.harness === currentHarness,+ (candidate) => !controlSession?.remoteHostId || candidate.harness === currentHarness,);return {isBot: true,diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.tsindex eb40c9d84f..7864806bb6 100644--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts@@ -90,7 +90,7 @@ export interface SessionControlServiceDeps {harness?: AgentKind;model?: string;providerId?: string | null;- effort?: Effort;+ effort?: Effort | null;fastMode?: boolean;};}): Promise<SessionRuntimeSetResult>;@@ -285,7 +285,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {harness?: AgentKind;model?: string;providerId?: string | null;- effort?: Effort;+ effort?: Effort | null;fastMode?: boolean;};}): Promise<SessionRuntimeSetResult> {diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.tsindex 0e423c31a4..85a7c5f2e1 100644--- a/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts@@ -52,7 +52,7 @@ export async function setSessionRuntimeHarness(harness: AgentKind;model?: string;providerId?: string | null;- effort?: Effort;+ effort?: Effort | null;fastMode?: boolean;};},@@ -92,7 +92,7 @@ export async function setSessionRuntimeHarness(model: patch.model!,// Never inherit an old harness's provider when selecting a new target.providerId: patch.providerId ?? null,- effort: patch.effort ?? effective.effort,+ effort: patch.effort !== undefined ? patch.effort : effective.effort,fastMode: patch.fastMode ?? effective.fastMode,},{ effort: patch.effort !== undefined, fast: patch.fastMode !== undefined },diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 0c2c90e302..307ae52fbc 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -684,6 +684,16 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc}return svc.stopSessionTask(callerSessionId, taskId, mode);},+ inspectSessionTaskRoute: async ({ callerSessionId, taskId }) => {+ const svc = tryGetBotDelegationService();+ if (!svc) return { ok: false, errorCode: 'HOST_NOT_READY', message: 'Session task service not initialized' };+ return svc.inspectSessionTaskRoute(callerSessionId, taskId);+ },+ advanceSessionTaskRoute: async ({ callerSessionId, taskId, expectedGeneration, selectionToken }) => {+ const svc = tryGetBotDelegationService();+ if (!svc) return { ok: false, errorCode: 'HOST_NOT_READY', message: 'Session task service not initialized' };+ return svc.advanceSessionTaskRoute(callerSessionId, taskId, expectedGeneration, selectionToken);+ },},botMessaging: {checkMessage: async (params) => {diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex ce38a84781..175db8e3eb 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -259,6 +259,9 @@ Session 任务遵守同一套机制与呈现契约:子任务仍需要决定时必须重新发出 interaction request,不能让一个失效按钮假装批准成功。- **代理交互**:子任务进入 `waiting` 时先唤回发起伙伴。它能根据用户已表达的意图安全回答就直接用 `message_session_task` 回答;拿不准才在原对话问用户一句。用户不需要跳到子任务找弹窗。+- **代理恢复选择**:发起伙伴可通过任务专属公共工具查看该任务的当前路由及其下一条已配置候选;+ 只在本轮执行结束后由伙伴明确选择切换。切换不自动重放工作;伙伴结合原目标和已完成动作,+ 再决定是否向同一任务发补充消息。未配置的供应商或型号不可擅自加入候选。- **任务卡**:发起方消息流原位出现一张持久任务卡,实时反映排队 / 执行 / 等待 / 终态。卡片不得使用“加入对话”等通讯语言,也不得再叠加顶部运行条或另造一套协同面板。状态由任务行推送驱动,不靠消息文本。diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex da7ca570ce..e6a3a237f8 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -206,6 +206,14 @@ describe("cindy_helper MCP server", () => {delegationId: "session-task-1",childSessionId: "desktop-child-session",}));+ const inspectSessionTaskRoute = vi.fn(async () => ({+ ok: true as const,+ generation: 3,+ current: { agentKind: 'codex', model: 'model-a', providerId: 'subscription', effort: null, fastMode: false },+ next: { agentKind: 'codex', model: 'model-a', providerId: 'paid', effort: null, fastMode: false },+ selectionToken: 'a'.repeat(64),+ }));+ const advanceSessionTaskRoute = vi.fn(async () => ({ ok: true as const, status: 'applied', generation: 4 }));const server = createXdtHelperMcpServer({ resolveSurface: async () => "bot",sessionTasks: {@@ -213,6 +221,8 @@ describe("cindy_helper MCP server", () => {messageSessionTask,getSessionTask,stopSessionTask,+ inspectSessionTaskRoute,+ advanceSessionTaskRoute,},},{@@ -234,6 +244,8 @@ describe("cindy_helper MCP server", () => {"check_session_task","message_session_task","stop_session_task",+ "inspect_session_task_route",+ "advance_session_task_route",]),);expect(tools.map((tool) => tool.name)).not.toContain("collaborate_with_bot");@@ -330,6 +342,18 @@ describe("cindy_helper MCP server", () => {callerSessionId: "bot-parent-session",taskId: "session-task-1",});+ expect(parsePayload(await client.callTool({ name: 'call_tool', arguments: {+ name: 'inspect_session_task_route', args: { task_id: 'session-task-1' },+ } }))).toMatchObject({ ok: true, generation: 3, next: { providerId: 'paid' }, selection_token: 'a'.repeat(64) });+ expect(inspectSessionTaskRoute).toHaveBeenCalledWith({+ callerSessionId: 'bot-parent-session', taskId: 'session-task-1',+ });+ expect(parsePayload(await client.callTool({ name: 'call_tool', arguments: {+ name: 'advance_session_task_route', args: { task_id: 'session-task-1', expected_generation: 3, selection_token: 'a'.repeat(64) },+ } }))).toMatchObject({ ok: true, status: 'applied', generation: 4 });+ expect(advanceSessionTaskRoute).toHaveBeenCalledWith({+ callerSessionId: 'bot-parent-session', taskId: 'session-task-1', expectedGeneration: 3, selectionToken: 'a'.repeat(64),+ });const stopped = parsePayload(await client.callTool({ name: "call_tool", arguments: { name: "stop_session_task", args: { task_id: "session-task-1" } } }),diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 705830bbe4..bb25e764ae 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -156,6 +156,8 @@ interface SessionTaskCallbacks {taskId: string;mode?: 'cancel' | 'request-stop' | 'pause';}): Promise<ControlResult<Record<string, unknown>, string>>;+ inspectSessionTaskRoute?(params: { callerSessionId: string; taskId: string }): Promise<ControlResult<Record<string, unknown>, string>>;+ advanceSessionTaskRoute?(params: { callerSessionId: string; taskId: string; expectedGeneration: number; selectionToken: string }): Promise<ControlResult<Record<string, unknown>, string>>;}interface BotMessagingCallbacks {@@ -480,6 +482,45 @@ function registerSessionTaskControlEntries(},});+ if (deps.sessionTasks.inspectSessionTaskRoute && deps.sessionTasks.advanceSessionTaskRoute) {+ registry.register({+ name: 'inspect_session_task_route',+ category: 'bots',+ description: 'Inspect the current model and next already-configured model route for one of your own Session tasks. This does not change its model or retry work. Use before deciding whether a failed task should use another route.',+ inputShape: { task_id: z.string().min(1).max(128) },+ handler: async ({ task_id }) => {+ const callerError = requireCaller();+ if (callerError) return callerError;+ const result = await deps.sessionTasks!.inspectSessionTaskRoute!({ callerSessionId: callerSessionId()!, taskId: task_id });+ return result.ok+ ? okPayload({ action: 'inspect_session_task_route', task_id,+ generation: result.generation, current: result.current, next: result.next,+ selection_token: result.selectionToken })+ : errorPayload(result.errorCode, result.message);+ },+ });+ registry.register({+ name: 'advance_session_task_route',+ category: 'bots',+ description: 'Choose the exact next already-configured model route shown by inspect_session_task_route for your own ended Session task. This never creates a route, changes your teammate Profile, approves a permission, or replays work. Pass the preview generation and selection token; after switching, send a separate deliberate follow-up with message_session_task if needed. Deferred selections apply at the next safe send boundary.',+ inputShape: {+ task_id: z.string().min(1).max(128),+ expected_generation: z.number().int().min(0),+ selection_token: z.string().regex(/^[a-f0-9]{64}$/),+ },+ handler: async ({ task_id, expected_generation, selection_token }) => {+ const callerError = requireCaller();+ if (callerError) return callerError;+ const result = await deps.sessionTasks!.advanceSessionTaskRoute!({+ callerSessionId: callerSessionId()!, taskId: task_id, expectedGeneration: expected_generation, selectionToken: selection_token,+ });+ return result.ok+ ? okPayload({ action: 'advance_session_task_route', task_id, ...result })+ : errorPayload(result.errorCode, result.message);+ },+ });+ }+registry.register({name: 'message_session_task',category: 'bots',diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.tsindex 1336f5e55b..68dbfe92a6 100644--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts@@ -69,7 +69,7 @@ export const TEAMMATE_CONTROL_GUIDANCE = ['Use `update_teammate_profile` when the user asks to change your name, introduction, identity or your own model selection. Read the current version first and patch only the requested fields. For modelChain, first read `get_app_default_model` for enabled route ids and supported effort/Fast settings; supply the complete ordered chain (1–5 routes), preserving existing candidates unless the user asks to replace them. Set modelChain to null to remove your override and follow the application default again. This saves only your profile through the same settings service, persists across restarts, and applies next turn; it never changes the application default, other teammates, personal Skills, memory or chat history. A next-turn save is not proof of the model running this turn.','For project work, set working_dir to the actual project and use_worktree=true for isolation before starting. check_session_task returns the registered directory. Shell cd/worktree creation does not relocate a Session. timeout_ms defaults to 30 minutes and supports up to 24 hours at creation; terminal follow-up inherits the original budget. Do not claim an existing deadline was extended without a verified host response.','message_session_task returns queued_message_id for queued or steered input. check_session_task exposes only your own queue; optionally query queued_message_id for queued/consuming/dispatched/not-found/unavailable; queue restore errors preserve task results and cannot prove a message is missing. Dispatched means accepted into host history, not proof of model action. Use mode=edit with message or mode=withdraw for your own unconsumed item; consuming input cannot be edited or withdrawn.',- 'Control your own background tasks with `message_session_task` (mode=queue by default, mode=steer for same-turn input, mode=resume for a reversible pause) and `stop_session_task` (mode=cancel by default, request-stop for a graceful stop request, pause to hold execution and queued input). General control tools are not part of the teammate toolset. A successful queue receipt is not a steer, and pausing/requested/unconfirmed is not proof the engine stopped. Check the returned control state; unsupported engines fail explicitly. Pause preserves the same task and Session, holds timers and automatic input, and resumes without replaying completed work. If paused, resume without a message before answering a pending interaction. Only tasks owned by your teammate are controllable.',+ 'Control your own background tasks with `message_session_task` (mode=queue by default, mode=steer for same-turn input, mode=resume for a reversible pause) and `stop_session_task` (mode=cancel by default, request-stop for a graceful stop request, pause to hold execution and queued input). General control tools are not part of the teammate toolset. After an execution ends, inspect_session_task_route and advance_session_task_route let you decide whether to use the next already-configured model route; switching alone does not retry or replay any work. A successful queue receipt is not a steer, and pausing/requested/unconfirmed is not proof the engine stopped. Check the returned control state; unsupported engines fail explicitly. Pause preserves the same task and Session, holds timers and automatic input, and resumes without replaying completed work. If paused, resume without a message before answering a pending interaction. Only tasks owned by your teammate are controllable.','Use `get_capabilities` for application features and UI guidance. It describes the product, not a permission grant or proof that every feature is available here. Use the matching live tool to act, and verify its result before claiming success.',].join('\n');