Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Allow per-cron runtime overrides to control recurring model spend (#1593)

Regan Bell5fecef037cfc
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index d177ed7b3..509c3b5d6 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -2980,7 +2980,14 @@ const apiRoutes: readonly WebRoute[] = [
handle: async (c) => {
const { req, res, user } = c;
const id = c.params.id!;
- let patch: { title?: string; task?: string; schedule?: unknown; enabled?: boolean; archived?: boolean } = {};
+ let patch: {
+ title?: string;
+ task?: string;
+ schedule?: unknown;
+ enabled?: boolean;
+ archived?: boolean;
+ runtime?: unknown;
+ } = {};
try {
const p = JSON.parse(await readBody(req)) as {
title?: unknown;
@@ -2988,7 +2995,9 @@ const apiRoutes: readonly WebRoute[] = [
schedule?: unknown;
enabled?: unknown;
archived?: unknown;
+ runtime?: unknown;
};
+ if ("runtime" in p) patch = { ...patch, runtime: p.runtime };
if ("title" in p) {
if (typeof p.title !== "string")
return json(res, 400, { error: "bad_request", message: "title must be a string" });
@@ -3017,7 +3026,7 @@ const apiRoutes: readonly WebRoute[] = [
if (Object.keys(patch).length === 0)
return json(res, 400, {
error: "bad_request",
- message: "expected title, task, schedule, enabled, or archived",
+ message: "expected title, task, schedule, enabled, archived, or runtime",
});
if (patch.archived === true) patch = { ...patch, enabled: false };
return relayCore(
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 4775ac0cd..e6e078ce6 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -325,7 +325,8 @@ const FAMILIES: AgentApiFamily[] = [
{
method: "GET|PATCH|DELETE",
path: "/v1/crons/:id",
- summary: "inspect, rename, archive, edit, or delete a cron",
+ summary:
+ "inspect, rename, archive, edit, or delete a cron; create/patch accepts runtime: {harnessId, modelId, effortLevel?, fastMode?} for agent tasks, null clears the override; omitted preserves existing defaults",
},
{
method: "GET",
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 3a9d5d634..7e44dc095 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -20,6 +20,9 @@ import { pickMatch, type DirectoryMember } from "../directory/directory-store.ts
import { externalMemberActive } from "../identity/external-members.ts";
import { hasRevisionEvents, recordMessageRevisions } from "../core/message-revisions.ts";
import { answerWebContextRequest } from "./web-context.ts";
+import { availableRuntimeError, validateRuntimeChoice } from "./runtime-config.ts";
+import { assertCronRuntime } from "../cron/runtime.ts";
+import type { Cron } from "../types.ts";
import { validateUserSchedule } from "../cron/schedule.ts";
import type { App, AppDeps, ReachNowResult } from "./app-types.ts";
@@ -71,6 +74,7 @@ export function createMessagingMethods(
| "cronFiresByThreadRefs"
| "latestCronFireForThread"
| "setCronDestination"
+ | "setCronRuntime"
| "setCronRecipientConsent"
| "createWebhook"
| "getWebhook"
@@ -153,8 +157,17 @@ export function createMessagingMethods(
return [...stored, ...viaEmail.filter((member) => !seen.has(personKey(member.principalId)))];
};
+ const validateRuntime = async (cron: Pick<Cron, "runtime" | "ownerScopeId" | "loopId" | "action" | "message">) => {
+ assertCronRuntime(cron);
+ if (!cron.runtime) return;
+ const error =
+ validateRuntimeChoice(cron.runtime) ?? (await availableRuntimeError({ deps }, cron.ownerScopeId, cron.runtime));
+ if (error) throw new Error(error);
+ };
+
return {
async createCron(input) {
+ await validateRuntime(input);
validateUserSchedule(input.schedule);
if (input.runAs === "scopeShared") {
if (input.ownerScopeId.startsWith("personal:"))
@@ -202,6 +215,7 @@ export function createMessagingMethods(
async updateCron(id, patch) {
const before = await deps.crons.get(id);
if (!before) return null;
+ if (patch.runtime !== undefined) await validateRuntime({ ...before, ...patch });
if (patch.schedule) validateUserSchedule(patch.schedule);
if (patch.runAs === "scopeShared") {
if (before.ownerScopeId.startsWith("personal:"))
@@ -252,6 +266,12 @@ export function createMessagingMethods(
}
return outcome;
},
+ async setCronRuntime(id, runtime) {
+ const before = await deps.crons.get(id);
+ if (!before) return null;
+ await validateRuntime({ ...before, runtime });
+ return deps.crons.update(id, { runtime });
+ },
async setCronDestination(id, destination) {
const before = await deps.crons.get(id);
if (!before) return null;
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index 2fc9101af..8f75b7229 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -1,3 +1,4 @@
+import { availableRuntimeError, runtimeConfigBody } from "./runtime-config.ts";
import type { Run } from "../runs/run-store.ts";
import { userRuntimeConfigBody } from "./runtime-config.ts";
import { isSubagentThreadRef, stopSessionTree } from "../sessions/session-syscalls.ts";
@@ -191,6 +192,20 @@ export function createTurnMethods(
? await deps.config.getModelAccountDurable(actor.id)
: "company";
const individualAuth = modelAccount !== "company";
+ if (req.triggered && (req.model || req.harness)) {
+ const choices = await runtimeConfigBody({ deps }, conversationScope(req.conversation, actor.id));
+ const harness = req.harness ?? choices.effective.harnessId;
+ const model = req.model ?? choices.effective.modelId;
+ const error = !isHarnessId(harness)
+ ? "harness_not_approved"
+ : await availableRuntimeError({ deps }, conversationScope(req.conversation, actor.id), {
+ harnessId: harness,
+ modelId: model,
+ effortLevel: req.thinkingLevel,
+ fastMode: req.fastMode,
+ });
+ if (error) return { status: "refused", reason: error };
+ }
let requestedModel = req.model;
let requestedHarness = req.harness;
if (req.surface === "web") {
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 3331fd565..3b25d2152 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -435,6 +435,7 @@ export interface App {
listCronFires(id: string, opts?: { limit?: number }): Promise<{ runs: CronFireLogEntry[]; total: number }>;
cronFiresByThreadRefs(threadRefs: readonly string[]): Promise<CronFireRecord[]>;
latestCronFireForThread(id: string, threadRef: string): Promise<CronFireLogEntry | undefined>;
+ setCronRuntime(id: string, runtime: Exclude<Cron["runtime"], undefined>): Promise<Cron | null>;
setCronDestination(id: string, destination: Destination | undefined): Promise<Cron | null>;
setCronRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
createWebhook(input: CreateWebhookInput): Promise<Webhook>;
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index d68ec7470..a5843d7e6 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -31,6 +31,7 @@ import { isSharedScope, parseScopeId, type Permission, type ScopeId } from "../t
import type { App, VisibleCron } from "./app.ts";
export interface CronCreateRequest {
+ runtime?: Cron["runtime"];
schedule: CronSchedule;
title?: string;
action?: string;
@@ -84,6 +85,7 @@ export type WebhookCreateResult =
| { ok: false; code: "bad_request" | "unknown_destination" | "webhook_create_failed"; message: string };
export interface CronPatchRequest {
+ runtime?: Cron["runtime"];
title?: string;
action?: string;
text?: string;
@@ -212,6 +214,7 @@ function scopeIsMembershipControlled(scope: string, cap: { scopeId: string; priv
function hasCronPatchField(req: CronPatchRequest): boolean {
return (
+ req.runtime !== undefined ||
req.title !== undefined ||
req.action !== undefined ||
req.text !== undefined ||
@@ -294,6 +297,7 @@ async function patchFromCronPatchRequest(
};
}
return {
+ ...(req.runtime !== undefined ? { runtime: req.runtime } : {}),
...(req.title !== undefined ? { title: req.title } : {}),
...(req.action !== undefined ? { action: req.action } : {}),
...(req.text !== undefined ? { message: req.text } : {}),
@@ -505,6 +509,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
const input: CreateCronInput = {
schedule: withDefaultTimezone(req.schedule, capability),
+ ...(req.runtime !== undefined ? { runtime: req.runtime } : {}),
...(req.action !== undefined ? { action: req.action } : {}),
...(req.text !== undefined ? { message: req.text } : {}),
owner: capability.actorId,
@@ -610,6 +615,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
const cron = await app.updateCron(id, patch);
if (!cron) return { ok: false, code: "not_found", message: `no cron ${id}` };
const changeSummary: string[] = [];
+ if (req.runtime !== undefined) changeSummary.push("runtime");
if (req.title !== undefined) changeSummary.push("title");
if (req.action !== undefined || req.text !== undefined) changeSummary.push("task");
if (req.schedule !== undefined) changeSummary.push("schedule");
diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.ts
index c9ef9c34c..37c850c2a 100644
--- a/src/api/routes/admin.ts
+++ b/src/api/routes/admin.ts
@@ -13,7 +13,13 @@ import { testAutoFlagger } from "./admin/auto-flagger-test.ts";
import { egress, listAdminAudit, listAdminErrors, listAdminRuns, metrics } from "./admin/observability.ts";
import { getAdminSession, getAdminSessionLlm, listAdminSessions, listAdminShadowDeliveries } from "./admin/sessions.ts";
import { downloadAdminFile, listAdminFiles, readAdminFile, uploadAdminFile } from "./admin/files.ts";
-import { archiveAdminSkill, getAdminSkill, listAdminArtifacts, putAdminCronDestination } from "./admin/artifacts.ts";
+import {
+ archiveAdminSkill,
+ getAdminSkill,
+ listAdminArtifacts,
+ putAdminCronDestination,
+ putAdminCronRuntime,
+} from "./admin/artifacts.ts";
import { getAdminMemory, listMemoryScopes, putAdminMemory } from "./admin/memory.ts";
import { listSandboxRoutes, migrateSandboxScope, manageSandboxResources } from "./admin/sandbox.ts";
import {
@@ -134,6 +140,7 @@ const routes: ReadonlyArray<Route<ApiCtx>> = [
auth: "either",
handle: listAdminArtifacts,
},
+ { method: "PUT", path: "/v1/admin/crons/:id/runtime", auth: "either", handle: putAdminCronRuntime },
{ method: "PUT", path: "/v1/admin/crons/:id/destination", auth: "either", handle: putAdminCronDestination },
{ method: "GET", path: "/v1/admin/skills/:id", auth: "either", handle: getAdminSkill },
{ method: "DELETE", path: "/v1/admin/skills/:id", auth: "either", handle: archiveAdminSkill },
diff --git a/src/api/routes/admin/artifacts.ts b/src/api/routes/admin/artifacts.ts
index 4b441b965..73b89362c 100644
--- a/src/api/routes/admin/artifacts.ts
+++ b/src/api/routes/admin/artifacts.ts
@@ -1,3 +1,5 @@
+import { isCronRuntime } from "../../../cron/runtime.ts";
+import { errMessage } from "../../../util/errors.ts";
import { parseScopeId, type Destination } from "../../../types.ts";
import { publicUrlOf } from "../../../deploy/deploy-store.ts";
import { sendJson } from "../../http.ts";
@@ -5,7 +7,6 @@ import { audit, requireScopedAdmin } from "../shared.ts";
import { type ApiCtx } from "../route.ts";
import { notifyOwnerOfCronEdit } from "../../../triggers/edit-notice.ts";
import { requireScopedResource } from "./common.ts";
-import { withoutFireLog } from "../crons.ts";
function isAdminCronDestination(v: unknown): v is Destination {
if (typeof v !== "object" || v === null) return false;
@@ -40,6 +41,10 @@ export async function listAdminArtifacts(ctx: ApiCtx): Promise<void> {
enabled: c.enabled,
archived: c.archived,
schedule: c.schedule,
+ runtime: c.runtime,
+ loopId: c.loopId,
+ runAs: c.runAs,
+ unattendedGrants: c.unattendedGrants,
destination: c.destination,
createdAt: c.createdAt,
lastFiredAt: c.lastFiredAt,
@@ -85,6 +90,39 @@ export async function listAdminArtifacts(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, { scopeId: scope, skills });
}
+export async function putAdminCronRuntime(ctx: ApiCtx): Promise<void> {
+ const { res, app, deps, params, body } = ctx;
+ const id = params.id!;
+ const scoped = await requireScopedResource(
+ ctx,
+ () => app.getCron(id),
+ (cron) => cron.ownerScopeId,
+ "cron",
+ );
+ if (!scoped) return;
+ if (
+ typeof body !== "object" ||
+ body === null ||
+ !("runtime" in body) ||
+ Object.keys(body).some((key) => key !== "runtime") ||
+ body.runtime === undefined ||
+ !isCronRuntime(body.runtime)
+ )
+ return sendJson(res, 400, { error: "bad_request", message: "runtime is required; use null to inherit" });
+ try {
+ const updated = await app.setCronRuntime(id, body.runtime);
+ audit(deps, {
+ principalId: scoped.actor.id,
+ action: "cron.runtime.update",
+ resource: id,
+ scopeLabel: scoped.record.ownerScopeId,
+ });
+ return sendJson(res, 200, { cron: updated ? { id: updated.id, runtime: updated.runtime } : null });
+ } catch (error) {
+ return sendJson(res, 400, { error: "bad_request", message: errMessage(error) });
+ }
+}
+
export async function putAdminCronDestination(ctx: ApiCtx): Promise<void> {
const { res, app, deps, params, body } = ctx;
const id = params.id!;
@@ -120,7 +158,7 @@ export async function putAdminCronDestination(ctx: ApiCtx): Promise<void> {
resource: id,
scopeLabel: cron.ownerScopeId,
});
- return sendJson(res, 200, { cron: updated ? withoutFireLog(updated) : null });
+ return sendJson(res, 200, { cron: updated ? { id: updated.id, destination: updated.destination } : null });
}
export async function getAdminSkill(ctx: ApiCtx): Promise<void> {
diff --git a/src/api/routes/crons.ts b/src/api/routes/crons.ts
index 2a8f36aa6..43eb82b8e 100644
--- a/src/api/routes/crons.ts
+++ b/src/api/routes/crons.ts
@@ -1,3 +1,4 @@
+import { isCronRuntime } from "../../cron/runtime.ts";
import type { Cron } from "../../types.ts";
import type { CreateCronInput, CronPatch } from "../../cron/cron-store.ts";
import { describeRunNowRefusal } from "../../cron/scheduler.ts";
@@ -20,6 +21,7 @@ function defaultTimezoneFor(capability: CapabilityClaims | null): string {
function isCreateCron(b: unknown): b is CreateCronInput {
return (
isObj(b) &&
+ isCronRuntime(b.runtime) &&
userScheduleFromBody(b.schedule) !== null &&
(typeof b.action === "string" || typeof (b as { message?: unknown }).message === "string") &&
(b as { unattendedGrants?: unknown }).unattendedGrants === undefined &&
@@ -32,6 +34,7 @@ function isCreateCron(b: unknown): b is CreateCronInput {
}
type CapabilityCronBody = {
+ runtime?: unknown;
schedule?: unknown;
title?: unknown;
task?: unknown;
@@ -60,7 +63,7 @@ function exactText(b: CapabilityCronBody): string | undefined {
return undefined;
}
-export function withoutFireLog<T extends Cron>(cron: T): Omit<T, "fireLog"> {
+function withoutFireLog<T extends Cron>(cron: T): Omit<T, "fireLog"> {
const { fireLog: _fireLog, ...rest } = cron;
return rest;
}
@@ -95,6 +98,7 @@ async function gateSourceCronRead(ctx: ApiCtx, id: string): Promise<Cron | null>
}
function isCronPatch(b: unknown): b is {
+ runtime?: Cron["runtime"];
title?: string;
task?: string;
action?: string;
@@ -105,7 +109,7 @@ function isCronPatch(b: unknown): b is {
runAs?: "owner" | "scopeFloor" | "scopeShared";
unattendedGrants?: string[];
} {
- if (!isObj(b)) return false;
+ if (!isObj(b) || !isCronRuntime(b.runtime)) return false;
if (!hasCronPatchFields(b)) return true;
const hasTitle = b.title !== undefined;
const hasAction = b.action !== undefined;
@@ -134,6 +138,7 @@ function isCronPatch(b: unknown): b is {
function hasCronPatchFields(b: Record<string, unknown>): boolean {
return (
+ b.runtime !== undefined ||
b.title !== undefined ||
b.action !== undefined ||
b.task !== undefined ||
@@ -188,9 +193,11 @@ async function createCron(ctx: ApiCtx): Promise<void> {
"schedule.cron (5-field expression) or schedule.everyMs/firstFireAt, plus task (what to do) or text (exact text to send), required",
});
}
+ if (!isCronRuntime(b.runtime)) return sendJson(res, 400, { error: "bad_request", message: "invalid cron runtime" });
const result = await ctx.deps.control.createCron(
{
schedule,
+ ...(b.runtime !== undefined ? { runtime: b.runtime } : {}),
...(task !== undefined ? { action: task } : {}),
...(text !== undefined ? { text } : {}),
...(typeof b.title === "string" ? { title: b.title } : {}),
@@ -370,6 +377,7 @@ async function cronById(ctx: ApiCtx): Promise<void> {
const r = await ctx.deps.control.patchCron(
id,
{
+ ...(body.runtime !== undefined ? { runtime: body.runtime } : {}),
...(body.title !== undefined ? { title: body.title } : {}),
...(task !== undefined ? { action: task } : {}),
...(schedule !== undefined ? { schedule } : {}),
@@ -420,6 +428,7 @@ async function cronById(ctx: ApiCtx): Promise<void> {
});
}
const patch: CronPatch = {
+ ...(body.runtime !== undefined ? { runtime: body.runtime } : {}),
...(body.title !== undefined ? { title: body.title } : {}),
...(task !== undefined ? { action: task } : {}),
...(schedule !== undefined ? { schedule } : {}),
diff --git a/src/api/runtime-config.ts b/src/api/runtime-config.ts
index e50641075..43b7ba3dd 100644
--- a/src/api/runtime-config.ts
+++ b/src/api/runtime-config.ts
@@ -236,3 +236,18 @@ export async function webuiModelEnabled(ctx: { deps: RuntimeDeps }, modelId: str
const orgModel = stored?.modelId ?? (await config.getBaseModelOwnDurable(org)) ?? runtimeFallback(ctx).modelId;
return modelId === orgModel;
}
+
+export async function availableRuntimeError(
+ ctx: { deps: RuntimeDeps },
+ scope: ScopeId,
+ choice: RuntimeChoice,
+): Promise<string | null> {
+ await ctx.deps.refreshModels?.();
+ const choices = await runtimeConfigBody(ctx, scope);
+ if (
+ !choices.modelsByHarness[choice.harnessId]?.includes(choice.modelId) ||
+ !(await webuiModelEnabled(ctx, choice.modelId))
+ )
+ return "runtime is no longer available or enabled on this deployment";
+ return validateRuntimeChoice({ ...choice, effortLevel: undefined });
+}
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 85f9ac273..08d6e6e88 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -3110,6 +3110,15 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
requestedRuntime = choice;
};
if (restoredRuntime) await adoptRuntime(restoredRuntime);
+ if (automatedTurn && input.model && input.harness && isHarnessId(input.harness)) {
+ const error = await deps.validateScheduledRuntime?.(scopeId, {
+ harnessId: input.harness,
+ modelId: input.model,
+ effortLevel: input.thinkingLevel,
+ fastMode: input.fastMode,
+ });
+ if (error) throw new NonRetryableTurnError(error);
+ }
const runHarnessSegment = (
harnessInput: string,
extras: {
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index 9ac0d8a6f..6952d24a2 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -176,6 +176,10 @@ export interface OrchestratorDeps {
webhooks?: WebhookStore;
control?: ControlService;
runtime?: RuntimeService;
+ validateScheduledRuntime?: (
+ scope: import("../../types.ts").ScopeId,
+ choice: import("../../harness/harness.ts").RuntimeChoice,
+ ) => Promise<string | null>;
livenessCache?: LivenessCache;
connectorTokens?: ConnectorTokenStore;
connectorStatusCache?: ConnectorStatusCache;
diff --git a/src/cron/cron-store.ts b/src/cron/cron-store.ts
index 616bad560..a20f3c484 100644
--- a/src/cron/cron-store.ts
+++ b/src/cron/cron-store.ts
@@ -22,10 +22,12 @@ import {
setTriggerRecipientConsent,
type CreateTriggerInput,
} from "../triggers/trigger-store.ts";
+import { assertCronRuntime } from "./runtime.ts";
import { hashId } from "../util/crypto.ts";
import { advanceNextFireAt, isCalendarSchedule, normalizeSchedule, recoverNextFireAt } from "./schedule.ts";
export interface CreateCronInput extends CreateTriggerInput {
+ runtime?: Cron["runtime"];
enabled?: boolean;
schedule: Cron["schedule"];
title?: string;
@@ -38,6 +40,7 @@ export interface CreateCronInput extends CreateTriggerInput {
}
export interface CronPatch {
+ runtime?: Cron["runtime"];
title?: string;
action?: string;
message?: string;
@@ -103,6 +106,7 @@ export function createCronStore(
return {
async create(input) {
assertNoEscalation(input);
+ assertCronRuntime(input);
const now = Date.now();
const title = normalizeTitle(input.title);
const { schedule, nextFireAt } = normalizeSchedule(input.schedule, now);
@@ -118,6 +122,7 @@ export function createCronStore(
contentPart(input.unattendedGrants),
contentPart(title),
...(input.loopId !== undefined ? [contentPart(input.loopId)] : []),
+ ...(input.runtime ? [contentPart(input.runtime)] : []),
]);
return createDeduped(backing, contentId, (id) => ({
...buildTriggerBase(input, id, now),
@@ -131,12 +136,17 @@ export function createCronStore(
...(input.members ? { members: input.members } : {}),
...(input.unattendedGrants ? { unattendedGrants: input.unattendedGrants } : {}),
...(input.loopId ? { loopId: input.loopId } : {}),
+ ...(input.runtime ? { runtime: input.runtime } : {}),
}));
},
get: (id) => backing.get(id),
list: () => backing.all(),
async update(id, patch) {
+ const before = await backing.get(id);
+ if (!before) return null;
+ assertCronRuntime({ ...before, ...patch });
const fields: Partial<Cron> = {};
+ if (patch.runtime !== undefined) fields.runtime = patch.runtime;
if (patch.title !== undefined) fields.title = normalizeTitle(patch.title);
if (patch.action !== undefined) fields.action = patch.action;
if (patch.message !== undefined) fields.message = patch.message;
diff --git a/src/cron/runtime.ts b/src/cron/runtime.ts
new file mode 100644
index 000000000..5acb7f0b4
--- /dev/null
+++ b/src/cron/runtime.ts
@@ -0,0 +1,29 @@
+import type { Cron } from "../types.ts";
+import type { RuntimeChoice } from "../harness/harness.ts";
+import { isHarnessId, thinkingLevelsForHarness } from "../model/pi-models.ts";
+import { isObj } from "../util/objects.ts";
+
+export function isCronRuntime(value: unknown): value is RuntimeChoice | null | undefined {
+ if (value === undefined || value === null) return true;
+ return (
+ isObj(value) &&
+ Object.keys(value).every((key) => ["harnessId", "modelId", "effortLevel", "fastMode"].includes(key)) &&
+ isHarnessId(value.harnessId) &&
+ typeof value.modelId === "string" &&
+ value.modelId.trim().length > 0 &&
+ (value.effortLevel === undefined ||
+ (typeof value.effortLevel === "string" &&
+ value.effortLevel !== "auto" &&
+ thinkingLevelsForHarness(value.harnessId).includes(value.effortLevel))) &&
+ (value.fastMode === undefined || typeof value.fastMode === "boolean")
+ );
+}
+
+export function assertCronRuntime(cron: Pick<Cron, "runtime" | "loopId" | "action" | "message">): void {
+ if (!isCronRuntime(cron.runtime))
+ throw new Error(
+ "runtime requires harnessId, modelId and optional explicit effortLevel/fastMode; null inherits defaults",
+ );
+ if (cron.runtime && (cron.loopId || !cron.action?.trim() || cron.message !== undefined))
+ throw new Error("runtime overrides require an agent cron task, not a loop or exact-message cron");
+}
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.ts
index a1c6e77e9..ab65c1aeb 100644
--- a/src/cron/scheduler.ts
+++ b/src/cron/scheduler.ts
@@ -270,6 +270,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
fireKey,
threadRef,
surface: "cron",
+ ...(cron.runtime ? { runtime: cron.runtime } : {}),
...(cron.title ? { title: cron.title } : {}),
onClaimed: async () => {
await deps.crons.beginFire(cron.id, runningEntry);
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index ef7f4d6d5..f3a7bf430 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -204,6 +204,7 @@ function fmtCronSchedule(c: {
}
interface CronLike {
+ runtime?: import("./harness.ts").RuntimeChoice | null;
id: string;
title?: string;
enabled: boolean;
@@ -276,7 +277,10 @@ function fmtCronLine(c: CronLike, preview = false): string {
!preview && c.lastFireNote && Number.isFinite(c.lastFireNote.at)
? `\n shift-change note (${utcMinute(c.lastFireNote.at)}${c.lastFireNote.by ? `, by ${c.lastFireNote.by}` : ""}): ${c.lastFireNote.text}`
: "";
- return `${c.id}${c.title ? ` "${c.title}"` : ""} — ${fmtCronSchedule(c)}${dest}${state}${next}${what ? `\n ${what}` : ""}${note}`;
+ const runtime = c.runtime
+ ? `\n runtime: ${c.runtime.harnessId}/${c.runtime.modelId}${c.runtime.effortLevel ? ` (${c.runtime.effortLevel})` : ""}`
+ : "";
+ return `${c.id}${c.title ? ` "${c.title}"` : ""} — ${fmtCronSchedule(c)}${dest}${state}${next}${what ? `\n ${what}` : ""}${runtime}${note}`;
}
function fmtCronCreated(r: {
@@ -2325,6 +2329,37 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"outcome + anything the next fire must know. Overwrites the previous note.",
}),
),
+ runtime: Type.Optional(
+ Type.Union(
+ [
+ Type.Null(),
+ Type.Object({
+ harnessId: Type.Union([
+ Type.Literal("pi"),
+ Type.Literal("opencode"),
+ Type.Literal("codex"),
+ Type.Literal("claude"),
+ ]),
+ modelId: Type.String(),
+ effortLevel: Type.Optional(
+ Type.Union([
+ Type.Literal("low"),
+ Type.Literal("medium"),
+ Type.Literal("high"),
+ Type.Literal("xhigh"),
+ Type.Literal("max"),
+ Type.Literal("ultracode"),
+ ]),
+ ),
+ fastMode: Type.Optional(Type.Boolean()),
+ }),
+ ],
+ {
+ description:
+ "create/patch: optional runtime override for an agent task. Omit to preserve defaults; null clears an override. Use runtime get to discover approved models/harnesses. Choose a cheaper model and explicit low effort when the whole task, including failure handling, is simple. Unavailable choices fail closed. Auto effort is not supported here yet.",
+ },
+ ),
+ ),
enabled: Type.Optional(Type.Boolean({ description: "patch only: false pauses the cron, true resumes it." })),
archived: Type.Optional(Type.Boolean({ description: "patch only: true archives the cron." })),
limit: Type.Optional(
@@ -2365,6 +2400,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
}
const r = await tc.cronCreate({
schedule: params.schedule,
+ ...(params.runtime !== undefined ? { runtime: params.runtime } : {}),
...(params.title !== undefined ? { title: params.title } : {}),
...(params.task !== undefined ? { action: params.task } : {}),
...(params.text !== undefined ? { text: params.text } : {}),
@@ -2496,6 +2532,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
true,
);
const r = await tc.cronPatch(id, {
+ ...(params.runtime !== undefined ? { runtime: params.runtime } : {}),
...(params.title !== undefined ? { title: params.title } : {}),
...(params.task !== undefined ? { action: params.task } : {}),
...(params.text !== undefined ? { text: params.text } : {}),
diff --git a/src/triggers/keychain-ask.ts b/src/triggers/keychain-ask.ts
index 2341eed5c..6df46dc43 100644
--- a/src/triggers/keychain-ask.ts
+++ b/src/triggers/keychain-ask.ts
@@ -78,6 +78,7 @@ export async function fireAskResolution(
input: resolutionInput(ask, grant),
fireKey: `ask:${ask.id}:${ask.status}`,
surface: "keychain-ask",
+ ...(cron?.runtime ? { runtime: cron.runtime } : {}),
deferWhenBusy: true,
...(cron
? {
diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.ts
index 59d7a09e8..d01218778 100644
--- a/src/triggers/run-trigger.ts
+++ b/src/triggers/run-trigger.ts
@@ -40,6 +40,7 @@ export interface TriggerDeps {
}
export interface TriggerSpec {
+ runtime?: import("../harness/harness.ts").RuntimeChoice | null;
title?: string;
owner: string;
ownerScopeId: ScopeId;
@@ -310,7 +311,12 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
...(!isScopeFloor && !isScopeShared && spec.unattendedGrants
? { unattendedGrants: spec.unattendedGrants }
: {}),
- ...turnModelOptions({ triggered: true, ...(spec.thinkingLevel ? { thinkingLevel: spec.thinkingLevel } : {}) }),
+ ...(spec.runtime ? { model: spec.runtime.modelId, harness: spec.runtime.harnessId } : {}),
+ ...turnModelOptions({
+ triggered: true,
+ thinkingLevel: spec.runtime?.effortLevel ?? spec.thinkingLevel,
+ fastMode: spec.runtime?.fastMode,
+ }),
...(spec.readOnly ? { readOnly: true } : {}),
...(typeof spec.turnWallClockMs === "number" ? { turnWallClockMs: spec.turnWallClockMs } : {}),
...(spec.destination ? { triggerDestination: spec.destination } : {}),
diff --git a/src/types.ts b/src/types.ts
index 0e98de5c8..e70ea6e19 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -268,6 +268,7 @@ export interface CronFireNote {
}
export interface Cron extends TriggerBase {
+ runtime?: import("./harness/harness.ts").RuntimeChoice | null;
schedule: CronSchedule;
nextFireAt?: number;
lastAttemptAt?: number;
diff --git a/src/wiring.ts b/src/wiring.ts
index 10c351880..dc2f364fd 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1,3 +1,4 @@
+import { availableRuntimeError } from "./api/runtime-config.ts";
import { createApprovalStore } from "./core/approval-store.ts";
import { createKeychainApprovals } from "./credentials/keychain-approval.ts";
import { flushErrorReporting, startTiming } from "../plugins/chassis/src/error-reporting.ts";
@@ -2388,6 +2389,22 @@ export function buildApp(
);
cronChanged.notify = (id) => scheduler.notifyChanged(id);
orchestratorDeps.control = createControlService(app, scheduler, admin);
+ orchestratorDeps.validateScheduledRuntime = (scope, choice) =>
+ availableRuntimeError(
+ {
+ deps: {
+ config: configStore,
+ harnessId: fallbackHarness,
+ baseModelDefault: fallback.modelId,
+ providerKeys: providerKeysPresent(config),
+ modelCredentials,
+ modelCredentialFetch: overrides.modelCredentialFetch,
+ refreshModels,
+ },
+ },
+ scope,
+ choice,
+ );
orchestratorDeps.runtime = createRuntimeService(
{
config: configStore,
diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.ts
index 3c68e4315..1ca9fb5c1 100644
--- a/test/admin-agent-capability.test.ts
+++ b/test/admin-agent-capability.test.ts
@@ -759,3 +759,44 @@ for (const room of [scopeId("personal", "admin-alice"), scopeId("channel", "C1")
}
});
}
+
+test("shared-channel admin runtime mutations do not return a private cron prompt", async () => {
+ const s = start();
+ try {
+ await s.built.config.setSharingPosture("channel:C1", "isolated");
+ const cron = await s.built.app.createCron({
+ ownerScopeId: "personal:U1",
+ owner: "U1",
+ createdBy: "U1",
+ schedule: { everyMs: 60_000 },
+ action: "private task details",
+ });
+ const cap = await capFor("admin-alice", { scope: "channel:C1" });
+ const headers = { "x-agent-capability": cap, "content-type": "application/json" };
+ const read = await fetch(`${s.base}/v1/admin/crons?scope=personal:U1`, { headers });
+ assert.equal(read.status, 403);
+ const updated = await fetch(`${s.base}/v1/admin/crons/${cron.id}/runtime?scope=personal:U1`, {
+ method: "PUT",
+ headers,
+ body: JSON.stringify({ runtime: null }),
+ });
+ assert.equal(updated.status, 200);
+ assert.deepEqual(await updated.json(), { cron: { id: cron.id, runtime: null } });
+ const retargeted = await fetch(`${s.base}/v1/admin/crons/${cron.id}/destination?scope=personal:U1`, {
+ method: "PUT",
+ headers,
+ body: JSON.stringify({ destination: null }),
+ });
+ assert.equal(retargeted.status, 200);
+ assert.deepEqual(await retargeted.json(), { cron: { id: cron.id } });
+ const unattended = await capFor("admin-alice", { live: false, scope: "channel:C1" });
+ const denied = await fetch(`${s.base}/v1/admin/crons/${cron.id}/runtime?scope=personal:U1`, {
+ method: "PUT",
+ headers: { ...headers, "x-agent-capability": unattended },
+ body: JSON.stringify({ runtime: null }),
+ });
+ assert.equal(denied.status, 403);
+ } finally {
+ await s.close();
+ }
+});
diff --git a/test/admin-artifact-pages.test.ts b/test/admin-artifact-pages.test.ts
index cd346bba8..9e227f40b 100644
--- a/test/admin-artifact-pages.test.ts
+++ b/test/admin-artifact-pages.test.ts
@@ -345,3 +345,45 @@ test("the skills list + detail link an imported skill to its pack; built-in/pers
await s.close();
}
});
+
+test("admin cron runtime edits preserve task authority and reject unavailable or out-of-scope choices", async () => {
+ const s = start();
+ try {
+ const cron = await s.built.crons.create({
+ ownerScopeId: "personal:U1",
+ owner: "U1",
+ createdBy: "U1",
+ schedule: { everyMs: 60_000 },
+ action: "run the existing script",
+ unattendedGrants: ["publish"],
+ destination: { type: "principal", target: "U1" },
+ });
+ const runtime = { harnessId: "mock", modelId: "claude-sonnet-5" };
+ const put = (body: unknown, scope = "personal:U1", actor = ALICE_ADMIN) =>
+ fetch(`${s.base}/v1/admin/crons/${cron.id}/runtime?scope=${scope}`, {
+ method: "PUT",
+ headers: { ...actor, "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ assert.equal((await put({ runtime }, "personal:U1", { "x-admin-actor": "nobody@default-org" })).status, 403);
+ assert.equal((await put({ runtime }, "channel:C9")).status, 403);
+ assert.equal((await put({ runtime: { ...runtime, modelId: "unavailable" } })).status, 400);
+ assert.equal((await put({ runtime, action: "replace the task" })).status, 400);
+ assert.equal((await put({})).status, 400);
+ const result = await put({ runtime });
+ assert.equal(result.status, 200);
+ assert.deepEqual(await result.json(), { cron: { id: cron.id, runtime } });
+ const updated = await s.built.app.getCron(cron.id);
+ assert.deepEqual(updated, { ...cron, runtime });
+ const listed = await json(await fetch(`${s.base}/v1/admin/crons?scope=personal:U1`, { headers: ALICE_ADMIN }));
+ assert.deepEqual(listed.crons[0].runtime, runtime);
+ assert.deepEqual(listed.crons[0].unattendedGrants, cron.unattendedGrants);
+ assert.equal((await put({ runtime: null })).status, 200);
+ assert.deepEqual(await s.built.app.getCron(cron.id), { ...cron, runtime: null });
+ const audit = (await s.built.auditLog.events()).filter((event) => event.action === "cron.runtime.update");
+ assert.equal(audit.length, 2);
+ assert.ok(audit.every((event) => event.principalId === "admin-alice" && event.resource === cron.id));
+ } finally {
+ await s.close();
+ }
+});
diff --git a/test/control-service.test.ts b/test/control-service.test.ts
index 24de63e01..9126697c8 100644
--- a/test/control-service.test.ts
+++ b/test/control-service.test.ts
@@ -1129,3 +1129,77 @@ test("a privileged cron's note is writable by its own fire (grants intact) but r
);
assert.ok(liveOwner.ok, "a live owner turn may still write the note");
});
+
+test("cron runtime create and patch retain ownership gates and refuse unavailable choices", async () => {
+ const { built, control } = setup();
+ built.config.setApprovedHarnesses(["mock"]);
+ const runtime = { harnessId: "mock" as const, modelId: "claude-sonnet-5" };
+ const created = await control.createCron(
+ { title: "runtime", schedule: { everyMs: 60_000 }, action: "check", runtime },
+ claims("U1"),
+ );
+ assert.ok(created.ok, JSON.stringify(created));
+ assert.deepEqual(created.cron.runtime, runtime);
+ const other = await control.patchCron(created.cron.id, { runtime: null }, claims("U9"));
+ assert.equal(other.ok, false);
+ assert.deepEqual((await built.app.getCron(created.cron.id))?.runtime, runtime);
+ const bad = await control.patchCron(
+ created.cron.id,
+ { runtime: { ...runtime, modelId: "does-not-exist" } },
+ claims("U1"),
+ );
+ assert.equal(bad.ok, false);
+ const cleared = await control.patchCron(created.cron.id, { runtime: null }, claims("U1"));
+ assert.ok(cleared.ok, JSON.stringify(cleared));
+ assert.equal(cleared.cron.runtime, null);
+ assert.equal(built.config.getBaseModel("personal:U1"), null);
+});
+
+test("scheduled runtime is refused before execution when its model is no longer enabled, including credential resumes", async () => {
+ const { built } = setup();
+ built.config.setApprovedHarnesses(["mock"]);
+ built.config.setWebuiModels("org:default-org", ["gpt-6-astra"]);
+ await built.config.flushScope("org:default-org");
+ for (const surface of ["cron", "keychain-ask"]) {
+ const result = await built.app.turn({
+ surface,
+ triggered: true,
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef: `cron-runtime-${surface}` },
+ text: "must not execute",
+ harness: "mock",
+ model: "claude-sonnet-5",
+ });
+ assert.equal(result.status, "refused", JSON.stringify(result));
+ assert.match(result.reason ?? "", /runtime is no longer available/);
+ }
+});
+
+test("queued cron rechecks its runtime after admission and preserves the override in durable work", async (t) => {
+ const { built } = setup();
+ built.config.setApprovedHarnesses(["mock"]);
+ await built.config.flushScope("org:default-org");
+ const original = built.runs.enqueue.bind(built.runs);
+ t.mock.method(built.runs, "enqueue", async (input: Parameters<typeof original>[0]) => {
+ const result = await original(input);
+ assert.equal(result.run.request.model, "claude-sonnet-5");
+ assert.equal(result.run.request.harness, "mock");
+ assert.equal(result.run.request.fastMode, false);
+ built.config.setWebuiModels("org:default-org", ["gpt-6-astra"]);
+ await built.config.flushScope("org:default-org");
+ return result;
+ });
+ await assert.rejects(
+ built.app.turn({
+ surface: "cron",
+ triggered: true,
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef: "cron-runtime-revoked-after-enqueue" },
+ text: "must not execute",
+ harness: "mock",
+ model: "claude-sonnet-5",
+ fastMode: false,
+ }),
+ /runtime is no longer available/,
+ );
+});
diff --git a/test/cron-credential-retry.test.ts b/test/cron-credential-retry.test.ts
index a074177d8..071dd633a 100644
--- a/test/cron-credential-retry.test.ts
+++ b/test/cron-credential-retry.test.ts
@@ -18,6 +18,7 @@ async function fixture(run: (request: TurnRequest) => Promise<TurnResult>) {
ownerScopeId: "personal:U_ALICE",
schedule: { everyMs: 60_000 },
action: "read a private dummy account",
+ runtime: { harnessId: "pi", modelId: "gpt-6-luna", effortLevel: "low" },
destination: {
type: "principal",
target: "U_BOB",
@@ -66,6 +67,8 @@ test("busy cron credential resolution leaves its fire retryable and resumes exac
await assert.rejects(fireAskResolution(f.deps, f.ask));
+ assert.equal(requests[0]?.model, "gpt-6-luna");
+ assert.equal(requests[0]?.thinkingLevel, "low");
assert.equal(await f.idempotency.committed(fireKey), false);
assert.equal((await f.deliveries.pending("principal")).length, 0);
const resumed = await fireAskResolution(f.deps, f.ask);
diff --git a/test/cron-scheduler.test.ts b/test/cron-scheduler.test.ts
index 3f7f73e40..5cf910738 100644
--- a/test/cron-scheduler.test.ts
+++ b/test/cron-scheduler.test.ts
@@ -1706,3 +1706,31 @@ test("manual cron preparation and detached fire retain admission across pause",
if (resumed.started) await resumed.settled;
await scheduler.stop();
});
+
+test("scheduled and manual fires use the saved runtime; clearing it restores inherited behavior", async () => {
+ const { crons, calls, scheduler } = harness();
+ const runtime = { harnessId: "pi" as const, modelId: "gpt-6-luna", effortLevel: "low", fastMode: false };
+ const cron = await crons.create({
+ schedule: { everyMs: 60_000 },
+ action: "check status",
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: "personal:U1",
+ runtime,
+ });
+ await scheduler.tick(cron.nextFireAt!);
+ await runNowSettled(scheduler, cron.id);
+ assert.equal(calls.length, 2);
+ for (const call of calls) {
+ assert.equal(call.model, runtime.modelId);
+ assert.equal(call.harness, runtime.harnessId);
+ assert.equal(call.thinkingLevel, "low");
+ assert.equal(call.fastMode, false);
+ }
+ await crons.update(cron.id, { runtime: null });
+ await scheduler.tick(cron.nextFireAt! + 60_000);
+ assert.equal(calls.length, 3);
+ assert.equal(calls[2]?.model, undefined);
+ assert.equal(calls[2]?.harness, undefined);
+ assert.equal(calls[2]?.thinkingLevel, "xhigh");
+});
diff --git a/test/cron-store.test.ts b/test/cron-store.test.ts
index cccc1ba19..2e4b3d375 100644
--- a/test/cron-store.test.ts
+++ b/test/cron-store.test.ts
@@ -894,3 +894,50 @@ test("backfillFires survives a cron deleted mid-loop: entries still reach the ta
assert.equal((await store.listFires("stays")).total, 1);
assert.equal((await backing.get("stays"))!.fireLog, undefined, "the surviving cron is still stripped");
});
+
+test("cron runtime overrides survive store reload, distinguish creation, and clear without changing the task", async () => {
+ const backing = createMemoryMap<Cron>();
+ const store = createCronStore(backing);
+ const input = { ...base, schedule: { everyMs: 60_000 } };
+ const runtime = { harnessId: "pi" as const, modelId: "gpt-6-luna", effortLevel: "low" };
+ const inherited = await store.create(input);
+ const overridden = await store.create({ ...input, runtime });
+ assert.notEqual(inherited.id, overridden.id);
+ assert.equal((await store.create({ ...input, runtime })).id, overridden.id);
+ const reloaded = createCronStore(backing);
+ assert.deepEqual((await reloaded.get(overridden.id))?.runtime, runtime);
+ await reloaded.update(overridden.id, { title: "new title" });
+ assert.deepEqual((await store.get(overridden.id))?.runtime, runtime);
+ const cleared = await reloaded.update(overridden.id, { runtime: null });
+ assert.equal(cleared?.runtime, null);
+ assert.equal(cleared?.action, input.action);
+ assert.deepEqual(cleared?.schedule, overridden.schedule);
+});
+
+test("cron runtime rejects malformed settings and tasks that would ignore them", async () => {
+ const store = createCronStore();
+ const runtime = { harnessId: "pi" as const, modelId: "gpt-6-luna", effortLevel: "low" };
+ for (const invalid of [
+ {},
+ { ...runtime, modelId: " " },
+ { ...runtime, effortLevel: "auto" },
+ { ...runtime, effortLevel: "garbage" },
+ { ...runtime, fastMode: "yes" },
+ { ...runtime, surprise: true },
+ ]) {
+ await assert.rejects(
+ store.create({ ...base, schedule: { everyMs: 60_000 }, runtime: invalid as never }),
+ /runtime requires/,
+ );
+ }
+ await assert.rejects(
+ store.create({ ...base, schedule: { everyMs: 60_000 }, loopId: "loop", runtime }),
+ /runtime overrides require/,
+ );
+ await assert.rejects(
+ store.create({ ...base, schedule: { everyMs: 60_000 }, message: "hello", runtime }),
+ /runtime overrides require/,
+ );
+ const cron = await store.create({ ...base, schedule: { everyMs: 60_000 }, runtime });
+ await assert.rejects(store.update(cron.id, { action: "" }), /runtime overrides require/);
+});
diff --git a/test/runtime-selection.test.ts b/test/runtime-selection.test.ts
index 0076756cb..74ed8524f 100644
--- a/test/runtime-selection.test.ts
+++ b/test/runtime-selection.test.ts
@@ -1,3 +1,4 @@
+import { availableRuntimeError } from "../src/api/runtime-config.ts";
import test from "node:test";
import assert from "node:assert/strict";
import {
@@ -202,3 +203,34 @@ test("durable runtime resolution hydrates the model catalog before rejecting an
await resolveRuntimeChoiceDurable(config, ORG, PERSONAL, fallback, undefined, hydrate);
assert.equal(hydrations, before);
});
+
+test("explicit runtime validation rejects a revoked scoped model and unsupported fast mode", async () => {
+ const config = createMemoryConfigStore("default-org");
+ config.setApprovedHarnesses(["pi"]);
+ config.setRuntimeSelection(ORG, { harnessId: "pi", modelId: "claude-sonnet-5" });
+ config.setRuntimeSelection(PERSONAL, { harnessId: "pi", modelId: "gpt-6-astra" });
+ config.setWebuiModels(ORG, ["claude-sonnet-5"]);
+ await config.flushScope(ORG);
+ await config.flushScope(PERSONAL);
+ const ctx = { deps: { config, harnessId: "pi" } };
+ assert.match(
+ (await availableRuntimeError(ctx, PERSONAL, { harnessId: "pi", modelId: "gpt-6-astra" }))!,
+ /no longer available/,
+ );
+ assert.equal(
+ await availableRuntimeError(ctx, PERSONAL, { harnessId: "pi", modelId: "claude-sonnet-5", fastMode: true }),
+ "fast_mode_not_supported",
+ );
+});
+
+test("runtime availability preserves the existing harness normalization of inherited scheduled effort", async () => {
+ const config = createMemoryConfigStore("default-org");
+ config.setApprovedHarnesses(["opencode"]);
+ config.setWebuiModels(ORG, ["claude-sonnet-5"]);
+ await config.flushScope(ORG);
+ const choice = { harnessId: "opencode" as const, modelId: "claude-sonnet-5", effortLevel: "xhigh", fastMode: false };
+ assert.equal(await availableRuntimeError({ deps: { config, harnessId: "opencode" } }, PERSONAL, choice), null);
+ const resolved = resolveRuntimeChoice(config, ORG, PERSONAL, choice, choice);
+ assert.equal(resolved.modelId, choice.modelId);
+ assert.equal(resolved.effortLevel, undefined);
+});
diff --git a/test/web-ui-crons.test.ts b/test/web-ui-crons.test.ts
index 517bce9a3..7b20eed02 100644
--- a/test/web-ui-crons.test.ts
+++ b/test/web-ui-crons.test.ts
@@ -266,3 +266,28 @@ test("a private-channel MEMBER may manage a shared cron via the web; a public-ch
for (const id of [privCron.id, pubCron.id]) await built.app.deleteCron(id);
});
+
+test("cron runtime patches pass through the web API, validate, and clear", async () => {
+ built.config.setApprovedHarnesses(["mock"]);
+ const cron = await built.app.createCron({
+ title: "runtime",
+ action: "check",
+ schedule: { everyMs: 60_000 },
+ owner: "alice",
+ createdBy: "alice",
+ ownerScopeId: "personal:alice",
+ });
+ const runtime = { harnessId: "mock", modelId: "claude-sonnet-5" };
+ const patch = (value: unknown) =>
+ fetch(
+ `${webBase}/api/crons/${cron.id}`,
+ asUser("alice", { method: "PATCH", body: JSON.stringify({ runtime: value }) }),
+ );
+ const selected = await patch(runtime);
+ assert.equal(selected.status, 200, await selected.clone().text());
+ assert.deepEqual((await built.app.getCron(cron.id))?.runtime, runtime);
+ assert.equal((await patch({ modelId: "does-not-exist" })).status, 400);
+ assert.equal((await patch({ ...runtime, modelId: "does-not-exist" })).status, 400);
+ assert.equal((await patch(null)).status, 200);
+ assert.equal((await built.app.getCron(cron.id))?.runtime, null);
+});