Skip to content

Commit d7ba10f

Browse files
Mika Hertlerclaude
andcommitted
feat: route each scheduled task through its own model priority list
A scheduled task can now carry modelRouting: candidates in priority order (same entries as autoRoutingAllowed: account, account/model, driver:kind) and an optional minUsageLeftPercent. When a run starts a thread, the first usable candidate whose model has at least that much left in every usage window it uses runs. When none has, the usable candidate with the most left runs (earlier entries win ties), so a run that could start never fails at start-up. Unknown, unavailable or exhausted candidates are skipped; only when none is usable does the run fail as before, with the reason. Which windows a model uses is exhaustedUsageWindow's rule, so model-scoped windows, separate pools and credit caps count as when deciding an account is out of usage. Accounts without usage data pass the threshold. A driver: entry tries its accounts with the most left first. autoRoutingAllowed and a webhook's t3.allowed stay the upper bound: the task list narrows them, never widens them. A webhook's t3.model and routing: "fixed" still decide their own run; the task list takes precedence over routing: "auto" and the automatic account setting. Tasks without the option run exactly as before. The routing is stored beside the model selection in model_selection_json under scheduledTaskRouting. ModelSelection decoding drops unknown keys, so builds without this read the row unchanged, and no fork migration id can collide with upstream's (the migrator skips every id up to the highest recorded). Saves that omit modelRouting keep it, null clears it, so the mobile editor and idempotent creates keep a stored list. schedule_task takes modelRouting on create and update and lists it back. The web task editor gets a Model priority field with the threshold. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 529e2e6 commit d7ba10f

15 files changed

Lines changed: 881 additions & 11 deletions

‎apps/server/src/mcp/OrchestratorMcpService.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4359,6 +4359,45 @@ describe("OrchestratorMcpService provider resolution", () => {
43594359
}),
43604360
);
43614361

4362+
it.effect(
4363+
"passes a task's model routing through on create, and keeps or clears it on update",
4364+
() =>
4365+
Effect.gen(function* () {
4366+
const routing = { candidates: ["claude-2", "driver:codex"], minUsageLeftPercent: 20 };
4367+
const inputs = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput>>([]);
4368+
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
4369+
Effect.provide(
4370+
service(
4371+
masterRepository,
4372+
yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]),
4373+
existing,
4374+
inputs,
4375+
),
4376+
),
4377+
);
4378+
yield* mcp.scheduleTask(client, {
4379+
projectId,
4380+
prompt: "Check the build",
4381+
schedule,
4382+
modelRouting: routing,
4383+
});
4384+
yield* mcp.updateScheduledTask(client, {
4385+
scheduledTaskId: existing.id,
4386+
title: "Renamed",
4387+
});
4388+
yield* mcp.updateScheduledTask(client, {
4389+
scheduledTaskId: existing.id,
4390+
modelRouting: null,
4391+
});
4392+
assert.deepEqual(
4393+
(yield* Ref.get(inputs)).map((input) =>
4394+
"modelRouting" in input ? input.modelRouting : "kept",
4395+
),
4396+
[routing, "kept", null],
4397+
);
4398+
}),
4399+
);
4400+
43624401
it.effect("keeps one thread when fresh sessions are turned off before the first run", () =>
43634402
Effect.gen(function* () {
43644403
const inputs = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput>>([]);

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,7 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato
307307
? {}
308308
: { webhookSignature: task.webhook.hasSecret ? "set" : "none" }),
309309
...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }),
310+
...(task.modelRouting === undefined ? {} : { modelRouting: task.modelRouting }),
310311
};
311312
}
312313

@@ -2478,6 +2479,8 @@ const make = Effect.gen(function* () {
24782479
: "new_thread",
24792480
workspaceStrategy: yield* scheduledTaskWorkspaceStrategy(bindToCurrentThread, projectId),
24802481
modelSelection,
2482+
// A replayed create keeps the routing it set unless this call names one.
2483+
...(input.modelRouting === undefined ? {} : { modelRouting: input.modelRouting }),
24812484
runtimeMode: limits.runtimeMode,
24822485
interactionMode: limits.interactionMode,
24832486
createdBy: "agent",
@@ -2591,6 +2594,7 @@ const make = Effect.gen(function* () {
25912594
: "continue",
25922595
workspaceStrategy,
25932596
modelSelection: existing.modelSelection,
2597+
...(input.modelRouting === undefined ? {} : { modelRouting: input.modelRouting }),
25942598
runtimeMode: existing.runtimeMode,
25952599
interactionMode: existing.interactionMode,
25962600
createdBy: existing.createdBy,

‎apps/server/src/mcp/toolkits/orchestrator/handlers.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,16 @@ const handlers = {
106106
{ refused: "schedule tasks in this environment" },
107107
),
108108
McpToolAccess.writes(
109-
({ scheduledTaskId, prompt, title, schedule, enabled, freshSession, bindToCurrentThread }) =>
109+
({
110+
scheduledTaskId,
111+
prompt,
112+
title,
113+
schedule,
114+
enabled,
115+
freshSession,
116+
bindToCurrentThread,
117+
modelRouting,
118+
}) =>
110119
Effect.gen(function* () {
111120
if (scheduledTaskId === undefined) return yield* Effect.die("unreachable");
112121
const scope = yield* McpInvocationContext.McpInvocationContext;
@@ -119,6 +128,7 @@ const handlers = {
119128
enabled,
120129
freshSession,
121130
bindToCurrentThread,
131+
modelRouting,
122132
});
123133
}),
124134
),
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"claudeSystemAppendBytes": 6245,
33
"codexAdditionalContextBytes": 7639,
4-
"mcpToolListJsonBytes": 61709
4+
"mcpToolListJsonBytes": 62199
55
}

‎apps/server/src/scheduledTasks/ScheduledTaskService.test.ts‎

Lines changed: 201 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ import * as Scheduler from "../scheduling/Scheduler.ts";
22
import * as NodeUtil from "node:util";
33

44
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5-
import { assert, it, vi } from "@effect/vitest";
5+
import { assert, describe, it, vi } from "@effect/vitest";
66
import {
77
CommandId,
8+
ModelSelection,
89
ProjectId,
910
ProviderDriverKind,
1011
ProviderInstanceId,
@@ -42,6 +43,9 @@ import * as ScheduledTaskService from "./ScheduledTaskService.ts";
4243
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
4344

4445
const isScheduledTaskError = Schema.is(ScheduledTaskError);
46+
const decodeStoredModelSelection = Schema.decodeUnknownEffect(
47+
Schema.fromJsonString(ModelSelection),
48+
);
4549

4650
const threadShell = (
4751
projectId: ProjectId,
@@ -1312,3 +1316,199 @@ it.effect("a run whose stored model is outside the allowed list fails instead of
13121316
assert.equal(unrestricted.task.lastRunStatus, "succeeded");
13131317
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
13141318
);
1319+
1320+
describe("per-task model routing", () => {
1321+
const account = (
1322+
instanceId: string,
1323+
driver: "codex" | "claudeAgent",
1324+
usedPercent: number,
1325+
): ServerProvider => ({
1326+
instanceId: ProviderInstanceId.make(instanceId),
1327+
driver: ProviderDriverKind.make(driver),
1328+
enabled: true,
1329+
installed: true,
1330+
version: null,
1331+
status: "ready",
1332+
auth: { status: "authenticated" },
1333+
checkedAt: "2026-09-13T00:00:00.000Z",
1334+
models:
1335+
driver === "codex"
1336+
? [{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null }]
1337+
: [{ slug: "claude-opus-5-5", name: "Opus", isCustom: false, capabilities: null }],
1338+
slashCommands: [],
1339+
skills: [],
1340+
usageLimits: {
1341+
checkedAt: "2026-09-13T00:00:00.000Z",
1342+
windows: [
1343+
{
1344+
id: "five_hour",
1345+
kind: "session",
1346+
label: "Session",
1347+
usedPercent,
1348+
resetsAt: "2099-01-01T00:00:00.000Z",
1349+
},
1350+
],
1351+
},
1352+
});
1353+
const stored = { instanceId: ProviderInstanceId.make("claude_a"), model: "claude-opus-5-5" };
1354+
const routing = { candidates: ["claude_a", "claude_b", "codex"], minUsageLeftPercent: 20 };
1355+
1356+
/** A fresh service over the test's database, as after a restart. */
1357+
const serviceLayer = (
1358+
providers: Ref.Ref<ReadonlyArray<ServerProvider>>,
1359+
launched: Ref.Ref<ReadonlyArray<ThreadLaunchService.ThreadLaunchInput>>,
1360+
autoRoutingAllowed: ReadonlyArray<string> = [],
1361+
) =>
1362+
ScheduledTaskService.layer.pipe(
1363+
Layer.provide(
1364+
Layer.mergeAll(
1365+
ManagedPolicy.layerTest(),
1366+
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
1367+
launch: (input) =>
1368+
Ref.update(launched, (all) => [...all, input]).pipe(
1369+
Effect.as({ threadId: ThreadId.make("thread:routed"), resumed: false } as never),
1370+
),
1371+
}),
1372+
Layer.mock(ThreadManagementService.ThreadManagementService)({}),
1373+
Layer.mock(SecretRequests.SecretRequests)({}),
1374+
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1375+
namedProjectsRoot: "/projects",
1376+
isScratchProject: () => Effect.succeed(false),
1377+
}),
1378+
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Ref.get(providers) }),
1379+
ServerSettings.layerTest({
1380+
autoRoutingAllowed: [...autoRoutingAllowed],
1381+
// Named instances run only when configured, as on a real server.
1382+
providerInstances: {
1383+
claude_a: { driver: "claudeAgent", enabled: true, config: {} },
1384+
claude_b: { driver: "claudeAgent", enabled: true, config: {} },
1385+
},
1386+
} as never),
1387+
NodeCrypto.layer,
1388+
Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
1389+
),
1390+
),
1391+
);
1392+
const taskInput = (patch: Partial<ScheduledTaskUpsertInput> = {}): ScheduledTaskUpsertInput => ({
1393+
id: ScheduledTaskId.make("task:routing"),
1394+
title: "Morning routine",
1395+
prompt: "Summarise the inbox",
1396+
enabled: true,
1397+
schedule: { type: "interval", everyMs: 60_000 },
1398+
projectId: ProjectId.make("project:test"),
1399+
workspaceStrategy: { type: "root" },
1400+
modelSelection: stored,
1401+
runtimeMode: "full-access",
1402+
interactionMode: "default",
1403+
...patch,
1404+
});
1405+
const lastLaunch = (launched: Ref.Ref<ReadonlyArray<ThreadLaunchService.ThreadLaunchInput>>) =>
1406+
Ref.get(launched).pipe(Effect.map((all) => all.at(-1)?.modelSelection.instanceId));
1407+
1408+
it.effect("starts each run on the first listed account with enough usage left", () =>
1409+
Effect.gen(function* () {
1410+
const providers = yield* Ref.make<ReadonlyArray<ServerProvider>>([
1411+
account("claude_a", "claudeAgent", 85),
1412+
account("claude_b", "claudeAgent", 30),
1413+
account("codex", "codex", 0),
1414+
]);
1415+
const launched = yield* Ref.make<ReadonlyArray<ThreadLaunchService.ThreadLaunchInput>>([]);
1416+
yield* Effect.gen(function* () {
1417+
const service = yield* ScheduledTaskService.ScheduledTaskService;
1418+
const { task } = yield* service.upsert(taskInput({ modelRouting: routing }));
1419+
assert.deepEqual(task.modelRouting, routing);
1420+
1421+
// claude_a has 15% left, below the threshold: the run goes to claude_b, the next one.
1422+
yield* service.runNow({ id: task.id });
1423+
assert.equal(yield* lastLaunch(launched), "claude_b");
1424+
1425+
// claude_b drops below too; codex is next in the list.
1426+
yield* Ref.update(providers, (all) =>
1427+
all.map((entry) =>
1428+
entry.instanceId === "claude_b" ? account("claude_b", "claudeAgent", 90) : entry,
1429+
),
1430+
);
1431+
yield* service.runNow({ id: task.id });
1432+
assert.equal(yield* lastLaunch(launched), "codex");
1433+
1434+
// Every account below the threshold: the one with the most left runs instead of none.
1435+
yield* Ref.set(providers, [
1436+
account("claude_a", "claudeAgent", 95),
1437+
account("claude_b", "claudeAgent", 85),
1438+
account("codex", "codex", 90),
1439+
]);
1440+
const fallback = yield* service.runNow({ id: task.id });
1441+
assert.equal(yield* lastLaunch(launched), "claude_b");
1442+
assert.equal(fallback.task.lastRunStatus, "succeeded");
1443+
}).pipe(Effect.provide(serviceLayer(providers, launched)));
1444+
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
1445+
);
1446+
1447+
it.effect("never routes outside the global allowed list", () =>
1448+
Effect.gen(function* () {
1449+
const providers = yield* Ref.make<ReadonlyArray<ServerProvider>>([
1450+
account("claude_a", "claudeAgent", 0),
1451+
account("claude_b", "claudeAgent", 50),
1452+
account("codex", "codex", 0),
1453+
]);
1454+
const launched = yield* Ref.make<ReadonlyArray<ThreadLaunchService.ThreadLaunchInput>>([]);
1455+
yield* Effect.gen(function* () {
1456+
const service = yield* ScheduledTaskService.ScheduledTaskService;
1457+
// codex comes first, but the setting allows only Claude accounts.
1458+
const { task } = yield* service.upsert(
1459+
taskInput({ modelRouting: { candidates: ["codex", "claude_b", "claude_a"] } }),
1460+
);
1461+
yield* service.runNow({ id: task.id });
1462+
assert.equal(yield* lastLaunch(launched), "claude_b");
1463+
}).pipe(Effect.provide(serviceLayer(providers, launched, ["driver:claudeAgent"])));
1464+
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
1465+
);
1466+
1467+
it.effect(
1468+
"keeps the routing across replayed and older saves and a restart, and clears it on null",
1469+
() =>
1470+
Effect.gen(function* () {
1471+
const providers = yield* Ref.make<ReadonlyArray<ServerProvider>>([
1472+
account("claude_a", "claudeAgent", 90),
1473+
account("claude_b", "claudeAgent", 10),
1474+
account("codex", "codex", 0),
1475+
]);
1476+
const launched = yield* Ref.make<ReadonlyArray<ThreadLaunchService.ThreadLaunchInput>>([]);
1477+
const commandId = CommandId.make("cmd:routing-create");
1478+
const created = yield* Effect.gen(function* () {
1479+
const service = yield* ScheduledTaskService.ScheduledTaskService;
1480+
const first = yield* service.upsert(
1481+
taskInput({ id: undefined, commandId, modelRouting: routing }),
1482+
);
1483+
// The same create replayed, and an edit from a client that does not know the field.
1484+
const replayed = yield* service.upsert(
1485+
taskInput({ id: undefined, commandId, modelRouting: routing }),
1486+
);
1487+
assert.equal(replayed.task.id, first.task.id);
1488+
const older = yield* service.upsert(taskInput({ id: first.task.id, title: "Renamed" }));
1489+
assert.deepEqual(older.task.modelRouting, routing);
1490+
return first.task;
1491+
}).pipe(Effect.provide(serviceLayer(providers, launched)));
1492+
1493+
// Stored beside the model selection, which still decodes as a plain one.
1494+
const sql = yield* SqlClient.SqlClient;
1495+
const [row] = yield* sql<{
1496+
model_selection_json: string;
1497+
}>`SELECT model_selection_json FROM scheduled_tasks WHERE task_id = ${created.id}`;
1498+
assert.deepEqual(yield* decodeStoredModelSelection(row?.model_selection_json), stored);
1499+
1500+
yield* Effect.gen(function* () {
1501+
const service = yield* ScheduledTaskService.ScheduledTaskService;
1502+
const { tasks } = yield* service.list();
1503+
assert.deepEqual(tasks.find((task) => task.id === created.id)?.modelRouting, routing);
1504+
yield* service.runNow({ id: created.id });
1505+
assert.equal(yield* lastLaunch(launched), "claude_b");
1506+
1507+
const cleared = yield* service.upsert(taskInput({ id: created.id, modelRouting: null }));
1508+
assert.isUndefined(cleared.task.modelRouting);
1509+
yield* service.runNow({ id: created.id });
1510+
assert.equal(yield* lastLaunch(launched), "claude_a");
1511+
}).pipe(Effect.provide(serviceLayer(providers, launched)));
1512+
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
1513+
);
1514+
});

0 commit comments

Comments
 (0)