Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): add bot reasoning effort controls (#613)
Genere8d81291b5ed
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex 0581fdb8c..2727c5688 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -167,6 +167,10 @@"key": "src/shared/src/db/queries/community/bot.ts:updateBotRuntime:inArray:1","strategy": "subquery"},+ {+ "key": "src/shared/src/db/queries/community/bot.ts:updateBotRuntimeConfig:inArray:1",+ "strategy": "subquery"+ },{"key": "src/shared/src/db/queries/community/category.ts:getCategoriesByIds:inArray:1","strategy": "json-set"diff --git a/src/daemon/agent-driver/src/adapters/codex/index.test.ts b/src/daemon/agent-driver/src/adapters/codex/index.test.tsindex c5e9a0a28..9bb9f975a 100644--- a/src/daemon/agent-driver/src/adapters/codex/index.test.ts+++ b/src/daemon/agent-driver/src/adapters/codex/index.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from "vitest";+import { beforeEach, describe, it, expect, vi } from "vitest";import { EventEmitter } from "events";import * as fs from "fs";import * as os from "os";@@ -7,18 +7,47 @@ import { CodexDriver } from "./index.js";import type { AdapterLaunchContext } from "../../internal/adapter.js";import { fakeLaunchContext } from "../../testing/adapter-fixture.js";+const runtimeMocks = vi.hoisted(() => ({+ spawnAgentProcess: vi.fn(),+ killProcessTree: vi.fn(async () => {}),+ probeCliRuntime: vi.fn(async (): Promise<+ | { status: "healthy"; version: string }+ | { status: "unhealthy"; lastError: string }+ > => ({ status: "healthy", version: "0.test" })),+}));+vi.mock("../../internal/killTree.js", async () => {const actual = await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js");return {...actual,- spawnAgentProcess: () => {- const proc = new EventEmitter() as EventEmitter & { stdin: { write: ReturnType<typeof vi.fn> } };- proc.stdin = { write: vi.fn() };- return proc as never;- },+ spawnAgentProcess: runtimeMocks.spawnAgentProcess,+ killProcessTree: runtimeMocks.killProcessTree,};});+vi.mock("../../internal/probe.js", async () => {+ const actual = await vi.importActual<typeof import("../../internal/probe.js")>("../../internal/probe.js");+ return { ...actual, probeCliRuntime: runtimeMocks.probeCliRuntime };+});++function simpleProcess() {+ const proc = new EventEmitter() as EventEmitter & {+ stdin: { write: ReturnType<typeof vi.fn> };+ kill: ReturnType<typeof vi.fn>;+ };+ proc.stdin = { write: vi.fn() };+ proc.kill = vi.fn();+ return proc;+}++beforeEach(() => {+ runtimeMocks.spawnAgentProcess.mockReset();+ runtimeMocks.spawnAgentProcess.mockImplementation(simpleProcess);+ runtimeMocks.killProcessTree.mockClear();+ runtimeMocks.probeCliRuntime.mockClear();+ runtimeMocks.probeCliRuntime.mockResolvedValue({ status: "healthy", version: "0.test" });+});+function mkTmp(): string {return fs.mkdtempSync(path.join(os.tmpdir(), "codex-test-"));}@@ -31,6 +60,253 @@ function baseCtx(): AdapterLaunchContext {});}+function probingProcess(+ respond: (request: Record<string, any>) => Record<string, unknown>,+) {+ const proc = simpleProcess() as ReturnType<typeof simpleProcess> & {+ stdout: EventEmitter;+ pid?: number;+ };+ proc.stdout = new EventEmitter();+ proc.stdin.write = vi.fn((line: string) => {+ const request = JSON.parse(line.trim()) as Record<string, any>;+ queueMicrotask(() => {+ proc.stdout.emit("data", Buffer.from(`${JSON.stringify(respond(request))}\n`));+ });+ return true;+ });+ return proc;+}++describe("CodexDriver reasoning catalog probe", () => {+ it("keeps an unhealthy CLI result unchanged without starting app-server", async () => {+ runtimeMocks.probeCliRuntime.mockResolvedValueOnce({+ status: "unhealthy",+ lastError: "missing",+ });++ await expect(new CodexDriver().probe()).resolves.toEqual({+ status: "unhealthy",+ lastError: "missing",+ });+ expect(runtimeMocks.spawnAgentProcess).not.toHaveBeenCalled();+ });++ it("keeps Codex healthy when the catalog process cannot spawn", async () => {+ runtimeMocks.spawnAgentProcess.mockImplementationOnce(() => {+ throw new Error("catalog spawn failed");+ });++ await expect(new CodexDriver().probe()).resolves.toEqual({+ status: "healthy",+ version: "0.test",+ reasoning: undefined,+ });+ });++ it("initializes, pages model/list, preserves reported options, and tears down", async () => {+ const proc = probingProcess((request) => {+ if (request.method === "initialize") return { jsonrpc: "2.0", id: request.id, result: {} };+ if (request.params.cursor === "next") {+ return {+ jsonrpc: "2.0",+ id: request.id,+ result: {+ data: [{+ id: "gpt-5.1",+ isDefault: true,+ supportedReasoningEfforts: [+ { reasoningEffort: "xhigh", description: "Deeper reasoning" },+ { reasoningEffort: "future_level" },+ ],+ defaultReasoningEffort: "xhigh",+ }],+ nextCursor: null,+ },+ };+ }+ return {+ jsonrpc: "2.0",+ id: request.id,+ result: {+ data: [{+ id: "gpt-5",+ supportedReasoningEfforts: [+ null,+ { reasoningEffort: "minimal", description: "Fast" },+ { reasoningEffort: "minimal", description: "duplicate" },+ { reasoningEffort: "bad effort" },+ ],+ defaultReasoningEffort: "minimal",+ }, null, { id: "", supportedReasoningEfforts: [] }],+ nextCursor: "next",+ },+ };+ });+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ await expect(new CodexDriver().probe()).resolves.toEqual({+ status: "healthy",+ version: "0.test",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gpt-5.1",+ models: [+ {+ id: "gpt-5",+ supportedReasoningEfforts: [{ value: "minimal", description: "Fast" }],+ defaultReasoningEffort: "minimal",+ },+ {+ id: "gpt-5.1",+ supportedReasoningEfforts: [+ { value: "xhigh", description: "Deeper reasoning" },+ { value: "future_level" },+ ],+ defaultReasoningEffort: "xhigh",+ },+ ],+ },+ });++ const requests = proc.stdin.write.mock.calls.map(([line]) => JSON.parse(line.trim()));+ expect(requests.map((request) => request.method)).toEqual(["initialize", "model/list", "model/list"]);+ expect(requests[2].params.cursor).toBe("next");+ expect(proc.kill).toHaveBeenCalledWith("SIGTERM");+ });++ it("keeps Codex healthy when model/list is unavailable", async () => {+ const proc = probingProcess((request) => request.method === "initialize"+ ? { jsonrpc: "2.0", id: request.id, result: {} }+ : { jsonrpc: "2.0", id: request.id, error: { code: -32601, message: "Method not found" } });+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ await expect(new CodexDriver().probe()).resolves.toEqual({+ status: "healthy",+ version: "0.test",+ reasoning: undefined,+ });+ expect(proc.kill).toHaveBeenCalledWith("SIGTERM");+ });++ it("normalizes missing option arrays and non-string catalog fields", async () => {+ const proc = probingProcess((request) => request.method === "initialize"+ ? { jsonrpc: "2.0", id: request.id, result: {} }+ : {+ jsonrpc: "2.0",+ id: request.id,+ result: {+ data: [+ { id: 42, supportedReasoningEfforts: [] },+ {+ id: "gpt-minimal",+ supportedReasoningEfforts: "not-an-array",+ defaultReasoningEffort: 42,+ },+ {+ id: "gpt-options",+ supportedReasoningEfforts: [+ { reasoningEffort: 42 },+ { reasoningEffort: "high", description: "" },+ ],+ },+ ],+ nextCursor: null,+ },+ });+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ await expect(new CodexDriver().probe()).resolves.toMatchObject({+ reasoning: {+ models: [+ { id: "gpt-minimal", supportedReasoningEfforts: [] },+ { id: "gpt-options", supportedReasoningEfforts: [{ value: "high" }] },+ ],+ },+ });+ });++ it("treats a non-array model/list data field as an empty catalog", async () => {+ const proc = probingProcess((request) => request.method === "initialize"+ ? { jsonrpc: "2.0", id: request.id, result: {} }+ : { jsonrpc: "2.0", id: request.id, result: { data: "invalid", nextCursor: null } });+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ await expect(new CodexDriver().probe()).resolves.toMatchObject({+ reasoning: { models: [] },+ });+ });++ it("ignores malformed and unrelated lines before consuming the catalog response", async () => {+ const proc = probingProcess(() => ({ jsonrpc: "2.0", id: -1, result: {} }));+ proc.stdin.write = vi.fn((line: string) => {+ const request = JSON.parse(line.trim()) as Record<string, any>;+ queueMicrotask(() => {+ proc.stdout.emit("data", Buffer.from("not-json\n"));+ proc.stdout.emit("data", Buffer.from(`${JSON.stringify({ jsonrpc: "2.0", id: -1, result: {} })}\n`));+ proc.stdout.emit("data", Buffer.from(`${JSON.stringify(+ request.method === "initialize"+ ? { jsonrpc: "2.0", id: request.id, result: {} }+ : { jsonrpc: "2.0", id: request.id, result: { data: [], nextCursor: null } },+ )}\n`));+ });+ return true;+ });+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ await expect(new CodexDriver().probe()).resolves.toMatchObject({+ status: "healthy",+ reasoning: { models: [] },+ });+ });++ it("treats initialize rejection as an unavailable catalog", async () => {+ const proc = probingProcess((request) => ({+ jsonrpc: "2.0",+ id: request.id,+ error: { code: -32000, message: "initialize rejected" },+ }));+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ await expect(new CodexDriver().probe()).resolves.toMatchObject({+ status: "healthy",+ reasoning: undefined,+ });+ });++ it("times out a silent catalog process", async () => {+ vi.useFakeTimers();+ try {+ const proc = simpleProcess() as ReturnType<typeof simpleProcess> & { stdout: EventEmitter };+ proc.stdout = new EventEmitter();+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ const pending = new CodexDriver().probe();+ await vi.advanceTimersByTimeAsync(5_000);++ await expect(pending).resolves.toMatchObject({ status: "healthy", reasoning: undefined });+ } finally {+ vi.useRealTimers();+ }+ });++ it("settles only once when catalog process error and exit race", async () => {+ const proc = simpleProcess() as ReturnType<typeof simpleProcess> & { stdout: EventEmitter; pid: number };+ proc.stdout = new EventEmitter();+ proc.pid = 42_424;+ runtimeMocks.killProcessTree.mockRejectedValueOnce(new Error("already exited"));+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);++ const pending = new CodexDriver().probe();+ await vi.waitFor(() => expect(runtimeMocks.spawnAgentProcess).toHaveBeenCalledOnce());+ proc.emit("error", new Error("catalog failed"));+ proc.emit("exit", 1, null);++ await expect(pending).resolves.toMatchObject({ status: "healthy", reasoning: undefined });+ expect(runtimeMocks.killProcessTree).toHaveBeenCalledWith(42_424, { graceMs: 250 });+ });+});+describe("CodexDriver initialize payload", () => {it("sends alook-daemon identity via clientInfo (matches Codex's schema)", async () => {const driver = new CodexDriver();@@ -47,6 +323,35 @@ describe("CodexDriver initialize payload", () => {expect(initPayload.method).toBe("initialize");expect(initPayload.params.clientInfo).toEqual({ name: "alook-agent-driver", version: "0.1.14" });});++ it("passes an explicit effort on fresh launch and omits Default", async () => {+ const explicit = new CodexDriver();+ const explicitCtx = baseCtx();+ explicitCtx.config.runtimeConfig = {+ model: { kind: "default" },+ mode: "default",+ reasoningEffort: "ultra",+ };+ const { process: explicitProc } = await explicit.spawn(explicitCtx);+ await Promise.resolve();+ const explicitStart = stdinWrites(explicitProc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/start");+ expect(explicitStart.params.config).toEqual({ model_reasoning_effort: "ultra" });++ const defaults = new CodexDriver();+ const defaultCtx = baseCtx();+ defaultCtx.config.runtimeConfig = {+ model: { kind: "default" },+ mode: "default",+ };+ const { process: defaultProc } = await defaults.spawn(defaultCtx);+ await Promise.resolve();+ const defaultStart = stdinWrites(defaultProc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/start");+ expect(defaultStart.params.config).toBeUndefined();+ });});// The `thread/start` (or resume) RESULT line carries the new thread id and is@@ -235,3 +540,177 @@ describe("CodexDriver encodeMessage — turn/steer expectedTurnId", () => {expect(msg.params.expectedTurnId).toBeUndefined();});});++describe("CodexDriver live reasoning settings", () => {+ it("rejects an update when no live thread is available", async () => {+ await expect(new CodexDriver().updateSettings({ reasoningEffort: "high" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_thread_unavailable", retryable: true },+ });+ });++ it("correlates an explicit effort update by JSON-RPC id", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ const pending = driver.updateSettings({ reasoningEffort: "xhigh" });+ const request = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/settings/update");+ expect(request.params).toEqual({ threadId: "th_settings", effort: "xhigh" });+ expect(driver.normalizeLine(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {} }))).toEqual([]);+ await expect(pending).resolves.toEqual({ status: "applied" });+ });++ it("sends null to restore Default and classifies method-not-found as unsupported", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ const pending = driver.updateSettings({ reasoningEffort: null });+ const request = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/settings/update");+ expect(request.params).toEqual({ threadId: "th_settings", effort: null });+ driver.normalizeLine(JSON.stringify({+ jsonrpc: "2.0",+ id: request.id,+ error: { code: -32601, message: "Method not found" },+ }));+ await expect(pending).resolves.toMatchObject({+ status: "unsupported",+ error: { code: "settings_update_unsupported" },+ });+ });++ it("maps a non-method RPC rejection to a sanitized retryable failure", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ const pending = driver.updateSettings({ reasoningEffort: "high" });+ const request = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/settings/update");+ driver.normalizeLine(JSON.stringify({+ jsonrpc: "2.0",+ id: request.id,+ error: { code: -32000, message: "settings rejected" },+ }));++ await expect(pending).resolves.toMatchObject({+ status: "failed",+ error: {+ category: "protocol",+ code: "settings_update_rejected",+ message: "settings rejected",+ retryable: true,+ },+ });+ });++ it("uses the fallback rejection message when the RPC error has no string message", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ const pending = driver.updateSettings({ reasoningEffort: "high" });+ const request = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/settings/update");+ driver.normalizeLine(JSON.stringify({+ jsonrpc: "2.0",+ id: request.id,+ error: { code: -32000, message: 42 },+ }));++ await expect(pending).resolves.toMatchObject({+ status: "failed",+ error: { message: "Codex rejected the settings update" },+ });+ });++ it("maps a synchronous settings write failure to a retryable result", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));+ const stdin = (proc as unknown as { stdin: { write: ReturnType<typeof vi.fn> } }).stdin;+ stdin.write.mockImplementationOnce(() => {+ throw new Error("write exploded");+ });++ await expect(driver.updateSettings({ reasoningEffort: "high" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_update_write_failed", retryable: true },+ });+ });++ it("passes malformed non-settings lines through without claiming them", () => {+ const driver = new CodexDriver();+ expect(driver.normalizeLine("not-json")).toEqual([]);+ expect(driver.normalizeLine("null")).toEqual([]);+ });++ it("fails an in-flight update immediately when the Codex process exits", async () => {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ const pending = driver.updateSettings({ reasoningEffort: "minimal" });+ (proc as unknown as EventEmitter).emit("exit", 1, null);++ await expect(pending).resolves.toMatchObject({+ status: "failed",+ error: { category: "process", code: "settings_process_exited", retryable: true },+ });+ });++ it("times out an unacknowledged update", async () => {+ vi.useFakeTimers();+ try {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ const pending = driver.updateSettings({ reasoningEffort: "minimal" });+ await vi.advanceTimersByTimeAsync(5_000);++ await expect(pending).resolves.toMatchObject({+ status: "failed",+ error: { category: "timeout", code: "settings_update_timeout", retryable: true },+ });+ expect(proc).toBeTruthy();+ } finally {+ vi.useRealTimers();+ }+ });++ it("ignores a timeout after its pending correlation was already removed", async () => {+ vi.useFakeTimers();+ try {+ const driver = new CodexDriver();+ const { process: proc } = await driver.spawn(baseCtx());+ await Promise.resolve();+ driver.normalizeLine(threadStartResult("th_settings"));++ void driver.updateSettings({ reasoningEffort: "minimal" });+ const request = stdinWrites(proc)+ .map((write) => JSON.parse(write.trim()))+ .find((message) => message.method === "thread/settings/update");+ (driver as unknown as { pendingSettingsUpdates: Map<number, unknown> })+ .pendingSettingsUpdates.delete(request.id);++ await vi.advanceTimersByTimeAsync(5_000);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.tsindex d48cdfa44..599b967e5 100644--- a/src/daemon/agent-driver/src/adapters/codex/index.ts+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts@@ -17,14 +17,26 @@ import type {BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, RuntimeLane,RuntimeLaneOpenOptions, SpawnedProcess,} from "../../internal/adapter.js";+import type {+ AgentDriverError,+ RuntimeSettingsUpdate,+ RuntimeSettingsUpdateResult,+ RuntimeReasoningCatalog,+} from "../../contract.js";import { createProcessLane } from "../../controller/process-host.js";import { prepareCliTransport } from "../../internal/cliTransport.js";import { CodexEventNormalizer } from "./normalizer.js";import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";import { resolveCodexHomeRootFromEnv } from "./home.js";import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";-import { spawnAgentProcess } from "../../internal/killTree.js";+import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";import { jsonRpcRequest } from "../../internal/utils.js";+import { scrubDriverErrorMessage } from "../../internal/errors.js";++const SETTINGS_UPDATE_TIMEOUT_MS = 5_000;+const MODEL_LIST_TIMEOUT_MS = 5_000;+const MODEL_LIST_MAX = 64;+const MODEL_EFFORT_MAX = 16;/** True when Codex cannot resume because the prior thread rollout is gone. */function isCodexMissingRolloutError(message: string): boolean {@@ -79,6 +91,10 @@ export class CodexDriver implements BackendAdapter {* `pendingInitialPrompt` so the fresh thread's `session_init` still delivers it.*/private pendingResumeFallbackParams: Record<string, unknown> | null = null;+ private readonly pendingSettingsUpdates = new Map<number, {+ resolve(result: RuntimeSettingsUpdateResult): void;+ timer: ReturnType<typeof setTimeout>;+ }>();private nextRequestId(): number {return ++this.requestId;}@@ -88,12 +104,133 @@ export class CodexDriver implements BackendAdapter {return this.codexHomeRoot;}- probe(command?: string) {+ async probe(command?: string) {// probeCliRuntime spawns `--version` — a missing vendored binary (npm// package resolves but the aarch64 blob is absent) fails there even// though resolveCommandOnPath returned a JS wrapper. See// plans/community-machine-presence-fix.md.- return probeCliRuntime("codex", {}, command);+ const result = await probeCliRuntime("codex", {}, command);+ if (result.status !== "healthy") return result;+ return {+ ...result,+ reasoning: await this.probeReasoningCatalog(command),+ };+ }++ private async probeReasoningCatalog(command?: string): Promise<RuntimeReasoningCatalog | undefined> {+ const spec = resolveSpawnSpec("codex", ["app-server", "--listen", "stdio://"], command);+ let proc: SpawnedProcess["process"];+ try {+ proc = spawnAgentProcess(spec.command, spec.args, {+ cwd: process.cwd(),+ env: { ...process.env, CI: "1" },+ shell: spec.shell,+ });+ } catch {+ return undefined;+ }+ return new Promise((resolve) => {+ let settled = false;+ let buffer = "";+ let nextId = 0;+ let initializeId = 0;+ let listId = 0;+ const models: RuntimeReasoningCatalog["models"][number][] = [];+ const seenModels = new Set<string>();+ let defaultModelId: string | undefined;+ const finish = (catalog?: RuntimeReasoningCatalog) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ const done = proc.pid+ ? killProcessTree(proc.pid, { graceMs: 250 }).catch(() => {})+ : Promise.resolve().then(() => { proc.kill("SIGTERM"); });+ void done.finally(() => resolve(catalog));+ };+ const requestModelPage = (cursor?: string) => {+ listId = ++nextId;+ proc.stdin?.write(jsonRpcRequest(+ "model/list",+ { limit: Math.min(MODEL_LIST_MAX - models.length, MODEL_LIST_MAX), includeHidden: false, ...(cursor ? { cursor } : {}) },+ listId,+ ) + "\n");+ };+ const consumeModel = (value: unknown) => {+ if (!value || typeof value !== "object" || models.length >= MODEL_LIST_MAX) return;+ const model = value as Record<string, unknown>;+ const id = typeof model.id === "string" ? model.id.trim() : "";+ if (!id || id.length > 100 || seenModels.has(id)) return;+ const rawOptions = Array.isArray(model.supportedReasoningEfforts)+ ? model.supportedReasoningEfforts+ : [];+ const seenEfforts = new Set<string>();+ const supportedReasoningEfforts = rawOptions.flatMap((raw) => {+ if (!raw || typeof raw !== "object") return [];+ const option = raw as Record<string, unknown>;+ const value = typeof option.reasoningEffort === "string"+ ? option.reasoningEffort.trim()+ : "";+ if (!value || value.length > 32 || !/^[A-Za-z0-9._-]+$/.test(value) || seenEfforts.has(value)) return [];+ seenEfforts.add(value);+ const description = typeof option.description === "string"+ ? option.description.slice(0, 256)+ : undefined;+ return [{ value, ...(description ? { description } : {}) }];+ }).slice(0, MODEL_EFFORT_MAX);+ const candidateDefault = typeof model.defaultReasoningEffort === "string"+ ? model.defaultReasoningEffort+ : undefined;+ seenModels.add(id);+ if (model.isDefault === true) defaultModelId = id;+ models.push({+ id,+ supportedReasoningEfforts,+ ...(candidateDefault && supportedReasoningEfforts.some((item) => item.value === candidateDefault)+ ? { defaultReasoningEffort: candidateDefault }+ : {}),+ });+ };+ const onLine = (line: string) => {+ let message: Record<string, unknown>;+ try {+ message = JSON.parse(line) as Record<string, unknown>;+ } catch {+ return;+ }+ if (message.id === initializeId) {+ if (message.error) return finish();+ requestModelPage();+ return;+ }+ if (message.id !== listId) return;+ if (message.error || !message.result || typeof message.result !== "object") return finish();+ const result = message.result as Record<string, unknown>;+ for (const model of Array.isArray(result.data) ? result.data : []) consumeModel(model);+ const cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;+ if (cursor && models.length < MODEL_LIST_MAX) return requestModelPage(cursor);+ finish({+ updateMode: "live_next_turn",+ ...(defaultModelId ? { defaultModelId } : {}),+ models,+ });+ };+ const timer = setTimeout(() => finish(), MODEL_LIST_TIMEOUT_MS);+ timer.unref?.();+ proc.stdout?.on("data", (chunk) => {+ buffer += chunk.toString();+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) if (line.trim()) onLine(line);+ });+ proc.on("error", () => finish());+ proc.on("exit", () => finish());+ initializeId = ++nextId;+ proc.stdin?.write(jsonRpcRequest(+ "initialize",+ { clientInfo: { name: "alook-agent-driver-probe", version: "0.1.24" }, capabilities: { experimentalApi: true } },+ initializeId,+ ) + "\n");+ });}async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {@@ -114,6 +251,12 @@ export class CodexDriver implements BackendAdapter {shell: spec.shell,});this.proc = proc;+ proc.once("exit", () => {+ this.failPendingSettingsUpdates(+ "settings_process_exited",+ "Codex exited before acknowledging the settings update",+ );+ });// Hold the initial user message until the thread id is adopted; `normalizeLine`// submits it as a `turn/start` on the first `session_init`. Empty/whitespace// (a bare wake with no message) → no pending prompt, so no empty turn.@@ -184,6 +327,8 @@ export class CodexDriver implements BackendAdapter {* sessionId wedges the bot: resume errors out, no turn ever runs.*/normalizeLine(line: string): AdapterEvent[] {+ const settingsResponse = this.consumeSettingsUpdateResponse(line);+ if (settingsResponse) return [];const events = this.eventNormalizer.normalizeLine(line);// Missing-rollout resume recovery — before any session_init is adopted.@@ -220,6 +365,120 @@ export class CodexDriver implements BackendAdapter {return events;}+ updateSettings(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult> {+ const threadId = this.eventNormalizer.currentSessionId;+ const stdin = this.proc?.stdin;+ if (!threadId || !stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) {+ return Promise.resolve({+ status: "failed",+ error: this.settingsError(+ "process",+ "settings_thread_unavailable",+ "Codex thread is not available for a settings update",+ true,+ ),+ });+ }+ const id = this.nextRequestId();+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ if (!this.pendingSettingsUpdates.delete(id)) return;+ resolve({+ status: "failed",+ error: this.settingsError(+ "timeout",+ "settings_update_timeout",+ "Codex did not acknowledge the settings update before the deadline",+ true,+ ),+ });+ }, SETTINGS_UPDATE_TIMEOUT_MS);+ timer.unref?.();+ this.pendingSettingsUpdates.set(id, { resolve, timer });+ try {+ stdin.write(jsonRpcRequest(+ "thread/settings/update",+ { threadId, effort: input.reasoningEffort },+ id,+ ) + "\n");+ } catch (error) {+ clearTimeout(timer);+ this.pendingSettingsUpdates.delete(id);+ resolve({+ status: "failed",+ error: this.settingsError(+ "process",+ "settings_update_write_failed",+ String(error),+ true,+ ),+ });+ }+ });+ }++ private consumeSettingsUpdateResponse(line: string): boolean {+ let value: unknown;+ try {+ value = JSON.parse(line);+ } catch {+ return false;+ }+ if (!value || typeof value !== "object") return false;+ const record = value as Record<string, unknown>;+ if (typeof record.id !== "number") return false;+ const pending = this.pendingSettingsUpdates.get(record.id);+ if (!pending) return false;+ clearTimeout(pending.timer);+ this.pendingSettingsUpdates.delete(record.id);+ const error = record.error;+ if (!error || typeof error !== "object") {+ pending.resolve({ status: "applied" });+ return true;+ }+ const rpcError = error as Record<string, unknown>;+ const message = typeof rpcError.message === "string"+ ? rpcError.message+ : "Codex rejected the settings update";+ if (rpcError.code === -32601 || /method\s+not\s+found/i.test(message)) {+ pending.resolve({+ status: "unsupported",+ error: this.settingsError(+ "protocol",+ "settings_update_unsupported",+ "Codex does not support live reasoning settings updates",+ false,+ ),+ });+ } else {+ pending.resolve({+ status: "failed",+ error: this.settingsError("protocol", "settings_update_rejected", message, true),+ });+ }+ return true;+ }++ private settingsError(+ category: AgentDriverError["category"],+ code: string,+ message: string,+ retryable: boolean,+ ): AgentDriverError {+ return { category, code, message: scrubDriverErrorMessage(message), retryable };+ }++ private failPendingSettingsUpdates(code: string, message: string): void {+ for (const [id, pending] of this.pendingSettingsUpdates) {+ clearTimeout(pending.timer);+ this.pendingSettingsUpdates.delete(id);+ pending.resolve({+ status: "failed",+ error: this.settingsError("process", code, message, true),+ });+ }+ }+get currentSessionId(): string | null {return this.eventNormalizer.currentSessionId;}diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.tsindex 42419b42c..665fe734d 100644--- a/src/daemon/agent-driver/src/contract.ts+++ b/src/daemon/agent-driver/src/contract.ts@@ -3,7 +3,37 @@ export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];export type JsonObject = { readonly [key: string]: JsonValue };export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";-export type ReasoningEffort = "low" | "medium" | "high";+export type ReasoningEffort =+ | "minimal"+ | "low"+ | "medium"+ | "high"+ | "xhigh"+ | "max"+ | "ultra"+ | (string & Record<never, never>);++export type RuntimeSettingsUpdate = {+ readonly reasoningEffort: ReasoningEffort | null;+};++export type RuntimeSettingsUpdateResult =+ | { readonly status: "applied" }+ | { readonly status: "unsupported"; readonly error?: AgentDriverError }+ | { readonly status: "failed"; readonly error: AgentDriverError };++export type RuntimeReasoningCatalog = {+ readonly updateMode: "live_next_turn" | "context_preserving_restart" | "unsupported";+ readonly defaultModelId?: string;+ readonly models: readonly {+ readonly id: string;+ readonly supportedReasoningEfforts: readonly {+ readonly value: ReasoningEffort;+ readonly description?: string;+ }[];+ readonly defaultReasoningEffort?: ReasoningEffort;+ }[];+};export type ModelSelection =| { readonly kind: "default" }@@ -453,6 +483,7 @@ export interface AgentSession<Specs, Id extends BackendId<Specs>> {start(message: AgentMessage): Promise<DeliveryReceipt>;send(message: AgentMessage): Promise<DeliveryReceipt>;interrupt(input: { readonly requestId: string; readonly reason: string }): Promise<InterruptResult>;+ updateSettings?(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult>;stop(input: StopInput): Promise<StopReceipt>;snapshot(): AgentSessionSnapshot;invokeExtension<Name extends ExtensionNames<Specs, Id>>(@@ -467,8 +498,18 @@ export interface ProbeInput<Specs, Id extends BackendId<Specs>> {}export type BackendProbe<Capabilities> =- | { readonly status: "healthy"; readonly version?: string; readonly capabilities: Capabilities }- | { readonly status: "unhealthy"; readonly error: AgentDriverError; readonly capabilities: Capabilities };+ | {+ readonly status: "healthy";+ readonly version?: string;+ readonly capabilities: Capabilities;+ readonly reasoning?: RuntimeReasoningCatalog;+ }+ | {+ readonly status: "unhealthy";+ readonly error: AgentDriverError;+ readonly capabilities: Capabilities;+ readonly reasoning?: RuntimeReasoningCatalog;+ };export interface OpenSessionInput<Specs, Id extends BackendId<Specs>> {readonly backend: Id;diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.tsindex 05260e160..8a3401b17 100644--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts@@ -12,6 +12,8 @@ import type {BuiltinBackendSpecs,ConfigOf,PreparedExecutionResource,+ RuntimeSettingsUpdate,+ RuntimeSettingsUpdateResult,} from "../contract.js";import type {BackendAdapter, BackendExecution, AdapterLaunchContext, AdapterEvent, LaneAdmission, LaneSendInput,@@ -129,6 +131,9 @@ class ControlledRuntimeLane implements RuntimeLane {onSend?: (input: LaneSendInput) => void;readonly stop = vi.fn(async () => {});readonly interrupt = vi.fn(async () => false);+ updateSettingsImpl?: (input: RuntimeSettingsUpdate) => Promise<RuntimeSettingsUpdateResult>;+ readonly updateSettings = vi.fn((input: RuntimeSettingsUpdate) =>+ this.updateSettingsImpl?.(input) ?? Promise.resolve({ status: "unsupported" as const }));on<K extends keyof RuntimeLaneEventMap>(event: K,@@ -150,6 +155,76 @@ class ControlledRuntimeLane implements RuntimeLane {}}+describe("LogicalAgentSession reasoning settings boundary", () => {+ it("holds an idle delivery until the settings update is applied", async () => {+ const lane = new ControlledRuntimeLane();+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };+ lane.sendAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:2" };+ const update = deferredValue<RuntimeSettingsUpdateResult>();+ const sent = vi.fn();+ lane.onSend = sent;+ lane.updateSettingsImpl = () => update.promise;+ const { session } = makeSession("codex", { lane });++ await expect(session.start({ id: "first", kind: "user", text: "hello" })).resolves.toMatchObject({+ status: "accepted",+ });+ const settings = session.updateSettings!({ reasoningEffort: "high" });+ lane.emit({ kind: "turn_end", sessionId: "thread_1", turnOwner: "codex:test:1" });+ await Promise.resolve();++ await expect(session.send({ id: "second", kind: "user", text: "next" })).resolves.toMatchObject({+ status: "queued",+ });+ expect(sent).toHaveBeenCalledTimes(0);++ update.resolve({ status: "applied" });+ await expect(settings).resolves.toEqual({ status: "applied" });+ await vi.waitFor(() => expect(sent).toHaveBeenCalledTimes(1));+ });++ it("rejects settings updates after the session is closed", async () => {+ const { session } = makeSession("codex");+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });++ await expect(session.updateSettings!({ reasoningEffort: "high" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_session_closed", retryable: true },+ });+ });++ it("reports unsupported when the runtime lane has no settings method", async () => {+ const lane = new ControlledRuntimeLane();+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };+ Object.defineProperty(lane, "updateSettings", { value: undefined });+ const { session } = makeSession("codex", { lane });+ await expect(session.start({ id: "first", kind: "user", text: "hello" })).resolves.toMatchObject({+ status: "accepted",+ });++ await expect(session.updateSettings!({ reasoningEffort: "high" })).resolves.toEqual({+ status: "unsupported",+ });+ });++ it("normalizes a runtime lane settings throw", async () => {+ const lane = new ControlledRuntimeLane();+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "codex:test:1" };+ lane.updateSettingsImpl = async () => {+ throw new Error("lane settings exploded");+ };+ const { session } = makeSession("codex", { lane });+ await expect(session.start({ id: "first", kind: "user", text: "hello" })).resolves.toMatchObject({+ status: "accepted",+ });++ await expect(session.updateSettings!({ reasoningEffort: "high" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_update_failed", retryable: true },+ });+ });+});+function deferred(): { promise: Promise<void>; resolve: () => void } {let resolve!: () => void;const promise = new Promise<void>((done) => { resolve = done; });diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.tsindex 0fddb3ce9..5af7facc0 100644--- a/src/daemon/agent-driver/src/controller/logical-session.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.ts@@ -18,6 +18,8 @@ import type {PreparedExecutionResource,StopInput,StopReceipt,+ RuntimeSettingsUpdate,+ RuntimeSettingsUpdateResult,} from "../contract.js";import type { AgentDriverHost } from "../contract.js";import type {@@ -216,6 +218,8 @@ implements AgentSession<Specs, Id> {private toolBoundaryFlushDisabled = false;private safeBoundaryFlush?: Promise<void>;private safeBoundaryDelivery?: SafeBoundaryDelivery;+ private settingsUpdateTail: Promise<void> = Promise.resolve();+ private settingsUpdatePending = false;private turnAdmission?: TurnAdmission;private instructionsMaterialized = false;private lifecycleGeneration = 0;@@ -280,6 +284,35 @@ implements AgentSession<Specs, Id> {return this.admit("send", message);}+ updateSettings(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult> {+ if (this.state === "closed" || this.state === "stopping" || this.finishing) {+ return Promise.resolve({+ status: "failed",+ error: driverError("process", "settings_session_closed", "Runtime session is closed", true),+ });+ }+ this.settingsUpdatePending = true;+ const operation = this.settingsUpdateTail.then(async (): Promise<RuntimeSettingsUpdateResult> => {+ if (!this.lane?.updateSettings) return { status: "unsupported" };+ try {+ return await this.lane.updateSettings(input);+ } catch (error) {+ return {+ status: "failed",+ error: driverError("process", "settings_update_failed", String(error), true),+ };+ }+ });+ this.settingsUpdateTail = operation.then((result) => {+ if (result.status === "applied") {+ this.settingsUpdatePending = false;+ return;+ }+ return new Promise<void>(() => {});+ });+ return operation;+ }+async interrupt(input: { readonly requestId: string; readonly reason: string }): Promise<InterruptResult> {if (this.state === "closed" || this.state === "stopping" || this.finishing) return { status: "closed" };if (!this.activeTurn || !this.lane) return { status: "not_running" };@@ -461,7 +494,12 @@ implements AgentSession<Specs, Id> {}if (this.state === "idle"- && (this.queued.length > 0 || this.safeBoundaryFlush !== undefined || this.safeBoundaryDelivery !== undefined)+ && (+ this.queued.length > 0+ || this.safeBoundaryFlush !== undefined+ || this.safeBoundaryDelivery !== undefined+ || this.settingsUpdatePending+ )) {return this.queue(message, "runtime_busy");}@@ -946,6 +984,7 @@ implements AgentSession<Specs, Id> {} else {void Promise.resolve().then(() => this.safeBoundaryFlush)+ .then(() => this.settingsUpdateTail).then(() => this.startNextQueued());}}diff --git a/src/daemon/agent-driver/src/controller/process-host.test.ts b/src/daemon/agent-driver/src/controller/process-host.test.tsindex 72876b9ec..81066be91 100644--- a/src/daemon/agent-driver/src/controller/process-host.test.ts+++ b/src/daemon/agent-driver/src/controller/process-host.test.ts@@ -375,6 +375,29 @@ describe("ProcessLane interrupt", () => {});});+describe("ProcessLane settings updates", () => {+ it("delegates to an adapter-provided settings method", async () => {+ const { driver } = controllableDriver(() => []);+ const updateSettings = vi.fn(async () => ({ status: "applied" as const }));+ driver.updateSettings = updateSettings;+ const session = new ProcessLane(driver, minimalCtx());++ await expect(session.updateSettings({ reasoningEffort: "high" })).resolves.toEqual({+ status: "applied",+ });+ expect(updateSettings).toHaveBeenCalledWith({ reasoningEffort: "high" });+ });++ it("reports unsupported when the adapter has no settings method", async () => {+ const { driver } = controllableDriver(() => []);+ const session = new ProcessLane(driver, minimalCtx());++ await expect(session.updateSettings({ reasoningEffort: "high" })).resolves.toEqual({+ status: "unsupported",+ });+ });+});+describe("ProcessLane stop", () => {it("idempotently kills the detached process group when its root handle is already terminal", async () => {const { driver, process: proc, kill } = controllableDriver(() => []);diff --git a/src/daemon/agent-driver/src/controller/process-host.ts b/src/daemon/agent-driver/src/controller/process-host.tsindex 10a85832b..fe80c5b26 100644--- a/src/daemon/agent-driver/src/controller/process-host.ts+++ b/src/daemon/agent-driver/src/controller/process-host.ts@@ -23,7 +23,11 @@ import type {SpawnedProcess,SpawnedProcessHandle,} from "../internal/adapter.js";-import type { BuiltinBackendId } from "../contract.js";+import type {+ BuiltinBackendId,+ RuntimeSettingsUpdate,+ RuntimeSettingsUpdateResult,+} from "../contract.js";import { killProcessTree, SESSION_STOP_GRACE_MS } from "../internal/killTree.js";const DEFAULT_PROMPT_ADMISSION_TIMEOUT_MS = 60_000;@@ -48,6 +52,7 @@ export interface ProcessAdapterPrimitives<Id extends string, Config> {sessionId: string | null,opts?: import("../internal/adapter.js").EncodeMessageOptions,): string | null;+ updateSettings?(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult>;}export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendConfig> implements RuntimeLane {@@ -240,6 +245,10 @@ export class ProcessLane<Id extends string = BuiltinBackendId, Config = BackendCreturn proc.kill("SIGINT");}+ updateSettings(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult> {+ return this.driver.updateSettings?.(input) ?? Promise.resolve({ status: "unsupported" });+ }+/** Wire stdout line-buffering → normalizeLine → runtime_event, plus lifecycle. */private attachProcess(proc: SpawnedProcessHandle): void {proc.stdout?.on("data", (chunk) => {diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.tsindex e21e0a89f..4b61ffe8b 100644--- a/src/daemon/agent-driver/src/internal/adapter.ts+++ b/src/daemon/agent-driver/src/internal/adapter.ts@@ -7,6 +7,9 @@ import type {PiConfig,PreparedExecutionResource,JsonValue,+ RuntimeReasoningCatalog,+ RuntimeSettingsUpdate,+ RuntimeSettingsUpdateResult,} from "../contract.js";export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | OpenCodeConfig | PiConfig;@@ -115,6 +118,7 @@ export interface RuntimeLane {start(input: LaneStartInput): Promise<LaneAdmission>;send(input: LaneSendInput): Promise<LaneAdmission>;interrupt(input: LaneInterruptInput): Promise<boolean>;+ updateSettings?(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult>;stop(input: LaneStopInput): Promise<void>;on<K extends keyof RuntimeLaneEventMap>(event: K,@@ -177,7 +181,12 @@ export interface SpawnedProcessHandle {}export interface SpawnedProcess { process: SpawnedProcessHandle }-export interface ProbeResult { status: "healthy" | "unhealthy"; version?: string; lastError?: string }+export interface ProbeResult {+ status: "healthy" | "unhealthy";+ version?: string;+ lastError?: string;+ reasoning?: RuntimeReasoningCatalog;+}export interface VendorSessionHandle {prompt(text: string): void | Promise<void>;diff --git a/src/daemon/agent-driver/src/internal/config.ts b/src/daemon/agent-driver/src/internal/config.tsindex fb074a78d..572794520 100644--- a/src/daemon/agent-driver/src/internal/config.ts+++ b/src/daemon/agent-driver/src/internal/config.ts@@ -10,7 +10,7 @@ import type {interface ResolvedLaunchFields {model?: string;- reasoningEffort?: "low" | "medium" | "high";+ reasoningEffort?: ReasoningEffort;fastMode: boolean;command?: string;disallowedTools?: string;diff --git a/src/daemon/agent-driver/src/public-contract.ts b/src/daemon/agent-driver/src/public-contract.tsindex bce89bb72..9d250f5f1 100644--- a/src/daemon/agent-driver/src/public-contract.ts+++ b/src/daemon/agent-driver/src/public-contract.ts@@ -1,6 +1,7 @@/** Consumer contract: logical SDK/session/event/result vocabulary only. */export type {- JsonPrimitive, JsonValue, JsonObject, BuiltinBackendId, ReasoningEffort, ModelSelection, DefaultProvider,+ JsonPrimitive, JsonValue, JsonObject, BuiltinBackendId, ReasoningEffort, RuntimeReasoningCatalog,+ RuntimeSettingsUpdate, RuntimeSettingsUpdateResult, ModelSelection, DefaultProvider,ClaudeProvider, PiProvider, BaseBackendConfig, ClaudeConfig, CodexConfig, ModelBackendConfig, CursorConfig,OpenCodeConfig, PiConfig, BackendCapabilities, ClaudeCapabilities, CodexCapabilities, CursorCapabilities,OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,diff --git a/src/daemon/agent-driver/src/sdk.ts b/src/daemon/agent-driver/src/sdk.tsindex ca568f0ba..230ebb6bf 100644--- a/src/daemon/agent-driver/src/sdk.ts+++ b/src/daemon/agent-driver/src/sdk.ts@@ -46,7 +46,14 @@ export function createAgentDriverSdkWithRegistry<Specs>(? input.command: undefined;const result = await adapter.probe(command);- if (result.status === "healthy") return { status: "healthy", version: result.version, capabilities };+ if (result.status === "healthy") {+ return {+ status: "healthy",+ version: result.version,+ capabilities,+ reasoning: result.reasoning,+ };+ }return {status: "unhealthy",error: {@@ -56,6 +63,7 @@ export function createAgentDriverSdkWithRegistry<Specs>(retryable: true,},capabilities,+ reasoning: result.reasoning,};} catch (error) {const contractInvalid = error instanceof Error && (diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.tsindex 6d6208f22..b6c9e389c 100644--- a/src/daemon/src/cli/daemonStart.ts+++ b/src/daemon/src/cli/daemonStart.ts@@ -910,7 +910,7 @@ async function activatePairingToken(arch: string,osRelease: string,daemonVersion: string,- runtimeReport: Array<{ id: string; version?: string; status?: "healthy" | "unhealthy"; lastError?: string; lastErrorAt?: string }>,+ runtimeReport: RuntimeInfo[],expectedMachineId?: string,): Promise<{ credential: string; machineId: string }> {let res: Response;diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 752f46b84..9f7d3adf3 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -262,6 +262,7 @@ export interface CreateDaemonOptions {status?: "healthy" | "unhealthy";lastError?: string;lastErrorAt?: string;+ reasoning?: import("@alook/shared").RuntimeReasoningCatalog;}>;/*** Per-agent runtime driver. `runtimeConfig` (server-pushed ondiff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.tsindex d98f3f81d..03d221272 100644--- a/src/daemon/src/discovery.test.ts+++ b/src/daemon/src/discovery.test.ts@@ -197,6 +197,30 @@ describe("detectRuntimes", () => {expect(result).toHaveLength(EXPECTED_RUNTIMES.length);expect(result[0]).toEqual({ id: EXPECTED_RUNTIMES[0], status: "healthy", version: "9.8.7" });});++ it("carries a healthy runtime's reasoning catalog into ready discovery", async () => {+ const reasoning = {+ updateMode: "live_next_turn" as const,+ defaultModelId: "gpt-5",+ models: [{+ id: "gpt-5",+ supportedReasoningEfforts: [{ value: "minimal" }, { value: "xhigh" }],+ defaultReasoningEffort: "minimal",+ }],+ };+ vi.spyOn(drivers, "getDriver").mockReturnValue({+ probe: async () => ({ status: "healthy", version: "9.8.7", reasoning }),+ } as never);++ const result = await detectRuntimes();++ expect(result[0]).toEqual({+ id: EXPECTED_RUNTIMES[0],+ status: "healthy",+ version: "9.8.7",+ reasoning,+ });+ });});describe("driver registry", () => {diff --git a/src/daemon/src/discovery.ts b/src/daemon/src/discovery.tsindex c9bd68a4c..c3610ea80 100644--- a/src/daemon/src/discovery.ts+++ b/src/daemon/src/discovery.ts@@ -8,6 +8,7 @@ import * as path from "path";import * as fs from "fs";import { fileURLToPath } from "url";import { getDriver, listRuntimeIds, type RuntimeId } from "./drivers/index.js";+import type { RuntimeReasoningCatalog } from "@alook/agent-driver";/* ------------------------------------------------------------------ *//* Agent CLI path resolution */@@ -100,6 +101,7 @@ export interface RuntimeInfo {lastError?: string;/** ISO-8601 timestamp of the last transition to unhealthy. */lastErrorAt?: string;+ reasoning?: RuntimeReasoningCatalog;}/**@@ -118,7 +120,12 @@ export async function detectRuntimes(): Promise<RuntimeInfo[]> {const driver = getDriver(id);const probe = await driver.probe();if (probe.status === "healthy") {- results.push({ id, status: "healthy", version: probe.version });+ results.push({+ id,+ status: "healthy",+ version: probe.version,+ reasoning: probe.reasoning,+ });} else {results.push({id,diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex 8336f8d2b..c69461dfa 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -481,6 +481,57 @@ describe("AgentRouter — agent:model_switch", () => {});});+describe("AgentRouter — agent:runtime_config_update", () => {+ const CFG = {+ version: 1 as const,+ runtime: "codex",+ model: { kind: "default" as const },+ mode: { kind: "default" as const },+ reasoningEffort: "xhigh",+ runtimeConfigRevision: 4,+ };++ it("passes the exact desired config to the manager without a restart-family enrollment", async () => {+ const updates: Array<{ agentId: string; config: typeof CFG }> = [];+ const mgr = {+ updateRuntimeConfig: async (agentId: string, config: typeof CFG) => {+ updates.push({ agentId, config });+ return "deferred" as const;+ },+ liveSessionReports: () => [],+ } as unknown as AgentProcessManager;+ const { ch, fire } = fakeChannel();+ const beforeCalls: string[] = [];+ const router = new AgentRouter({+ manager: mgr,+ channel: ch,+ runtimeReport: [{ id: "codex" }],+ onBeforeAgent: async (agentId) => { beforeCalls.push(agentId); },+ });+ await router.start();++ await fire({ type: "agent:runtime_config_update", agentId: "a1", config: CFG });++ expect(updates).toEqual([{ agentId: "a1", config: CFG }]);+ expect(beforeCalls).toEqual([]);+ });++ it("logs a conflicting revision and keeps the control loop alive", async () => {+ const mgr = {+ updateRuntimeConfig: async () => { throw new Error("Conflicting runtime config"); },+ liveSessionReports: () => [],+ } as unknown as AgentProcessManager;+ const { ch, fire } = fakeChannel();+ const logger = stubLogger();+ const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "codex" }], logger });+ await router.start();++ await fire({ type: "agent:runtime_config_update", agentId: "a1", config: CFG });++ expect(logger.calls.warn.some(([message]) => message === "agent:runtime_config_update rejected")).toBe(true);+ });+});+// B2 convergence: the RESTART-FAMILY commands (reset / nap / model_switch) all// route through the shared `runRestartCommand` handler. This pins that every// restart-family command is handled (none silently missing an arm) AND handleddiff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex 73b791f86..bdc1bf9ae 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -195,6 +195,7 @@ export class AgentRouter {status: r.status ?? "healthy",lastError: r.lastError,lastErrorAt: r.lastErrorAt,+ reasoning: r.reasoning,});}}@@ -574,6 +575,27 @@ export class AgentRouter {}),);break;+ case "agent:runtime_config_update": {+ this.log.info("agent:runtime_config_update received", {+ agentId: cmd.agentId,+ revision: cmd.config.runtimeConfigRevision ?? 0,+ });+ try {+ const result = await this.opts.manager.updateRuntimeConfig(cmd.agentId, cmd.config);+ this.log.info("agent:runtime_config_update accepted", {+ agentId: cmd.agentId,+ revision: cmd.config.runtimeConfigRevision ?? 0,+ result,+ });+ } catch (err) {+ this.log.warn("agent:runtime_config_update rejected", {+ agentId: cmd.agentId,+ revision: cmd.config.runtimeConfigRevision ?? 0,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ break;+ }case "agent:stop":this.log.info("agent:stop received", { agentId: cmd.agentId });try {diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.tsindex 5a04f915c..7f10a40db 100644--- a/src/daemon/src/manager/managerPolicy.ts+++ b/src/daemon/src/manager/managerPolicy.ts@@ -182,6 +182,8 @@ export type ManagerEvent =| { type: "idle_reset_committed"; agentId: string; nowMs: number }| { type: "begin_reset"; agentId: string; nowMs: number }| { type: "rewake_after_reset"; agentId: string; message: AgentMsg }+ | { type: "runtime_config_queued"; agentId: string; message: AgentMsg }+ | { type: "runtime_config_applied"; agentId: string }| {type: "runtime_signal";agentId: string;@@ -397,6 +399,34 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceRa.idleSince = null;});+ case "runtime_config_queued":+ return mutate(state, event.agentId, (a) => {+ if (!a.inbox.some((message) => message.id === event.message.id)) {+ a.inbox = [...a.inbox, event.message];+ }+ syncExecutionProjection(a);+ a.idleSince = null;+ });++ case "runtime_config_applied": {+ const existing = state.agents[event.agentId];+ if (!existing) return { state, effects: [] };+ const agent = clone(existing);+ if (+ agent.status !== "running"+ || leaseIsWorking(agent.execution.lease)+ || agent.pendingAdmissions.length > 0+ || agent.inbox.length === 0+ ) return { state, effects: [] };+ const messages = drainInbox(agent);+ return commit(state, agent, messages.map((message) => ({+ type: "send" as const,+ agentId: event.agentId,+ message,+ mode: "idle" as const,+ })));+ }+case "turn_started": {const existing = state.agents[event.agentId];if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId) return { state, effects: [] };@@ -627,7 +657,7 @@ function onTurnCompleted(const clearEffects: ManagerEffect[] = clearedStallSessionId === null? []: [{ type: "clear_stall_recovery", agentId, sessionId: clearedStallSessionId }];- if (agent.inbox.length > 0) {+ if (agent.inbox.length > 0 && !agent.resetting) {const messages = drainInbox(agent);return commit(state, agent, [...clearEffects,diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex 389cad4dd..957c5dbf6 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -447,6 +447,341 @@ describe("AgentProcessManager — idle session reset", () => {});});+describe("AgentProcessManager runtime config revisions", () => {+ const config = (revision: number, reasoningEffort: RuntimeConfig["reasoningEffort"]): RuntimeConfig => ({+ version: 1,+ runtime: "codex",+ model: { kind: "default" },+ mode: { kind: "default" },+ reasoningEffort,+ runtimeConfigRevision: revision,+ });++ it("coalesces busy updates and applies only the newest revision after turn completion", async () => {+ const { mgr, session } = makeManager();+ const updateSettings = vi.fn(async () => ({ status: "applied" as const }));+ session.updateSettings = updateSettings;+ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "work" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));++ await expect(mgr.updateRuntimeConfig("a1", config(2, "medium"))).resolves.toBe("deferred");+ await expect(mgr.updateRuntimeConfig("a1", config(3, "high"))).resolves.toBe("deferred");+ expect(updateSettings).not.toHaveBeenCalled();++ await session.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledWith({ reasoningEffort: "high" });+ });++ it("ignores stale updates and rejects a conflicting tuple at the same revision", async () => {+ const { mgr } = makeManager();+ await expect(mgr.updateRuntimeConfig("offline", config(4, "high"))).resolves.toBe("saved_for_start");+ await expect(mgr.updateRuntimeConfig("offline", config(3, "low"))).resolves.toBe("stale");+ await expect(mgr.updateRuntimeConfig("offline", config(4, "high"))).resolves.toBe("idempotent");+ await expect(mgr.updateRuntimeConfig("offline", config(4, "medium"))).rejects.toThrow(+ "Conflicting runtime config",+ );+ });++ it("holds an idle admission until an in-flight native update succeeds", async () => {+ const { mgr, session } = makeManager();+ let resolveUpdate!: (value: { status: "applied" }) => void;+ const updateSettings = vi.fn(() => new Promise<{ status: "applied" }>((resolve) => {+ resolveUpdate = resolve;+ }));+ session.updateSettings = updateSettings;+ const send = vi.spyOn(session, "send");+ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "first" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await session.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("none"));++ const updating = mgr.updateRuntimeConfig("a1", config(2, "high"));+ await vi.waitFor(() => expect(updateSettings).toHaveBeenCalledOnce());+ mgr.deliver("a1", { id: "after-update", text: "after update" });+ expect(send).not.toHaveBeenCalled();++ resolveUpdate({ status: "applied" });+ await expect(updating).resolves.toBe("applied");+ await vi.waitFor(() => expect(send).toHaveBeenCalledOnce());+ expect(send).toHaveBeenCalledWith(expect.objectContaining({+ id: "after-update",+ text: "after update",+ }));+ });++ it("converges a newer config supplied by an idle re-registration", async () => {+ const { mgr, session } = makeManager();+ session.updateSettings = vi.fn(async () => ({ status: "applied" as const }));+ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "first" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await session.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("none"));++ mgr.register("a1", { runtimeConfig: config(2, "high") });++ await vi.waitFor(() => expect(session.updateSettings).toHaveBeenCalledWith({ reasoningEffort: "high" }));+ });++ it("classifies already-applied pending revisions as idempotent or stale", async () => {+ const { mgr, session } = makeManager();+ mgr.deliver("a1", { id: "root", text: "first" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await session.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ const internal = mgr as unknown as {+ appliedRuntimeConfigs: Map<string, RuntimeConfig>;+ pendingRuntimeConfigUpdates: Map<string, RuntimeConfig>;+ convergeRuntimeConfig(agentId: string): Promise<string>;+ };+ internal.appliedRuntimeConfigs.set("a1", config(4, "high"));++ internal.pendingRuntimeConfigUpdates.set("a1", config(4, "high"));+ await expect(internal.convergeRuntimeConfig("a1")).resolves.toBe("idempotent");++ internal.pendingRuntimeConfigUpdates.set("a1", config(3, "medium"));+ await expect(internal.convergeRuntimeConfig("a1")).resolves.toBe("stale");+ });++ it("saves a newer revision for the next start when the session changes during a native apply", async () => {+ const { mgr, session } = makeManager();+ let resolveUpdate!: (result: { status: "applied" }) => void;+ session.updateSettings = vi.fn(() => new Promise((resolve) => {+ resolveUpdate = resolve;+ }));+ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "first" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await session.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("none"));++ const updating = mgr.updateRuntimeConfig("a1", config(2, "high"));+ await vi.waitFor(() => expect(session.updateSettings).toHaveBeenCalledOnce());+ await expect(mgr.updateRuntimeConfig("a1", config(3, "medium"))).resolves.toBe("deferred");+ (mgr as unknown as { sessions: Map<string, FakeSession> }).sessions.delete("a1");+ resolveUpdate({ status: "applied" });++ await expect(updating).resolves.toBe("saved_for_start");+ });++ it("recovers when boundary convergence itself rejects", async () => {+ const logger = stubLogger();+ const { mgr, session } = makeManager({ logger });+ session.updateSettings = vi.fn(async () => Object.defineProperty({}, "status", {+ get() { throw new Error("malformed settings result"); },+ }) as never);+ const stop = vi.spyOn(session, "stop");+ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "first" });+ session.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await expect(mgr.updateRuntimeConfig("a1", config(2, "high"))).resolves.toBe("deferred");++ await session.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });++ await vi.waitFor(() => expect(stop).toHaveBeenCalledOnce());+ expect(logger.calls.error.some(([message]) => message === "runtime config convergence failed")).toBe(true);+ });++ it("falls back once at the boundary and keeps queued work recoverable when native apply is unsupported", async () => {+ const oldSession = fakeSession("reasoning-old");+ const replacementSession = fakeSession("reasoning-new");+ const created: FakeSession[] = [];+ const factory: SessionFactory = () => {+ const session = created.length === 0 ? oldSession : replacementSession;+ created.push(session);+ return session;+ };+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: factory,+ });+ const updateSettings = vi.fn(async () => ({ status: "unsupported" as const }));+ oldSession.updateSettings = updateSettings;+ const oldStop = vi.spyOn(oldSession, "stop");+ const oldSend = vi.spyOn(oldSession, "send");+ const replacementStart = vi.spyOn(replacementSession, "start");++ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "current turn" });+ oldSession.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await expect(mgr.updateRuntimeConfig("a1", config(2, "xhigh"))).resolves.toBe("deferred");+ mgr.deliver("a1", { id: "queued-first", text: "first queued message" });+ mgr.deliver("a1", { id: "queued-second", text: "second queued message" });+ expect(oldSend).not.toHaveBeenCalled();++ await oldSession.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(oldStop).toHaveBeenCalledTimes(1));+ expect(updateSettings).toHaveBeenCalledOnce();+ expect(oldSend).not.toHaveBeenCalled();++ await oldSession.fire("exit", { reason: "requested", code: 0, signal: null });+ await vi.waitFor(() => expect(created).toEqual([oldSession, replacementSession]));+ expect(replacementStart).toHaveBeenCalledTimes(1);+ expect(replacementStart).toHaveBeenCalledWith(expect.objectContaining({+ id: "queued-first",+ text: "first queued message",+ }));+ });++ it("falls back from an idle native apply throw without stranding revision-fenced unread", async () => {+ const oldSession = fakeSession("reasoning-idle-throw-old");+ const replacementSession = fakeSession("reasoning-idle-throw-new");+ const created: FakeSession[] = [];+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: () => {+ const session = created.length === 0 ? oldSession : replacementSession;+ created.push(session);+ return session;+ },+ });+ let rejectUpdate!: (error: unknown) => void;+ oldSession.updateSettings = vi.fn(() => new Promise((_resolve, reject) => {+ rejectUpdate = reject;+ }));+ const oldStop = vi.spyOn(oldSession, "stop");+ const oldSend = vi.spyOn(oldSession, "send");+ const replacementStart = vi.spyOn(replacementSession, "start");++ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "first turn" });+ oldSession.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await oldSession.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("none"));++ const updating = mgr.updateRuntimeConfig("a1", config(2, "high"));+ await vi.waitFor(() => expect(oldSession.updateSettings).toHaveBeenCalledOnce());+ mgr.deliver("a1", { id: "queued-idle-throw", text: "must survive" });+ expect(oldSend).not.toHaveBeenCalled();++ rejectUpdate(new Error("idle settings exploded"));+ await expect(updating).resolves.toBe("saved_for_start");+ expect(oldStop).toHaveBeenCalledOnce();+ expect(oldSend).not.toHaveBeenCalled();++ await oldSession.fire("exit", { reason: "requested", code: 0, signal: null });+ await vi.waitFor(() => expect(created).toEqual([oldSession, replacementSession]));+ expect(replacementStart).toHaveBeenCalledWith(expect.objectContaining({+ id: "queued-idle-throw",+ text: "must survive",+ }));+ });++ it("keeps queued work behind the revision barrier when a live apply throws", async () => {+ const oldSession = fakeSession("reasoning-throw-old");+ const replacementSession = fakeSession("reasoning-throw-new");+ const created: FakeSession[] = [];+ const mgr = new AgentProcessManager({+ driverFor: () => fakeDriver("codex"),+ baseContextFor: () => ({+ workingDirectory: "/tmp",+ agentId: "a1",+ standingPrompt: "",+ config: {} as LaunchContext["config"],+ credentialProxy: {} as LaunchContext["credentialProxy"],+ }),+ sessionFactory: () => {+ const session = created.length === 0 ? oldSession : replacementSession;+ created.push(session);+ return session;+ },+ });+ oldSession.updateSettings = vi.fn(async () => {+ throw new Error("native settings exploded");+ });+ const oldStop = vi.spyOn(oldSession, "stop");+ const oldSend = vi.spyOn(oldSession, "send");+ const replacementStart = vi.spyOn(replacementSession, "start");++ mgr.register("a1", { runtimeConfig: config(1, "low") });+ mgr.deliver("a1", { id: "root", text: "current turn" });+ oldSession.startResolver?.();+ await vi.waitFor(() => expect(mgr.snapshot().agents.a1.execution.lease.state).toBe("active"));+ await expect(mgr.updateRuntimeConfig("a1", config(2, "max"))).resolves.toBe("deferred");+ mgr.deliver("a1", { id: "queued-after-throw", text: "must wait" });++ await oldSession.pushAgentEvent({+ type: "turn_completed",+ turnId: "test-turn",+ commandIds: ["root"],+ result: { outcome: "success", backendSessionId: "thread_1" },+ });+ await vi.waitFor(() => expect(oldStop).toHaveBeenCalledOnce());+ expect(oldSend).not.toHaveBeenCalled();++ await oldSession.fire("exit", { reason: "requested", code: 0, signal: null });+ await vi.waitFor(() => expect(created).toEqual([oldSession, replacementSession]));+ expect(replacementStart).toHaveBeenCalledWith(expect.objectContaining({+ id: "queued-after-throw",+ text: "must wait",+ }));+ });+});+function recordObservedTurn(recorder: ReturnType<typeof createTimelineRecorder>,agentId: string,diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex ba067f0ae..e3b27dac6 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -22,6 +22,7 @@ import type {BuiltinBackendId,BuiltinBackendSpecs,DeliveryReceipt,+ RuntimeSettingsUpdateResult,} from "@alook/agent-driver";import type { HostLaunchContext } from "./hostContext.js";import { runtimeModelName, type RuntimeConfig } from "../runtimeConfig.js";@@ -36,6 +37,7 @@ import type { TimelineTurnOwner } from "../timeline/recorder.js";const SESSION_STOP_GRACE_MS = 2_000;export type AgentActivityState = "idle" | "starting" | "running" | "stopping";export type DaemonAgentSession = AgentSession<BuiltinBackendSpecs, BuiltinBackendId>;+export type RuntimeConfigUpdateResult = "applied" | "deferred" | "saved_for_start" | "stale" | "idempotent";type ManagedEvent = AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>;type TraceTerminationCause = "runtime_error" | "killed_stalled" | "other";type TraceSpawnFailureReason = "ENOENT" | "handshake_timeout" | "pre_handshake_exit" | "spawn_threw" | "other";@@ -439,6 +441,9 @@ export class AgentProcessManager {private state: ManagerState;private readonly sessions = new Map<string, DaemonAgentSession>();private readonly runtimeConfigs = new Map<string, RuntimeConfig>();+ private readonly appliedRuntimeConfigs = new Map<string, RuntimeConfig>();+ private readonly pendingRuntimeConfigUpdates = new Map<string, RuntimeConfig>();+ private readonly runtimeConfigApplyRunning = new Set<string>();private readonly resumeSessions = new Map<string, string>();private readonly launchIds = new Map<string, string>();private readonly liveSessions = new Map<string, string>();@@ -513,11 +518,160 @@ export class AgentProcessManager {this.opts.idleResetTimeoutMs,);}- register(agentId: string, launch?: { runtimeConfig?: RuntimeConfig; sessionId?: string; launchId?: string }): void {- if (launch?.runtimeConfig) this.runtimeConfigs.set(agentId, launch.runtimeConfig);+ register(agentId: string, launch?: {+ runtimeConfig?: RuntimeConfig;+ sessionId?: string;+ launchId?: string;+ applyRuntimeConfig?: boolean;+ }): void {+ const runtimeConfigAcceptance = launch?.runtimeConfig+ ? this.acceptRuntimeConfig(agentId, launch.runtimeConfig)+ : undefined;if (launch?.sessionId) this.resumeSessions.set(agentId, launch.sessionId);if (launch?.launchId) this.launchIds.set(agentId, launch.launchId);this.dispatch({ type: "register", agentId });+ const registered = this.state.agents[agentId];+ if (+ launch?.runtimeConfig+ && launch.applyRuntimeConfig !== false+ && (runtimeConfigAcceptance === "accepted" || this.pendingRuntimeConfigUpdates.has(agentId))+ && this.sessions.has(agentId)+ && registered+ && !isActivelyWorking(registered)+ ) {+ void this.convergeRuntimeConfig(agentId);+ }+ }++ async updateRuntimeConfig(agentId: string, config: RuntimeConfig): Promise<RuntimeConfigUpdateResult> {+ const accepted = this.acceptRuntimeConfig(agentId, config);+ if (accepted === "stale" || accepted === "idempotent") return accepted;+ const session = this.sessions.get(agentId);+ if (!session) {+ this.pendingRuntimeConfigUpdates.delete(agentId);+ return "saved_for_start";+ }+ const agent = this.state.agents[agentId];+ if (agent && (agent.turnActive || isActivelyWorking(agent))) return "deferred";+ return this.convergeRuntimeConfig(agentId);+ }++ private acceptRuntimeConfig(+ agentId: string,+ config: RuntimeConfig,+ ): "accepted" | "stale" | "idempotent" {+ const desired = this.runtimeConfigs.get(agentId);+ const revision = config.runtimeConfigRevision ?? 0;+ const desiredRevision = desired?.runtimeConfigRevision ?? 0;+ if (desired && revision < desiredRevision) return "stale";+ if (desired && revision === desiredRevision) {+ if (this.runtimeConfigTuple(desired) !== this.runtimeConfigTuple(config)) {+ throw new Error(`Conflicting runtime config for ${agentId} at revision ${revision}`);+ }+ this.runtimeConfigs.set(agentId, config);+ return "idempotent";+ }+ this.runtimeConfigs.set(agentId, config);+ this.pendingRuntimeConfigUpdates.set(agentId, config);+ return "accepted";+ }++ private runtimeConfigTuple(config: RuntimeConfig): string {+ return JSON.stringify({+ version: config.version,+ runtime: config.runtime,+ model: config.model,+ mode: config.mode,+ reasoningEffort: config.reasoningEffort ?? null,+ provider: config.provider ?? null,+ command: config.command ?? null,+ disallowedTools: config.disallowedTools ?? null,+ envVars: config.envVars ?? null,+ });+ }++ private runtimeLaunchTuple(config: RuntimeConfig): string {+ return JSON.stringify({+ version: config.version,+ runtime: config.runtime,+ model: config.model,+ mode: config.mode,+ provider: config.provider ?? null,+ command: config.command ?? null,+ disallowedTools: config.disallowedTools ?? null,+ envVars: config.envVars ?? null,+ });+ }++ private async convergeRuntimeConfig(+ agentId: string,+ restartOnFailure = true,+ ): Promise<RuntimeConfigUpdateResult> {+ if (this.runtimeConfigApplyRunning.has(agentId)) return "deferred";+ const session = this.sessions.get(agentId);+ if (!session) return "saved_for_start";+ this.runtimeConfigApplyRunning.add(agentId);+ try {+ while (this.sessions.get(agentId) === session) {+ const desired = this.pendingRuntimeConfigUpdates.get(agentId) ?? this.runtimeConfigs.get(agentId);+ if (!desired) return "idempotent";+ const desiredRevision = desired.runtimeConfigRevision ?? 0;+ const applied = this.appliedRuntimeConfigs.get(agentId);+ const appliedRevision = applied?.runtimeConfigRevision ?? -1;+ if (applied && desiredRevision <= appliedRevision) {+ this.pendingRuntimeConfigUpdates.delete(agentId);+ return desiredRevision === appliedRevision ? "idempotent" : "stale";+ }+ const canApplyNatively = applied+ && this.runtimeLaunchTuple(applied) === this.runtimeLaunchTuple(desired)+ && typeof session.updateSettings === "function";+ let result: RuntimeSettingsUpdateResult = { status: "unsupported" };+ if (canApplyNatively) {+ try {+ result = await session.updateSettings!({+ reasoningEffort: desired.reasoningEffort ?? null,+ });+ } catch (error) {+ this.log.warn("runtime config live apply threw; restarting at safe boundary", {+ agentId,+ revision: desiredRevision,+ error: String(error),+ });+ if (restartOnFailure) await this.restartForRuntimeConfig(agentId, session);+ return "saved_for_start";+ }+ }+ if (result.status !== "applied") {+ this.log.warn("runtime config live apply unavailable; restarting at safe boundary", {+ agentId,+ revision: desiredRevision,+ status: result.status,+ code: result.error?.code,+ });+ if (restartOnFailure) await this.restartForRuntimeConfig(agentId, session);+ return "saved_for_start";+ }+ this.appliedRuntimeConfigs.set(agentId, desired);+ if ((this.pendingRuntimeConfigUpdates.get(agentId)?.runtimeConfigRevision ?? -1) === desiredRevision) {+ this.pendingRuntimeConfigUpdates.delete(agentId);+ }+ const latestRevision = this.runtimeConfigs.get(agentId)?.runtimeConfigRevision ?? 0;+ if (latestRevision <= desiredRevision) {+ this.dispatch({ type: "runtime_config_applied", agentId });+ return "applied";+ }+ }+ return "saved_for_start";+ } finally {+ this.runtimeConfigApplyRunning.delete(agentId);+ }+ }++ private async restartForRuntimeConfig(agentId: string, session: DaemonAgentSession): Promise<void> {+ if (this.sessions.get(agentId) !== session) return;+ this.opts.timeline?.fenceSession(agentId);+ this.markResetting(agentId);+ await this.stop(agentId);}deliver(agentId: string, message: AgentMsg): boolean {const normalized = message.id@@ -528,6 +682,14 @@ export class AgentProcessManager {? `${agentId}:source:${message.seq}`: `${agentId}:synthetic:${this.nextDeliveryOrdinal++}`,};+ if (this.sessions.has(agentId) && this.pendingRuntimeConfigUpdates.has(agentId)) {+ this.dispatch({+ type: "runtime_config_queued",+ agentId,+ message: normalized,+ });+ return this.state.agents[agentId] !== undefined;+ }const effects = this.dispatch({ type: "wake", agentId, message: normalized, nowMs: this.now() });return effects.length > 0;}@@ -609,7 +771,11 @@ export class AgentProcessManager {this.emitErrorAudit(agentId, "reset", "resume_control_update_failed", "Reset aborted because resume control could not be persisted");throw new Error("Reset aborted because resume control could not be persisted");}- this.register(agentId, { runtimeConfig: opts.runtimeConfig, launchId: opts.launchId });+ this.register(agentId, {+ runtimeConfig: opts.runtimeConfig,+ launchId: opts.launchId,+ applyRuntimeConfig: false,+ });if (!opts.forgetSession) this.opts.timeline?.fenceSession(agentId);this.abortCurrentTurn(agentId, opts.abortCause);this.markResetting(agentId);@@ -1477,6 +1643,7 @@ export class AgentProcessManager {if (state.session && this.sessions.get(agentId) === state.session) this.sessions.delete(agentId);this.liveSessions.delete(agentId);if (this.activeSpawnState.get(agentId) === state) {+ this.appliedRuntimeConfigs.delete(agentId);this.activeSpawnState.delete(agentId);this.nonCleanEndMarker.delete(agentId);}@@ -1527,6 +1694,13 @@ export class AgentProcessManager {state.session = session;state.sessionInstanceId = session.sessionInstanceId;this.sessions.set(agentId, session);+ this.appliedRuntimeConfigs.set(agentId, runtimeConfig);+ if (+ (this.pendingRuntimeConfigUpdates.get(agentId)?.runtimeConfigRevision ?? -1)+ <= (runtimeConfig.runtimeConfigRevision ?? 0)+ ) {+ this.pendingRuntimeConfigUpdates.delete(agentId);+ }this.dispatch({type: "attach_session",agentId,@@ -1905,27 +2079,40 @@ export class AgentProcessManager {this.logSessionEnded(agentId, "turn_end");const marker = this.nonCleanEndMarker.get(agentId);this.nonCleanEndMarker.delete(agentId);- this.dispatch(- marker !== undefined- ? {- type: "turn_completed",- agentId,- sessionInstanceId: event.sessionInstanceId,- nowMs: this.now(),- turnId: event.turnId,- endReason: "errored",- terminationCause: marker.cause,- errorDetail: marker.detail,- }- : {- type: "turn_completed",- agentId,- sessionInstanceId: event.sessionInstanceId,- nowMs: this.now(),- turnId: event.turnId,- },- owner,- );+ const completionEvent: Extract<ManagerEvent, { type: "turn_completed" }> = marker !== undefined+ ? {+ type: "turn_completed",+ agentId,+ sessionInstanceId: event.sessionInstanceId,+ nowMs: this.now(),+ turnId: event.turnId,+ endReason: "errored",+ terminationCause: marker.cause,+ errorDetail: marker.detail,+ }+ : {+ type: "turn_completed",+ agentId,+ sessionInstanceId: event.sessionInstanceId,+ nowMs: this.now(),+ turnId: event.turnId,+ };+ if (this.pendingRuntimeConfigUpdates.has(agentId) && this.sessions.get(agentId) === owner.session) {+ void this.convergeRuntimeConfig(agentId, false).then((result) => {+ if (result === "saved_for_start" && owner.session) this.markResetting(agentId);+ this.dispatch(completionEvent, owner);+ if (result === "saved_for_start" && owner.session) {+ void this.restartForRuntimeConfig(agentId, owner.session);+ }+ }).catch((error) => {+ this.log.error("runtime config convergence failed", { agentId, error: String(error) });+ if (owner.session) this.markResetting(agentId);+ this.dispatch(completionEvent, owner);+ if (owner.session) void this.restartForRuntimeConfig(agentId, owner.session);+ });+ return;+ }+ this.dispatch(completionEvent, owner);}}}diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 62d1f6545..01047a05c 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -23,7 +23,7 @@*/import { z } from "zod";-import type { RuntimeConfig } from "./runtime-config";+import type { RuntimeConfig, RuntimeReasoningCatalog } from "./runtime-config";import type { ChannelType, StoredChannelType } from "./utils/community-roles";import { CHANNEL_TRAITS } from "./utils/community-roles";import { parseNameAndTag } from "./lib/discriminator";@@ -770,6 +770,11 @@ export type HostCommand =* new model, never wrong about it. See `AgentProcessManager.switchModel`.*/| { type: "agent:model_switch"; agentId: AgentId; config: RuntimeConfig; launchId: string }+ | {+ type: "agent:runtime_config_update";+ agentId: AgentId;+ config: RuntimeConfig;+ }/*** Owner-triggered BATCH reset — reset every agent bound to this machine in a* SINGLE command (not N fanned-out `agent:reset` frames). The server@@ -834,6 +839,7 @@ export interface HostReadyRuntime {status?: "healthy" | "unhealthy";lastError?: string;lastErrorAt?: string;+ reasoning?: RuntimeReasoningCatalog;}/** What the host reports to the server on connect (the registration handshake). */@@ -1428,6 +1434,11 @@ export const HostCommandSchema = z.discriminatedUnion("type", [config: z.unknown(),launchId: z.string().min(1),}),+ z.object({+ type: z.literal("agent:runtime_config_update"),+ agentId: z.string().min(1),+ config: z.unknown(),+ }),z.object({type: z.literal("machine:reset_all"),resets: z.array(diff --git a/src/shared/src/community/bot-reasoning-effort.ts b/src/shared/src/community/bot-reasoning-effort.tsnew file mode 100644index 000000000..e3138f293--- /dev/null+++ b/src/shared/src/community/bot-reasoning-effort.ts@@ -0,0 +1,38 @@+import type {+ ReasoningEffort,+ ReasoningEffortOption,+ RuntimeReasoningCatalog,+} from "../runtime-config";++export type RuntimeReasoningDescriptor = {+ reasoning?: RuntimeReasoningCatalog;+};++export type ReasoningEffortResolution = {+ modelId: string | null;+ options: readonly ReasoningEffortOption[];+ defaultReasoningEffort: ReasoningEffort | null;+ canonicalEffort: ReasoningEffort | null;+ supported: boolean;+};++export function resolveReasoningEffort(+ runtime: RuntimeReasoningDescriptor | null | undefined,+ modelName: string | null,+ requested: ReasoningEffort | null,+): ReasoningEffortResolution {+ const catalog = runtime?.reasoning;+ const modelId = modelName ?? catalog?.defaultModelId ?? null;+ const model = modelId+ ? catalog?.models.find((candidate) => candidate.id === modelId)+ : undefined;+ const options = model?.supportedReasoningEfforts ?? [];+ const supported = requested === null || options.some((option) => option.value === requested);+ return {+ modelId,+ options,+ defaultReasoningEffort: model?.defaultReasoningEffort ?? null,+ canonicalEffort: supported ? requested : null,+ supported,+ };+}diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 538482b4c..3517cb87c 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -212,6 +212,8 @@ export async function buildUnreadWakeCommand(const config = makeRuntimeConfig({runtime: botCtx.runtime,model: resolveModelConfig(botCtx.runtime, botCtx.modelName),+ reasoningEffort: botCtx.reasoningEffort ?? undefined,+ runtimeConfigRevision: botCtx.runtimeConfigRevision,agentName: botCtx.name,agentHandle: `@${formatHandle(botCtx.name, botCtx.discriminator)}`,});diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.tsindex ebed2b2ad..646527d11 100644--- a/src/shared/src/db/community-machine-schema.ts+++ b/src/shared/src/db/community-machine-schema.ts@@ -262,6 +262,8 @@ export const communityBotBinding = sqliteTable(// stored. Hand-maintained in lockstep with migration 0063 (no drizzle-kit// generate in this repo).modelName: text("model_name"),+ reasoningEffort: text("reasoning_effort"),+ runtimeConfigRevision: integer("runtime_config_revision").notNull().default(0),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex a44713cf5..3256387c9 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -38,6 +38,8 @@ import { communityBotSyntheticEmail } from "../../../constants";import { withUniqueDiscriminator } from "../user";import { nanoid } from "nanoid";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import type { ReasoningEffort } from "../../../runtime-config";+import { CommunityMachineRuntimeSchema, type CommunityMachineRuntime } from "../../../schemas";// ─── Types ──────────────────────────────────────────────────────────────────@@ -64,6 +66,8 @@ export type BotBinding = {runtime: string;instruction: string;modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ runtimeConfigRevision: number;createdAt: string;};@@ -83,7 +87,13 @@ export class OwnerHasBotsError extends Error {export async function listBotsForOwner(db: Database,ownerId: string-): Promise<Array<BotRow & { machineId: string; runtime: string; modelName: string | null }>> {+): Promise<Array<BotRow & {+ machineId: string;+ runtime: string;+ modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ runtimeConfigRevision: number;+}>> {const rows = await db.select({id: user.id,@@ -98,6 +108,8 @@ export async function listBotsForOwner(machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,modelName: communityBotBinding.modelName,+ reasoningEffort: communityBotBinding.reasoningEffort,+ runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,}).from(user).innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -121,6 +133,8 @@ export async function listBotsForOwner(machineId: r.machineId,runtime: r.runtime,modelName: r.modelName ?? null,+ reasoningEffort: r.reasoningEffort ?? null,+ runtimeConfigRevision: r.runtimeConfigRevision ?? 0,}));}@@ -132,7 +146,13 @@ export async function getBotOwnedBy(db: Database,botId: string,ownerId: string-): Promise<(BotRow & { machineId: string | null; runtime: string | null; modelName: string | null }) | null> {+): Promise<(BotRow & {+ machineId: string | null;+ runtime: string | null;+ modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ runtimeConfigRevision: number;+}) | null> {const rows = await db.select({id: user.id,@@ -147,6 +167,8 @@ export async function getBotOwnedBy(machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,modelName: communityBotBinding.modelName,+ reasoningEffort: communityBotBinding.reasoningEffort,+ runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,}).from(user).leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -174,6 +196,8 @@ export async function getBotOwnedBy(machineId: r.machineId ?? null,runtime: r.runtime ?? null,modelName: r.modelName ?? null,+ reasoningEffort: r.reasoningEffort ?? null,+ runtimeConfigRevision: r.runtimeConfigRevision ?? 0,};}@@ -225,19 +249,33 @@ export async function countLiveBotsForOwner(export async function getBotBinding(db: Database,botId: string-): Promise<{ machineId: string; runtime: string; modelName: string | null } | null> {+): Promise<{+ machineId: string;+ runtime: string;+ modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ runtimeConfigRevision: number;+} | null> {const rows = await db.select({machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,modelName: communityBotBinding.modelName,+ reasoningEffort: communityBotBinding.reasoningEffort,+ runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,}).from(communityBotBinding).where(eq(communityBotBinding.userId, botId)).limit(1);const r = rows[0];if (!r) return null;- return { machineId: r.machineId, runtime: r.runtime, modelName: r.modelName ?? null };+ return {+ machineId: r.machineId,+ runtime: r.runtime,+ modelName: r.modelName ?? null,+ reasoningEffort: r.reasoningEffort ?? null,+ runtimeConfigRevision: r.runtimeConfigRevision ?? 0,+ };}/**@@ -349,6 +387,8 @@ export type BotWakeContext =machineId: string;runtime: string;modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ runtimeConfigRevision: number;ownerUserId: string | null;};@@ -364,6 +404,8 @@ export async function getBotWakeContext(db: Database, botUserId: string): PromismachineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,modelName: communityBotBinding.modelName,+ reasoningEffort: communityBotBinding.reasoningEffort,+ runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,}).from(user).leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -381,6 +423,8 @@ export async function getBotWakeContext(db: Database, botUserId: string): PromismachineId: r.machineId,runtime: r.runtime,modelName: r.modelName ?? null,+ reasoningEffort: r.reasoningEffort ?? null,+ runtimeConfigRevision: r.runtimeConfigRevision ?? 0,ownerUserId: r.ownerUserId,};}@@ -405,6 +449,8 @@ export async function listBotsForMachine(ownerDiscriminator: string;runtime: string;modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ runtimeConfigRevision: number;}>> {// Guard against orphaned bots: if a future flow soft-deletes an owner user@@ -420,6 +466,8 @@ export async function listBotsForMachine(ownerDiscriminator: owner.discriminator,runtime: communityBotBinding.runtime,modelName: communityBotBinding.modelName,+ reasoningEffort: communityBotBinding.reasoningEffort,+ runtimeConfigRevision: communityBotBinding.runtimeConfigRevision,}).from(user).innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -441,6 +489,8 @@ export async function listBotsForMachine(ownerDiscriminator: r.ownerDiscriminator,runtime: r.runtime,modelName: r.modelName ?? null,+ reasoningEffort: r.reasoningEffort ?? null,+ runtimeConfigRevision: r.runtimeConfigRevision ?? 0,}));}@@ -497,6 +547,7 @@ export type CreateBotInput = {runtime: string;image?: string | null;modelName?: string | null;+ reasoningEffort?: ReasoningEffort | null;};/**@@ -542,6 +593,7 @@ export async function createBot(runtime: data.runtime,instruction: description,modelName: data.modelName ?? null,+ reasoningEffort: data.reasoningEffort ?? null,createdAt: nowIso,});// Match updateBot's upsert semantics — reincarnation paths (nanoid collision@@ -692,7 +744,10 @@ export async function updateBotModel();const rows = await db.update(communityBotBinding)- .set({ modelName })+ .set({+ modelName,+ runtimeConfigRevision: sql`${communityBotBinding.runtimeConfigRevision} + 1`,+ }).where(inArray(communityBotBinding.userId, ownerScopedIds)).returning({ userId: communityBotBinding.userId });return rows.length > 0;@@ -718,12 +773,50 @@ export async function updateBotRuntime();const rows = await db.update(communityBotBinding)- .set({ runtime, modelName })+ .set({+ runtime,+ modelName,+ runtimeConfigRevision: sql`${communityBotBinding.runtimeConfigRevision} + 1`,+ }).where(inArray(communityBotBinding.userId, ownerScopedIds)).returning({ userId: communityBotBinding.userId });return rows.length > 0;}+export async function updateBotRuntimeConfig(+ db: Database,+ botId: string,+ ownerId: string,+ desired: {+ runtime: string;+ modelName: string | null;+ reasoningEffort: ReasoningEffort | null;+ },+): Promise<{ runtimeConfigRevision: number } | null> {+ const ownerScopedIds = db+ .select({ id: user.id })+ .from(user)+ .where(+ and(+ eq(user.id, botId),+ eq(user.ownerUserId, ownerId),+ eq(user.isBot, true),+ isNull(user.deletedAt),+ ),+ );+ const rows = await db+ .update(communityBotBinding)+ .set({+ runtime: desired.runtime,+ modelName: desired.modelName,+ reasoningEffort: desired.reasoningEffort,+ runtimeConfigRevision: sql`${communityBotBinding.runtimeConfigRevision} + 1`,+ })+ .where(inArray(communityBotBinding.userId, ownerScopedIds))+ .returning({ runtimeConfigRevision: communityBotBinding.runtimeConfigRevision });+ return rows[0] ?? null;+}+/*** Record a context refresh on a bot: stamp `lastRefreshContextAt`. Called at —* and ONLY at — the audit chokepoints that record a context refresh: `nap`,@@ -1124,13 +1217,7 @@ export async function getMachineForOwner(ownerId: string): Promise<{id: string;- availableRuntimes: Array<{- id: string;- version?: string;- status?: "healthy" | "unhealthy";- lastError?: string;- lastErrorAt?: string;- }>;+ availableRuntimes: CommunityMachineRuntime[];} | null> {const rows = await db.select({@@ -1146,35 +1233,13 @@ export async function getMachineForOwner(// `{id, version?, status?, lastError?, lastErrorAt?}[]`. Drop empty ids so// the route's `.includes()` / `.find()` checks can't be fooled by `""`.const raw = (r.availableRuntimes ?? []) as Array<unknown>;- const normalized: Array<{- id: string;- version?: string;- status?: "healthy" | "unhealthy";- lastError?: string;- lastErrorAt?: string;- }> = [];+ const normalized: CommunityMachineRuntime[] = [];for (const entry of raw) {if (typeof entry === "string") {- if (entry.length > 0) normalized.push({ id: entry });+ if (entry.length > 0) normalized.push({ id: entry, status: "healthy" });} else if (entry && typeof entry === "object") {- const obj = entry as {- id?: unknown;- version?: unknown;- status?: unknown;- lastError?: unknown;- lastErrorAt?: unknown;- };- if (typeof obj.id === "string" && obj.id.length > 0) {- const status =- obj.status === "unhealthy" ? "unhealthy" : obj.status === "healthy" ? "healthy" : undefined;- normalized.push({- id: obj.id,- ...(typeof obj.version === "string" ? { version: obj.version } : {}),- ...(status ? { status } : {}),- ...(typeof obj.lastError === "string" ? { lastError: obj.lastError } : {}),- ...(typeof obj.lastErrorAt === "string" ? { lastErrorAt: obj.lastErrorAt } : {}),- });- }+ const parsed = CommunityMachineRuntimeSchema.safeParse(entry);+ if (parsed.success) normalized.push(parsed.data);}}return { id: r.id, availableRuntimes: normalized };diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex b11a64316..5c0edbc76 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -266,6 +266,8 @@ export {DaemonPushMessageSchema,CommunityMachineRuntimeSchema,CommunityMachineRuntimeListSchema,+ ReasoningEffortSchema,+ RuntimeReasoningCatalogSchema,CommunityMachineSummarySchema,CommunityDaemonReadySchema,CommunityPairTokenResponseSchema,@@ -286,6 +288,10 @@ export {COMMUNITY_RUNTIME_ID_MAX,COMMUNITY_RUNTIME_VERSION_MAX,COMMUNITY_RUNTIME_LIST_MAX,+ COMMUNITY_REASONING_EFFORT_MAX,+ COMMUNITY_REASONING_DESCRIPTION_MAX,+ COMMUNITY_REASONING_OPTIONS_MAX,+ COMMUNITY_REASONING_MODELS_MAX,CommunityBotCreateRequestSchema,CommunityBotPatchRequestSchema,CommunityBotAddToServerRequestSchema,@@ -485,18 +491,26 @@ export type { CanonicalRefScope } from "./community-cli-contract";export type {ReasoningEffort,+ KnownReasoningEffort,+ ReasoningEffortOption,+ RuntimeReasoningCatalog,ModelConfig,ProviderConfig,ModeConfig,RuntimeConfig,} from "./runtime-config";-export { RUNTIME_CONFIG_VERSION, makeRuntimeConfig } from "./runtime-config";+export { RUNTIME_CONFIG_VERSION, KNOWN_REASONING_EFFORTS, makeRuntimeConfig } from "./runtime-config";export type { RuntimeModelCatalogEntry } from "./constants/runtime-models";export {RUNTIME_MODEL_CATALOG,getRuntimeModelCatalog,} from "./constants/runtime-models";+export type {+ RuntimeReasoningDescriptor,+ ReasoningEffortResolution,+} from "./community/bot-reasoning-effort";+export { resolveReasoningEffort } from "./community/bot-reasoning-effort";export {MODEL_SELECT_DEFAULT,diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.tsindex 22473f9d2..7358edf71 100644--- a/src/shared/src/runtime-config.ts+++ b/src/shared/src/runtime-config.ts@@ -14,16 +14,40 @@* `ResolvedLaunchFields` stay daemon-only (host-side launch resolution, not* needed server-side).*- * The host doesn't act on `RuntimeConfig` directly; it `resolveLaunchFields()`s- * it into flat launch fields (CLI args + env) that each driver consumes. Config- * is start-time: changing it means relaunching the agent with a new RuntimeConfig- * (there is no live-reconfigure path — model/effort are spawn-time args).+ * The host resolves launch fields from this config. Reasoning effort is also a+ * desired live setting: a capable driver may apply it at a safe turn boundary,+ * while other drivers relaunch with the same session context.*/export const RUNTIME_CONFIG_VERSION = 1;-/** Reasoning/thinking effort. */-export type ReasoningEffort = "low" | "medium" | "high";+export const KNOWN_REASONING_EFFORTS = [+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ "ultra",+] as const;++export type KnownReasoningEffort = (typeof KNOWN_REASONING_EFFORTS)[number];+export type ReasoningEffort = KnownReasoningEffort | (string & Record<never, never>);++export type ReasoningEffortOption = {+ value: ReasoningEffort;+ description?: string;+};++export type RuntimeReasoningCatalog = {+ readonly updateMode: "live_next_turn" | "context_preserving_restart" | "unsupported";+ readonly defaultModelId?: string;+ readonly models: readonly {+ readonly id: string;+ readonly supportedReasoningEfforts: readonly ReasoningEffortOption[];+ readonly defaultReasoningEffort?: ReasoningEffort;+ }[];+};/** Model selection — structured, not a bare string. */export type ModelConfig =@@ -50,6 +74,8 @@ export interface RuntimeConfig {model: ModelConfig;mode: ModeConfig;reasoningEffort?: ReasoningEffort;+ /** Server-generated last-write-wins ordering token for desired runtime config. */+ runtimeConfigRevision?: number;provider?: ProviderConfig;/** Override the runtime's default executable path. */command?: string;@@ -88,6 +114,7 @@ export function makeRuntimeConfig(model: input.model ?? { kind: "default" },mode: input.mode ?? { kind: "default" },reasoningEffort: input.reasoningEffort,+ runtimeConfigRevision: input.runtimeConfigRevision,provider: input.provider,command: input.command,disallowedTools: input.disallowedTools,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 371feaf0c..5bdc61fc3 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -829,6 +829,66 @@ export type CreateThreadRequest = z.infer<typeof CreateThreadRequestSchema>;// Runtime id charset: alnum + `._@/-`. Length capped at 64 to match the// on-wire, on-disk, and DB expectations. Version optional, length-capped.const RUNTIME_ID_RE = /^[A-Za-z0-9._@/-]+$/;+const REASONING_EFFORT_RE = /^[A-Za-z0-9._-]+$/;+export const COMMUNITY_REASONING_EFFORT_MAX = 32;+export const COMMUNITY_REASONING_DESCRIPTION_MAX = 256;+export const COMMUNITY_REASONING_OPTIONS_MAX = 16;+export const COMMUNITY_REASONING_MODELS_MAX = 64;++export const ReasoningEffortSchema = z+ .string()+ .min(1)+ .max(COMMUNITY_REASONING_EFFORT_MAX)+ .regex(REASONING_EFFORT_RE, "invalid reasoning effort charset");++const RuntimeReasoningOptionSchema = z.object({+ value: ReasoningEffortSchema,+ description: z.string().max(COMMUNITY_REASONING_DESCRIPTION_MAX).optional(),+});++const RuntimeReasoningModelSchema = z.object({+ id: z.string().min(1).max(100),+ supportedReasoningEfforts: z+ .array(z.unknown())+ .max(COMMUNITY_REASONING_OPTIONS_MAX)+ .transform((options) => {+ const seen = new Set<string>();+ return options.flatMap((candidate) => {+ const parsed = RuntimeReasoningOptionSchema.safeParse(candidate);+ if (!parsed.success) return [];+ const option = parsed.data;+ if (seen.has(option.value)) return [];+ seen.add(option.value);+ return [option];+ });+ }),+ defaultReasoningEffort: ReasoningEffortSchema.optional().catch(undefined),+}).transform((model) => {+ const { defaultReasoningEffort, ...rest } = model;+ return defaultReasoningEffort !== undefined+ && model.supportedReasoningEfforts.some((option) => option.value === defaultReasoningEffort)+ ? { ...rest, defaultReasoningEffort }+ : rest;+});++export const RuntimeReasoningCatalogSchema = z.object({+ updateMode: z.enum(["live_next_turn", "context_preserving_restart", "unsupported"]),+ defaultModelId: z.string().min(1).max(100).optional().catch(undefined),+ models: z+ .array(z.unknown())+ .max(COMMUNITY_REASONING_MODELS_MAX)+ .transform((models) => {+ const seen = new Set<string>();+ return models.flatMap((candidate) => {+ const parsed = RuntimeReasoningModelSchema.safeParse(candidate);+ if (!parsed.success) return [];+ const model = parsed.data;+ if (seen.has(model.id)) return [];+ seen.add(model.id);+ return [model];+ });+ }),+});// Per-runtime health, reported by the daemon. `status` defaults to "healthy"// so an older daemon that ships {id, version} still parses; `.catch("healthy")`@@ -846,6 +906,7 @@ export const CommunityMachineRuntimeSchema = z.object({status: z.enum(["healthy", "unhealthy"]).catch("healthy").default("healthy"),lastError: z.string().max(128).optional(),lastErrorAt: z.string().optional(),+ reasoning: RuntimeReasoningCatalogSchema.optional().catch(undefined),});export type CommunityMachineRuntime = z.infer<typeof CommunityMachineRuntimeSchema>;@@ -1133,6 +1194,7 @@ export const CommunityBotCreateRequestSchema = z.object({// Full launchable model id, or null for the runtime's default. `undefined`// ⇒ untouched (default), explicit `null` ⇒ default.model: z.string().trim().min(1).max(100).nullable().optional(),+ reasoningEffort: ReasoningEffortSchema.nullable().optional(),});export type CommunityBotCreateRequest = z.infer<typeof CommunityBotCreateRequestSchema>;@@ -1151,6 +1213,7 @@ export const CommunityBotPatchRequestSchema = z// `null` clears a set model; `undefined` leaves it untouched.model: z.string().trim().min(1).max(100).nullable().optional(),runtime: z.string().trim().min(1).max(COMMUNITY_RUNTIME_ID_MAX).optional(),+ reasoningEffort: ReasoningEffortSchema.nullable().optional(),}).refine((v) =>@@ -1158,6 +1221,7 @@ export const CommunityBotPatchRequestSchema = zv.description !== undefined ||v.image !== undefined ||v.runtime !== undefined ||+ "reasoningEffort" in v ||// `model` alone is a valid patch. An explicit `null` must count as// present — hence the `in` form, not a truthiness check."model" in v,diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex 023320d4e..83ce75364 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -325,6 +325,31 @@ describe("HostCommand control heartbeat contract", () => {});});+describe("HostCommand runtime config update contract", () => {+ it("keeps the narrow revisioned config arm in the type and runtime schema", () => {+ const config = {+ version: 1,+ runtime: "codex",+ model: { kind: "default" as const },+ mode: { kind: "default" as const },+ reasoningEffort: "xhigh",+ runtimeConfigRevision: 8,+ };+ type RuntimeConfigUpdate = {+ type: "agent:runtime_config_update";+ agentId: string;+ config: typeof config;+ };+ expectTypeOf<Extract<HostCommand, { type: "agent:runtime_config_update" }>>()+ .toMatchTypeOf<RuntimeConfigUpdate>();+ expect(HostCommandSchema.parse({+ type: "agent:runtime_config_update",+ agentId: "bot_1",+ config,+ })).toEqual({ type: "agent:runtime_config_update", agentId: "bot_1", config });+ });+});+describe("HostCommand machine update contract", () => {it("keeps the no-payload arm in the type and strict runtime schema", () => {type UpdateCommand = { type: "machine:update" };diff --git a/src/shared/test/community/bot-reasoning-effort.test.ts b/src/shared/test/community/bot-reasoning-effort.test.tsnew file mode 100644index 000000000..ab617e49d--- /dev/null+++ b/src/shared/test/community/bot-reasoning-effort.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";+import { resolveReasoningEffort } from "../../src/community/bot-reasoning-effort";++const runtime = {+ reasoning: {+ updateMode: "live_next_turn" as const,+ defaultModelId: "model-a",+ models: [+ {+ id: "model-a",+ supportedReasoningEfforts: [{ value: "minimal" }, { value: "xhigh" }],+ defaultReasoningEffort: "minimal",+ },+ {+ id: "model-b",+ supportedReasoningEfforts: [{ value: "low" }],+ },+ ],+ },+};++describe("resolveReasoningEffort", () => {+ it("uses the reported default model without persisting the reported default effort", () => {+ expect(resolveReasoningEffort(runtime, null, null)).toEqual({+ modelId: "model-a",+ options: [{ value: "minimal" }, { value: "xhigh" }],+ defaultReasoningEffort: "minimal",+ canonicalEffort: null,+ supported: true,+ });+ });++ it("accepts exact known and forward-compatible reported values", () => {+ expect(resolveReasoningEffort(runtime, "model-a", "xhigh").canonicalEffort).toBe("xhigh");+ const future = {+ reasoning: {+ ...runtime.reasoning,+ models: [{ id: "future", supportedReasoningEfforts: [{ value: "new_level" }] }],+ },+ };+ expect(resolveReasoningEffort(future, "future", "new_level").canonicalEffort).toBe("new_level");+ });++ it("falls an incompatible or unreported explicit effort back to Default", () => {+ expect(resolveReasoningEffort(runtime, "model-b", "xhigh")).toMatchObject({+ canonicalEffort: null,+ supported: false,+ });+ expect(resolveReasoningEffort(undefined, null, "high")).toMatchObject({+ options: [],+ canonicalEffort: null,+ supported: false,+ });+ });+});diff --git a/src/shared/test/migrations/community-bot-reasoning-effort.test.ts b/src/shared/test/migrations/community-bot-reasoning-effort.test.tsnew file mode 100644index 000000000..bc3fc7c0d--- /dev/null+++ b/src/shared/test/migrations/community-bot-reasoning-effort.test.ts@@ -0,0 +1,45 @@+import Sqlite from "better-sqlite3";+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";++const testDirectory = dirname(fileURLToPath(import.meta.url));+const migrationPath = resolve(+ testDirectory,+ "../../../web/migrations/0091_community_bot_reasoning_effort.sql",+);++describe("0091 community bot reasoning effort migration", () => {+ let sqlite: Sqlite.Database | undefined;++ afterEach(() => sqlite?.close());++ it("preserves existing bindings with Default effort and revision zero", () => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE community_bot_binding (+ user_id TEXT PRIMARY KEY,+ machine_id TEXT NOT NULL,+ runtime TEXT NOT NULL,+ instruction TEXT NOT NULL DEFAULT '',+ model_name TEXT,+ created_at TEXT NOT NULL+ );+ INSERT INTO community_bot_binding (+ user_id, machine_id, runtime, instruction, model_name, created_at+ ) VALUES ('bot_1', 'machine_1', 'codex', 'role', 'gpt-5', '2026-08-29');+ `);++ sqlite.exec(readFileSync(migrationPath, "utf8"));++ expect(sqlite.prepare(`+ SELECT user_id, reasoning_effort, runtime_config_revision+ FROM community_bot_binding+ `).get()).toEqual({+ user_id: "bot_1",+ reasoning_effort: null,+ runtime_config_revision: 0,+ });+ });+});diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex e7733b43c..b4aeb3e0e 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -1,5 +1,7 @@import { describe, it, expect, vi } from "vitest"import { drizzle } from "drizzle-orm/d1"+import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3"+import Sqlite from "better-sqlite3"import * as q from "../../src/db/queries/community/bot"import {communityBotSyntheticEmail,@@ -164,6 +166,72 @@ describe("createBot", () => {})})+describe("bot runtime-config read projections", () => {+ const storedBot = {+ id: "bot_1",+ name: "helper",+ discriminator: "1234",+ image: null,+ ownerUserId: "owner_1",+ description: "does things",+ createdAt: "2026-08-29T00:00:00.000Z",+ updatedAt: "2026-08-29T00:00:00.000Z",+ lastRefreshContextAt: null,+ machineId: "machine_1",+ runtime: "codex",+ modelName: "gpt-5",+ reasoningEffort: "high",+ runtimeConfigRevision: 7,+ }++ function makeOwnerListChain(rows: unknown[]) {+ const chain: any = {}+ chain.select = vi.fn(() => chain)+ chain.from = vi.fn(() => chain)+ chain.innerJoin = vi.fn(() => chain)+ chain.where = vi.fn(() => Promise.resolve(rows))+ return chain+ }++ function makeLimitedReadChain(rows: unknown[]) {+ const chain: any = {}+ chain.select = vi.fn(() => chain)+ chain.from = vi.fn(() => chain)+ chain.leftJoin = vi.fn(() => chain)+ chain.where = vi.fn(() => chain)+ chain.limit = vi.fn(() => Promise.resolve(rows))+ return chain+ }++ it("returns reasoning effort and revision when listing an owner's bots", async () => {+ await expect(q.listBotsForOwner(makeOwnerListChain([storedBot]), "owner_1")).resolves.toEqual([+ storedBot,+ ])+ })++ it("returns reasoning effort and revision from the owner-scoped lookup", async () => {+ await expect(q.getBotOwnedBy(makeLimitedReadChain([storedBot]), "bot_1", "owner_1")).resolves.toEqual(+ storedBot,+ )+ })++ it("returns reasoning effort and revision in a ready wake context", async () => {+ await expect(q.getBotWakeContext(makeLimitedReadChain([{ ...storedBot, isBot: true, deletedAt: null }]), "bot_1"))+ .resolves.toEqual({+ state: "ready",+ botUserId: "bot_1",+ name: "helper",+ discriminator: "1234",+ machineId: "machine_1",+ runtime: "codex",+ modelName: "gpt-5",+ reasoningEffort: "high",+ runtimeConfigRevision: 7,+ ownerUserId: "owner_1",+ })+ })+})+describe("getBotBinding", () => {function makeSelectChain(rows: unknown[]) {const chain: any = {}@@ -174,16 +242,28 @@ describe("getBotBinding", () => {return chain}- it("returns { machineId, runtime, modelName } when the binding exists (modelName defaults to null)", async () => {+ it("returns the full runtime binding when it exists", async () => {const chain = makeSelectChain([{ machineId: "machine_1", runtime: "codex", modelName: null }])const result = await q.getBotBinding(chain, "bot_1")- expect(result).toEqual({ machineId: "machine_1", runtime: "codex", modelName: null })+ expect(result).toEqual({+ machineId: "machine_1",+ runtime: "codex",+ modelName: null,+ reasoningEffort: null,+ runtimeConfigRevision: 0,+ })})it("surfaces a stored modelName", async () => {const chain = makeSelectChain([{ machineId: "machine_1", runtime: "claude", modelName: "claude-opus-4-6" }])const result = await q.getBotBinding(chain, "bot_1")- expect(result).toEqual({ machineId: "machine_1", runtime: "claude", modelName: "claude-opus-4-6" })+ expect(result).toEqual({+ machineId: "machine_1",+ runtime: "claude",+ modelName: "claude-opus-4-6",+ reasoningEffort: null,+ runtimeConfigRevision: 0,+ })})it("returns null when no binding row matches", async () => {@@ -193,6 +273,124 @@ describe("getBotBinding", () => {})})+describe("getMachineForOwner", () => {+ function makeSelectChain(rows: unknown[]) {+ const chain: any = {}+ chain.select = vi.fn(() => chain)+ chain.from = vi.fn(() => chain)+ chain.where = vi.fn(() => chain)+ chain.limit = vi.fn(() => Promise.resolve(rows))+ return chain+ }++ it("returns null when the owner-scoped machine lookup has no row", async () => {+ await expect(q.getMachineForOwner(makeSelectChain([]), "machine_1", "owner_1")).resolves.toBeNull()+ })++ it("normalizes legacy strings and valid objects while dropping malformed entries", async () => {+ const db = makeSelectChain([{+ id: "machine_1",+ availableRuntimes: [+ "codex",+ "",+ { id: "claude", status: "unhealthy", lastError: "missing credentials" },+ { id: "bad runtime", status: "healthy" },+ null,+ ],+ }])++ await expect(q.getMachineForOwner(db, "machine_1", "owner_1")).resolves.toEqual({+ id: "machine_1",+ availableRuntimes: [+ { id: "codex", status: "healthy" },+ { id: "claude", status: "unhealthy", lastError: "missing credentials" },+ ],+ })+ })+})++describe("updateBotRuntimeConfig", () => {+ function createDatabase() {+ const sqlite = new Sqlite(":memory:")+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ isBot INTEGER NOT NULL DEFAULT 0,+ ownerUserId TEXT,+ deletedAt TEXT+ );+ CREATE TABLE community_bot_binding (+ user_id TEXT PRIMARY KEY,+ machine_id TEXT NOT NULL,+ runtime TEXT NOT NULL,+ instruction TEXT NOT NULL DEFAULT '',+ model_name TEXT,+ reasoning_effort TEXT,+ runtime_config_revision INTEGER NOT NULL DEFAULT 0,+ created_at TEXT NOT NULL+ );+ INSERT INTO user (id, isBot, ownerUserId, deletedAt)+ VALUES ('bot_1', 1, 'owner_1', NULL);+ INSERT INTO community_bot_binding (+ user_id, machine_id, runtime, instruction, model_name,+ reasoning_effort, runtime_config_revision, created_at+ ) VALUES (+ 'bot_1', 'machine_1', 'codex', '', 'gpt-old',+ 'low', 4, '2026-08-29T00:00:00.000Z'+ );+ `)+ return { sqlite, db: drizzleSqlite(sqlite) }+ }++ it("atomically replaces the full tuple and increments one server revision", async () => {+ const { sqlite, db } = createDatabase()+ try {+ await expect(q.updateBotRuntimeConfig(db as never, "bot_1", "owner_1", {+ runtime: "codex",+ modelName: "gpt-new",+ reasoningEffort: "xhigh",+ })).resolves.toEqual({ runtimeConfigRevision: 5 })+ expect(sqlite.prepare(`+ SELECT runtime, model_name AS modelName,+ reasoning_effort AS reasoningEffort,+ runtime_config_revision AS runtimeConfigRevision+ FROM community_bot_binding WHERE user_id = 'bot_1'+ `).get()).toEqual({+ runtime: "codex",+ modelName: "gpt-new",+ reasoningEffort: "xhigh",+ runtimeConfigRevision: 5,+ })+ } finally {+ sqlite.close()+ }+ })++ it("does not change the tuple or revision for a different owner", async () => {+ const { sqlite, db } = createDatabase()+ try {+ await expect(q.updateBotRuntimeConfig(db as never, "bot_1", "owner_2", {+ runtime: "claude",+ modelName: "foreign-model",+ reasoningEffort: "max",+ })).resolves.toBeNull()+ expect(sqlite.prepare(`+ SELECT runtime, model_name AS modelName,+ reasoning_effort AS reasoningEffort,+ runtime_config_revision AS runtimeConfigRevision+ FROM community_bot_binding WHERE user_id = 'bot_1'+ `).get()).toEqual({+ runtime: "codex",+ modelName: "gpt-old",+ reasoningEffort: "low",+ runtimeConfigRevision: 4,+ })+ } finally {+ sqlite.close()+ }+ })+})+describe("listBotsForMachine", () => {function makeJoinChain(rows: unknown[]) {const chain: any = {}@@ -216,6 +414,8 @@ describe("listBotsForMachine", () => {ownerDiscriminator: "5678",runtime: "claude",modelName: "claude-opus-4-6",+ reasoningEffort: null,+ runtimeConfigRevision: 0,},])const result = await q.listBotsForMachine(chain, "machine_1")@@ -229,6 +429,8 @@ describe("listBotsForMachine", () => {ownerDiscriminator: "5678",runtime: "claude",modelName: "claude-opus-4-6",+ reasoningEffort: null,+ runtimeConfigRevision: 0,},])})diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.tsindex 189637630..ae035ac2d 100644--- a/src/shared/test/schemas/community-runtime.test.ts+++ b/src/shared/test/schemas/community-runtime.test.ts@@ -77,6 +77,73 @@ describe("CommunityMachineRuntimeSchema", () => {expect(CommunityMachineRuntimeSchema.parse({ id })).toEqual({ id, status: "healthy" });}});++ it("keeps a healthy runtime while dropping malformed reasoning entries individually", () => {+ const parsed = CommunityMachineRuntimeSchema.parse({+ id: "codex",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gpt-5",+ models: [+ {+ id: "gpt-5",+ supportedReasoningEfforts: [+ { value: "minimal", description: "Fast" },+ { value: "future_effort" },+ { value: "bad effort" },+ { value: "minimal", description: "duplicate" },+ ],+ defaultReasoningEffort: "medium",+ },+ {+ id: "gpt-5",+ supportedReasoningEfforts: [{ value: "high" }],+ },+ { id: "", supportedReasoningEfforts: [{ value: "high" }] },+ null,+ ],+ },+ });++ expect(parsed).toEqual({+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gpt-5",+ models: [{+ id: "gpt-5",+ supportedReasoningEfforts: [+ { value: "minimal", description: "Fast" },+ { value: "future_effort" },+ ],+ }],+ },+ });+ });++ it("keeps a supported default reasoning effort", () => {+ const parsed = CommunityMachineRuntimeSchema.parse({+ id: "codex",+ reasoning: {+ updateMode: "live_next_turn",+ models: [{+ id: "gpt-5",+ supportedReasoningEfforts: [{ value: "medium" }, { value: "high" }],+ defaultReasoningEffort: "medium",+ }],+ },+ });++ expect(parsed.reasoning?.models[0]?.defaultReasoningEffort).toBe("medium");+ });++ it("drops a malformed reasoning catalog without poisoning runtime health", () => {+ expect(CommunityMachineRuntimeSchema.parse({+ id: "codex",+ reasoning: { updateMode: "eventually", models: [] },+ })).toEqual({ id: "codex", status: "healthy" });+ });});describe("CommunityMachineRuntimeListSchema", () => {diff --git a/src/web/migrations/0091_community_bot_reasoning_effort.sql b/src/web/migrations/0091_community_bot_reasoning_effort.sqlnew file mode 100644index 000000000..8cfd2d92d--- /dev/null+++ b/src/web/migrations/0091_community_bot_reasoning_effort.sql@@ -0,0 +1,2 @@+ALTER TABLE `community_bot_binding` ADD `reasoning_effort` text;+ALTER TABLE `community_bot_binding` ADD `runtime_config_revision` integer DEFAULT 0 NOT NULL;diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.tsindex e65e3ed53..f28e06a3e 100644--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts@@ -32,6 +32,8 @@ export const POST = withAuth(async (_req, ctx) => {const config = makeRuntimeConfig({runtime: wakeCtx.runtime,model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),+ reasoningEffort: wakeCtx.reasoningEffort ?? undefined,+ runtimeConfigRevision: wakeCtx.runtimeConfigRevision,agentName: wakeCtx.name,agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,})diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.tsindex 3f848b5c4..b97fc3fbc 100644--- a/src/web/src/app/api/community/bots/[id]/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts@@ -5,12 +5,14 @@ const mockGetBotOwnedBy = vi.fn()const mockUpdateBot = vi.fn()const mockUpdateBotModel = vi.fn()const mockUpdateBotRuntime = vi.fn()+const mockUpdateBotRuntimeConfig = vi.fn()const mockGetMachineForOwner = vi.fn()const mockIsBotOnline = vi.fn()const mockGetUserPublic = vi.fn()const mockPushBotEventToMachine = vi.fn()const mockPushAgentModelSwitchToMachine = vi.fn()const mockPushAgentProviderSwitchToMachine = vi.fn()+const mockPushAgentRuntimeConfigUpdateToMachine = vi.fn()const mockLogError = vi.fn()const mockListBotServerMemberships = vi.fn()const mockSoftDeleteBot = vi.fn()@@ -41,6 +43,7 @@ vi.mock("@alook/shared", async () => {updateBot: (...a: unknown[]) => mockUpdateBot(...a),updateBotModel: (...a: unknown[]) => mockUpdateBotModel(...a),updateBotRuntime: (...a: unknown[]) => mockUpdateBotRuntime(...a),+ updateBotRuntimeConfig: (...a: unknown[]) => mockUpdateBotRuntimeConfig(...a),getMachineForOwner: (...a: unknown[]) => mockGetMachineForOwner(...a),listBotServerMemberships: (...a: unknown[]) => mockListBotServerMemberships(...a),softDeleteBot: (...a: unknown[]) => mockSoftDeleteBot(...a),@@ -59,6 +62,7 @@ vi.mock("@/lib/community/bot-push", () => ({pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),pushAgentModelSwitchToMachine: (...a: unknown[]) => mockPushAgentModelSwitchToMachine(...a),pushAgentProviderSwitchToMachine: (...a: unknown[]) => mockPushAgentProviderSwitchToMachine(...a),+ pushAgentRuntimeConfigUpdateToMachine: (...a: unknown[]) => mockPushAgentRuntimeConfigUpdateToMachine(...a),}))vi.mock("@/lib/broadcast", () => ({broadcastToUser: vi.fn(),@@ -104,7 +108,7 @@ describe("PATCH /api/community/bots/[id]", () => {vi.clearAllMocks()mockGetBotOwnedBy.mockResolvedValue({id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",- runtime: "claude", modelName: null,+ runtime: "claude", modelName: null, reasoningEffort: null, runtimeConfigRevision: 0,})mockUpdateBot.mockResolvedValue({id: "b1", name: "New", discriminator: "0001", description: "new desc", image: null,@@ -122,6 +126,8 @@ describe("PATCH /api/community/bots/[id]", () => {mockPushAgentProviderSwitchToMachine.mockResolvedValue({ sent: 1, deliveryError: false })mockUpdateBotModel.mockResolvedValue(true)mockUpdateBotRuntime.mockResolvedValue(true)+ mockUpdateBotRuntimeConfig.mockResolvedValue({ runtimeConfigRevision: 1 })+ mockPushAgentRuntimeConfigUpdateToMachine.mockResolvedValue({ sent: 1, deliveryError: false })})it("updates and pushes bot:updated to the daemon when the name changed", async () => {@@ -152,8 +158,7 @@ describe("PATCH /api/community/bots/[id]", () => {expect(mockUpdateBot).toHaveBeenCalled()})- // Melisa #1294 push-first: push then D1 write; offline/sent===0 never touch D1 runtime columns.- it("changed model online: push-first then writes column; from/to on push; no dispatch-time audit", async () => {+ it("changed model online: persists desired config before the best-effort push", async () => {const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)expect(res.status).toBe(200)const body = (await res.json()) as { applied: boolean; deliveryError: boolean; bot: { modelName: string } }@@ -170,14 +175,18 @@ describe("PATCH /api/community/bots/[id]", () => {config: expect.objectContaining({ model: { kind: "named", name: "claude-sonnet-4-6" } }),}),)- expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "claude-sonnet-4-6")- expect(mockPushAgentModelSwitchToMachine.mock.invocationCallOrder[0]!).toBeLessThan(- mockUpdateBotModel.mock.invocationCallOrder[0]!,+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledWith(expect.anything(), "b1", "u1", {+ runtime: "claude",+ modelName: "claude-sonnet-4-6",+ reasoningEffort: null,+ })+ expect(mockUpdateBotRuntimeConfig.mock.invocationCallOrder[0]!).toBeLessThan(+ mockPushAgentModelSwitchToMachine.mock.invocationCallOrder[0]!,)expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()})- it("changed provider online: push provider_switch first, then updateBotRuntime (clears model)", async () => {+ it("changed provider online: persists the full tuple before provider_switch", async () => {mockUpdateBot.mockResolvedValue({id: "b1", name: "Old", discriminator: "0001", description: "old desc", image: null,})@@ -197,9 +206,13 @@ describe("PATCH /api/community/bots/[id]", () => {config: expect.objectContaining({ runtime: "codex" }),}),)- expect(mockUpdateBotRuntime).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "codex", null)- expect(mockPushAgentProviderSwitchToMachine.mock.invocationCallOrder[0]!).toBeLessThan(- mockUpdateBotRuntime.mock.invocationCallOrder[0]!,+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledWith(expect.anything(), "b1", "u1", {+ runtime: "codex",+ modelName: null,+ reasoningEffort: null,+ })+ expect(mockUpdateBotRuntimeConfig.mock.invocationCallOrder[0]!).toBeLessThan(+ mockPushAgentProviderSwitchToMachine.mock.invocationCallOrder[0]!,)expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()})@@ -226,15 +239,18 @@ describe("PATCH /api/community/bots/[id]", () => {config: expect.objectContaining({ runtime: "codex", model: { kind: "default" } }),}),)- expect(mockUpdateBotRuntime).toHaveBeenCalledWith(expect.anything(), "b1", "u1", "codex", null)+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledWith(expect.anything(), "b1", "u1", {+ runtime: "codex",+ modelName: null,+ reasoningEffort: null,+ })})it("changed model, daemon offline (isBotOnline false): 409, no column write, no push", async () => {mockIsBotOnline.mockResolvedValue(false)const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)expect(res.status).toBe(409)- expect(mockUpdateBotModel).not.toHaveBeenCalled()- expect(mockUpdateBotRuntime).not.toHaveBeenCalled()+ expect(mockUpdateBotRuntimeConfig).not.toHaveBeenCalled()expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()})@@ -242,82 +258,92 @@ describe("PATCH /api/community/bots/[id]", () => {mockIsBotOnline.mockResolvedValue(false)const res = await PATCH(patchReq({ runtime: "codex" }), ctx)expect(res.status).toBe(409)- expect(mockUpdateBotRuntime).not.toHaveBeenCalled()+ expect(mockUpdateBotRuntimeConfig).not.toHaveBeenCalled()expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()})- it("changed model, push sent===0: 409, zero D1 runtime write (no soft-save, no rollback)", async () => {+ it("changed model, push sent===0: keeps the saved desired config and reports deferred", async () => {mockGetBotOwnedBy.mockResolvedValue({id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1",runtime: "claude", modelName: "claude-opus-4-6",})mockPushAgentModelSwitchToMachine.mockResolvedValue({ sent: 0, deliveryError: false })const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)- expect(res.status).toBe(409)- expect(mockUpdateBotModel).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: false,+ deliveryError: false,+ application: "saved_not_applied",+ bot: { modelName: "claude-sonnet-4-6", runtimeConfigRevision: 1 },+ })+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledOnce()})- it("changed provider, push sent===0: 409, zero D1 runtime write", async () => {+ it("changed provider, push sent===0: keeps the saved desired config and reports deferred", async () => {mockGetBotOwnedBy.mockResolvedValue({id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1",runtime: "claude", modelName: "claude-opus-4-6",})mockPushAgentProviderSwitchToMachine.mockResolvedValue({ sent: 0, deliveryError: false })const res = await PATCH(patchReq({ runtime: "codex" }), ctx)- expect(res.status).toBe(409)- expect(mockUpdateBotRuntime).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: false,+ application: "saved_not_applied",+ bot: { runtime: "codex", runtimeConfigRevision: 1 },+ })+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledOnce()})- it("changed model, push transport error: 503, zero D1 runtime write", async () => {+ it("changed model, push transport error: keeps D1 desired state and reports delivery failure", async () => {mockGetBotOwnedBy.mockResolvedValue({id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1",runtime: "claude", modelName: "claude-opus-4-6",})mockPushAgentModelSwitchToMachine.mockResolvedValue({ sent: 0, deliveryError: true })const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)- expect(res.status).toBe(503)- expect(mockUpdateBotModel).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: false,+ deliveryError: true,+ application: "saved_not_applied",+ })+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledOnce()})- // Melisa #1294 / Cecilia #1295: push succeeded but D1 persist failed → explicit- // log.error + 5xx (no silent divergence, UI must not toast success).- it("changed model, sent>0 but D1 write throws: log.error(bot_runtime_switch_persist_failed) + 500", async () => {- mockUpdateBotModel.mockRejectedValue(new Error("d1 down"))+ it("changed model, desired-state write throws: logs, returns 500, and does not push", async () => {+ mockUpdateBotRuntimeConfig.mockRejectedValue(new Error("d1 down"))const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)expect(res.status).toBe(500)- expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()expect(mockLogError).toHaveBeenCalledWith("bot_runtime_switch_persist_failed",expect.objectContaining({ botId: "b1", persistErr: expect.stringContaining("d1 down") }),)})- it("changed provider, sent>0 but D1 write throws: log.error(bot_runtime_switch_persist_failed) + 500", async () => {- mockUpdateBotRuntime.mockRejectedValue(new Error("d1 down"))+ it("changed provider, desired-state write throws: logs, returns 500, and does not push", async () => {+ mockUpdateBotRuntimeConfig.mockRejectedValue(new Error("d1 down"))const res = await PATCH(patchReq({ runtime: "codex" }), ctx)expect(res.status).toBe(500)- expect(mockPushAgentProviderSwitchToMachine).toHaveBeenCalled()+ expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()expect(mockLogError).toHaveBeenCalledWith("bot_runtime_switch_persist_failed",expect.objectContaining({ botId: "b1" }),)})- it("model PATCH on a bot with no binding row after successful push → 500 + persist_failed log", async () => {- mockUpdateBotModel.mockResolvedValue(false)+ it("model PATCH on a bot with no binding row returns 409 before push", async () => {+ mockUpdateBotRuntimeConfig.mockResolvedValue(false)const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)- expect(res.status).toBe(500)- expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalled()- expect(mockLogError).toHaveBeenCalledWith(- "bot_runtime_switch_persist_failed",- expect.objectContaining({ botId: "b1" }),- )+ expect(res.status).toBe(409)+ expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()})it("same model / omitted model: no push, column untouched", async () => {let res = await PATCH(patchReq({ model: null }), ctx)expect(res.status).toBe(200)- expect(mockUpdateBotModel).not.toHaveBeenCalled()+ expect(mockUpdateBotRuntimeConfig).not.toHaveBeenCalled()expect(mockPushAgentModelSwitchToMachine).not.toHaveBeenCalled()vi.clearAllMocks()@@ -326,10 +352,10 @@ describe("PATCH /api/community/bots/[id]", () => {mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })res = await PATCH(patchReq({ name: "New" }), ctx)expect(res.status).toBe(200)- expect(mockUpdateBotModel).not.toHaveBeenCalled()+ expect(mockUpdateBotRuntimeConfig).not.toHaveBeenCalled()})- it("model:null on a bot that had one: push default with from/to, then clear column", async () => {+ it("model:null on a bot that had one: persists Default then pushes with from/to", async () => {mockGetBotOwnedBy.mockResolvedValue({ id: "b1", name: "Old", description: "d", machineId: "mac1", ownerUserId: "u1", runtime: "claude", modelName: "claude-opus-4-6" })mockUpdateBot.mockResolvedValue({ id: "b1", name: "Old", discriminator: "0001", description: "d", image: null })const res = await PATCH(patchReq({ model: null }), ctx)@@ -343,7 +369,11 @@ describe("PATCH /api/community/bots/[id]", () => {config: expect.objectContaining({ model: { kind: "default" } }),}),)- expect(mockUpdateBotModel).toHaveBeenCalledWith(expect.anything(), "b1", "u1", null)+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledWith(expect.anything(), "b1", "u1", {+ runtime: "claude",+ modelName: null,+ reasoningEffort: null,+ })})it("name AND model changed: both bot:updated and model_switch are pushed", async () => {@@ -356,9 +386,219 @@ describe("PATCH /api/community/bots/[id]", () => {it("runtime not on machine → 400", async () => {const res = await PATCH(patchReq({ runtime: "unknown-runtime" }), ctx)expect(res.status).toBe(400)- expect(mockUpdateBotRuntime).not.toHaveBeenCalled()+ expect(mockUpdateBotRuntimeConfig).not.toHaveBeenCalled()expect(mockPushAgentProviderSwitchToMachine).not.toHaveBeenCalled()})++ it("persists and forwards a supported reasoning-only edit with a server revision", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",+ runtime: "codex", modelName: "gpt-5", reasoningEffort: null, runtimeConfigRevision: 3,+ })+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gpt-5",+ models: [{+ id: "gpt-5",+ supportedReasoningEfforts: [{ value: "minimal" }, { value: "xhigh" }],+ defaultReasoningEffort: "minimal",+ }],+ },+ }],+ })+ mockUpdateBotRuntimeConfig.mockResolvedValue({ runtimeConfigRevision: 4 })++ const res = await PATCH(patchReq({ reasoningEffort: "xhigh" }), ctx)++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: true,+ application: "next_turn",+ bot: { reasoningEffort: "xhigh", runtimeConfigRevision: 4 },+ })+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledWith(expect.anything(), "b1", "u1", {+ runtime: "codex",+ modelName: "gpt-5",+ reasoningEffort: "xhigh",+ })+ expect(mockPushAgentRuntimeConfigUpdateToMachine).toHaveBeenCalledWith(+ expect.anything(),+ "mac1",+ expect.objectContaining({+ agentId: "b1",+ config: expect.objectContaining({ reasoningEffort: "xhigh", runtimeConfigRevision: 4 }),+ }),+ )+ })++ it("rejects a forged unsupported explicit effort without writing or forwarding", async () => {+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "claude",+ status: "healthy",+ reasoning: {+ updateMode: "context_preserving_restart",+ defaultModelId: "default",+ models: [{ id: "default", supportedReasoningEfforts: [{ value: "low" }] }],+ },+ }],+ })++ const res = await PATCH(patchReq({ reasoningEffort: "ultra" }), ctx)++ expect(res.status).toBe(400)+ expect(mockUpdateBotRuntimeConfig).not.toHaveBeenCalled()+ expect(mockPushAgentRuntimeConfigUpdateToMachine).not.toHaveBeenCalled()+ })++ it("persists an offline reasoning edit and sends no control frame", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",+ runtime: "codex", modelName: "gpt-5", reasoningEffort: null, runtimeConfigRevision: 3,+ })+ mockIsBotOnline.mockResolvedValue(false)+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ models: [{ id: "gpt-5", supportedReasoningEfforts: [{ value: "high" }] }],+ },+ }],+ })+ mockUpdateBotRuntimeConfig.mockResolvedValue({ runtimeConfigRevision: 4 })++ const res = await PATCH(patchReq({ reasoningEffort: "high" }), ctx)++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: false,+ deliveryError: false,+ application: "saved_not_applied",+ bot: { reasoningEffort: "high", runtimeConfigRevision: 4 },+ })+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledOnce()+ expect(mockPushAgentRuntimeConfigUpdateToMachine).not.toHaveBeenCalled()+ })++ it("returns 500 when a reasoning-only tuple cannot be persisted", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",+ runtime: "codex", modelName: "gpt-5", reasoningEffort: null, runtimeConfigRevision: 3,+ })+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ models: [{ id: "gpt-5", supportedReasoningEfforts: [{ value: "high" }] }],+ },+ }],+ })+ mockUpdateBotRuntimeConfig.mockRejectedValue(new Error("d1 unavailable"))++ const res = await PATCH(patchReq({ reasoningEffort: "high" }), ctx)++ expect(res.status).toBe(500)+ await expect(res.json()).resolves.toEqual({ error: "failed to persist reasoning effort" })+ expect(mockPushAgentRuntimeConfigUpdateToMachine).not.toHaveBeenCalled()+ expect(mockLogError).toHaveBeenCalledWith(+ "bot_reasoning_effort_persist_failed",+ expect.objectContaining({ botId: "b1" }),+ )+ })++ it("keeps a persisted reasoning edit recoverable when live delivery throws", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",+ runtime: "codex", modelName: "gpt-5", reasoningEffort: null, runtimeConfigRevision: 3,+ })+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ models: [{ id: "gpt-5", supportedReasoningEfforts: [{ value: "high" }] }],+ },+ }],+ })+ mockUpdateBotRuntimeConfig.mockResolvedValue({ runtimeConfigRevision: 4 })+ mockPushAgentRuntimeConfigUpdateToMachine.mockRejectedValue(new Error("ws unavailable"))++ const res = await PATCH(patchReq({ reasoningEffort: "high" }), ctx)++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: false,+ deliveryError: true,+ application: "saved_not_applied",+ bot: { reasoningEffort: "high", runtimeConfigRevision: 4 },+ })+ })++ it("keeps a persisted model switch recoverable when delivery throws", async () => {+ mockPushAgentModelSwitchToMachine.mockRejectedValue(new Error("ws unavailable"))++ const res = await PATCH(patchReq({ model: "claude-sonnet-4-6" }), ctx)++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ applied: false,+ deliveryError: true,+ application: "saved_not_applied",+ })+ })++ it("falls back to Default when a model switch makes the stored effort incompatible", async () => {+ mockGetBotOwnedBy.mockResolvedValue({+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",+ runtime: "codex", modelName: "model-a", reasoningEffort: "high", runtimeConfigRevision: 7,+ })+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ models: [+ { id: "model-a", supportedReasoningEfforts: [{ value: "high" }] },+ { id: "model-b", supportedReasoningEfforts: [{ value: "low" }] },+ ],+ },+ }],+ })+ mockUpdateBotRuntimeConfig.mockResolvedValue({ runtimeConfigRevision: 8 })++ const res = await PATCH(patchReq({ model: "model-b" }), ctx)++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({+ bot: { modelName: "model-b", reasoningEffort: null, runtimeConfigRevision: 8 },+ })+ expect(mockUpdateBotRuntimeConfig).toHaveBeenCalledWith(expect.anything(), "b1", "u1", {+ runtime: "codex",+ modelName: "model-b",+ reasoningEffort: null,+ })+ expect(mockPushAgentModelSwitchToMachine).toHaveBeenCalledWith(+ expect.anything(),+ "mac1",+ expect.objectContaining({ config: expect.not.objectContaining({ reasoningEffort: expect.anything() }) }),+ )+ })})describe("DELETE /api/community/bots/[id]", () => {diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex a8edc5521..9be2ebf4b 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -10,6 +10,7 @@ import {resolveModelConfig,formatHandle,createLogger,+ resolveReasoningEffort,} from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -18,6 +19,7 @@ import {pushBotEventToMachine,pushAgentModelSwitchToMachine,pushAgentProviderSwitchToMachine,+ pushAgentRuntimeConfigUpdateToMachine,} from "@/lib/community/bot-push"import { fanOutToServerMembers } from "@/lib/community/fanout"import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"@@ -54,22 +56,38 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {: undefinedconst modelChanged = nextModel !== undefined && nextModel !== (before.modelName ?? null)const restartChanged = runtimeChanged || modelChanged+ const configRequested = restartChanged || "reasoningEffort" in body+ let runtimeDescriptor: import("@alook/shared").CommunityMachineRuntime | null = null+ let botOnline = false- if (restartChanged) {+ if (configRequested) {if (!before.machineId || !targetRuntime || !before.runtime) {return writeError("bot has no active runtime binding", 409)}- if (!(await queries.communityMachine.isBotOnline(db, id))) {+ botOnline = await queries.communityMachine.isBotOnline(db, id)+ if (restartChanged && !botOnline) {return writeError("bot is offline — bring it online before changing provider or model", 409)}const machine = await queries.communityBot.getMachineForOwner(db, before.machineId, ctx.userId)if (!machine) return writeError("machine not found", 404)- const runtime = machine.availableRuntimes.find((item) => item.id === targetRuntime)- if (!runtime) return writeError(`runtime ${targetRuntime} not available on this machine`, 400)- if (runtime.status === "unhealthy") {+ runtimeDescriptor = machine.availableRuntimes.find((item) => item.id === targetRuntime) ?? null+ if (!runtimeDescriptor) return writeError(`runtime ${targetRuntime} not available on this machine`, 400)+ if (restartChanged && runtimeDescriptor.status === "unhealthy") {return writeError(`runtime ${targetRuntime} is currently unavailable on this machine`, 400)}}+ const storedModel = nextModel !== undefined ? nextModel : (before.modelName ?? null)+ const requestedEffort = "reasoningEffort" in body+ ? (body.reasoningEffort ?? null)+ : before.reasoningEffort+ const effortResolution = resolveReasoningEffort(runtimeDescriptor, storedModel, requestedEffort)+ if ("reasoningEffort" in body && requestedEffort !== null && !effortResolution.supported && !restartChanged) {+ return writeError(`reasoning effort ${requestedEffort} is not supported by this runtime/model`, 400)+ }+ const storedEffort = configRequested+ ? effortResolution.canonicalEffort+ : before.reasoningEffort+ const effortChanged = storedEffort !== before.reasoningEffort// Will we push bot:updated to the daemon? (Iff name/description changed —// image-only is display-only and doesn't affect the system prompt.) If so,// resolve the owner handle BEFORE mutating the row: the frame shape must stay@@ -104,55 +122,132 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {let applied = falselet deliveryError = false+ let application: "unchanged" | "next_turn" | "saved_not_applied" = "unchanged"+ let runtimeConfigRevision = before.runtimeConfigRevisionif (restartChanged && before.machineId && before.runtime && targetRuntime) {- const storedModel = nextModel !== undefined ? nextModel : (before.modelName ?? null)+ let wrote: Awaited<ReturnType<typeof queries.communityBot.updateBotRuntimeConfig>>+ try {+ wrote = await queries.communityBot.updateBotRuntimeConfig(db, id, ctx.userId, {+ runtime: targetRuntime,+ modelName: storedModel,+ reasoningEffort: storedEffort,+ })+ } catch (persistErr) {+ log.error("bot_runtime_switch_persist_failed", {+ botId: id,+ persistErr: String(persistErr),+ })+ return writeError("failed to persist runtime configuration", 500)+ }+ if (!wrote) return writeError("runtime binding disappeared before persistence", 409)+ runtimeConfigRevision = wrote.runtimeConfigRevisionconst config = makeRuntimeConfig({runtime: targetRuntime,model: resolveModelConfig(targetRuntime, storedModel),+ reasoningEffort: storedEffort ?? undefined,+ runtimeConfigRevision,agentName: updated.name,agentHandle: `@${formatHandle(updated.name, updated.discriminator)}`,})const launchId = nanoid()- const result = runtimeChanged- ? await pushAgentProviderSwitchToMachine(ctx.env, before.machineId, {- agentId: id,- config,- launchId,- from: before.runtime,- to: targetRuntime,- })- : await pushAgentModelSwitchToMachine(ctx.env, before.machineId, {- agentId: id,- config,- launchId,- from: before.modelName ?? null,- to: storedModel,- })+ let result = { sent: 0, deliveryError: true }+ try {+ result = runtimeChanged+ ? await pushAgentProviderSwitchToMachine(ctx.env, before.machineId, {+ agentId: id,+ config,+ launchId,+ from: before.runtime,+ to: targetRuntime,+ })+ : await pushAgentModelSwitchToMachine(ctx.env, before.machineId, {+ agentId: id,+ config,+ launchId,+ from: before.modelName ?? null,+ to: storedModel,+ })+ } catch (pushErr) {+ log.warn("bot_runtime_switch_delivery_deferred", {+ botId: id,+ machineId: before.machineId,+ runtimeConfigRevision,+ pushErr: String(pushErr),+ })+ }deliveryError = result.deliveryErrorapplied = result.sent > 0+ application = applied ? "next_turn" : "saved_not_applied"if (!applied) {- return deliveryError- ? writeError("failed to reach the bot daemon", 503)- : writeError("bot is offline — bring it online before changing provider or model", 409)- }-- try {- const wrote = runtimeChanged- ? await queries.communityBot.updateBotRuntime(db, id, ctx.userId, targetRuntime, storedModel)- : await queries.communityBot.updateBotModel(db, id, ctx.userId, storedModel)- if (!wrote) throw new Error("runtime binding disappeared before persistence")- } catch (persistErr) {- log.error("bot_runtime_switch_persist_failed", {+ log.warn("bot_runtime_switch_delivery_deferred", {botId: id,machineId: before.machineId,runtimeFrom: before.runtime,runtimeTo: targetRuntime,modelFrom: before.modelName ?? null,modelTo: storedModel,+ runtimeConfigRevision,+ deliveryError,+ })+ }+ } else if (effortChanged && before.machineId && targetRuntime) {+ let wrote: Awaited<ReturnType<typeof queries.communityBot.updateBotRuntimeConfig>>+ try {+ wrote = await queries.communityBot.updateBotRuntimeConfig(db, id, ctx.userId, {+ runtime: targetRuntime,+ modelName: storedModel,+ reasoningEffort: storedEffort,+ })+ } catch (persistErr) {+ log.error("bot_reasoning_effort_persist_failed", {+ botId: id,persistErr: String(persistErr),})- return writeError("bot switched, but its runtime binding failed to persist", 500)+ return writeError("failed to persist reasoning effort", 500)+ }+ if (!wrote) return writeError("runtime binding disappeared before persistence", 409)+ runtimeConfigRevision = wrote.runtimeConfigRevision+ if (!botOnline) {+ return writeJSON({+ bot: {+ id,+ name: updated.name,+ description: updated.description,+ image: updated.image,+ runtime: targetRuntime,+ modelName: storedModel,+ reasoningEffort: storedEffort,+ runtimeConfigRevision,+ },+ applied: false,+ deliveryError: false,+ application: "saved_not_applied",+ })}+ let result = { sent: 0, deliveryError: true }+ try {+ result = await pushAgentRuntimeConfigUpdateToMachine(ctx.env, before.machineId, {+ agentId: id,+ config: makeRuntimeConfig({+ runtime: targetRuntime,+ model: resolveModelConfig(targetRuntime, storedModel),+ reasoningEffort: storedEffort ?? undefined,+ runtimeConfigRevision,+ agentName: updated.name,+ agentHandle: `@${formatHandle(updated.name, updated.discriminator)}`,+ }),+ })+ } catch (pushErr) {+ log.warn("bot_reasoning_effort_delivery_deferred", {+ botId: id,+ machineId: before.machineId,+ runtimeConfigRevision,+ pushErr: String(pushErr),+ })+ }+ deliveryError = result.deliveryError+ applied = result.sent > 0+ application = applied ? "next_turn" : "saved_not_applied"}return writeJSON({@@ -163,9 +258,12 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {image: updated.image,runtime: targetRuntime,modelName: nextModel !== undefined ? nextModel : (before.modelName ?? null),+ reasoningEffort: storedEffort,+ runtimeConfigRevision,},applied,deliveryError,+ application,})})diff --git a/src/web/src/app/api/community/bots/me/nap/route.ts b/src/web/src/app/api/community/bots/me/nap/route.tsindex e86c75da8..71452b7a1 100644--- a/src/web/src/app/api/community/bots/me/nap/route.ts+++ b/src/web/src/app/api/community/bots/me/nap/route.ts@@ -73,6 +73,8 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const config = makeRuntimeConfig({runtime: wakeCtx.runtime,model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),+ reasoningEffort: wakeCtx.reasoningEffort ?? undefined,+ runtimeConfigRevision: wakeCtx.runtimeConfigRevision,agentName: wakeCtx.name,agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,})diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsindex b5f2752a9..f64e89439 100644--- a/src/web/src/app/api/community/bots/route.test.ts+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -146,6 +146,57 @@ describe("POST /api/community/bots — model", () => {expect(res.status).toBe(400)expect(mockCreateBot).not.toHaveBeenCalled()})++ it("persists a supported capability-backed reasoning effort", async () => {+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gpt-5",+ models: [{+ id: "gpt-5",+ supportedReasoningEfforts: [+ { value: "minimal" },+ { value: "xhigh", description: "Deeper reasoning" },+ ],+ }],+ },+ }],+ })++ const res = await POST(postReq({ ...base("gpt-5", "codex"), reasoningEffort: "xhigh" }), ctx)++ expect(res.status).toBe(201)+ await expect(res.json()).resolves.toMatchObject({+ bot: { runtime: "codex", modelName: "gpt-5", reasoningEffort: "xhigh", runtimeConfigRevision: 0 },+ })+ expect(mockCreateBot).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ reasoningEffort: "xhigh" }),+ )+ })++ it("rejects an explicit effort the selected model did not report", async () => {+ mockGetMachineForOwner.mockResolvedValue({+ id: "mac1",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ models: [{ id: "gpt-5", supportedReasoningEfforts: [{ value: "minimal" }] }],+ },+ }],+ })++ const res = await POST(postReq({ ...base("gpt-5", "codex"), reasoningEffort: "ultra" }), ctx)++ expect(res.status).toBe(400)+ expect(mockCreateBot).not.toHaveBeenCalled()+ })})describe("GET /api/community/bots — heatmap activity", () => {diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex 61716452f..959472600 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -4,6 +4,7 @@ import {CommunityBotCreateRequestSchema,COMMUNITY_BOT_LIMIT_PER_OWNER,utcDayKeyDaysAgo,+ resolveReasoningEffort,} from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -69,6 +70,11 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}const modelName = body.model ?? null+ const effort = body.reasoningEffort ?? null+ const effortResolution = resolveReasoningEffort(runtime, modelName, effort)+ if (effort !== null && !effortResolution.supported) {+ return writeError(`reasoning effort ${effort} is not supported by this runtime/model`, 400)+ }const created = await queries.communityBot.createBot(db, {ownerId: ctx.userId,@@ -78,6 +84,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {runtime: body.runtime,image: body.image ?? null,modelName,+ reasoningEffort: effortResolution.canonicalEffort,})// The bot's owner is the authenticated caller — resolve their handle to@@ -136,6 +143,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {machineId: body.machineId,runtime: body.runtime,modelName,+ reasoningEffort: effortResolution.canonicalEffort,+ runtimeConfigRevision: 0,},},201,diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.tsindex a6837c270..e51da2523 100644--- a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts@@ -43,6 +43,8 @@ export const POST = withAuth(async (_req, ctx) => {config: makeRuntimeConfig({runtime: bot.runtime,model: resolveModelConfig(bot.runtime, bot.modelName),+ reasoningEffort: bot.reasoningEffort ?? undefined,+ runtimeConfigRevision: bot.runtimeConfigRevision,agentName: bot.name,agentHandle: `@${formatHandle(bot.name, bot.discriminator)}`,}),diff --git a/src/web/src/components/community/bots/bot-runtime-fields.test.ts b/src/web/src/components/community/bots/bot-runtime-fields.test.tsindex 7b7c07f02..f2a7acfc9 100644--- a/src/web/src/components/community/bots/bot-runtime-fields.test.ts+++ b/src/web/src/components/community/bots/bot-runtime-fields.test.ts@@ -31,6 +31,7 @@ const OPTIONS = [function renderFields(overrides: Partial<React.ComponentProps<typeof BotRuntimeFields>> = {}) {const onRuntimeChange = vi.fn()const onModelChange = vi.fn()+ const onReasoningEffortChange = vi.fn()let renderer!: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(@@ -38,13 +39,15 @@ function renderFields(overrides: Partial<React.ComponentProps<typeof BotRuntimeFoptions: OPTIONS,runtime: "claude",model: "claude-sonnet-4-6",+ reasoningEffort: "high",onRuntimeChange,onModelChange,+ onReasoningEffortChange,...overrides,}),)})- return { renderer, onRuntimeChange, onModelChange }+ return { renderer, onRuntimeChange, onModelChange, onReasoningEffortChange }}function radio(renderer: TestRenderer.ReactTestRenderer, value: string) {@@ -62,10 +65,11 @@ describe("BotRuntimeFields", () => {})it("changes runtime and clears the previous provider model together", () => {- const { renderer, onRuntimeChange, onModelChange } = renderFields()+ const { renderer, onRuntimeChange, onModelChange, onReasoningEffortChange } = renderFields()act(() => radio(renderer, "codex").props.onChange())expect(onRuntimeChange).toHaveBeenCalledWith("codex")expect(onModelChange).toHaveBeenCalledWith(null)+ expect(onReasoningEffortChange).toHaveBeenCalledWith(null)})it("does not clear the model when the selected runtime is chosen again", () => {diff --git a/src/web/src/components/community/bots/bot-runtime-fields.tsx b/src/web/src/components/community/bots/bot-runtime-fields.tsxindex 8a96d117e..666c24b8f 100644--- a/src/web/src/components/community/bots/bot-runtime-fields.tsx+++ b/src/web/src/components/community/bots/bot-runtime-fields.tsx@@ -4,18 +4,23 @@ import { ProviderLogo } from "@/components/provider-logo"import { Label } from "@/components/ui/label"import { cn } from "@/lib/utils"import { ModelField } from "./model-field"+import { ReasoningEffortField } from "./reasoning-effort-field"+import type { CommunityMachineRuntime, ReasoningEffort } from "@alook/shared"-export type BotRuntimeOption = {- id: string+export type BotRuntimeOption = Pick<CommunityMachineRuntime, "id" | "reasoning"> & {unhealthy: boolean}+const ignoreReasoningEffortChange = () => {}+export function BotRuntimeFields({options,runtime,model,+ reasoningEffort = null,onRuntimeChange,onModelChange,+ onReasoningEffortChange = ignoreReasoningEffortChange,radioName = "edit-bot-runtime",motionTargetPrefix,modelMotionTarget,@@ -27,8 +32,10 @@ export function BotRuntimeFields({options: BotRuntimeOption[]runtime: stringmodel: string | null+ reasoningEffort?: ReasoningEffort | nullonRuntimeChange: (runtime: string) => voidonModelChange: (model: string | null) => void+ onReasoningEffortChange?: (effort: ReasoningEffort | null) => voidradioName?: stringmotionTargetPrefix?: stringmodelMotionTarget?: string@@ -41,6 +48,7 @@ export function BotRuntimeFields({if (next === runtime) returnonRuntimeChange(next)onModelChange(null)+ onReasoningEffortChange(null)}return (@@ -98,8 +106,14 @@ export function BotRuntimeFields({{runtimeError ? <p className="text-xs text-destructive">{runtimeError}</p> : null}</div>{runtime ? (- <div data-motion-target={modelMotionTarget} className={modelClassName}>+ <div data-motion-target={modelMotionTarget} className={cn("flex flex-col gap-4", modelClassName)}><ModelField runtime={runtime} value={model} onChange={onModelChange} />+ <ReasoningEffortField+ runtime={options.find((option) => option.id === runtime) ?? null}+ model={model}+ value={reasoningEffort}+ onChange={onReasoningEffortChange}+ /></div>) : null}</>diff --git a/src/web/src/components/community/bots/create-bot-sheet.test.ts b/src/web/src/components/community/bots/create-bot-sheet.test.tsindex 2ad731f51..dcdfcbc81 100644--- a/src/web/src/components/community/bots/create-bot-sheet.test.ts+++ b/src/web/src/components/community/bots/create-bot-sheet.test.ts@@ -105,13 +105,14 @@ describe("firstHealthyRuntimeId", () => {// runtime radios, which is all this change touches.const useMachinesMock = vi.fn()+const createMutateAsync = vi.fn()vi.mock("@/hooks/community/use-machines", () => ({useMachines: () => useMachinesMock(),}))vi.mock("@/hooks/community/use-bots", () => ({- useCreateBot: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useCreateBot: () => ({ mutateAsync: createMutateAsync, isPending: false }),useUploadBotAvatar: () => ({ mutateAsync: vi.fn() }),}))@@ -147,6 +148,14 @@ vi.mock("./model-field", () => ({},}))+vi.mock("./reasoning-effort-field", () => ({+ ReasoningEffortField: ({ onChange }: { onChange: (value: string | null) => void }) =>+ React.createElement("button", {+ "data-testid": "set-reasoning-effort",+ onClick: () => onChange("xhigh"),+ }),+}))+vi.mock("@/components/provider-logo", () => ({ProviderLogo: () => React.createElement("span", { "data-mock": "provider-logo" }),}))@@ -178,6 +187,8 @@ function render(props: { avatarSeed?: string } = {}): TestRenderer.ReactTestRenddescribe("CreateBotSheet — auto-select defaults", () => {beforeEach(() => {useMachinesMock.mockReset()+ createMutateAsync.mockReset()+ createMutateAsync.mockResolvedValue({ bot: { id: "b1", name: "MyBot" } })botFormFieldsRenders.length = 0})@@ -310,6 +321,37 @@ describe("CreateBotSheet — auto-select defaults", () => {expect(last.value).toBeNull()})+ it("includes the selected runtime-reported reasoning effort in create", async () => {+ useMachinesMock.mockReturnValue({+ machines: [+ machine({+ id: "mac",+ status: "online",+ availableRuntimes: [{+ id: "codex",+ status: "healthy",+ reasoning: {+ updateMode: "live_next_turn",+ defaultModelId: "gpt-5",+ models: [{ id: "gpt-5", supportedReasoningEfforts: [{ value: "xhigh" }] }],+ },+ }] as unknown as CommunityMachineSummary["availableRuntimes"],+ }),+ ],+ })+ const renderer = render()+ act(() => renderer.root.findByProps({ "data-testid": "set-reasoning-effort" }).props.onClick())+ await act(async () => {+ await renderer.root.find(+ (node) => node.type === "button" && node.props.children === "Create bot",+ ).props.onClick()+ })++ expect(createMutateAsync).toHaveBeenCalledWith(+ expect.objectContaining({ machineId: "mac", runtime: "codex", reasoningEffort: "xhigh" }),+ )+ })+it("re-defaults the runtime when the user switches to another machine", () => {useMachinesMock.mockReturnValue({machines: [diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsxindex 6ec34fa02..9246900d8 100644--- a/src/web/src/components/community/bots/create-bot-sheet.tsx+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx@@ -3,7 +3,11 @@import { useEffect, useMemo, useRef, useState } from "react"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"-import { isPresenceOnline, type CommunityMachineSummary } from "@alook/shared"+import {+ isPresenceOnline,+ type CommunityMachineSummary,+ type ReasoningEffort,+} from "@alook/shared"import { machineName } from "@/lib/community/machine-name"import { CommunitySheet } from "@/components/community/shell/community-sheet"import { Button } from "@/components/ui/button"@@ -14,7 +18,7 @@ import { ProviderLogo } from "@/components/provider-logo"import { useMachines } from "@/hooks/community/use-machines"import { useCreateBot, useUploadBotAvatar } from "@/hooks/community/use-bots"import { BotFormFields } from "./bot-form-fields"-import { BotRuntimeFields } from "./bot-runtime-fields"+import { BotRuntimeFields, type BotRuntimeOption } from "./bot-runtime-fields"import {type BotCreateFieldErrors,hasBotCreateFieldErrors,@@ -31,7 +35,7 @@ function randomBotName(): string {return uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" })}-type NormalizedRuntime = { id: string; unhealthy: boolean }+type NormalizedRuntime = BotRuntimeOption/*** Normalize a machine's runtimes into `{ id, unhealthy }`, healthy-first.@@ -48,7 +52,11 @@ export function normalizeRuntimes(machine: CommunityMachineSummary | undefined):const normalized = rt.map((r) =>typeof r === "string"? { id: r, unhealthy: false }- : { id: (r as { id: string }).id, unhealthy: (r as { status?: string }).status === "unhealthy" },+ : {+ id: r.id,+ ...(r.reasoning !== undefined ? { reasoning: r.reasoning } : {}),+ unhealthy: r.status === "unhealthy",+ },)return normalized.sort((a, b) => Number(a.unhealthy) - Number(b.unhealthy))}@@ -84,6 +92,7 @@ export function CreateBotSheet({const [machineId, setMachineId] = useState<string>("")const [runtime, setRuntime] = useState<string>("")const [model, setModel] = useState<string | null>(null)+ const [reasoningEffort, setReasoningEffort] = useState<ReasoningEffort | null>(null)const [fieldErrors, setFieldErrors] = useState<BotCreateFieldErrors>({})const [technicalExpanded, setTechnicalExpanded] = useState(false)const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>({@@ -118,6 +127,7 @@ export function CreateBotSheet({setMachineId("")setRuntime("")setModel(null)+ setReasoningEffort(null)setFieldErrors({})setTechnicalExpanded(false)}, [open, avatarSeed])@@ -158,6 +168,7 @@ export function CreateBotSheet({// A model id is runtime-specific; a machine switch can change the runtime,// so drop any selected model back to Default.setModel(null)+ setReasoningEffort(null)setFieldErrors((prev) => ({ ...prev, machineId: undefined }))}@@ -179,6 +190,7 @@ export function CreateBotSheet({runtime,image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,model,+ reasoningEffort,})// Bots don't have an id until creation resolves — the photo upload is// deferred until now so a cropped-then-cancelled dialog never uploads@@ -300,8 +312,10 @@ export function CreateBotSheet({options={runtimeOptions}runtime={runtime}model={model}+ reasoningEffort={reasoningEffort}onRuntimeChange={selectRuntime}onModelChange={setModel}+ onReasoningEffortChange={setReasoningEffort}radioName="bot-runtime"runtimeError={fieldErrors.runtime}disableUnhealthyOptionsdiff --git a/src/web/src/components/community/bots/edit-bot-sheet.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.test.tsindex 7d8302dd4..d3f8579db 100644--- a/src/web/src/components/community/bots/edit-bot-sheet.test.ts+++ b/src/web/src/components/community/bots/edit-bot-sheet.test.ts@@ -130,6 +130,16 @@ vi.mock("./model-field", () => {}),}})+vi.mock("./reasoning-effort-field", () => {+ const React = require("react")+ return {+ ReasoningEffortField: ({ onChange }: { onChange: (value: string | null) => void }) =>+ React.createElement("button", {+ "data-testid": "set-reasoning-effort",+ onClick: () => onChange("xhigh"),+ }),+ }+})vi.mock("@/components/avatar", () => ({isPhotoAvatarUrl: () => false,}))@@ -226,6 +236,34 @@ describe("EditBotSheet — model switch toast (online-only)", () => {})})+describe("EditBotSheet — reasoning effort", () => {+ beforeEach(() => {+ toastSuccess.mockReset()+ toastApiError.mockReset()+ updateMutateAsync.mockReset()+ useMachinesMock.mockReturnValue(HEALTHY_MACHINES)+ })++ it("PATCHes the explicit effort without provider confirmation and reports next-turn application", async () => {+ updateMutateAsync.mockResolvedValue({+ bot: { ...BOT, reasoningEffort: "xhigh", runtimeConfigRevision: 2 },+ application: "next_turn",+ })+ const renderer = renderSheet()+ act(() => renderer.root.findByProps({ "data-testid": "set-reasoning-effort" }).props.onClick())+ act(() => {+ void saveButton(renderer).props.onClick()+ })+ await flush()++ expect(updateMutateAsync).toHaveBeenCalledWith(+ expect.objectContaining({ id: "b1", reasoningEffort: "xhigh" }),+ )+ expect(renderer.root.findAllByProps({ "data-testid": "provider-confirm" })).toHaveLength(0)+ expect(toastSuccess).toHaveBeenCalledWith("Reasoning effort saved. Next turn takes effect.")+ })+})+describe("EditBotSheet — provider switch AlertDialog + toast", () => {beforeEach(() => {toastSuccess.mockReset()diff --git a/src/web/src/components/community/bots/edit-bot-sheet.tsx b/src/web/src/components/community/bots/edit-bot-sheet.tsxindex 6bf19a95e..a768abfca 100644--- a/src/web/src/components/community/bots/edit-bot-sheet.tsx+++ b/src/web/src/components/community/bots/edit-bot-sheet.tsx@@ -27,6 +27,7 @@ import { BotRuntimeFields } from "./bot-runtime-fields"import { validateBotModel } from "./bot-form-validation"import { uniqueNamesGenerator, names } from "unique-names-generator"import { normalizeRuntimes } from "./create-bot-sheet"+import type { ReasoningEffort } from "@alook/shared"function draftFromBot(bot: BotSummary): AvatarDraft {if (isPhotoAvatarUrl(bot.image)) return { kind: "photo", file: null, previewUrl: bot.image! }@@ -52,6 +53,9 @@ export function EditBotSheet({const [name, setName] = useState(bot?.name ?? "")const [description, setDescription] = useState(bot?.description ?? "")const [model, setModel] = useState<string | null>(bot?.modelName ?? null)+ const [reasoningEffort, setReasoningEffort] = useState<ReasoningEffort | null>(+ bot?.reasoningEffort ?? null,+ )const [runtime, setRuntime] = useState(bot?.runtime ?? "")const [confirmProviderSwitch, setConfirmProviderSwitch] = useState(false)const [nameError, setNameError] = useState<string | undefined>(undefined)@@ -82,6 +86,7 @@ export function EditBotSheet({setName(bot.name)setDescription(bot.description ?? "")setModel(bot.modelName ?? null)+ setReasoningEffort(bot.reasoningEffort ?? null)setRuntime(bot.runtime)setAvatarDraft(draftFromBot(bot))setNameError(undefined)@@ -111,11 +116,12 @@ export function EditBotSheet({}const modelChanged = model !== (bot.modelName ?? null)const runtimeChanged = runtime !== bot.runtime+ const reasoningEffortChanged = reasoningEffort !== (bot.reasoningEffort ?? null)try {// Sequence matters — only attempt the avatar upload AFTER the// name/description update resolves, inside the same try block, so a// failed field update never triggers an upload.- await update.mutateAsync({+ const result = await update.mutateAsync({id: bot.id,name: name.trim(),description: description.trim() || undefined,@@ -124,6 +130,7 @@ export function EditBotSheet({// never triggers a stop-and-rewake....(modelChanged ? { model } : {}),...(runtimeChanged ? { runtime } : {}),+ ...(reasoningEffortChanged ? { reasoningEffort } : {}),})let avatarFailed = falseif (avatarDraft.kind === "photo" && avatarDraft.file) {@@ -135,11 +142,19 @@ export function EditBotSheet({}}if (!avatarFailed) {- if (runtimeChanged) {+ if ((runtimeChanged || modelChanged) && result.application === "saved_not_applied") {+ toast.success("Runtime settings saved for next start.")+ } else if (runtimeChanged) {toast.success(`Provider switch to ${runtime} dispatched`)} else if (modelChanged) {const label = model ?? "the runtime default"toast.success(`Model switch to ${label} dispatched`)+ } else if (reasoningEffortChanged) {+ toast.success(+ result.application === "next_turn"+ ? "Reasoning effort saved. Next turn takes effect."+ : "Reasoning effort saved for next start.",+ )} else {toast.success("Bot updated")}@@ -169,7 +184,7 @@ export function EditBotSheet({open={open}onOpenChange={onOpenChange}title={`Edit ${bot?.name ?? "bot"}`}- description="Name and description edits take effect on the next wake. Provider and model switches require the bot to be online."+ description="Name and description edits take effect on the next wake. Reasoning effort applies on the next turn when online, or the next start when offline. Provider and model switches require the bot to be online."bodyClassName="flex flex-col gap-6"footer={(requestClose) => (<>@@ -197,8 +212,10 @@ export function EditBotSheet({options={runtimeOptions}runtime={runtime}model={model}+ reasoningEffort={reasoningEffort}onRuntimeChange={setRuntime}onModelChange={setModel}+ onReasoningEffortChange={setReasoningEffort}/>)}</CommunitySheet>diff --git a/src/web/src/components/community/bots/reasoning-effort-field.test.ts b/src/web/src/components/community/bots/reasoning-effort-field.test.tsnew file mode 100644index 000000000..5741b1204--- /dev/null+++ b/src/web/src/components/community/bots/reasoning-effort-field.test.ts@@ -0,0 +1,88 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"+import { ReasoningEffortField } from "./reasoning-effort-field"++vi.mock("@/components/ui/label", () => ({+ Label: ({ children }: { children?: React.ReactNode }) =>+ React.createElement("label", null, children),+}))++vi.mock("@/components/ui/select", () => ({+ Select: ({ children, disabled, items, value, onValueChange }: {+ children?: React.ReactNode+ disabled?: boolean+ items?: unknown[]+ value?: string+ onValueChange?: (value: string | null) => void+ }) => React.createElement("select", { disabled, items, value, onValueChange }, children),+ SelectContent: ({ children }: { children?: React.ReactNode }) =>+ React.createElement("div", null, children),+ SelectItem: ({ children, value }: { children?: React.ReactNode; value: string }) =>+ React.createElement("option", { value }, children),+ SelectTrigger: ({ children, ...props }: React.ComponentProps<"button">) =>+ React.createElement("button", props, children),+ SelectValue: ({ placeholder }: { placeholder?: string }) =>+ React.createElement("span", null, placeholder),+}))++const RUNTIME = {+ reasoning: {+ updateMode: "live_next_turn" as const,+ defaultModelId: "gpt-5",+ models: [{+ id: "gpt-5",+ supportedReasoningEfforts: [+ { value: "minimal" },+ { value: "future_level", description: "A future runtime-provided level" },+ ],+ defaultReasoningEffort: "minimal",+ }],+ },+}++function renderField(props: Partial<React.ComponentProps<typeof ReasoningEffortField>> = {}) {+ const onChange = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(ReasoningEffortField, {+ runtime: RUNTIME,+ model: "gpt-5",+ value: null,+ onChange,+ ...props,+ }))+ })+ return { renderer, onChange }+}++describe("ReasoningEffortField", () => {+ it("shows Default plus the exact runtime-reported options and default", () => {+ const { renderer } = renderField()+ const select = renderer.root.findByType("select")+ expect(select.props.disabled).toBe(false)+ expect(select.props.items).toEqual([+ { value: "__default__", label: "Default (Minimal)" },+ { value: "minimal", label: "Minimal" },+ { value: "future_level", label: "Future_level" },+ ])+ expect(renderer.root.findAllByType("option").map((node) => node.props.value)).toEqual([+ "__default__",+ "minimal",+ "future_level",+ ])+ })++ it("renders disabled Default-only help when no catalog is reported", () => {+ const { renderer } = renderField({ runtime: { reasoning: undefined } })+ expect(renderer.root.findByType("select").props.disabled).toBe(true)+ expect(renderer.root.findAllByType("p")[0]?.children.join("")).toBe(+ "This runtime/model does not report reasoning effort options.",+ )+ })++ it("resets an incompatible selected value to Default", () => {+ const { onChange } = renderField({ value: "ultra" })+ expect(onChange).toHaveBeenCalledWith(null)+ })+})diff --git a/src/web/src/components/community/bots/reasoning-effort-field.tsx b/src/web/src/components/community/bots/reasoning-effort-field.tsxnew file mode 100644index 000000000..66fd74a60--- /dev/null+++ b/src/web/src/components/community/bots/reasoning-effort-field.tsx@@ -0,0 +1,97 @@+"use client"++import { useEffect, useMemo } from "react"+import {+ resolveReasoningEffort,+ type ReasoningEffort,+ type RuntimeReasoningDescriptor,+} from "@alook/shared"+import { Label } from "@/components/ui/label"+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select"+import { tid } from "@/lib/community/testids"++const DEFAULT_VALUE = "__default__"++function effortLabel(value: string): string {+ return value.length === 0 ? value : value[0]!.toUpperCase() + value.slice(1)+}++export function ReasoningEffortField({+ runtime,+ model,+ value,+ onChange,+ disabled,+}: {+ runtime: RuntimeReasoningDescriptor | null+ model: string | null+ value: ReasoningEffort | null+ onChange: (value: ReasoningEffort | null) => void+ disabled?: boolean+}) {+ const resolution = useMemo(+ () => resolveReasoningEffort(runtime, model, value),+ [runtime, model, value],+ )++ useEffect(() => {+ if (!resolution.supported && value !== null) onChange(null)+ }, [onChange, resolution.supported, value])++ const defaultLabel = resolution.defaultReasoningEffort+ ? `Default (${effortLabel(resolution.defaultReasoningEffort)})`+ : "Default"+ const items = [+ { value: DEFAULT_VALUE, label: defaultLabel },+ ...resolution.options.map((option) => ({+ value: option.value,+ label: effortLabel(option.value),+ })),+ ]+ const selected = value ?? DEFAULT_VALUE+ const selectedDescription = value+ ? resolution.options.find((option) => option.value === value)?.description+ : undefined+ const unavailable = resolution.options.length === 0++ return (+ <div className="flex flex-col gap-2">+ <Label className="text-xs text-muted-foreground">Reasoning effort</Label>+ <Select+ items={items}+ value={selected}+ onValueChange={(next: string | null) => {+ onChange(!next || next === DEFAULT_VALUE ? null : next)+ }}+ disabled={disabled || unavailable}+ >+ <SelectTrigger+ data-testid={tid.botReasoningEffort}+ className="w-full data-[size=default]:h-11 sm:data-[size=default]:h-8"+ aria-describedby="bot-reasoning-effort-help"+ >+ <SelectValue placeholder={defaultLabel} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={DEFAULT_VALUE}>{defaultLabel}</SelectItem>+ {resolution.options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {effortLabel(option.value)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p id="bot-reasoning-effort-help" className="text-xs text-muted-foreground">+ {unavailable+ ? "This runtime/model does not report reasoning effort options."+ : selectedDescription ?? "Default lets the runtime choose for this model."}+ </p>+ </div>+ )+}diff --git a/src/web/src/hooks/community/use-bots.test.ts b/src/web/src/hooks/community/use-bots.test.tsindex 8f159d44f..b0dc1f6bb 100644--- a/src/web/src/hooks/community/use-bots.test.ts+++ b/src/web/src/hooks/community/use-bots.test.ts@@ -1,5 +1,7 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"import { describe, it, expect, vi, beforeEach } from "vitest"-import { QueryClient } from "@tanstack/react-query"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"// The React harness for the hooks themselves isn't available in the repo@@ -61,6 +63,38 @@ describe("invalidateBotSurfaces", () => {})describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {+ it("useUpdateBot forwards explicit reasoning effort values and omission", async () => {+ const { useUpdateBot } = await import("./use-bots")+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })+ let mutation!: ReturnType<typeof useUpdateBot>+ function Probe() {+ mutation = useUpdateBot()+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ),+ )+ })+ apiFetchMock.mockResolvedValue({ bot: { id: "bot_1" } })++ await act(async () => {+ await mutation.mutateAsync({ id: "bot_1", reasoningEffort: "xhigh" })+ await mutation.mutateAsync({ id: "bot_1", name: "Renamed" })+ })++ expect(JSON.parse(apiFetchMock.mock.calls[0]![1].body)).toMatchObject({+ reasoningEffort: "xhigh",+ })+ expect(JSON.parse(apiFetchMock.mock.calls[1]![1].body)).not.toHaveProperty("reasoningEffort")+ act(() => renderer.unmount())+ })+it("useUpdateBot's mutationFn PATCHes description and the response carries the id onSuccess needs", async () => {apiFetchMock.mockResolvedValueOnce({bot: { id: "bot_1", name: "Bot", description: "new description", image: null, machineId: "m_1", runtime: "node" },diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.tsindex bfa469bb7..63f66a72e 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -4,6 +4,7 @@ import { useQuery, useMutation, useQueryClient, type UseQueryResult } from "@tanimport { apiFetch, readUploadError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { BotActivityDay } from "@/lib/community/models/people"+import type { ReasoningEffort } from "@alook/shared"export type BotSummary = {id: string@@ -13,6 +14,8 @@ export type BotSummary = {machineId: stringruntime: stringmodelName: string | null+ reasoningEffort: ReasoningEffort | null+ runtimeConfigRevision: number// Context lifecycle (my-bots #516): when the agent last refreshed its context// (nap, session reset, or provider switch), ISO string, null if it never has. Rendered as the// awake-duration "Awake 17h" (Gus #672/#674 — how long the agent has been@@ -42,6 +45,7 @@ export type CreateBotInput = {runtime: stringimage?: stringmodel?: string | null+ reasoningEffort?: ReasoningEffort | null}// Bot identity (name, image) is projected into friends() (self-bot rows) and@@ -83,11 +87,23 @@ export type UpdateBotInput = {// Explicit `null` clears a set model; `undefined` leaves it untouched.model?: string | nullruntime?: string+ reasoningEffort?: ReasoningEffort | null}export type UpdateBotResponse = {- bot: Pick<BotSummary, "id" | "name" | "description" | "image" | "runtime" | "modelName">+ bot: Pick<+ BotSummary,+ | "id"+ | "name"+ | "description"+ | "image"+ | "runtime"+ | "modelName"+ | "reasoningEffort"+ | "runtimeConfigRevision"+ >applied?: booleandeliveryError?: boolean+ application?: "unchanged" | "next_turn" | "saved_not_applied"}export function useUpdateBot() {@@ -105,6 +121,9 @@ export function useUpdateBot() {// explicit key the server would read as "clear to default"....("model" in input ? { model: input.model } : {}),...("runtime" in input ? { runtime: input.runtime } : {}),+ ...("reasoningEffort" in input+ ? { reasoningEffort: input.reasoningEffort }+ : {}),}),}),onSuccess: (data) => invalidateBotSurfaces(qc, data.bot.id),diff --git a/src/web/src/lib/community/bot-push.test.ts b/src/web/src/lib/community/bot-push.test.tsindex 2a00cad85..60b4a1919 100644--- a/src/web/src/lib/community/bot-push.test.ts+++ b/src/web/src/lib/community/bot-push.test.ts@@ -9,6 +9,7 @@ import {pushAgentResetToMachine,pushAgentModelSwitchToMachine,pushAgentProviderSwitchToMachine,+ pushAgentRuntimeConfigUpdateToMachine,pushMachineUpdate,} from "./bot-push"@@ -239,3 +240,60 @@ describe("pushAgentProviderSwitchToMachine", () => {})})})++describe("pushAgentRuntimeConfigUpdateToMachine", () => {+ beforeEach(() => {+ wsDoFetch.mockReset()+ })++ const args = {+ agentId: "bot-1",+ config: {+ version: 1 as const,+ runtime: "codex",+ model: { kind: "default" as const },+ mode: { kind: "default" as const },+ reasoningEffort: "xhigh",+ runtimeConfigRevision: 4,+ },+ }++ it("forwards the exact revisioned desired config", async () => {+ wsDoFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))++ await expect(pushAgentRuntimeConfigUpdateToMachine(FAKE_ENV, "machine/1", args)).resolves.toEqual({+ sent: 1,+ deliveryError: false,+ })+ const [, path, init, meta] = wsDoFetch.mock.calls[0]!+ expect(path).toBe("/community-machine/by-id/machine%2F1/forward-agent-runtime-config-update")+ expect(JSON.parse(init.body as string)).toEqual(args)+ expect(meta).toEqual({ label: "machine/1", type: "agent:runtime_config_update" })+ })++ it("distinguishes offline from non-ok, malformed, and thrown delivery failures", async () => {+ wsDoFetch.mockResolvedValueOnce(new Response(JSON.stringify({}), { status: 200 }))+ await expect(pushAgentRuntimeConfigUpdateToMachine(FAKE_ENV, "m", args)).resolves.toEqual({+ sent: 0,+ deliveryError: false,+ })++ wsDoFetch.mockResolvedValueOnce(new Response("down", { status: 503 }))+ await expect(pushAgentRuntimeConfigUpdateToMachine(FAKE_ENV, "m", args)).resolves.toEqual({+ sent: 0,+ deliveryError: true,+ })++ wsDoFetch.mockResolvedValueOnce(new Response("not-json", { status: 200 }))+ await expect(pushAgentRuntimeConfigUpdateToMachine(FAKE_ENV, "m", args)).resolves.toEqual({+ sent: 0,+ deliveryError: true,+ })++ wsDoFetch.mockRejectedValueOnce(new Error("network"))+ await expect(pushAgentRuntimeConfigUpdateToMachine(FAKE_ENV, "m", args)).resolves.toEqual({+ sent: 0,+ deliveryError: true,+ })+ })+})diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.tsindex 2073d6bef..833353285 100644--- a/src/web/src/lib/community/bot-push.ts+++ b/src/web/src/lib/community/bot-push.ts@@ -291,6 +291,32 @@ export async function pushAgentModelSwitchToMachine(}}+export async function pushAgentRuntimeConfigUpdateToMachine(+ env: Env,+ machineId: string,+ args: { agentId: string; config: RuntimeConfig },+): Promise<{ sent: number; deliveryError: boolean }> {+ const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-runtime-config-update`+ try {+ const res = await wsDoFetch(+ env,+ path,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(args),+ },+ { label: machineId, type: "agent:runtime_config_update" },+ )+ if (!res.ok) return { sent: 0, deliveryError: true }+ const data = (await res.json()) as { sent?: number }+ return { sent: data.sent ?? 0, deliveryError: false }+ } catch (err) {+ log.warn("agent:runtime_config_update push threw", { machineId, err: String(err) })+ return { sent: 0, deliveryError: true }+ }+}+export async function pushAgentProviderSwitchToMachine(env: Env,machineId: string,diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 9ff9ed922..c16f9e9f8 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -79,6 +79,7 @@ export const tid = {botReportProblemSubmit: "bot-report-problem-submit",botReportProblemStatus: "bot-report-problem-status",botAvatarPickerTrigger: "community-bot-avatar-picker-trigger",+ botReasoningEffort: "community-bot-reasoning-effort",forumTagDialog: "community-forum-tag-dialog",forumTagDialogChip: (tag: string) => `community-forum-tag-dialog-chip-${tag}`,diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex 4e428c5b0..b0bac8ea7 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -92,6 +92,7 @@ describe("ws-do router", () => {"handleMachineBatchReset","handleMachineModelSwitch","handleMachineProviderSwitch",+ "handleMachineRuntimeConfigUpdate","handleMachineNap","handleMachineForceClose",])diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.tsindex 0dbae8668..2dd3eb793 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -16,7 +16,11 @@ import {handleMachineReset,handleMachineUpdate,} from "./routes/community-machine-lifecycle"-import { handleMachineModelSwitch, handleMachineProviderSwitch } from "./routes/community-machine-switch"+import {+ handleMachineModelSwitch,+ handleMachineProviderSwitch,+ handleMachineRuntimeConfigUpdate,+} from "./routes/community-machine-switch"import { handleHealth } from "./routes/health"import { handleBatchPresence, handleSinglePresence } from "./routes/presence"import { handleRateLimit } from "./routes/rate-limit"@@ -78,6 +82,8 @@ export default {if (response) return responseresponse = await handleMachineProviderSwitch(context)if (response) return response+ response = await handleMachineRuntimeConfigUpdate(context)+ if (response) return responseresponse = await handleMachineNap(context)if (response) return responseresponse = await handleMachineForceClose(context)diff --git a/src/ws-do/src/routes/community-machine-switch.test.ts b/src/ws-do/src/routes/community-machine-switch.test.tsindex a8adde7b3..69a748990 100644--- a/src/ws-do/src/routes/community-machine-switch.test.ts+++ b/src/ws-do/src/routes/community-machine-switch.test.ts@@ -197,4 +197,103 @@ describe("ws-do router", () => {expect(doMock.stubFetch).not.toHaveBeenCalled()})})++ describe("POST /community-machine/by-id/:machineId/forward-agent-runtime-config-update", () => {+ const validBody = {+ agentId: "bot-1",+ config: {+ version: 1,+ runtime: "codex",+ model: { kind: "default" },+ mode: { kind: "default" },+ reasoningEffort: "xhigh",+ runtimeConfigRevision: 4,+ },+ }++ beforeEach(() => {+ mockGetActiveDoNamesForMachine.mockReset()+ mockGetActiveDoNamesForMachine.mockResolvedValue([])+ })++ it("forwards the exact revisioned desired config to the machine DO", async () => {+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))+ const res = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: JSON.stringify(validBody) },+ ), env as any)++ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request+ expect(stubReq.url).toBe("http://internal/push-runtime-config-update")+ expect(JSON.parse(await stubReq.text())).toEqual(validBody)+ await expect(res.json()).resolves.toEqual({ sent: 1 })+ })++ it("rejects extra keys and returns sent:0 when no live machine DO exists", async () => {+ const invalid = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: JSON.stringify({ ...validBody, launchId: "not-allowed" }) },+ ), env as any)+ expect(invalid.status).toBe(400)++ const absent = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: JSON.stringify(validBody) },+ ), env as any)+ await expect(absent.json()).resolves.toEqual({ sent: 0 })+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("rejects malformed JSON and missing required fields before resolving a machine", async () => {+ const malformed = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: "{" },+ ), env as any)+ expect(malformed.status).toBe(400)++ const nullBody = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: "null" },+ ), env as any)+ expect(nullBody.status).toBe(400)++ const missing = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: JSON.stringify({ agentId: "", config: null }) },+ ), env as any)+ expect(missing.status).toBe(400)+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()+ })++ it("returns 503 when the owner-scoped machine resolution fails", async () => {+ mockGetActiveDoNamesForMachine.mockRejectedValue(new Error("d1 unavailable"))++ const res = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: JSON.stringify(validBody) },+ ), env as any)++ expect(res.status).toBe(503)+ await expect(res.json()).resolves.toEqual({ error: "failed to resolve machine" })+ expect(doMock.stubFetch).not.toHaveBeenCalled()+ })++ it("returns 503 when every active machine DO response is transiently unusable", async () => {+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])+ doMock.stubFetch+ .mockResolvedValueOnce(new Response("down", { status: 503 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: "one" }), { status: 200 }))+ .mockRejectedValueOnce(new Error("do unavailable"))++ for (let attempt = 0; attempt < 3; attempt += 1) {+ const res = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-runtime-config-update",+ { method: "POST", body: JSON.stringify(validBody) },+ ), env as any)+ expect(res.status).toBe(503)+ await expect(res.json()).resolves.toEqual({ error: "failed to forward runtime config update" })+ }+ })+ })})diff --git a/src/ws-do/src/routes/community-machine-switch.ts b/src/ws-do/src/routes/community-machine-switch.tsindex 44a9bc6b7..8411a22ff 100644--- a/src/ws-do/src/routes/community-machine-switch.ts+++ b/src/ws-do/src/routes/community-machine-switch.ts@@ -163,3 +163,68 @@ export async function handleMachineProviderSwitch({ request, env, url, traceId,}return Response.json({ sent: delivered })}++export async function handleMachineRuntimeConfigUpdate({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {+ const match = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-runtime-config-update$/)+ if (!match || request.method !== "POST") return null++ const machineId = decodeURIComponent(match[1])+ const reqLog = log.child({ traceId, machineId })+ let payload: unknown+ try {+ payload = await request.json()+ } catch {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (!payload || typeof payload !== "object") {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ const raw = payload as Record<string, unknown>+ if (Object.keys(raw).some((key) => key !== "agentId" && key !== "config")) {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }+ if (typeof raw.agentId !== "string" || raw.agentId.length === 0 || !raw.config || typeof raw.config !== "object") {+ return Response.json({ error: "invalid payload" }, { status: 400 })+ }++ let doNames: string[]+ try {+ const shared = await import("@alook/shared")+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)+ } catch (err) {+ reqLog.error("failed to resolve machine for runtime config update", { err })+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })+ }+ if (doNames.length === 0) return Response.json({ sent: 0 })++ const frame = JSON.stringify({ agentId: raw.agentId, config: raw.config })+ let sent = 0+ let transientFailure = false+ for (const doName of doNames) {+ try {+ const stub = env.WS_DO.get(env.WS_DO.idFromName("community-machine:" + doName))+ const res = await stub.fetch(new Request("http://internal/push-runtime-config-update", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: frame,+ }))+ if (!res.ok) {+ transientFailure = true+ continue+ }+ const data = (await res.json()) as { sent?: unknown }+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {+ transientFailure = true+ continue+ }+ sent += data.sent+ } catch {+ transientFailure = true+ }+ }+ if (sent === 0 && transientFailure) {+ return Response.json({ error: "failed to forward runtime config update" }, { status: 503 })+ }+ return Response.json({ sent })+}diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.tsindex ba956919a..2ba71fc8d 100644--- a/src/ws-do/src/ws-durable/machine-control.test.ts+++ b/src/ws-do/src/ws-durable/machine-control.test.ts@@ -273,6 +273,63 @@ describe("WebSocketDurableObject", () => {expect(storage.put).not.toHaveBeenCalled()})+ it("stamps and forwards a revisioned runtime config update without restart attribution", async () => {+ const { durable, getWebSockets, storage } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })+ getWebSockets.mockReturnValue([ws])+ const config = {+ version: 1,+ runtime: "codex",+ model: { kind: "default" },+ mode: { kind: "default" },+ reasoningEffort: "xhigh",+ runtimeConfigRevision: 9,+ }++ const response = await durable.fetch(new Request("http://internal/push-runtime-config-update", {+ method: "POST",+ body: JSON.stringify({ agentId: "a_1", config }),+ }))++ expect(response.status).toBe(200)+ await expect(response.json()).resolves.toEqual({ sent: 1 })+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({+ type: "agent:runtime_config_update",+ agentId: "a_1",+ config,+ }))+ expect(storage.put).not.toHaveBeenCalled()+ })++ it("rejects malformed runtime config update bodies before touching sockets", async () => {+ const { durable, getWebSockets } = createDO()+ const response = await durable.fetch(new Request("http://internal/push-runtime-config-update", {+ method: "POST",+ body: JSON.stringify({ agentId: "a_1", config: {}, extra: true }),+ }))++ expect(response.status).toBe(400)+ expect(getWebSockets).not.toHaveBeenCalled()+ })++ it("rejects malformed runtime config update JSON before touching sockets", async () => {+ const { durable, getWebSockets } = createDO()+ const response = await durable.fetch(new Request("http://internal/push-runtime-config-update", {+ method: "POST",+ body: "{",+ }))++ expect(response.status).toBe(400)+ await expect(response.json()).resolves.toEqual({ sent: 0 })+ expect(getWebSockets).not.toHaveBeenCalled()+ })+it("returns the forward-wake send count when optimistic overlay clearing rejects", async () => {const { durable, getWebSockets, storage } = createDO()const ws = createMockWebSocket()diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.tsindex 3054f30bd..c65e6b9aa 100644--- a/src/ws-do/src/ws-durable/machine-control.ts+++ b/src/ws-do/src/ws-durable/machine-control.ts@@ -90,6 +90,34 @@ export async function handleMachineControlFetch(})}+ if (url.pathname === "/push-runtime-config-update" && request.method === "POST") {+ let payload: unknown+ try {+ payload = await request.json()+ } catch {+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })+ }+ const raw = payload && typeof payload === "object" ? payload as Record<string, unknown> : null+ if (+ !raw ||+ Object.keys(raw).some((key) => key !== "agentId" && key !== "config") ||+ typeof raw.agentId !== "string" ||+ raw.agentId.length === 0 ||+ !raw.config ||+ typeof raw.config !== "object"+ ) {+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })+ }+ const sent = forwardToCommunityMachine(context, JSON.stringify({+ type: "agent:runtime_config_update",+ agentId: raw.agentId,+ config: raw.config,+ }))+ return new Response(JSON.stringify({ sent }), {+ headers: { "Content-Type": "application/json" },+ })+ }+if (url.pathname === "/forward-agent-wake" && request.method === "POST") {const body = await request.text()const attempted = forwardToCommunityMachine(context, body)diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.tsindex 3b5a95c00..f182cb4d4 100644--- a/src/ws-do/src/ws-durable/machine-ready.ts+++ b/src/ws-do/src/ws-durable/machine-ready.ts@@ -31,6 +31,7 @@ function canonicalRuntimes(list: CommunityMachineRuntime[]): string {...(runtime.version !== undefined ? { version: runtime.version } : {}),status: runtime.status ?? "healthy",...(runtime.lastError !== undefined ? { lastError: runtime.lastError } : {}),+ ...(runtime.reasoning !== undefined ? { reasoning: runtime.reasoning } : {}),})))}