Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add separate org runtime defaults for crons and sub-agents (#1619)

Joshua Francef7718c33d19f
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index 658e8ce0e..f184f33d9 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -6662,6 +6662,8 @@
[
$("card-base-model"),
+ $("card-cron-runtime"),
+ $("card-subagent-runtime"),
providers,
$("card-webui-models"),
$("card-soul"),
@@ -8158,6 +8160,8 @@
const modelsByHarness = r.data.modelsByHarness || {};
if (requestedView === "models") {
governanceUI.settings.load(r.data, scope, "runtime");
+ governanceUI.settings.load(r.data, scope, "cron-runtime");
+ governanceUI.settings.load(r.data, scope, "subagent-runtime");
governanceUI.settings.load(r.data, scope, "webui-models");
}
refreshModelChoices.push(() => governanceUI.settings.updateCatalog(r.data));
@@ -8660,6 +8664,8 @@
"org-ambient": "st-governance-org-ambient",
"channel-header-pin-default": "st-channel-header-pin-default",
runtime: "st-runtime",
+ "cron-runtime": "st-cron-runtime",
+ "subagent-runtime": "st-subagent-runtime",
"webui-models": "st-webui-models",
"ack-emoji": "st-ack-emoji",
branding: "st-branding",
@@ -8670,6 +8676,8 @@
"soul",
"external-slack-participants",
"runtime",
+ "cron-runtime",
+ "subagent-runtime",
"webui-models",
"ack-emoji",
"branding",
diff --git a/plugins/admin/test/default-view.test.ts b/plugins/admin/test/default-view.test.ts
index 42f924d4d..c64d09f83 100644
--- a/plugins/admin/test/default-view.test.ts
+++ b/plugins/admin/test/default-view.test.ts
@@ -428,7 +428,7 @@ test("admin parity views expose the requested card groups and real navigation ac
"Ambient reply policy",
"Egress policy",
"External Slack audience",
- "Default runtime",
+ "Conversation runtime",
"Custom providers",
"Enabled models",
"Organization SOUL",
diff --git a/plugins/admin/test/settings-lit.test.ts b/plugins/admin/test/settings-lit.test.ts
index b7a039d7b..5a4e7f34f 100644
--- a/plugins/admin/test/settings-lit.test.ts
+++ b/plugins/admin/test/settings-lit.test.ts
@@ -203,3 +203,41 @@ test("runtime reasoning choices follow the selected model and preserve legacy de
dom.window.close();
}
});
+
+test("purpose runtime cards independently set and clear overrides using the runtime editor", () => {
+ const dom = setup();
+ try {
+ dom.window.eval(
+ "settingsUI.load(" + JSON.stringify({ ...models, cronRuntime: null, subagentRuntime: null }) + ',"org:test")',
+ );
+ const doc = dom.window.document;
+ for (const key of ["cron-runtime", "subagent-runtime"]) {
+ const collect = () => JSON.parse(String(dom.window.eval(`JSON.stringify(settingsUI.collect("${key}"))`)));
+ assert.deepEqual(collect(), { inherit: true });
+ assert.equal(doc.querySelectorAll(`#card-${key}`).length, 1);
+ assert.equal((doc.getElementById(`${key}-harness`) as HTMLSelectElement).disabled, true);
+ (doc.getElementById(`${key}-inherit`) as HTMLInputElement).click();
+ const harness = doc.getElementById(`${key}-harness`) as HTMLSelectElement;
+ harness.value = "codex";
+ harness.dispatchEvent(new dom.window.Event("change"));
+ assert.deepEqual(collect(), { harnessId: "codex", modelId: "b", effortLevel: "auto", fastMode: false });
+ (doc.getElementById(`${key}-inherit`) as HTMLInputElement).click();
+ assert.deepEqual(collect(), { inherit: true });
+ assert.equal(dom.window.eval(`settingsUI.states.get("${key}").dirty`), false);
+ }
+ assert.equal(dom.window.eval('settingsUI.collect("runtime").fastMode'), true);
+ dom.window.eval(
+ "settingsUI.load(" +
+ JSON.stringify({
+ ...models,
+ cronRuntime: { harnessId: "codex", modelId: "b", effortLevel: "low", fastMode: false },
+ subagentRuntime: null,
+ }) +
+ ',"org:test")',
+ );
+ assert.equal((doc.getElementById("cron-runtime-inherit") as HTMLInputElement).checked, false);
+ assert.equal((doc.getElementById("cron-runtime-model") as HTMLSelectElement).value, "b");
+ } finally {
+ dom.window.close();
+ }
+});
diff --git a/plugins/admin/test/settings-load.test.ts b/plugins/admin/test/settings-load.test.ts
index ead314621..6030c8333 100644
--- a/plugins/admin/test/settings-load.test.ts
+++ b/plugins/admin/test/settings-load.test.ts
@@ -298,3 +298,59 @@ test("admin shell calls resolve against the shipped Lit bundle", () => {
f.dom.window.close();
}
});
+
+test("models view loads and saves purpose cards through the real page handlers", async () => {
+ const f = litFixture();
+ try {
+ f.root.innerHTML = '<template data-settings-card="card-base-model"></template>';
+ f.ui.settings.mountCards();
+ const data = {
+ baseModelDefault: "model",
+ baseModelOptions: [{ id: "model" }],
+ harnessOptions: ["pi"],
+ thinkingLevelsByHarness: { pi: ["auto", "low"] },
+ runtime: null,
+ cronRuntime: null,
+ subagentRuntime: null,
+ };
+ const requests: any[] = [];
+ const context = vm.createContext({
+ document: f.document,
+ governanceUI: f.ui,
+ requestedView: "models",
+ r: { data },
+ scope: "org:test",
+ governanceReq: 1,
+ governanceSaveSeq: 0,
+ sectionSnapshots: new Map(),
+ governanceSaveReview: async () => true,
+ setStatus: (id: string, message: string, tone: string) => f.ui.status(id.replace(/^st-/, ""), message, tone),
+ api: async (...args: any[]) => {
+ requests.push(args);
+ return { ok: true };
+ },
+ });
+ vm.runInContext(extract('if (requestedView === "models") {', "refreshModelChoices.push"), context);
+ vm.runInContext(extract("const SAVE = Object.fromEntries(", "const sectionSnapshots ="), context);
+ vm.runInContext(
+ extract('document.querySelectorAll("[data-save]").forEach', '$("view-governance").addEventListener("input"'),
+ context,
+ );
+ for (const key of ["cron-runtime", "subagent-runtime"]) {
+ assert.equal(f.document.getElementById(`card-${key}`)!.classList.contains("hidden"), false);
+ const button = f.document.querySelector<HTMLButtonElement>(`[data-save="${key}"]`)!;
+ (f.document.getElementById(`${key}-inherit`) as HTMLInputElement).click();
+ await button.onclick!(new f.window.PointerEvent("click"));
+ assert.equal(requests.at(-1)[1], `/api/scopes/org%3Atest/${key}`);
+ assert.equal(requests.at(-1)[2].modelId, "model");
+ assert.equal(f.ui.states.get(key).dirty, false);
+ (f.document.getElementById(`${key}-inherit`) as HTMLInputElement).click();
+ await button.onclick!(new f.window.PointerEvent("click"));
+ assert.equal(JSON.stringify(requests.at(-1)[2]), '{"inherit":true}');
+ assert.equal(f.ui.states.get(key).dirty, false);
+ assert.ok(html.includes(`$("card-${key}"),`));
+ }
+ } finally {
+ f.dom.window.close();
+ }
+});
diff --git a/plugins/admin/ui/settings.ts b/plugins/admin/ui/settings.ts
index bbd3b386f..1b42d974a 100644
--- a/plugins/admin/ui/settings.ts
+++ b/plugins/admin/ui/settings.ts
@@ -21,6 +21,8 @@ import { repeat } from "lit/directives/repeat.js";
type Model = { id: string; name?: string; effortLevels?: string[] };
type Data = Record<string, any>;
+const runtimeKeys = ["runtime", "cron-runtime", "subagent-runtime"];
+const runtimeReadKey = (key: string) => key.replace(/-runtime$/, "Runtime");
export class SettingsState extends SettingState {
context: Data = {};
selected = "";
@@ -29,6 +31,11 @@ export class SettingsState extends SettingState {
collect(_validate = true): Data {
if (_validate && this.key === "soul" && (this.draft.content || "").length > 100000)
throw new Error("Maximum length reached");
+ if (this.key !== "runtime" && runtimeKeys.includes(this.key)) {
+ if (this.draft.inherit) return { inherit: true };
+ const { inherit: _inherit, ...selection } = this.draft;
+ return structuredClone(selection);
+ }
if (this.key === "branding")
return Object.fromEntries(Object.entries(this.draft).map(([key, value]) => [key, String(value).trim()]));
return structuredClone(this.draft);
@@ -60,7 +67,7 @@ export class SettingsState extends SettingState {
);
}
normalize() {
- if (this.key !== "runtime") return;
+ if (!runtimeKeys.includes(this.key)) return;
if (!this.harnesses.includes(this.draft.harnessId)) this.draft.harnessId = this.harnesses[0];
if (!this.models.some((m) => m.id === this.draft.modelId)) this.draft.modelId = this.models[0]?.id || "";
if (!this.efforts.includes(this.draft.effortLevel))
@@ -93,7 +100,7 @@ export class SettingsState extends SettingState {
}
}
export const states = new Map(
- ["runtime", "webui-models", "soul", "branding"].map((key) => [key, new SettingsState(key)]),
+ [...runtimeKeys, "webui-models", "soul", "branding"].map((key) => [key, new SettingsState(key)]),
);
export const { owns, collect, capture, commit, status, statusKey } = settingRegistry(states);
export function load(data: Data, scope: string, only?: string) {
@@ -125,16 +132,17 @@ export function load(data: Data, scope: string, only?: string) {
s.available =
scope.startsWith("org:") &&
!!data.baseModelOptions?.length &&
- (key !== "runtime" || (!!data.baseModelDefault && "runtime" in data));
- s.draft =
- key === "runtime"
- ? {
- harnessId: data.runtime?.harnessId || data.harnessDefault || "pi",
- modelId: data.runtime?.modelId || data.baseModel || data.baseModelDefault || "",
- effortLevel: data.runtime?.effortLevel || "auto",
- fastMode: data.runtime?.fastMode === true,
- }
- : { ids: (data.webuiModels || []).filter(Boolean) };
+ (!runtimeKeys.includes(key) || (!!data.baseModelDefault && runtimeReadKey(key) in data));
+ const runtime = data[runtimeReadKey(key)];
+ s.draft = runtimeKeys.includes(key)
+ ? {
+ ...(key !== "runtime" ? { inherit: !runtime } : {}),
+ harnessId: runtime?.harnessId || data.harnessDefault || "pi",
+ modelId: runtime?.modelId || data.baseModel || data.baseModelDefault || "",
+ effortLevel: runtime?.effortLevel || "auto",
+ fastMode: runtime?.fastMode === true,
+ }
+ : { ids: (data.webuiModels || []).filter(Boolean) };
s.normalize();
s.saving = false;
s.selected = "";
@@ -172,21 +180,48 @@ const label = (s: SettingsState, id: string) => {
function card(s: SettingsState) {
if (s.key === "soul") return soulCard(s);
if (s.key === "branding") return brandingCard(s);
- if (s.key === "runtime")
+ if (runtimeKeys.includes(s.key)) {
+ const prefix = s.key === "runtime" ? "base" : s.key;
+ const purpose = s.key !== "runtime";
+ const [title, description] = {
+ runtime: ["Conversation runtime", "The default runtime for conversations unless overridden."],
+ "cron-runtime": ["Cron runtime", "Used for scheduled jobs without a per-job runtime override."],
+ "subagent-runtime": ["Sub-agent runtime", "Used for new sub-agents unless explicitly overridden."],
+ }[s.key]!;
return html`<section
class=${classMap({ card: true, "sv-models": true, hidden: !s.available, dirty: s.dirty })}
- id="card-base-model"
+ id=${s.key === "runtime" ? "card-base-model" : `card-${s.key}`}
>
<div class="head">
- <h2>Default runtime</h2>
- <p>The harness, model, and reasoning level used across your organization unless overridden.</p>
+ <h2>${title}</h2>
+ <p>${description}</p>
</div>
<div class="body">
+ ${
+ purpose
+ ? html`<label class="setting-toggle">
+ <input
+ type="checkbox"
+ id=${`${prefix}-inherit`}
+ .checked=${!!s.draft.inherit}
+ @change=${(e: Event) => s.change("inherit", (e.target as HTMLInputElement).checked)}
+ />
+ <span class="setting-switch" aria-hidden="true"></span>
+ <span class="setting-copy"
+ ><strong>Use existing fallback</strong
+ ><small
+ >${s.key === "cron-runtime" ? "Use the job's scope default." : "Use the child’s scope default."}</small
+ ></span
+ >
+ </label>`
+ : null
+ }
<div class="model-runtime-fields">
<div>
- <label for="base-harness">Harness</label
+ <label for=${`${prefix}-harness`}>Harness</label
><select
- id="base-harness"
+ id=${`${prefix}-harness`}
+ ?disabled=${purpose && s.draft.inherit}
.value=${s.draft.harnessId || ""}
@change=${(e: Event) => s.change("harnessId", value(e))}
>
@@ -194,32 +229,43 @@ function card(s: SettingsState) {
</select>
</div>
<div>
- <label for="base-model">Model</label
+ <label for=${`${prefix}-model`}>Model</label
><select
- id="base-model"
+ id=${`${prefix}-model`}
+ ?disabled=${purpose && s.draft.inherit}
.value=${s.draft.modelId || ""}
@change=${(e: Event) => s.change("modelId", value(e))}
>
- ${s.models.map((m) => html`<option value=${m.id} ?selected=${m.id === s.draft.modelId}>${m.name} (${m.id})</option>`)}
+ ${repeat(
+ s.models,
+ (m) => m.id,
+ (m) => html`<option value=${m.id} ?selected=${m.id === s.draft.modelId}>${m.name} (${m.id})</option>`,
+ )}
</select>
</div>
<div>
- <label for="base-effort">Reasoning level</label
+ <label for=${`${prefix}-effort`}>Reasoning level</label
><select
- id="base-effort"
+ id=${`${prefix}-effort`}
+ ?disabled=${purpose && s.draft.inherit}
.value=${s.draft.effortLevel || "auto"}
@change=${(e: Event) => s.change("effortLevel", value(e))}
>
- ${s.efforts.map((id) => html`<option value=${id} ?selected=${id === s.draft.effortLevel}>${effortLabels[id] || id}</option>`)}
+ ${repeat(
+ s.efforts,
+ (id) => id,
+ (id) =>
+ html`<option value=${id} ?selected=${id === s.draft.effortLevel}>${effortLabels[id] || id}</option>`,
+ )}
</select>
</div>
</div>
- <label class="setting-toggle" id="base-fast-mode-control" style=${s.fastCapable ? "" : "display: none"}
+ <label class="setting-toggle" id=${`${prefix}-fast-mode-control`} style=${s.fastCapable ? "" : "display: none"}
><input
type="checkbox"
- id="base-fast-mode"
+ id=${`${prefix}-fast-mode`}
.checked=${!!s.draft.fastMode}
- ?disabled=${!s.fastCapable}
+ ?disabled=${!s.fastCapable || (purpose && s.draft.inherit)}
@change=${(e: Event) => s.change("fastMode", (e.target as HTMLInputElement).checked)}
/><span class="setting-switch" aria-hidden="true"></span
><span class="setting-copy"
@@ -229,6 +275,7 @@ function card(s: SettingsState) {
</div>
${saveFooter(s)}
</section>`;
+ }
const ids: string[] = s.draft.ids || [];
const available = s.catalog.filter((m) => !ids.includes(m.id));
return html`<section
@@ -291,10 +338,16 @@ export function mountCards() {
mountFlags();
mountProviders();
mountCredentials();
+ const renderRuntimes = mountTemplate('template[data-settings-card="card-base-model"]', () =>
+ runtimeKeys.map((key) => card(states.get(key)!)),
+ );
for (const [key, s] of states) {
+ if (runtimeKeys.includes(key)) {
+ s.render = renderRuntimes;
+ continue;
+ }
const id = (
{
- runtime: "card-base-model",
soul: "card-soul",
branding: "card-branding",
"webui-models": "card-webui-models",
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index ce53c6255..908f6adbb 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -164,7 +164,8 @@ export function createMessagingMethods(
assertCronRuntime(cron);
if (!cron.runtime) return;
const error =
- validateRuntimeChoice(cron.runtime) ?? (await availableRuntimeError({ deps }, cron.ownerScopeId, cron.runtime));
+ validateRuntimeChoice(cron.runtime) ??
+ (await availableRuntimeError({ deps }, cron.ownerScopeId, cron.runtime, "cron"));
if (error) throw new Error(error);
};
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index 0371f68c8..48ef34c26 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -11,7 +11,7 @@ import { isPersonAuthored, resolveTurnOrigin } from "../core/turn-origin.ts";
import { conversationScope } from "../resolution/resolution-service.ts";
import { isTerminal, leaseLapsed } from "../runs/run-store.ts";
import type { SessionStateEvent } from "../runs/session-state-bus.ts";
-import { turnModelOptions, validateWebTurnModelOptions } from "../core/turn-options.ts";
+import { turnModelOptions, turnRuntimePurpose, validateWebTurnModelOptions } from "../core/turn-options.ts";
import { isProjectGroupRef, projectIdFromGroupRef } from "../projects/project-store.ts";
import { samePerson } from "../directory/person.ts";
import {
@@ -194,18 +194,35 @@ export function createTurnMethods(
? await deps.config.getModelAccountDurable(actor.id)
: "company";
const individualAuth = modelAccount !== "company";
+ const runtimePurpose = turnRuntimePurpose(req, isSubagentThreadRef(req.conversation.threadRef));
if (req.triggered && (req.model || req.harness)) {
- const choices = await runtimeConfigBody({ deps }, conversationScope(req.conversation, actor.id));
+ const choices = await runtimeConfigBody(
+ { deps },
+ conversationScope(req.conversation, actor.id),
+ undefined,
+ runtimePurpose,
+ {
+ ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),
+ ...(req.model ? { modelId: req.model } : {}),
+ ...(req.thinkingLevel ? { effortLevel: req.thinkingLevel } : {}),
+ ...(typeof req.fastMode === "boolean" ? { fastMode: req.fastMode } : {}),
+ },
+ );
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,
- });
+ : await availableRuntimeError(
+ { deps },
+ conversationScope(req.conversation, actor.id),
+ {
+ harnessId: harness,
+ modelId: model,
+ effortLevel: req.thinkingLevel,
+ fastMode: req.fastMode,
+ },
+ runtimePurpose,
+ );
if (error) return { status: "refused", reason: error };
}
let requestedModel = req.model;
@@ -254,10 +271,20 @@ export function createTurnMethods(
orgRuntime = modelUnavailableReason(orgModel)
? { harnessId: storedOrgRuntime?.harnessId ?? runtimeFallback.harnessId, modelId: orgModel }
: await resolveRuntimeChoiceDurable(deps.config, org, org, runtimeFallback);
- runtime = await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback, {
- ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),
- ...(req.model ? { modelId: req.model } : {}),
- });
+ runtime = await resolveRuntimeChoiceDurable(
+ deps.config,
+ org,
+ targetScope,
+ runtimeFallback,
+ {
+ ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),
+ ...(req.model ? { modelId: req.model } : {}),
+ ...(req.thinkingLevel ? { effortLevel: req.thinkingLevel } : {}),
+ ...(typeof req.fastMode === "boolean" ? { fastMode: req.fastMode } : {}),
+ },
+ undefined,
+ runtimePurpose,
+ );
} catch (error) {
swallow("turn: runtime resolution", error);
return { status: "refused", reason: `I couldn't set up that runtime choice — ${GENERIC_FAILURE_CLAUSE}` };
diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.ts
index 0baf5e649..1cac287a8 100644
--- a/src/api/routes/admin-resources.ts
+++ b/src/api/routes/admin-resources.ts
@@ -623,31 +623,46 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [
return { ok: true };
},
},
- {
- id: "runtime",
+ ...([undefined, "cron", "subagent"] as const).map((purpose): AdminResource => ({
+ id: purpose ? `${purpose}-runtime` : "runtime",
kind: "custom",
- target: "any",
+ target: purpose ? "org" : "any",
clearable: true,
- readKey: "runtime",
- get: (deps, scope) => deps.config!.getRuntimeSelection(scope),
+ readKey: purpose ? `${purpose}Runtime` : "runtime",
+ get: async (deps, scope) =>
+ purpose
+ ? ((await deps.config!.getPurposeRuntimeDurable(purpose)) ?? null)
+ : deps.config!.getRuntimeSelection(scope),
apply: async (ctx, _actor, scope) => {
- if ((ctx.body as { inherit?: unknown }).inherit === true) {
- await ctx.deps.config!.setRuntimeSelectionLatest(scope, null);
+ if (purpose) {
+ const bad = orgOnly(scope, `${purpose} runtime defaults are org-wide`);
+ if (bad) return bad;
+ }
+ if ((ctx.body as { inherit?: unknown } | null)?.inherit === true || (purpose && ctx.body === null)) {
+ if (purpose) await ctx.deps.config!.clearPurposeRuntime(purpose);
+ else await ctx.deps.config!.setRuntimeSelectionLatest(scope, null);
return { ok: true };
}
const harnessId = (ctx.body as { harnessId?: unknown }).harnessId;
const modelId = (ctx.body as { modelId?: unknown }).modelId;
- const effortLevel = (ctx.body as { effortLevel?: unknown }).effortLevel ?? "auto";
- const fastMode = (ctx.body as { fastMode?: unknown }).fastMode ?? false;
+ const effortLevel = (ctx.body as { effortLevel?: unknown }).effortLevel ?? (purpose ? undefined : "auto");
+ const fastMode = (ctx.body as { fastMode?: unknown }).fastMode ?? (purpose ? undefined : false);
if (!isHarnessId(harnessId)) return { error: `runtime requires harnessId (${HARNESS_IDS.join(" | ")})` };
const approved = (await ctx.deps.config!.getApprovedHarnessesDurable()) ?? [ctx.deps.harnessId ?? "pi"];
if (!approved.includes(harnessId)) return { error: `harness ${harnessId} is not approved` };
if (typeof modelId !== "string" || !modelSupportedByHarness(modelId, harnessId))
return { error: `model ${String(modelId)} is not supported by ${harnessId}` };
const thinkingLevels = thinkingLevelsForHarness(harnessId, modelId);
- if (typeof effortLevel !== "string" || !thinkingLevels.includes(effortLevel))
+ if (effortLevel !== undefined && (typeof effortLevel !== "string" || !thinkingLevels.includes(effortLevel)))
return { error: `runtime requires effortLevel (${thinkingLevels.join(" | ")}) for ${harnessId}` };
- if (typeof fastMode !== "boolean") return { error: "runtime requires fastMode (boolean)" };
+ if (fastMode !== undefined && typeof fastMode !== "boolean")
+ return { error: "runtime requires fastMode (boolean)" };
+ if (
+ purpose &&
+ fastMode === true &&
+ (!harnessSupportsFastMode(harnessId) || !fastModeModelIds().includes(modelId))
+ )
+ return { error: `fast mode is not supported by ${harnessId} with ${modelId}` };
const configuredKeys = ctx.deps.providerKeys ?? ALL_PROVIDERS_AVAILABLE;
const managedKeys = ctx.deps.modelCredentials ? await ctx.deps.modelCredentials.availability() : configuredKeys;
if (!modelServiceable(modelId, modelProviderAvailabilityFor(harnessId, configuredKeys, managedKeys)))
@@ -657,13 +672,16 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [
const choice = {
harnessId,
modelId,
- effortLevel,
- fastMode: fastMode && harnessSupportsFastMode(harnessId) && fastModeModelIds().includes(modelId),
+ ...(typeof effortLevel === "string" ? { effortLevel } : {}),
+ ...(typeof fastMode === "boolean"
+ ? { fastMode: fastMode && harnessSupportsFastMode(harnessId) && fastModeModelIds().includes(modelId) }
+ : {}),
};
- await ctx.deps.config!.setRuntimeSelectionLatest(scope, choice);
+ if (purpose) await ctx.deps.config!.setPurposeRuntime(purpose, choice);
+ else await ctx.deps.config!.setRuntimeSelectionLatest(scope, choice);
return { ok: true };
},
- },
+ })),
{
id: "approved-harnesses",
kind: "string-list",
diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.ts
index 26f442bb9..c7000b16f 100644
--- a/src/api/routes/admin/scope-config.ts
+++ b/src/api/routes/admin/scope-config.ts
@@ -46,7 +46,17 @@ export async function putScopeConfig(ctx: ApiCtx): Promise<void> {
const actor = await authorizeAdmin(ctx, targetScope);
if (!actor) return;
- if (["base-model", "runtime", "webui-models", "browse-model", "auto-flagger"].includes(resource))
+ if (
+ [
+ "base-model",
+ "runtime",
+ "cron-runtime",
+ "subagent-runtime",
+ "webui-models",
+ "browse-model",
+ "auto-flagger",
+ ].includes(resource)
+ )
await deps.refreshModels?.();
const withScopeMutationLock = async <T>(fn: () => Promise<T>): Promise<T> =>
deps.advisoryLock ? deps.advisoryLock.withLock(`admin-governance:${targetScope}`, fn) : fn();
@@ -257,6 +267,8 @@ const SETTINGS_RESOURCES = {
models: [
"baseModel",
"runtime",
+ "cronRuntime",
+ "subagentRuntime",
"approvedHarnesses",
"webuiModels",
"interactiveFastMode",
@@ -357,14 +369,30 @@ async function scopeModelOptions(deps: ApiCtx["deps"], values: Record<string, un
name: resolvedCurrent?.name ?? currentId + " (configured)",
provider: resolvedCurrent?.provider ?? (currentId.includes("/") ? "openrouter" : ""),
};
+ const purposeRuntimes = [values.cronRuntime, values.subagentRuntime].filter(
+ (value): value is { harnessId: string; modelId: string } =>
+ !!value &&
+ typeof (value as { harnessId?: unknown }).harnessId === "string" &&
+ typeof (value as { modelId?: unknown }).modelId === "string",
+ );
const modelsFor = (harnessId: string) => {
const models = selectableCatalogForHarness(catalog, harnessId);
if (preserveCurrent && currentHarness === harnessId && !models.some((model) => model.id === currentModel.id))
models.push(currentModel);
+ const configured = purposeRuntimes.filter((runtime) => runtime.harnessId === harnessId);
+ for (const runtime of configured) {
+ if (!models.some((model) => model.id === runtime.modelId))
+ models.push({
+ id: runtime.modelId,
+ name: resolveModel(runtime.modelId)?.name ?? `${runtime.modelId} (configured)`,
+ provider: resolveModel(runtime.modelId)?.provider ?? "",
+ });
+ }
return models.filter(
(model) =>
modelServiceable(model.id, providersFor(harnessId)) ||
- (preserveCurrent && currentHarness === harnessId && currentModel.id === model.id),
+ (preserveCurrent && currentHarness === harnessId && currentModel.id === model.id) ||
+ configured.some((runtime) => runtime.modelId === model.id),
);
};
return {
@@ -373,7 +401,11 @@ async function scopeModelOptions(deps: ApiCtx["deps"], values: Record<string, un
baseModelOptions: modelsFor(deps.harnessId ?? "pi"),
harnessDefault: deps.harnessId ?? "pi",
harnessOptions: HARNESS_IDS.filter(
- (id) => id !== "mock" && (approvedHarnesses.includes(id) || runtime?.harnessId === id),
+ (id) =>
+ id !== "mock" &&
+ (approvedHarnesses.includes(id) ||
+ runtime?.harnessId === id ||
+ purposeRuntimes.some((runtime) => runtime.harnessId === id)),
),
modelsByHarness: Object.fromEntries(
HARNESS_IDS.map((id) => [
diff --git a/src/api/runtime-config.ts b/src/api/runtime-config.ts
index 563d0bc86..d8d489b31 100644
--- a/src/api/runtime-config.ts
+++ b/src/api/runtime-config.ts
@@ -1,3 +1,5 @@
+import type { RuntimePurpose } from "../resolution/config-store.ts";
+import { resolveRuntimeChoiceDurable } from "../harness/harness-router.ts";
import { resolveIndividualAuthRouting } from "../core/individual-auth-routing.ts";
import { gatewayModelCatalog } from "../model/gateway-models.ts";
import type { AppDeps } from "./app-types.ts";
@@ -89,6 +91,8 @@ export async function runtimeConfigBody(
ctx: { deps: RuntimeDeps },
scope: ScopeId,
authorizeChoice?: (choice: RuntimeChoice) => Promise<string | null>,
+ purpose?: RuntimePurpose,
+ requested?: Partial<RuntimeChoice>,
) {
if (authorizeChoice)
ctx = { deps: { ...ctx.deps, providerKeys: ALL_PROVIDERS_AVAILABLE, modelCredentials: undefined } };
@@ -143,8 +147,11 @@ export async function runtimeConfigBody(
} else if (legacyModel) {
scopeOverride = { harnessId: fallback.harnessId, modelId: legacyModel, orgRevision: 0 };
}
- const effective = scopeOverride ?? orgDefault;
- const selected = [orgDefault, scopeOverride, effective].filter((choice) => choice !== null);
+ const effective = purpose
+ ? await resolveRuntimeChoiceDurable(config, org, scope, fallback, requested, undefined, purpose)
+ : (scopeOverride ?? orgDefault);
+ const purposeDefault = purpose ? await config.getPurposeRuntimeDurable(purpose) : undefined;
+ const selected = [orgDefault, scopeOverride, effective, purposeDefault].filter((choice) => choice != null);
const allowlist = await config.getWebuiModelsDurable(org);
const modelsByHarness = Object.fromEntries(
approvedHarnesses.map((harnessId) => {
@@ -160,6 +167,7 @@ export async function runtimeConfigBody(
(!authorizeChoice ||
!allowlist ||
choice.modelId === orgDefault.modelId ||
+ choice.modelId === purposeDefault?.modelId ||
allowlist.includes(codexProviderModelId(choice.modelId))) &&
choice.harnessId === harnessId &&
modelSupportedByHarness(choice.modelId, harnessId) &&
@@ -194,6 +202,7 @@ export async function runtimeConfigBody(
);
return {
scopeId: scope,
+ ...(purpose ? { executionPurpose: purpose } : {}),
approvedHarnesses,
modelsByHarness,
modelCatalog,
@@ -230,7 +239,11 @@ export function validateRuntimeChoice(choice: RuntimeChoice): string | null {
return null;
}
-export async function webuiModelEnabled(ctx: { deps: RuntimeDeps }, modelId: string): Promise<boolean> {
+export async function webuiModelEnabled(
+ ctx: { deps: RuntimeDeps },
+ modelId: string,
+ purpose?: RuntimePurpose,
+): Promise<boolean> {
modelId = codexProviderModelId(modelId);
const config = ctx.deps.config!;
const picker = await config.getWebuiModelsDurable(orgScope());
@@ -239,19 +252,21 @@ export async function webuiModelEnabled(ctx: { deps: RuntimeDeps }, modelId: str
const org = orgScope();
const stored = await config.getRuntimeSelectionDurable(org);
const orgModel = stored?.modelId ?? (await config.getBaseModelOwnDurable(org)) ?? runtimeFallback(ctx).modelId;
- return modelId === orgModel;
+ const purposeModel = purpose ? (await config.getPurposeRuntimeDurable(purpose))?.modelId : undefined;
+ return modelId === orgModel || modelId === purposeModel;
}
export async function availableRuntimeError(
ctx: { deps: RuntimeDeps },
scope: ScopeId,
choice: RuntimeChoice,
+ purpose?: RuntimePurpose,
): Promise<string | null> {
await ctx.deps.refreshModels?.();
- const choices = await runtimeConfigBody(ctx, scope);
+ const choices = await runtimeConfigBody(ctx, scope, undefined, purpose, choice);
if (
!choices.modelsByHarness[choice.harnessId]?.includes(choice.modelId) ||
- !(await webuiModelEnabled(ctx, choice.modelId))
+ !(await webuiModelEnabled(ctx, choice.modelId, purpose))
)
return "runtime is no longer available or enabled on this deployment";
return validateRuntimeChoice({
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 0ff0e45d0..603fb185a 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -25,7 +25,7 @@ import type {
} from "../types.ts";
import { scopeId as toScopeId, personalScope } from "../types.ts";
import { turnOriginRequestFields } from "./turn-origin.ts";
-import { resolveTurnFastMode } from "./turn-options.ts";
+import { resolveTurnFastMode, turnRuntimePurpose } from "./turn-options.ts";
import { orgId } from "../config.ts";
import { renderGatewayContext } from "./gateway-context.ts";
import { deriveTurnOutcome, approvalBlocksInput } from "./turn-outcome.ts";
@@ -538,6 +538,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
)
throw new NonRetryableTurnError("swarm service unavailable");
const swarmBinding = await deps.swarms?.binding(input);
+ if (input.swarm && swarmBinding?.member.parentId && (await deps.config?.getPurposeRuntimeDurable("subagent")))
+ input = { ...input, model: undefined, harness: undefined, thinkingLevel: undefined, fastMode: undefined };
const swarmEntryProvenance = input.swarm ? { origin: "automation", swarm: input.swarm } : {};
await deps.refreshModels?.();
const { actor, conversation } = input;
@@ -3076,8 +3078,16 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
? Math.min(requestedTurnWallClockMs, configuredTurnWallClockMs)
: requestedTurnWallClockMs;
}
+ const runtimePurpose = turnRuntimePurpose(
+ { surface: input.surface, triggered: automatedTurn },
+ !!session.parentSessionId || !!swarmBinding?.member.parentId,
+ );
+ const purposeDefault = runtimePurpose ? await deps.config?.getPurposeRuntimeDurable(runtimePurpose) : undefined;
const wantsOrgFastMode =
- typeof input.fastMode !== "boolean" && humanTurn && (await deps.config?.getInteractiveFastModeDurable());
+ typeof input.fastMode !== "boolean" &&
+ !purposeDefault &&
+ humanTurn &&
+ (await deps.config?.getInteractiveFastModeDurable());
const effectiveFastMode = resolveTurnFastMode(input.fastMode, humanTurn, wantsOrgFastMode === true);
const loadRuntimeAuth = async (runtime: Partial<RuntimeChoice>) => {
let userProviderKeys: ProviderKeys | undefined;
@@ -3093,12 +3103,21 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
account === "anthropic" ? null : userCredStore.get(actor.id, "openai"),
]);
const orgRuntime = await deps.config?.getRuntimeSelectionDurable(resolution.orgScopeId);
- const preferredHarness = runtime.harnessId ?? input.harness ?? orgRuntime?.harnessId ?? deps.defaultHarness;
+ const preferredHarness =
+ runtime.harnessId ??
+ input.harness ??
+ purposeDefault?.harnessId ??
+ orgRuntime?.harnessId ??
+ deps.defaultHarness;
const routing = resolveIndividualAuthRouting(
anthCred ?? null,
oaiCred ?? null,
- account === "personal" || input.surface === "web" ? (runtime.modelId ?? input.model) : runtime.modelId,
- account === "personal" || input.surface === "web" ? preferredHarness : runtime.harnessId,
+ account === "personal" || input.surface === "web"
+ ? (runtime.modelId ?? input.model ?? purposeDefault?.modelId)
+ : (runtime.modelId ?? purposeDefault?.modelId),
+ account === "personal" || input.surface === "web"
+ ? preferredHarness
+ : (runtime.harnessId ?? purposeDefault?.harnessId),
);
if (routing?.kind === "apikey") {
userHarnessOverride = "pi";
@@ -3147,10 +3166,12 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
let { userProviderKeys, userModelOverride, userHarnessOverride, claudeOauthToken, codexTurnAuth } =
await loadRuntimeAuth({});
if (
- input.surface === "web" &&
+ (input.surface === "web" || purposeDefault) &&
userHarnessOverride &&
- ((input.model && input.model !== userModelOverride) ||
- (input.harness && input.harness !== userHarnessOverride))
+ (((input.model ?? purposeDefault?.modelId) &&
+ (input.model ?? purposeDefault?.modelId) !== userModelOverride) ||
+ ((input.harness ?? purposeDefault?.harnessId) &&
+ (input.harness ?? purposeDefault?.harnessId) !== userHarnessOverride))
)
throw new NonRetryableTurnError("Your connected AI account cannot serve this model on that harness.");
const effectiveModel = userModelOverride ?? input.model;
@@ -3172,6 +3193,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
...(input.thinkingLevel ? { effortLevel: input.thinkingLevel } : {}),
...(typeof effectiveFastMode === "boolean" ? { fastMode: effectiveFastMode } : {}),
};
+ const runtimeDefaults = requestedRuntime;
const runtimeClaims: CapabilityClaims = controlClaims ?? {
...scopeAttestation,
exp: Date.now() + CAPABILITY_TTL_MS,
@@ -3204,12 +3226,16 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
};
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,
- });
+ const error = await deps.validateScheduledRuntime?.(
+ scopeId,
+ {
+ harnessId: input.harness,
+ modelId: input.model,
+ effortLevel: input.thinkingLevel,
+ fastMode: input.fastMode,
+ },
+ runtimePurpose,
+ );
if (error) throw new NonRetryableTurnError(error);
}
const runHarnessSegment = (
@@ -3378,8 +3404,11 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
},
...(userProviderKeys ? { providerKeys: userProviderKeys } : {}),
...(claudeOauthToken ? { claudeOauthToken } : {}),
- ...(userHarnessOverride && !restoredRuntime && runtimeHandoffs === 0 ? { runtimePinned: true } : {}),
+ ...(userHarnessOverride && !purposeDefault && !restoredRuntime && runtimeHandoffs === 0
+ ? { runtimePinned: true }
+ : {}),
runtimeActorId: actor.id,
+ ...(runtimePurpose ? { runtimePurpose } : {}),
...(deps.runtime && input.runId
? {
runtimeControl: (
@@ -3395,6 +3424,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
!!userHarnessOverride,
signal,
automatedTurn && input.surface === "cron",
+ runtimePurpose,
+ runtimeDefaults,
),
}
: {}),
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index 9a2c83170..5e660488d 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -182,6 +182,7 @@ export interface OrchestratorDeps {
validateScheduledRuntime?: (
scope: import("../../types.ts").ScopeId,
choice: import("../../harness/harness.ts").RuntimeChoice,
+ purpose?: import("../../resolution/config-store.ts").RuntimePurpose,
) => Promise<string | null>;
livenessCache?: LivenessCache;
connectorTokens?: ConnectorTokenStore;
diff --git a/src/core/turn-options.ts b/src/core/turn-options.ts
index 5f1736738..73f52228f 100644
--- a/src/core/turn-options.ts
+++ b/src/core/turn-options.ts
@@ -1,3 +1,4 @@
+import type { RuntimePurpose } from "../resolution/config-store.ts";
import {
defaultWebuiModelIds,
THINKING_LEVELS,
@@ -11,6 +12,15 @@ import {
export const NON_INTERACTIVE_THINKING_LEVEL = "xhigh";
export const NON_INTERACTIVE_FAST_MODE = false;
+export function turnRuntimePurpose(
+ input: { surface?: string; triggered?: boolean },
+ subagent = false,
+): RuntimePurpose | undefined {
+ if (subagent) return "subagent";
+ if (input.triggered && (input.surface === "cron" || input.surface === "loop")) return "cron";
+ return undefined;
+}
+
export function resolveTurnFastMode(
requested: boolean | undefined,
humanTurn: boolean,
@@ -20,14 +30,20 @@ export function resolveTurnFastMode(
return humanTurn && interactiveDefault ? true : undefined;
}
-export function turnModelOptions(input: { triggered?: boolean; thinkingLevel?: string; fastMode?: boolean }): {
+export function turnModelOptions(input: {
+ triggered?: boolean;
+ surface?: string;
+ thinkingLevel?: string;
+ fastMode?: boolean;
+}): {
thinkingLevel?: string;
fastMode?: boolean;
} {
+ const legacyDefaults = input.triggered && input.surface !== "cron" && input.surface !== "loop";
let thinkingLevel = input.thinkingLevel;
- if (!thinkingLevel && input.triggered) thinkingLevel = NON_INTERACTIVE_THINKING_LEVEL;
+ if (!thinkingLevel && legacyDefaults) thinkingLevel = NON_INTERACTIVE_THINKING_LEVEL;
let fastMode = input.fastMode;
- if (typeof fastMode !== "boolean" && input.triggered) fastMode = NON_INTERACTIVE_FAST_MODE;
+ if (typeof fastMode !== "boolean" && legacyDefaults) fastMode = NON_INTERACTIVE_FAST_MODE;
return {
...(thinkingLevel ? { thinkingLevel } : {}),
...(typeof fastMode === "boolean" ? { fastMode } : {}),
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index d35856e54..d089c1bdf 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -1510,6 +1510,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
model: Type.Optional(Type.String({ description: "open: model override; fails closed if unavailable." })),
harness: Type.Optional(Type.String({ description: "open: harness override." })),
thinkingLevel: Type.Optional(Type.String({ description: "open: reasoning effort override." })),
+ fastMode: Type.Optional(Type.Boolean({ description: "open: fast mode override." })),
target: Type.Optional(
Type.String({
description:
@@ -1529,6 +1530,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
requestId?: string;
harness?: string;
thinkingLevel?: string;
+ fastMode?: boolean;
task?: string;
name?: string;
readOnly?: boolean;
@@ -1573,6 +1575,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
task: p.task ?? "",
...(p.harness ? { harness: p.harness } : {}),
...(p.thinkingLevel ? { thinkingLevel: p.thinkingLevel } : {}),
+ ...(p.fastMode !== undefined ? { fastMode: p.fastMode } : {}),
...(p.name ? { name: p.name } : {}),
...(p.readOnly !== undefined ? { readOnly: p.readOnly } : {}),
...(p.model ? { model: p.model } : {}),
diff --git a/src/harness/harness-router.ts b/src/harness/harness-router.ts
index b001da334..eea070283 100644
--- a/src/harness/harness-router.ts
+++ b/src/harness/harness-router.ts
@@ -1,4 +1,4 @@
-import type { ScopedConfigStore } from "../resolution/config-store.ts";
+import type { ScopedConfigStore, RuntimePurpose } from "../resolution/config-store.ts";
import {
defaultModelForHarness,
fastModeModelIds,
@@ -13,6 +13,7 @@ import {
import type { ScopeId, SessionEntry } from "../types.ts";
import type { Harness, HarnessTurnInput, HarnessTurnResult, RuntimeChoice } from "./harness.ts";
import { withTapedEntryMirrors } from "./harness-shared.ts";
+import { NON_INTERACTIVE_THINKING_LEVEL, NON_INTERACTIVE_FAST_MODE } from "../core/turn-options.ts";
import { NonRetryableTurnError } from "../core/turn-error.ts";
import { createGrindMeter } from "./grind.ts";
import { enforceGoal, latestGoalRecord, rehydrateOpenGoal, type GoalRecord } from "./goal.ts";
@@ -121,14 +122,42 @@ function normalizeRuntimeChoice(choice: RuntimeChoice): RuntimeChoice {
}
export function resolveRuntimeChoice(
- config: Pick<ScopedConfigStore, "getApprovedHarnesses" | "getRuntimeSelection" | "getBaseModel">,
+ config: Pick<ScopedConfigStore, "getApprovedHarnesses" | "getRuntimeSelection" | "getBaseModel"> &
+ Partial<Pick<ScopedConfigStore, "getPurposeRuntime">>,
orgScopeId: ScopeId,
scope: ScopeId,
fallback: RuntimeChoice,
requested?: Partial<RuntimeChoice>,
+ purpose?: RuntimePurpose,
): RuntimeChoice {
const approved = config.getApprovedHarnesses() ?? [fallback.harnessId];
if (approved.length === 0) throw new NonRetryableTurnError("No harnesses are approved");
+ const purposeRuntime = purpose ? config.getPurposeRuntime?.(purpose) : undefined;
+ if (purposeRuntime) {
+ const explicit = Object.fromEntries(Object.entries(requested ?? {}).filter(([, value]) => value !== undefined));
+ const choice = { ...purposeRuntime, ...explicit };
+ if (
+ !isHarnessId(choice.harnessId) ||
+ !approved.includes(choice.harnessId) ||
+ !modelSupportedByHarness(choice.modelId, choice.harnessId)
+ )
+ throw new NonRetryableTurnError(`runtime ${choice.harnessId}/${choice.modelId} is not approved`);
+ const unavailable = modelUnavailableReason(choice.modelId);
+ if (unavailable) throw new NonRetryableTurnError(`${choice.modelId}: ${unavailable}`);
+ if (
+ choice.effortLevel !== undefined &&
+ !thinkingLevelsForHarness(choice.harnessId, choice.modelId).includes(choice.effortLevel)
+ )
+ throw new NonRetryableTurnError(
+ `${choice.effortLevel} reasoning is not supported by ${choice.harnessId}/${choice.modelId}`,
+ );
+ if (choice.fastMode && (!harnessSupportsFastMode(choice.harnessId) || !fastModeModelIds().includes(choice.modelId)))
+ throw new NonRetryableTurnError(`fast mode is not supported by ${choice.harnessId}/${choice.modelId}`);
+ return { ...choice, harnessId: choice.harnessId };
+ }
+ if (purpose === "cron")
+ requested = { effortLevel: NON_INTERACTIVE_THINKING_LEVEL, fastMode: NON_INTERACTIVE_FAST_MODE, ...requested };
+
const orgStored = config.getRuntimeSelection(orgScopeId);
const orgLegacy = config.getBaseModel(orgScopeId);
const configuredOrg: RuntimeChoice =
@@ -185,20 +214,26 @@ export async function resolveRuntimeChoiceDurable(
fallback: RuntimeChoice,
requested?: Partial<RuntimeChoice>,
hydrateModelCatalog?: () => Promise<unknown>,
+ purpose?: RuntimePurpose,
): Promise<RuntimeChoice> {
const approved = (await config.getApprovedHarnessesDurable()) ?? [fallback.harnessId];
- const [orgStored, scopedStored, orgLegacy, scopedLegacy] = await Promise.all([
+ const [orgStored, scopedStored, orgLegacy, scopedLegacy, purposeRuntime] = await Promise.all([
config.getRuntimeSelectionDurable(orgScopeId),
scope === orgScopeId ? null : config.getRuntimeSelectionDurable(scope),
config.getBaseModelOwnDurable(orgScopeId),
scope === orgScopeId ? null : config.getBaseModelOwnDurable(scope),
+ purpose ? config.getPurposeRuntimeDurable(purpose) : undefined,
]);
if (hydrateModelCatalog) {
- const candidates = [requested?.modelId, scopedStored?.modelId, orgStored?.modelId];
+ const candidates = [requested?.modelId, purposeRuntime?.modelId, scopedStored?.modelId, orgStored?.modelId];
if (candidates.some((modelId) => modelId && !resolveModel(modelId))) await hydrateModelCatalog();
}
- const view: Pick<ScopedConfigStore, "getApprovedHarnesses" | "getRuntimeSelection" | "getBaseModel"> = {
+ const view: Pick<
+ ScopedConfigStore,
+ "getApprovedHarnesses" | "getRuntimeSelection" | "getBaseModel" | "getPurposeRuntime"
+ > = {
getApprovedHarnesses: () => approved,
+ getPurposeRuntime: () => purposeRuntime,
getRuntimeSelection: (id: ScopeId) => {
if (id === orgScopeId) return orgStored;
return id === scope ? scopedStored : null;
@@ -208,7 +243,7 @@ export async function resolveRuntimeChoiceDurable(
return id === scope ? scopedLegacy : null;
},
};
- return resolveRuntimeChoice(view, orgScopeId, scope, fallback, requested);
+ return resolveRuntimeChoice(view, orgScopeId, scope, fallback, requested, purpose);
}
export function createHarnessRouter(
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 0def2f218..13eadc52f 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -116,6 +116,7 @@ export interface HarnessTurnInput {
): Promise<{ text: string; attachments?: AttachmentMeta[]; images?: HarnessImage[]; documents?: DocumentInput[] }>;
documents?: DocumentInput[];
runtime?: Partial<RuntimeChoice>;
+ runtimePurpose?: import("../resolution/config-store.ts").RuntimePurpose;
runtimeControl?: RuntimeControl;
runtimeActorId?: string;
readOnly?: boolean;
diff --git a/src/harness/runtime-control.ts b/src/harness/runtime-control.ts
index b29bc1d2a..56738a75b 100644
--- a/src/harness/runtime-control.ts
+++ b/src/harness/runtime-control.ts
@@ -12,7 +12,17 @@ import { parseScopeId } from "../types.ts";
import { isHarnessId, thinkingLevelsForHarness } from "../model/pi-models.ts";
export function createRuntimeService(deps: RuntimeDeps, app: Pick<App, "authorizesCapabilityScope">): RuntimeService {
- return async (claims, active, request, authorizeChoice, individualAuth, signal, cronFire = false) => {
+ return async (
+ claims,
+ active,
+ request,
+ authorizeChoice,
+ individualAuth,
+ signal,
+ cronFire = false,
+ purpose,
+ defaults,
+ ) => {
if (!deps.config) return { ok: false, error: "runtime_unavailable" };
const scope = parseScopeId(claims.scopeId);
if (
@@ -22,7 +32,14 @@ export function createRuntimeService(deps: RuntimeDeps, app: Pick<App, "authoriz
)
return { ok: false, error: "forbidden" };
await deps.refreshModels?.();
- const snapshot = await runtimeConfigBody({ deps }, claims.scopeId, individualAuth ? authorizeChoice : undefined);
+ purpose ??= cronFire ? "cron" : undefined;
+ const snapshot = await runtimeConfigBody(
+ { deps },
+ claims.scopeId,
+ individualAuth ? authorizeChoice : undefined,
+ purpose,
+ defaults,
+ );
if (request.action === "get")
return {
ok: true,
@@ -39,7 +56,8 @@ export function createRuntimeService(deps: RuntimeDeps, app: Pick<App, "authoriz
if (!cronTask && (!livePersonCapability(claims) || claims.triggered || claims.botActor))
return { ok: false, error: "live_actor_required" };
if (request.action === "inherit") {
- const choice = lifetime === "scope" ? snapshot.orgDefault : snapshot.effective;
+ const purposeConfigured = purpose && (await deps.config.getPurposeRuntimeDurable(purpose));
+ const choice = lifetime === "scope" && !purposeConfigured ? snapshot.orgDefault : snapshot.effective;
const error = validateRuntimeChoice(choice);
if (error) return { ok: false, error };
if (
@@ -47,7 +65,8 @@ export function createRuntimeService(deps: RuntimeDeps, app: Pick<App, "authoriz
!snapshot.modelsByHarness[choice.harnessId]?.includes(choice.modelId)
)
return { ok: false, error: "runtime_unavailable" };
- if (!(await webuiModelEnabled({ deps }, choice.modelId))) return { ok: false, error: "model_not_enabled" };
+ if (!(await webuiModelEnabled({ deps }, choice.modelId, purpose)))
+ return { ok: false, error: "model_not_enabled" };
const authError = await authorizeChoice?.(choice);
if (authError) return { ok: false, error: "account_runtime_unavailable", message: authError };
if (signal?.aborted) return { ok: false, error: "cancelled" };
@@ -74,7 +93,7 @@ export function createRuntimeService(deps: RuntimeDeps, app: Pick<App, "authoriz
};
modelId = matches[0]!;
}
- if (!(await webuiModelEnabled({ deps }, modelId))) return { ok: false, error: "model_not_enabled" };
+ if (!(await webuiModelEnabled({ deps }, modelId, purpose))) return { ok: false, error: "model_not_enabled" };
const choice: RuntimeChoice = {
harnessId,
modelId,
diff --git a/src/harness/runtime-types.ts b/src/harness/runtime-types.ts
index 46073abae..9d393de3c 100644
--- a/src/harness/runtime-types.ts
+++ b/src/harness/runtime-types.ts
@@ -32,4 +32,6 @@ export type RuntimeService = (
individualAuth?: boolean,
signal?: AbortSignal,
cronFire?: boolean,
+ purpose?: import("../resolution/config-store.ts").RuntimePurpose,
+ defaults?: Partial<RuntimeChoice>,
) => Promise<RuntimeResult>;
diff --git a/src/resolution/config-store.ts b/src/resolution/config-store.ts
index 655378c0a..56915837f 100644
--- a/src/resolution/config-store.ts
+++ b/src/resolution/config-store.ts
@@ -71,13 +71,17 @@ export interface PersistedScopedFlag {
}
export interface PersistedBaseModel {
scopeId: ScopeId;
- modelId: string;
+ modelId?: string;
+ cronRuntime?: RuntimeSelection;
+ subagentRuntime?: RuntimeSelection;
harnessId?: string;
orgRevision?: number;
revision?: number;
effortLevel?: string;
fastMode?: boolean;
}
+export type RuntimePurpose = "cron" | "subagent";
+
interface RuntimeSelection {
harnessId: string;
modelId: string;
@@ -207,6 +211,10 @@ export interface ScopedConfigStore {
getChannelHeaderPinOverrideDurable(id: ScopeId): Promise<boolean | null>;
getChannelHeaderPinDefaultDurable(): Promise<boolean>;
onChannelHeaderPinChanged(listener: (id: ScopeId) => void): void;
+ getPurposeRuntime(purpose: RuntimePurpose): RuntimeSelection | undefined;
+ getPurposeRuntimeDurable(purpose: RuntimePurpose): Promise<RuntimeSelection | undefined>;
+ setPurposeRuntime(purpose: RuntimePurpose, selection: RuntimeSelection): Promise<void>;
+ clearPurposeRuntime(purpose: RuntimePurpose): Promise<void>;
getBaseModel(id: ScopeId): string | null;
setBaseModel(id: ScopeId, modelId: string | null): void;
getRuntimeSelection(id: ScopeId): ScopedRuntimeSelection | null;
@@ -390,6 +398,38 @@ export function createMemoryConfigStore(
const connectorMapKey = (id: ScopeId, provider: string) => `${id}|${provider}`;
const org = scopeId("org", orgId);
+ const purposeFields = (id: ScopeId, row?: PersistedBaseModel | null) =>
+ id === org
+ ? {
+ ...(row?.cronRuntime ? { cronRuntime: row.cronRuntime } : {}),
+ ...(row?.subagentRuntime ? { subagentRuntime: row.subagentRuntime } : {}),
+ }
+ : {};
+ const clearRuntime = async (id: ScopeId, row?: PersistedBaseModel | null) => {
+ const purposes = purposeFields(id, row);
+ if (Object.keys(purposes).length) {
+ const next = { scopeId: id, ...purposes };
+ await baseModelStore.put(id, next);
+ return next;
+ }
+ await baseModelStore.delete(id);
+ return null;
+ };
+ const setPurposeRuntime = async (purpose: RuntimePurpose, selection?: RuntimeSelection) => {
+ await writeQueue(`model:${org}`, async () => {
+ const row = { ...(await baseModelStore.get(org)), scopeId: org };
+ const key = `${purpose}Runtime` as const;
+ if (selection) row[key] = { ...selection };
+ else delete row[key];
+ if (Object.keys(row).length === 1) {
+ await baseModelStore.delete(org);
+ baseModels.delete(org);
+ } else {
+ await baseModelStore.put(org, row);
+ baseModels.set(org, row);
+ }
+ });
+ };
const defaultSecurityPosture = opts.defaultSecurityPosture ?? "auto";
const defaultSharingPosture = opts.defaultSharingPosture ?? "isolated";
const DEFAULT_APPROVAL_GRANT_MODES: ApprovalGrantModes = { session: true, always: true };
@@ -798,11 +838,23 @@ export function createMemoryConfigStore(
onChannelHeaderPinChanged(listener) {
channelHeaderPinListeners.add(listener);
},
+ getPurposeRuntime: (purpose) => {
+ const selection = baseModels.get(org)?.[`${purpose}Runtime`];
+ return selection ? { ...selection } : undefined;
+ },
+ getPurposeRuntimeDurable: async (purpose) => {
+ const selection = (await baseModelStore.get(org))?.[`${purpose}Runtime`];
+ return selection ? { ...selection } : undefined;
+ },
+ setPurposeRuntime,
+ clearPurposeRuntime: (purpose) => setPurposeRuntime(purpose),
getBaseModel: (id) => baseModels.get(id)?.modelId ?? null,
setBaseModel(id, modelId) {
if (modelId === null) {
- baseModels.delete(id);
- persist(`model:${id}`, "base model", () => baseModelStore.delete(id));
+ const purposes = purposeFields(id, baseModels.get(id));
+ if (Object.keys(purposes).length) baseModels.set(id, { scopeId: id, ...purposes });
+ else baseModels.delete(id);
+ persist(`model:${id}`, "base model", async () => clearRuntime(id, await baseModelStore.get(id)));
} else {
const prior = baseModels.get(id);
if (prior?.harnessId && isHarnessId(prior.harnessId) && !modelSupportedByHarness(modelId, prior.harnessId))
@@ -815,7 +867,7 @@ export function createMemoryConfigStore(
},
getRuntimeSelection(id) {
const row = baseModels.get(id);
- if (!row?.harnessId) return null;
+ if (!row?.harnessId || !row.modelId) return null;
return {
harnessId: row.harnessId,
modelId: row.modelId,
@@ -827,8 +879,10 @@ export function createMemoryConfigStore(
},
setRuntimeSelection(id, selection) {
if (selection === null) {
- baseModels.delete(id);
- persist(`model:${id}`, "runtime selection", () => baseModelStore.delete(id));
+ const purposes = purposeFields(id, baseModels.get(id));
+ if (Object.keys(purposes).length) baseModels.set(id, { scopeId: id, ...purposes });
+ else baseModels.delete(id);
+ persist(`model:${id}`, "runtime selection", async () => clearRuntime(id, await baseModelStore.get(id)));
noteRuntimeSelectionChanged(id);
return;
}
@@ -836,7 +890,7 @@ export function createMemoryConfigStore(
const revision = (orgRow?.revision ?? 0) + 1;
const row: PersistedBaseModel =
id === org
- ? { scopeId: id, ...selection, revision, orgRevision: revision }
+ ? { scopeId: id, ...purposeFields(id, orgRow), ...selection, revision, orgRevision: revision }
: { scopeId: id, ...selection, orgRevision: orgRow?.revision ?? 0 };
baseModels.set(id, row);
persist(`model:${id}`, "runtime selection", () => baseModelStore.put(id, row));
@@ -845,15 +899,16 @@ export function createMemoryConfigStore(
async setRuntimeSelectionLatest(id, selection) {
await writeQueue(`model:${id}`, async () => {
if (selection === null) {
- await baseModelStore.delete(id);
- baseModels.delete(id);
+ const row = await clearRuntime(id, await baseModelStore.get(id));
+ if (row) baseModels.set(id, row);
+ else baseModels.delete(id);
return;
}
const orgRow = await baseModelStore.get(org);
const revision = (orgRow?.revision ?? 0) + 1;
const row: PersistedBaseModel =
id === org
- ? { scopeId: id, ...selection, revision, orgRevision: revision }
+ ? { scopeId: id, ...purposeFields(id, orgRow), ...selection, revision, orgRevision: revision }
: { scopeId: id, ...selection, orgRevision: orgRow?.revision ?? 0 };
await baseModelStore.put(id, row);
baseModels.set(id, row);
@@ -883,7 +938,7 @@ export function createMemoryConfigStore(
},
getRuntimeSelectionDurable: async (id) => {
const row = await baseModelStore.get(id);
- if (!row?.harnessId) return null;
+ if (!row?.harnessId || !row.modelId) return null;
return {
harnessId: row.harnessId,
modelId: row.modelId,
diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.ts
index 756075a58..cdbc7da79 100644
--- a/src/sessions/session-syscalls.ts
+++ b/src/sessions/session-syscalls.ts
@@ -113,6 +113,7 @@ export interface SessionOpenInput {
model?: string;
harness?: string;
thinkingLevel?: string;
+ fastMode?: boolean;
}
type SessionOpenResult =
@@ -318,6 +319,7 @@ function childRunRequest(child: Session, meta: SpawnMeta, text: string, displayT
...(meta.model ? { model: meta.model } : {}),
...(meta.harness ? { harness: meta.harness } : {}),
...(meta.thinkingLevel ? { thinkingLevel: meta.thinkingLevel } : {}),
+ ...(meta.fastMode !== undefined ? { fastMode: meta.fastMode } : {}),
...(meta.timezone ? { timezone: meta.timezone } : {}),
};
}
@@ -604,6 +606,7 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscalls
...(input.model ? { model: input.model } : {}),
...(input.harness ? { harness: input.harness } : {}),
...(input.thinkingLevel ? { thinkingLevel: input.thinkingLevel } : {}),
+ ...(input.fastMode !== undefined ? { fastMode: input.fastMode } : {}),
};
if (!existing?.spawnMeta) {
await deps.sessions.setParentSession(child.id, binding.session.id);
@@ -670,6 +673,14 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscalls
target,
{
...meta,
+ ...(target.parentSessionId
+ ? {
+ model: target.spawnMeta?.model,
+ harness: target.spawnMeta?.harness,
+ thinkingLevel: target.spawnMeta?.thinkingLevel,
+ fastMode: target.spawnMeta?.fastMode,
+ }
+ : {}),
surface: meta.surface ?? target.surface ?? "web",
actor: caller.actor,
origin: caller.origin,
diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.ts
index 38c04ca08..8451709b6 100644
--- a/src/triggers/run-trigger.ts
+++ b/src/triggers/run-trigger.ts
@@ -335,6 +335,7 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
...(spec.runtime ? { model: spec.runtime.modelId, harness: spec.runtime.harnessId } : {}),
...turnModelOptions({
triggered: true,
+ surface: spec.surface,
thinkingLevel: spec.runtime?.effortLevel ?? spec.thinkingLevel,
fastMode: spec.fastMode ?? spec.runtime?.fastMode,
}),
diff --git a/src/types.ts b/src/types.ts
index d360f0c6d..e04caef82 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -84,6 +84,7 @@ export interface SpawnMeta {
model?: string;
harness?: string;
thinkingLevel?: string;
+ fastMode?: boolean;
}
export interface SessionStatus {
diff --git a/src/wiring.ts b/src/wiring.ts
index 5d278feb7..f0d649982 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1439,6 +1439,7 @@ export function buildApp(
fallback,
input.runtime,
hydrateModelCatalog,
+ input.runtimePurpose,
);
});
@@ -1851,11 +1852,20 @@ export function buildApp(
prepareRequest: prepareSessionRequest,
authorize: (session, actorId) => canWriteScope(actorId, session.scopeId),
async validateRuntime(input, scope) {
- await resolveRuntimeChoiceDurable(configStore, runtimeOrgScope, scope, fallback, {
- ...(input.harness ? { harnessId: input.harness as HarnessId } : {}),
- ...(input.model ? { modelId: input.model } : {}),
- ...(input.thinkingLevel ? { effortLevel: input.thinkingLevel } : {}),
- });
+ await resolveRuntimeChoiceDurable(
+ configStore,
+ runtimeOrgScope,
+ scope,
+ fallback,
+ {
+ ...(input.harness ? { harnessId: input.harness as HarnessId } : {}),
+ ...(input.model ? { modelId: input.model } : {}),
+ ...(input.thinkingLevel ? { effortLevel: input.thinkingLevel } : {}),
+ ...(typeof input.fastMode === "boolean" ? { fastMode: input.fastMode } : {}),
+ },
+ hydrateModelCatalog,
+ "subagent",
+ );
},
});
const orchestratorDeps: OrchestratorDeps = {
@@ -2411,7 +2421,7 @@ export function buildApp(
);
cronChanged.notify = (id) => scheduler.notifyChanged(id);
orchestratorDeps.control = createControlService(app, scheduler, admin);
- orchestratorDeps.validateScheduledRuntime = (scope, choice) =>
+ orchestratorDeps.validateScheduledRuntime = (scope, choice, purpose) =>
availableRuntimeError(
{
deps: {
@@ -2426,6 +2436,7 @@ export function buildApp(
},
scope,
choice,
+ purpose,
);
orchestratorDeps.runtime = createRuntimeService(
{
diff --git a/test/admin-resources.test.ts b/test/admin-resources.test.ts
index a4c42673c..c798de634 100644
--- a/test/admin-resources.test.ts
+++ b/test/admin-resources.test.ts
@@ -937,3 +937,47 @@ test("historical cutover policies remain visible and clearable without layer too
await srv.close();
}
});
+
+test("org purpose runtimes round-trip, validate, and clear independently", async () => {
+ const srv = start();
+ const scopeUrl = `${srv.base}/v1/admin/scopes/org:default-org`;
+ const get = async () =>
+ (await (await fetch(`${scopeUrl}?view=models`, { headers: ADMIN })).json()) as Record<string, unknown>;
+ const put = (resource: string, body: unknown, scope = "org:default-org", headers = ADMIN) =>
+ fetch(`${srv.base}/v1/admin/scopes/${scope}/${resource}`, { method: "PUT", headers, body: JSON.stringify(body) });
+ try {
+ assert.equal((await get()).cronRuntime, null);
+ assert.equal((await get()).subagentRuntime, null);
+ for (const purpose of ["cron", "subagent"] as const) {
+ const resource = `${purpose}-runtime`;
+ const choice = { harnessId: "pi", modelId: "claude-opus-5", effortLevel: "low", fastMode: false };
+ assert.equal(
+ (await put(resource, choice, "org:default-org", { ...ADMIN, "x-admin-actor": "nobody@default-org" })).status,
+ 403,
+ );
+ assert.equal((await put(resource, choice, "personal:alice")).status, 400);
+ for (const bad of [
+ { ...choice, harnessId: "invalid" },
+ { ...choice, harnessId: "codex" },
+ { ...choice, modelId: "invalid" },
+ { ...choice, effortLevel: "invalid" },
+ { ...choice, fastMode: "yes" },
+ { ...choice, modelId: "claude-fable-5", fastMode: true },
+ { modelId: choice.modelId },
+ ])
+ assert.equal((await put(resource, bad)).status, 400);
+ assert.equal((await put(resource, choice)).status, 200);
+ assert.deepEqual((await get())[`${purpose}Runtime`], choice);
+ assert.equal((await put(resource, { harnessId: "pi", modelId: choice.modelId })).status, 200);
+ assert.deepEqual((await get())[`${purpose}Runtime`], { harnessId: "pi", modelId: choice.modelId });
+ assert.equal((await put(resource, { inherit: true })).status, 200);
+ assert.equal((await get())[`${purpose}Runtime`], null);
+ assert.equal((await put(resource, choice)).status, 200);
+ assert.equal((await put(resource, null)).status, 200);
+ assert.equal((await get())[`${purpose}Runtime`], null);
+ }
+ assert.equal((await get()).runtime, null);
+ } finally {
+ await srv.close();
+ }
+});
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index f8ca20db4..8c687dd13 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -3365,6 +3365,22 @@ test("conversation coordinators cannot execute commands through any command tool
);
});
+test("sessions open schema and dispatch preserve an explicit false fast mode", async () => {
+ const tc = fakeToolContext();
+ tc.sessionSyscalls = {
+ open: async (input) => {
+ assert.equal(input.fastMode, false);
+ return { ok: true, sessionId: "child", title: "child", liveRunsRemaining: 9 };
+ },
+ write: async () => ({ ok: false, message: "unused" }),
+ read: async () => ({ ok: false, message: "unused" }),
+ };
+ const session = createAgentTools({ current: tc }).find((tool) => tool.name === "sessions")!;
+ assert.ok(Check(session.parameters, { action: "open", task: "test", fastMode: false }));
+ assert.ok(!Check(session.parameters, { action: "open", task: "test", fastMode: "false" }));
+ assert.match(textOut(await call(session, { action: "open", task: "test", fastMode: false })), /child/);
+});
+
test("conversation coordinator mailbox checks never block on children", async () => {
const waits: number[] = [];
const tc = fakeToolContext();
diff --git a/test/config-store-org.test.ts b/test/config-store-org.test.ts
index 4f5faf021..3b326a4bc 100644
--- a/test/config-store-org.test.ts
+++ b/test/config-store-org.test.ts
@@ -29,3 +29,38 @@ test("internal member overrides normalize, persist org-wide, and hydrate back",
await rehydrated.hydrate!();
assert.deepEqual(rehydrated.getInternalMemberOverrides(), ["[email protected]", "u123abc"]);
});
+
+test("purpose runtimes persist independently without manufacturing a conversation default", async () => {
+ const baseModels = createMemoryMap<import("../src/resolution/config-store.ts").PersistedBaseModel>();
+ const store = createMemoryConfigStore("default-org", { baseModels });
+ const org = "org:default-org";
+ const cron = { harnessId: "pi", modelId: "gpt-5.5", fastMode: false };
+ const subagent = { harnessId: "pi", modelId: "claude-opus-5", effortLevel: "low" };
+ assert.equal(store.getPurposeRuntime("cron"), undefined);
+ await store.setPurposeRuntime("cron", cron);
+ await store.setPurposeRuntime("subagent", subagent);
+ assert.equal(store.getBaseModel(org), null);
+ assert.equal(await store.getRuntimeSelectionDurable(org), null);
+ const reader = createMemoryConfigStore("default-org", { baseModels });
+ await reader.hydrate!();
+ assert.deepEqual(reader.getPurposeRuntime("cron"), cron);
+ assert.deepEqual(await reader.getPurposeRuntimeDurable("subagent"), subagent);
+ reader.getPurposeRuntime("cron")!.modelId = "not-persisted";
+ assert.deepEqual(reader.getPurposeRuntime("cron"), cron);
+ await store.setRuntimeSelectionLatest(org, { harnessId: "pi", modelId: "gpt-5.5" });
+ await store.setRuntimeSelectionLatest(org, null);
+ store.setRuntimeSelection(org, null);
+ store.setRuntimeSelection(org, { harnessId: "pi", modelId: "gpt-5.5" });
+ await store.flushScope(org);
+ assert.equal(store.getRuntimeSelection(org)?.modelId, "gpt-5.5");
+ store.setBaseModel(org, "gpt-5.5");
+ store.setBaseModel(org, null);
+ await store.flushScope(org);
+ assert.deepEqual(await reader.getPurposeRuntimeDurable("cron"), cron);
+ assert.deepEqual(await reader.getPurposeRuntimeDurable("subagent"), subagent);
+ await store.clearPurposeRuntime("cron");
+ assert.equal(await reader.getPurposeRuntimeDurable("cron"), undefined);
+ assert.deepEqual(await reader.getPurposeRuntimeDurable("subagent"), subagent);
+ await store.clearPurposeRuntime("subagent");
+ assert.equal(await baseModels.get(org), null);
+});
diff --git a/test/context-compaction.test.ts b/test/context-compaction.test.ts
index db9dc061b..9e31beed7 100644
--- a/test/context-compaction.test.ts
+++ b/test/context-compaction.test.ts
@@ -1,3 +1,5 @@
+import { swarmFixture } from "./support/swarm-fixture.ts";
+import { createHarnessRouter, resolveRuntimeChoiceDurable } from "../src/harness/harness-router.ts";
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
@@ -100,12 +102,17 @@ function fakeSandbox(): Sandbox {
};
}
-function buildOrchestrator(harness: Harness, maxContextTokens?: number, defaultTurnWallClockMs?: number) {
+function buildOrchestrator(
+ harness: Harness,
+ maxContextTokens?: number,
+ defaultTurnWallClockMs?: number,
+ swarm?: Awaited<ReturnType<typeof swarmFixture>>,
+) {
const config = createMemoryConfigStore(ORG);
const acl = createAclStore();
const auditLog = createAuditLog();
const errors = createErrorLog();
- const sessions = createMemorySessionStore();
+ const sessions = swarm?.sessions ?? createMemorySessionStore();
const workspace = createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "cc-")));
const deploy = createDeployService({
deployStore: createDeployStore(),
@@ -115,12 +122,14 @@ function buildOrchestrator(harness: Harness, maxContextTokens?: number, defaultT
acl,
});
const orch = createOrchestrator({
+ config,
identity: createIdentityService(),
resolution: createResolutionService(ORG, config, acl),
sessions,
workspace,
files: createMemoryFileArtifactStore(createMemoryDurableByteStore()),
- sandbox: fakeSandbox(),
+ sandbox: swarm?.sandbox ?? fakeSandbox(),
+ ...(swarm ? { swarms: swarm.service, sandboxResources: swarm.sandboxes } : {}),
modelGateway: createModelGateway(),
auditLog,
errors,
@@ -136,7 +145,7 @@ function buildOrchestrator(harness: Harness, maxContextTokens?: number, defaultT
{ authorizesCapabilityScope: async () => true },
),
});
- return { orch, sessions, errors };
+ return { orch, sessions, errors, config };
}
async function seed(sessions: SessionStore, entries: Array<Partial<SessionEntry>>): Promise<string> {
@@ -1221,3 +1230,152 @@ test("only a cron automation receives task-runtime authority and each fire start
);
assert.equal(resumed, 2);
});
+
+test("cron and loop dispatch use purpose defaults while task handoffs and later fires stay isolated", async () => {
+ const base = createMockHarness();
+ const category = { harnessId: "pi" as const, modelId: "gpt-6-astra", effortLevel: "low", fastMode: true };
+ const handoff = { ...category, modelId: "gpt-6-sol", fastMode: false };
+ const seen: import("../src/harness/harness.ts").RuntimeChoice[] = [];
+ const adapter: Harness = {
+ ...base,
+ turns: {
+ ...base.turns,
+ runTurn: async (input) => {
+ seen.push(input.runtime as typeof category);
+ const state = await input.runtimeControl!(input.runtime as typeof category, { action: "get" });
+ assert.ok(state.ok);
+ assert.deepEqual(state.effective, category);
+ if (seen.length === 1) return { reply: "", runtimeHandoff: { choice: handoff, lifetime: "task" } };
+ return { reply: "done" };
+ },
+ },
+ };
+ const router = createHarnessRouter(new Map([["pi", adapter]]), base, (input) =>
+ resolveRuntimeChoiceDurable(
+ built.config,
+ "org:default-org",
+ input.scopeLabel,
+ category,
+ input.runtime,
+ undefined,
+ input.runtimePurpose,
+ ),
+ );
+ const built = buildOrchestrator(router);
+ built.config.setApprovedHarnesses(["pi"]);
+ await built.config.setRuntimeSelectionLatest(PERSONAL, {
+ harnessId: "pi",
+ modelId: "claude-sonnet-5",
+ effortLevel: "high",
+ });
+ await built.config.setPurposeRuntime("cron", category);
+ for (const surface of ["cron", "loop"]) {
+ const result = await built.orch.handleTurn({
+ ...turn(surface),
+ surface,
+ origin: { kind: "automation" },
+ runId: surface,
+ surfaceTools: false,
+ });
+ assert.equal(result.status, "ok");
+ }
+ assert.deepEqual(seen, [category, handoff, category]);
+});
+
+test("human child continuations respect non-fast category defaults", async () => {
+ const base = createMockHarness();
+ const category = { harnessId: "pi" as const, modelId: "gpt-6-astra", effortLevel: "low", fastMode: false };
+ const seen: unknown[] = [];
+ const adapter: Harness = {
+ ...base,
+ turns: {
+ ...base.turns,
+ runTurn: async (input) => {
+ seen.push(input.runtime);
+ return { reply: "done" };
+ },
+ },
+ };
+ const router = createHarnessRouter(new Map([["pi", adapter]]), base, (input) =>
+ resolveRuntimeChoiceDurable(
+ built.config,
+ "org:default-org",
+ input.scopeLabel,
+ category,
+ input.runtime,
+ undefined,
+ input.runtimePurpose,
+ ),
+ );
+ const built = buildOrchestrator(router);
+ built.config.setApprovedHarnesses(["pi"]);
+ built.config.setInteractiveFastMode(true);
+ await built.config.flushScope("org:default-org");
+ await built.config.setPurposeRuntime("subagent", category);
+ const parent = await built.sessions.getOrCreateByThread("parent", "dm", PERSONAL);
+ const child = await built.sessions.getOrCreateByThread("subagent:review", "dm", PERSONAL);
+ await built.sessions.setParentSession(child.id, parent.id);
+ await built.orch.handleTurn({
+ surface: "web",
+ actor,
+ conversation: { ...conv, threadRef: child.threadRef },
+ origin: { kind: "human" },
+ text: "continue",
+ surfaceTools: false,
+ });
+ assert.deepEqual(seen, [category]);
+});
+
+test("verified swarm workers use category defaults instead of copied parent choices, retaining unset behavior and handoffs", async () => {
+ const inherited = { harnessId: "pi" as const, modelId: "claude-opus-5", effortLevel: "high", fastMode: true };
+ const category = { harnessId: "pi" as const, modelId: "gpt-6-astra", effortLevel: "low", fastMode: false };
+ const handoff = { ...category, modelId: "gpt-6-sol" };
+ for (const configured of [false, true]) {
+ const f = await swarmFixture({
+ runtime: {
+ harness: inherited.harnessId,
+ model: inherited.modelId,
+ thinkingLevel: inherited.effortLevel,
+ fastMode: inherited.fastMode,
+ },
+ });
+ const [peer] = await f.service.spawn(f.caller, { requestId: "initial", text: "work" });
+ await f.service.sweep();
+ const worker = await f.workerCaller(peer!.id);
+ assert.equal(worker.kind, "agent");
+ if (worker.kind !== "agent") throw new Error("expected worker");
+ const run = (await f.runs.get(worker.claims.runId!))!;
+ const base = createMockHarness();
+ const seen: unknown[] = [];
+ const adapter: Harness = {
+ ...base,
+ turns: {
+ ...base.turns,
+ runTurn: async (input) => {
+ seen.push(input.runtime);
+ if (seen.length === 1) return { reply: "", runtimeHandoff: { choice: handoff, lifetime: "task" } };
+ return { reply: "done" };
+ },
+ },
+ };
+ const router = createHarnessRouter(new Map([["pi", adapter]]), base, (input) =>
+ resolveRuntimeChoiceDurable(
+ built.config,
+ "org:default-org",
+ input.scopeLabel,
+ inherited,
+ input.runtime,
+ undefined,
+ input.runtimePurpose,
+ ),
+ );
+ const built = buildOrchestrator(router, undefined, undefined, f);
+ built.config.setApprovedHarnesses(["pi"]);
+ await built.config.flushScope("org:default-org");
+ if (configured) await built.config.setPurposeRuntime("subagent", category);
+ const result = await built.orch.handleTurn({ ...run.request, runId: run.id });
+ assert.equal(result.status, "ok");
+ assert.deepEqual(seen, [configured ? category : inherited, handoff]);
+ assert.equal(run.request.model, inherited.modelId, "the verified stored dispatch is not mutated");
+ }
+});
diff --git a/test/cron-scheduler.test.ts b/test/cron-scheduler.test.ts
index fe7404cfd..069033b45 100644
--- a/test/cron-scheduler.test.ts
+++ b/test/cron-scheduler.test.ts
@@ -1765,5 +1765,6 @@ test("scheduled and manual fires use the saved runtime; clearing it restores inh
assert.equal(calls.length, 3);
assert.equal(calls[2]?.model, undefined);
assert.equal(calls[2]?.harness, undefined);
- assert.equal(calls[2]?.thinkingLevel, "xhigh");
+ assert.equal(calls[2]?.thinkingLevel, undefined);
+ assert.equal(calls[2]?.fastMode, undefined);
});
diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.ts
index cea4f4f24..a3d069d33 100644
--- a/test/keychain-ask.test.ts
+++ b/test/keychain-ask.test.ts
@@ -426,8 +426,8 @@ test("runTrigger marks every trigger-fired turn `triggered` (the consent-gate cl
);
assert.equal(outcome.ran, true);
assert.equal(seen?.triggered, true);
- assert.equal(seen?.thinkingLevel, "xhigh");
- assert.equal(seen?.fastMode, false);
+ assert.equal(seen?.thinkingLevel, undefined);
+ assert.equal(seen?.fastMode, undefined);
assert.equal(seen?.conversation.threadRef, "ch:C1-t1", "an explicit threadRef overrides the per-fire fireKey thread");
});
diff --git a/test/runtime-purpose.test.ts b/test/runtime-purpose.test.ts
new file mode 100644
index 000000000..4882ff570
--- /dev/null
+++ b/test/runtime-purpose.test.ts
@@ -0,0 +1,252 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createMemoryConfigStore, type PersistedBaseModel } from "../src/resolution/config-store.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { resolveRuntimeChoice, resolveRuntimeChoiceDurable } from "../src/harness/harness-router.ts";
+import { createRuntimeService } from "../src/harness/runtime-control.ts";
+import { recoveredRuntime } from "../src/harness/runtime-recovery.ts";
+import { turnModelOptions } from "../src/core/turn-options.ts";
+import type { RuntimeChoice } from "../src/harness/harness.ts";
+import type { SessionEntry } from "../src/types.ts";
+
+const ORG = "org:default-org";
+const SCOPE = "personal:alice";
+const fallback: RuntimeChoice = { harnessId: "pi", modelId: "claude-opus-5" };
+const category: RuntimeChoice = { harnessId: "pi", modelId: "gpt-6-astra", effortLevel: "low", fastMode: true };
+
+function setup() {
+ const config = createMemoryConfigStore("default-org");
+ config.setApprovedHarnesses(["pi", "codex", "claude"]);
+ config.setRuntimeSelection(ORG, { ...fallback, effortLevel: "high", fastMode: true });
+ config.setRuntimeSelection(SCOPE, { ...fallback, modelId: "claude-sonnet-5", effortLevel: "medium" });
+ return config;
+}
+
+test("unset categories preserve legacy conversation, child, and cron behavior", () => {
+ const config = setup();
+ const legacy = resolveRuntimeChoice(config, ORG, SCOPE, fallback);
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback, undefined, "subagent"), legacy);
+ assert.deepEqual(
+ resolveRuntimeChoice(config, ORG, SCOPE, fallback, undefined, "cron"),
+ resolveRuntimeChoice(config, ORG, SCOPE, fallback, { effortLevel: "xhigh", fastMode: false }),
+ );
+ assert.deepEqual(turnModelOptions({ triggered: true }), { thinkingLevel: "xhigh", fastMode: false });
+});
+
+test("cron and loop entry points defer legacy injections until runtime resolution", () => {
+ for (const surface of ["cron", "loop"]) {
+ assert.deepEqual(turnModelOptions({ triggered: true, surface }), {});
+ assert.deepEqual(turnModelOptions({ triggered: true, surface, thinkingLevel: "low", fastMode: false }), {
+ thinkingLevel: "low",
+ fastMode: false,
+ });
+ }
+});
+
+test("each purpose ignores conversation overrides and explicit fields including false win", async () => {
+ const config = setup();
+ const conversation = resolveRuntimeChoice(config, ORG, SCOPE, fallback);
+ for (const purpose of ["cron", "subagent"] as const) {
+ await config.setPurposeRuntime(purpose, category);
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback, undefined, purpose), category);
+ assert.deepEqual(
+ resolveRuntimeChoice(config, ORG, SCOPE, fallback, { effortLevel: undefined, fastMode: undefined }, purpose),
+ category,
+ );
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback, { fastMode: false }, purpose), {
+ ...category,
+ fastMode: false,
+ });
+ assert.deepEqual(
+ resolveRuntimeChoice(config, ORG, SCOPE, fallback, { modelId: "gpt-6-sol", effortLevel: "high" }, purpose),
+ {
+ ...category,
+ modelId: "gpt-6-sol",
+ effortLevel: "high",
+ },
+ );
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback), conversation);
+ }
+ await config.clearPurposeRuntime("cron");
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback, undefined, "subagent"), category);
+});
+
+test("durable purpose defaults refresh between child followups", async () => {
+ const baseModels = createMemoryMap<PersistedBaseModel>();
+ const writer = createMemoryConfigStore("default-org", { baseModels });
+ const reader = createMemoryConfigStore("default-org", { baseModels });
+ await writer.setPurposeRuntime("subagent", category);
+ assert.deepEqual(
+ await resolveRuntimeChoiceDurable(reader, ORG, SCOPE, fallback, undefined, undefined, "subagent"),
+ category,
+ );
+ await writer.setPurposeRuntime("subagent", { ...category, modelId: "gpt-6-sol" });
+ assert.deepEqual(
+ await resolveRuntimeChoiceDurable(reader, ORG, SCOPE, fallback, { fastMode: false }, undefined, "subagent"),
+ {
+ ...category,
+ modelId: "gpt-6-sol",
+ fastMode: false,
+ },
+ );
+});
+
+test("configured purpose fails closed for unapproved or incompatible merged choices", async () => {
+ const config = setup();
+ await config.setPurposeRuntime("cron", category);
+ assert.throws(
+ () => resolveRuntimeChoice(config, ORG, SCOPE, fallback, { harnessId: "opencode" }, "cron"),
+ /not approved/,
+ );
+ assert.throws(
+ () => resolveRuntimeChoice(config, ORG, SCOPE, fallback, { effortLevel: "nonsense" }, "cron"),
+ /not supported/,
+ );
+ assert.throws(
+ () => resolveRuntimeChoice(config, ORG, SCOPE, fallback, { modelId: "claude-sonnet-5" }, "cron"),
+ /fast mode is not supported/,
+ );
+ config.setApprovedHarnesses(["claude"]);
+ assert.throws(() => resolveRuntimeChoice(config, ORG, SCOPE, fallback, undefined, "cron"), /not approved/);
+});
+
+test("runtime get and inherit use job execution defaults, and handoffs survive retries", async () => {
+ const config = setup();
+ await config.flushScope(ORG);
+ await config.flushScope(SCOPE);
+ await config.setPurposeRuntime("cron", category);
+ const service = createRuntimeService(
+ { config, harnessId: "pi", baseModelDefault: fallback.modelId },
+ {
+ authorizesCapabilityScope: async () => true,
+ },
+ );
+ const claims = { actorId: "alice", scopeId: SCOPE, exp: Date.now() + 60_000, triggered: true } as const;
+ const explicit = { fastMode: false };
+ const get = await service(claims, fallback, { action: "get" }, undefined, false, undefined, true, "cron", explicit);
+ assert.ok(get.ok);
+ assert.deepEqual(get.effective, { ...category, ...explicit });
+ const inherit = await service(
+ claims,
+ fallback,
+ { action: "inherit" },
+ undefined,
+ false,
+ undefined,
+ true,
+ "cron",
+ explicit,
+ );
+ assert.ok(inherit.ok);
+ assert.deepEqual(inherit.handoff, { choice: { ...category, ...explicit }, lifetime: "task" });
+ const handoff = await service(
+ claims,
+ { ...category, ...explicit },
+ { action: "set", model: "gpt-6-sol" },
+ undefined,
+ false,
+ undefined,
+ true,
+ "cron",
+ explicit,
+ );
+ assert.ok(handoff.ok && handoff.handoff);
+ const entries = [
+ {
+ type: "tool_result",
+ payload: { tool: "runtime", runId: "run", actorId: "alice", runtimeHandoff: handoff.handoff },
+ },
+ ] as SessionEntry[];
+ const restored = recoveredRuntime(entries, "run", "alice");
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback, restored, "cron"), {
+ ...category,
+ ...explicit,
+ modelId: "gpt-6-sol",
+ });
+ assert.equal(recoveredRuntime(entries, "another-run", "alice"), undefined);
+ assert.deepEqual(resolveRuntimeChoice(config, ORG, SCOPE, fallback, undefined, "cron"), category);
+});
+
+test("scope inheritance in a human child continuation retains its configured purpose", async () => {
+ const config = setup();
+ await config.setPurposeRuntime("subagent", category);
+ const service = createRuntimeService(
+ { config, harnessId: "pi", baseModelDefault: fallback.modelId },
+ { authorizesCapabilityScope: async () => true },
+ );
+ const result = await service(
+ { actorId: "alice", scopeId: SCOPE, exp: Date.now() + 60_000, liveActor: true },
+ category,
+ { action: "inherit", lifetime: "scope" },
+ undefined,
+ false,
+ undefined,
+ false,
+ "subagent",
+ );
+ assert.ok(result.ok);
+ assert.deepEqual(result.handoff, { choice: category, lifetime: "scope" });
+ assert.equal(await config.getRuntimeSelectionDurable(SCOPE), null);
+});
+
+test("configured categories remain selectable outside the conversation picker without weakening explicit restrictions", async () => {
+ const config = setup();
+ await config.setPurposeRuntime("cron", category);
+ config.setWebuiModels(ORG, ["claude-sonnet-5"]);
+ await config.flushScope(ORG);
+ const service = createRuntimeService(
+ { config, harnessId: "pi", baseModelDefault: fallback.modelId },
+ { authorizesCapabilityScope: async () => true },
+ );
+ const claims = { actorId: "alice", scopeId: SCOPE, exp: Date.now() + 60_000, triggered: true } as const;
+ const result = await service(claims, category, { action: "inherit" }, undefined, false, undefined, true);
+ assert.ok(result.ok);
+ assert.deepEqual(result.handoff, { choice: category, lifetime: "task" });
+ const denied = await service(
+ claims,
+ category,
+ { action: "set", model: "gpt-6-sol" },
+ undefined,
+ false,
+ undefined,
+ true,
+ );
+ assert.equal(denied.ok, false);
+ config.getWebuiModelsDurable = async () => [];
+ assert.equal((await service(claims, category, { action: "inherit" }, undefined, false, undefined, true)).ok, false);
+});
+
+test("personal-account human child inheritance recognizes a configured purpose outside the chat picker", async () => {
+ const config = setup();
+ await config.setPurposeRuntime("subagent", category);
+ config.setWebuiModels(ORG, ["claude-sonnet-5"]);
+ await config.flushScope(ORG);
+ const service = createRuntimeService(
+ { config, harnessId: "pi", baseModelDefault: fallback.modelId },
+ { authorizesCapabilityScope: async () => true },
+ );
+ const claims = { actorId: "alice", scopeId: SCOPE, exp: Date.now() + 60_000, liveActor: true } as const;
+ const result = await service(
+ claims,
+ category,
+ { action: "inherit" },
+ async () => null,
+ true,
+ undefined,
+ false,
+ "subagent",
+ );
+ assert.ok(result.ok);
+ assert.deepEqual(result.handoff, { choice: category, lifetime: "task" });
+ const denied = await service(
+ claims,
+ category,
+ { action: "inherit" },
+ async () => "account denied",
+ true,
+ undefined,
+ false,
+ "subagent",
+ );
+ assert.equal(denied.ok, false);
+});
diff --git a/test/session-syscalls.test.ts b/test/session-syscalls.test.ts
index ff975d5a9..e6d6be04f 100644
--- a/test/session-syscalls.test.ts
+++ b/test/session-syscalls.test.ts
@@ -38,7 +38,10 @@ interface Rig {
syscallsFor(session: Session): ReturnType<ReturnType<typeof createSessionSyscalls>["forTurn"]>;
}
-async function rig(opts?: { treeRunCap?: number }): Promise<Rig> {
+async function rig(opts?: {
+ treeRunCap?: number;
+ prepareRequest?: (request: OrchestratorInput) => Promise<OrchestratorInput>;
+}): Promise<Rig> {
const sessions = createMemorySessionStore();
const { runs } = createMemoryRunStore();
const signals = createMemoryRunSignalStore();
@@ -50,6 +53,7 @@ async function rig(opts?: { treeRunCap?: number }): Promise<Rig> {
signals,
maxAttempts: 3,
...(opts?.treeRunCap !== undefined ? { treeRunCap: opts.treeRunCap } : {}),
+ ...(opts?.prepareRequest ? { prepareRequest: opts.prepareRequest } : {}),
});
const room = await sessions.getOrCreateByThread("slack:dm:D1", "dm", scope, undefined, "slack");
await sessions.updateTitle(room.id, "dm with alex");
@@ -101,6 +105,63 @@ test("open creates a child session with parent pointer, spawn meta, and a queued
assert.equal(out.liveRunsRemaining, SUBAGENT_TREE_RUN_CAP - 1);
});
+for (const explicit of [
+ {},
+ { fastMode: false },
+ { model: "chosen-model", harness: "pi", thinkingLevel: "high", fastMode: false },
+ { model: "chosen-model", fastMode: true },
+]) {
+ test(`child followups preserve only explicit runtime choices: ${JSON.stringify(explicit)}`, async () => {
+ const runtimeKeys = ["model", "harness", "thinkingLevel", "fastMode"] as const;
+ let defaults = { model: "old-default", harness: "codex", thinkingLevel: "low", fastMode: true };
+ const preparedInputs: OrchestratorInput[] = [];
+ const r = await rig({
+ prepareRequest: async (request) => {
+ preparedInputs.push(request);
+ return { ...defaults, ...request };
+ },
+ });
+ const syscalls = r.syscallsFor(r.room);
+ const opened = await syscalls.open({ task: "initial task", ...explicit });
+ assert.ok(opened.ok);
+ const child = await freshSession(r.sessions, opened.sessionId);
+ const first = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ for (const key of runtimeKeys) {
+ assert.equal(child.spawnMeta?.[key], explicit[key as keyof typeof explicit]);
+ assert.equal(Object.hasOwn(child.spawnMeta!, key), Object.hasOwn(explicit, key));
+ assert.equal(first.request[key], { ...defaults, ...explicit }[key]);
+ }
+ const claimed = await r.runs.claimById(first.id, "worker", 60_000);
+ assert.ok(claimed);
+ await r.runs.complete(first.id, claimed.leaseToken!, { status: "ok", reply: "done" });
+ defaults = { model: "new-default", harness: "claude", thinkingLevel: "medium", fastMode: false };
+ const followup = await syscalls.write({ followup: true, target: child.id, text: "next task" });
+ assert.ok(followup.ok);
+ assert.equal(followup.delivered, "queued_turn");
+ const next = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ for (const key of runtimeKeys) {
+ assert.equal(Object.hasOwn(preparedInputs[1]!, key), Object.hasOwn(explicit, key));
+ assert.equal(next.request[key], { ...defaults, ...explicit }[key]);
+ }
+ assert.equal((await freshSession(r.sessions, child.id)).parentSessionId, r.room.id);
+ });
+}
+
+test("followup tasks cannot turn an ordinary session into a child", async () => {
+ const r = await rig();
+ const ordinary = await r.sessions.getOrCreateByThread("web:ordinary", "dm", scope, undefined, "web");
+ await r.sessions.addParticipant(ordinary.id, actor.id);
+ await r.runs.enqueue({
+ sessionId: ordinary.threadRef,
+ request: { actor, conversation, surface: "web", origin: { kind: "human" }, text: "hello" },
+ });
+ const out = await r.syscallsFor(r.room).write({ followup: true, target: ordinary.id, text: "new task" });
+ assert.ok(!out.ok);
+ assert.match(out.message, /only target an attached subagent/);
+ assert.equal((await freshSession(r.sessions, ordinary.id)).parentSessionId, undefined);
+ assert.equal((await r.runs.inFlightForThread(ordinary.threadRef)).length, 1);
+});
+
test("nested sessions share the same tree without an artificial depth limit", async () => {
const r = await rig();
const first = await r.syscallsFor(r.room).open({ task: "level one" });
diff --git a/test/support/swarm-fixture.ts b/test/support/swarm-fixture.ts
index e82312fa3..519c82fb7 100644
--- a/test/support/swarm-fixture.ts
+++ b/test/support/swarm-fixture.ts
@@ -20,6 +20,7 @@ export async function swarmFixture(
runs?: RunStore;
lock?: AdvisoryLock;
backend?: Sandbox;
+ runtime?: Pick<OrchestratorInput, "model" | "harness" | "thinkingLevel" | "fastMode">;
} = {},
) {
const sessions = options.sessions ?? createMemorySessionStore();
@@ -95,6 +96,7 @@ export async function swarmFixture(
text: "Start workers",
surface: "slack",
deliveryTarget: "private-dm",
+ ...options.runtime,
};
const { run } = await runs.enqueue({ sessionId: root.threadRef, request: template });
const claim = (await runs.claimById(run.id, "swarm-fixture", 60_000))!;