From eaebc5ab3fcef51d9712d1a0a3720456f7827be7 Mon Sep 17 00:00:00 2001 From: Custom Nightly Repair Date: Tue, 24 Nov 2026 18:42:20 -0500 Subject: [PATCH] fix(tots): close the MCP gaps Tots hit on 24 Nov - t3_tot_instructions reads or replaces a Tot's saved instructions and re-renders its AGENTS.md. A Tot reaches only its own; Home and a person at a client outside any thread reach any. Capped at 20,000 characters. - schedule_task takes an optional modelSelection on create and update. A task given one pins it, so bound runs use it instead of following the thread's model (new model_pinned column, migration 113). The full opencode-go/glm-5.3 is refused; flash variants are fine. - t3_project_update saves defaultModelSelection to the project's Settings override, where new threads read it, and the reply reports what is stored. - list_scheduled_tasks with no projectId, called by a Tot, also lists tasks in the projects it owns and tasks it created, and notes that sidebar groups are not covered. Co-Authored-By: Claude Opus 5.5 --- CUSTOM.md | 9 +- .../src/mcp/OrchestratorMcpService.test.ts | 97 +++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 52 +++++++++- .../src/mcp/toolkits/orchestrator/handlers.ts | 38 +++++++- .../src/mcp/toolkits/orchestrator/tools.ts | 4 +- .../src/mcp/toolkits/project/handlers.test.ts | 75 ++++++++++++++ .../src/mcp/toolkits/project/handlers.ts | 36 ++++++- .../src/mcp/toolkits/tots/handlers.test.ts | 90 +++++++++++++++-- apps/server/src/mcp/toolkits/tots/handlers.ts | 63 +++++++++++- apps/server/src/mcp/toolkits/tots/tools.ts | 21 ++++ apps/server/src/persistence/Migrations.ts | 2 + .../113_ScheduledTaskModelPinned.test.ts | 50 ++++++++++ .../113_ScheduledTaskModelPinned.ts | 14 +++ .../reconcileV2PreviewMigration.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- .../ScheduledTaskService.failure.test.ts | 25 +++++ .../ScheduledTaskService.test.ts | 64 ++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 25 +++-- apps/server/src/tots/totAgents.ts | 2 + docs/internals/tots.md | 4 + packages/contracts/src/orchestratorMcp.ts | 14 ++- packages/contracts/src/scheduledTask.ts | 4 + 22 files changed, 656 insertions(+), 37 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.test.ts create mode 100644 apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.ts diff --git a/CUSTOM.md b/CUSTOM.md index 9be4799a89cd9..39c72e7fc08bf 100644 --- a/CUSTOM.md +++ b/CUSTOM.md @@ -82,10 +82,11 @@ so renumbering a migration that already shipped breaks every existing database. the `.4941` custom build failed: it moved `ScheduledTaskCreatedByTot` from 99 to 101, and every database that had recorded 99 refused to start. -- 99 is `ScheduledTaskCreatedByTot`. Upstream's migrations from its 99 on sit one id higher - here (upstream 099 is our 100, and so on). When a rebase brings a new upstream migration, - rename its file and manifest entry to upstream id + 1, append it after ours, and update any - test that names its id. +- 99 is `ScheduledTaskCreatedByTot` and 113 is `ScheduledTaskModelPinned`. Upstream's + migrations 99 to 111 sit one id higher here (upstream 099 is our 100, and so on); from + upstream 112 on they sit two higher. When a rebase brings a new upstream migration, rename + its file and manifest entry to its id here, append it after ours, and update any test that + names its id. - Every migration from 99 on must be idempotent (`IF NOT EXISTS`, a column check, or a drop and rebuild). Startup and the update preflight rewind a history recorded in another order (stock upstream, or the `.4941` custom build) and replay it in ours; see diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f94ce8208c6f3..ce457734e1354 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -4182,6 +4182,43 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect("lists a Tot's unattributed tasks in the projects it owns", () => + Effect.gen(function* () { + const upserted = yield* Ref.make(0); + const owned = task({}); + const elsewhere = ProjectId.make("project:elsewhere"); + const authored = task({ + id: ScheduledTaskId.make("scheduled-task:authored"), + projectId: elsewhere, + createdByTotId: TotId.make("t3bot"), + }); + const unowned = task({ + id: ScheduledTaskId.make("scheduled-task:unowned"), + projectId: elsewhere, + }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide(service([owned, authored, unowned], null, upserted)), + ); + const tot = { totId: TotId.make("t3bot"), projects: new Set([projectId]), hasGroups: true }; + const listed = yield* mcp.listScheduledTasks(supervisedClient, {}, tot); + assert.deepEqual( + listed.tasks.map((summary) => summary.scheduledTaskId), + [owned.id, authored.id], + ); + assert.match(listed.note ?? "", /sidebar groups/); + const named = yield* mcp.listScheduledTasks( + supervisedClient, + { projectId: elsewhere }, + tot, + ); + assert.deepEqual( + named.tasks.map((summary) => summary.scheduledTaskId), + [authored.id, unowned.id], + ); + assert.isUndefined(named.note); + }), + ); + it.effect("returns a webhook URL when creating a task, not when updating it", () => Effect.gen(function* () { const upserted = yield* Ref.make(0); @@ -4490,6 +4527,66 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "pins a model the caller names, on create and update, and refuses the banned one", + () => + Effect.gen(function* () { + const flash = { + instanceId: ProviderInstanceId.make("opencode"), + model: "opencode-go/glm-5.3-flash", + }; + const inputs = yield* Ref.make>([]); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + masterRepository, + yield* Ref.make>([]), + existing, + inputs, + ), + ), + ); + yield* mcp.scheduleTask(client, { + projectId, + prompt: "Check the build", + schedule, + modelSelection: flash, + }); + yield* mcp.scheduleTask(client, { projectId, prompt: "Check the build", schedule }); + yield* mcp.updateScheduledTask(client, { + scheduledTaskId: existing.id, + modelSelection: flash, + }); + yield* mcp.updateScheduledTask(client, { scheduledTaskId: existing.id, prompt: "Again" }); + assert.deepEqual( + (yield* Ref.get(inputs)).map((input) => [ + input.modelSelection.model, + input.modelPinned, + ]), + [ + [flash.model, true], + [existing.modelSelection.model, undefined], + [flash.model, true], + [existing.modelSelection.model, undefined], + ], + ); + const banned = { ...flash, model: "opencode-go/glm-5.3" }; + const created = yield* mcp + .scheduleTask(client, { + projectId, + prompt: "Check the build", + schedule, + modelSelection: banned, + }) + .pipe(Effect.flip); + const updated = yield* mcp + .updateScheduledTask(client, { scheduledTaskId: existing.id, modelSelection: banned }) + .pipe(Effect.flip); + assert.deepEqual([created.code, updated.code], ["invalid_request", "invalid_request"]); + assert.equal((yield* Ref.get(inputs)).length, 4); + }), + ); + it.effect.each([ { name: "drops an emoji the limit splits", diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4f4b97a6ec5a8..fee9045a672e5 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -179,6 +179,14 @@ type TerminalTaskStatus = Extract< "completed" | "failed" | "cancelled" | "interrupted" >; +export interface ScheduledTaskListTot { + readonly totId: TotId; + /** Projects here the Tot owns; `all` owns every one. */ + readonly projects: "all" | ReadonlySet; + /** Sidebar groups in its scope, which this server cannot resolve to projects. */ + readonly hasGroups: boolean; +} + export interface OrchestratorMcpServiceShape { readonly capabilities: ( scope: McpInvocationScope, @@ -209,6 +217,8 @@ export interface OrchestratorMcpServiceShape { readonly listScheduledTasks: ( scope: McpInvocationScope, input: OrchestratorMcpListScheduledTasksInput, + /** The Tot that asked: with no `projectId`, its listing covers what it owns. */ + tot?: ScheduledTaskListTot, ) => Effect.Effect; readonly updateScheduledTask: ( scope: McpInvocationScope, @@ -293,6 +303,19 @@ function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } +// The user's own ban on this deployment; its flash variants stay allowed. +const BANNED_SCHEDULED_MODELS: ReadonlySet = new Set(["opencode-go/glm-5.3"]); + +const bannedScheduledModel = (selection: ModelSelection | undefined) => + selection !== undefined && BANNED_SCHEDULED_MODELS.has(selection.model.trim().toLowerCase()) + ? Effect.fail( + failure( + "invalid_request", + `${selection.model} is not allowed for scheduled tasks. Pick another model, such as a flash variant.`, + ), + ) + : Effect.void; + function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): OrchestratorMcpScheduledTask { return { scheduledTaskId: task.id, @@ -302,6 +325,7 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato projectId: task.projectId, boundThreadId: task.threadId, freshSession: scheduledTaskThreadMode(task) === "fresh_session", + modelSelection: task.modelSelection, schedule: task.schedule, nextRunAt: task.nextRunAt, lastRunStatus: task.lastRunStatus, @@ -2473,8 +2497,11 @@ const make = Effect.gen(function* () { : "bindToCurrentThread binds to this thread, which belongs to a different project.", ); } + yield* bannedScheduledModel(input.modelSelection); const modelSelection = - parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project)); + input.modelSelection ?? + parent?.thread.modelSelection ?? + (yield* projectDefaultModelSelection(project)); // Never end on a lone high surrogate, which renders as a broken character. const derivedTitle = (input.prompt.split("\n")[0]?.trim() ?? "") .slice(0, 80) @@ -2504,6 +2531,7 @@ const make = Effect.gen(function* () { : "new_thread", workspaceStrategy: yield* scheduledTaskWorkspaceStrategy(bindToCurrentThread, projectId), modelSelection, + ...(input.modelSelection === undefined ? {} : { modelPinned: true }), runtimeMode: limits.runtimeMode, interactionMode: limits.interactionMode, createdBy: "agent", @@ -2535,9 +2563,18 @@ const make = Effect.gen(function* () { return yield* summarizeScheduledTask(scope, { parent, limits }, task); }), listScheduledTasks: Effect.fn("OrchestratorMcpService.listScheduledTasks")( - function* (scope, input) { + function* (scope, input, tot) { const { parent } = yield* loadCaller(scope, []); const projectId = input.projectId ?? parent?.thread.projectId; + // A Tot's thread lives in its own folder; its routines live in the projects it owns. + const totListing = input.projectId === undefined ? tot : undefined; + const inScope = (task: ScheduledTask) => + totListing === undefined + ? projectId === undefined || task.projectId === projectId + : task.projectId === projectId || + task.createdByTotId === totListing.totId || + totListing.projects === "all" || + totListing.projects.has(task.projectId); const { tasks } = yield* scheduledTasks .list() .pipe( @@ -2549,10 +2586,15 @@ const make = Effect.gen(function* () { tasks: tasks .filter( (task) => - (projectId === undefined || task.projectId === projectId) && + inScope(task) && (input.scheduledTaskId === undefined || task.id === input.scheduledTaskId), ) .map((task) => scheduledTaskSummary(task, false)), + ...(totListing?.hasGroups === true + ? { + note: "Projects in your sidebar groups are not covered by this default listing. Pass their projectId to list them.", + } + : {}), }; }, ), @@ -2561,6 +2603,7 @@ const make = Effect.gen(function* () { const { parent, limits } = yield* loadCaller(scope, ["runs"]); const existing = yield* loadScheduledTask(input.scheduledTaskId, limits); yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId); + yield* bannedScheduledModel(input.modelSelection); if ( input.bindToCurrentThread === true && (parent === undefined || parent.thread.projectId !== existing.projectId) @@ -2617,7 +2660,8 @@ const make = Effect.gen(function* () { ? "new_thread" : "continue", workspaceStrategy, - modelSelection: existing.modelSelection, + modelSelection: input.modelSelection ?? existing.modelSelection, + ...(input.modelSelection === undefined ? {} : { modelPinned: true }), runtimeMode: existing.runtimeMode, interactionMode: existing.interactionMode, createdBy: existing.createdBy, diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 8e3744b55a65b..1a533dcb1487e 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -22,6 +22,30 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts"; import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; +/** A Tot here and what it owns, so its default task listing covers its projects. */ +const scheduledTaskListTot = Effect.fnUntraced(function* ( + scope: McpInvocationContext.McpInvocationScope, +) { + const caller = yield* readTotCaller(); + if (Option.isNone(caller) || caller.value.via !== "local") return undefined; + const tot = (yield* (yield* TotService.TotService).list).find( + (candidate) => candidate.id === caller.value.totId, + ); + if (tot === undefined) return undefined; + return { + totId: tot.id, + projects: + tot.scope === "all" + ? ("all" as const) + : new Set( + tot.scope.projects + .filter((project) => project.environmentId === scope.environmentId) + .map((project) => project.projectId), + ), + hasGroups: tot.scope !== "all" && tot.scope.groups.length > 0, + } satisfies OrchestratorMcpService.ScheduledTaskListTot; +}); + const handlers = { orchestrator_capabilities: McpToolAccess.reads((input) => Effect.gen(function* () { @@ -121,7 +145,16 @@ const handlers = { { refused: "schedule tasks in this environment" }, ), McpToolAccess.writes( - ({ scheduledTaskId, prompt, title, schedule, enabled, freshSession, bindToCurrentThread }) => + ({ + scheduledTaskId, + prompt, + title, + schedule, + enabled, + freshSession, + bindToCurrentThread, + modelSelection, + }) => Effect.gen(function* () { if (scheduledTaskId === undefined) return yield* Effect.die("unreachable"); const scope = yield* McpInvocationContext.McpInvocationContext; @@ -134,6 +167,7 @@ const handlers = { enabled, freshSession, bindToCurrentThread, + modelSelection, }); }), ), @@ -142,7 +176,7 @@ const handlers = { Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; const service = yield* OrchestratorMcpService.OrchestratorMcpService; - return yield* service.listScheduledTasks(scope, input); + return yield* service.listScheduledTasks(scope, input, yield* scheduledTaskListTot(scope)); }), ), delete_scheduled_task: McpToolAccess.writes((input) => diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index a156a8fd3f63f..bfa652aac570b 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -188,11 +188,11 @@ const ScheduleTaskTool = Tool.make("schedule_task", { const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", { parameters: OrchestratorMcpListScheduledTasksInput, description: - "List scheduled tasks. Omit `projectId` for this thread's project. Pass a `scheduledTaskId` to `schedule_task` or `delete_scheduled_task`. In a scheduled run, do not call this to find your task. Do the prompt.", + "List scheduled tasks. Omit `projectId` for this thread's project, or as a Tot for the projects you own. Pass a `scheduledTaskId` to `schedule_task` or `delete_scheduled_task`. In a scheduled run, do not call this to find your task. Do the prompt.", success: OrchestratorMcpListScheduledTasksResult, failure: OrchestratorMcpFailure, failureMode: "return", - dependencies, + dependencies: [...dependencies, TotService.TotService], }) .annotate(Tool.Title, "List scheduled tasks") .annotate(Tool.Readonly, true) diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 62b4cfae7e116..b64159b7c611f 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -1372,6 +1372,81 @@ it.effect("reading a project shows the default model and actions saved in Settin }), ); +it.effect( + "a project update saves its default model where new threads read it, and reports it", + () => + Effect.gen(function* () { + const overrideModel = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet", + }; + const overrideScripts = [ + { + id: "test", + name: "Test", + command: "pnpm test", + icon: "test", + runOnWorktreeCreate: false, + }, + ] satisfies ProjectScript[]; + const chosen = { instanceId: ProviderInstanceId.make("opencode"), model: "glm-5.3-flash" }; + const harness = clientLaunchHarness({ + runtimeModeCeiling: "full-access", + overrideModel, + overrideScripts, + launched: [], + }); + const record = (projectId: ProjectId, defaultModelSelection: ModelSelection | null) => ({ + id: projectId, + title: "Client target", + workspaceRoot: "/projects/client-target", + defaultModelSelection, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: null, + }); + const dependencies = Layer.merge( + harness.dependencies, + Layer.mock(Project.ProjectService)({ + // The row keeps its legacy copy, which Settings no longer reads once folded. + update: (input) => + Effect.succeed(record(input.projectId, input.defaultModelSelection ?? null)), + getById: (projectId) => Effect.succeedSome(record(projectId, null)), + }), + ); + yield* Effect.gen(function* () { + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide(McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer)), + ); + const updated = yield* toolkit + .handle("t3_project_update", { + projectId: harness.projectId, + defaultModelSelection: chosen, + }) + .pipe(Stream.unwrap, Stream.runCollect); + expect(updated.at(-1)?.result).toMatchObject({ + defaultModelSelection: chosen, + scripts: overrideScripts, + }); + const read = yield* toolkit + .handle("t3_project_read", { projectId: harness.projectId }) + .pipe(Stream.unwrap, Stream.runCollect); + expect(read.at(-1)?.result).toMatchObject({ defaultModelSelection: chosen }); + const cleared = yield* toolkit + .handle("t3_project_update", { + projectId: harness.projectId, + defaultModelSelection: null, + }) + .pipe(Stream.unwrap, Stream.runCollect); + expect(cleared.at(-1)?.result).toMatchObject({ + defaultModelSelection: null, + scripts: overrideScripts, + }); + }).pipe(Effect.provide(dependencies)); + }), +); + it.effect("a project update or create that is refused tells the agent why", () => Effect.gen(function* () { const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] }); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index b6f8d247c76e8..83cf5d93c704c 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -206,15 +206,41 @@ const withSavedProjectSettings = Effect.gen(function* () { const resolved = resolveProjectSettings(settings, project.id, project); return { ...project, - defaultModelSelection: - resolved.sources.defaultModelSelection === "project" - ? resolved.settings.defaultModelSelection - : null, + // What is stored, even when a disabled provider or hidden model keeps it from applying. + defaultModelSelection: resolved.overrides.defaultModelSelection ?? null, scripts: resolveProjectScripts(settings, project), }; }; }); +/** + * New threads read a project's default model from its Settings override; the project row's + * copy is only folded in once, on first start. Null clears the override. + */ +const saveProjectDefaultModel = Effect.fn("mcp.saveProjectDefaultModel")(function* ( + projectId: ProjectId, + selection: ModelSelection | null, +) { + const settings = yield* ServerSettings.ServerSettingsService; + const current = yield* settings.getSettings.pipe(Effect.mapError(unavailable)); + const { defaultModelSelection: _previous, ...rest } = + current.projectSettingsOverrides[projectId] ?? {}; + const entry = selection === null ? rest : { ...rest, defaultModelSelection: selection }; + yield* settings + .updateSettings({ + projectSettingsOverrides: { [projectId]: Object.keys(entry).length === 0 ? null : entry }, + }) + .pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: `The project was updated, but its default model could not be saved: ${error.message}`, + }), + ), + ); +}); + // The project is already committed, so a failed Settings read must not report the create as failed. const withSavedProjectSettingsAfterCreate = withSavedProjectSettings.pipe( Effect.orElseSucceed(() => (project: ProjectRecord) => project), @@ -659,6 +685,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { const updated = yield* projects .update({ ...input, commandId: yield* newCommandId() }) .pipe(Effect.mapError(projectFailure)); + if (input.defaultModelSelection !== undefined) + yield* saveProjectDefaultModel(updated.id, input.defaultModelSelection); return (yield* withSavedProjectSettings)(updated); }), ), diff --git a/apps/server/src/mcp/toolkits/tots/handlers.test.ts b/apps/server/src/mcp/toolkits/tots/handlers.test.ts index 983bd64e64c89..ed2de4f586140 100644 --- a/apps/server/src/mcp/toolkits/tots/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/tots/handlers.test.ts @@ -53,8 +53,10 @@ const asTot = (input: TotCreateInput): Tot => ({ threadId: ThreadId.make(`tot:${input.name.toLowerCase()}:new`), }); -const harness = (callerThread: ThreadId) => { +/** A thread caller, or the user at a full-access client outside any thread. */ +const harness = (callerThread: ThreadId | "person") => { const watches: Array = []; + const instructions = new Map(); const created: Array = []; const removed: Array = []; const themes = new Map(); @@ -65,7 +67,9 @@ const harness = (callerThread: ThreadId) => { const home: Tot = { ...DEFAULT_HOME_TOT, threadId: homeThread, modelSelection: model }; const stored = (tot: Tot): Tot => { const theme = themes.get(tot.id); - return theme === undefined ? tot : { ...tot, theme }; + const text = instructions.get(tot.id); + const withText = text === undefined ? tot : { ...tot, instructions: text }; + return theme === undefined ? withText : { ...withText, theme }; }; const saveTheme = (id: TotId, patch: TotThemePatch): Tot => { themePatches.push({ id, patch }); @@ -85,12 +89,18 @@ const harness = (callerThread: ThreadId) => { Layer.succeed(McpInvocationContext.McpInvocationContext, { environmentId, requestNamespace: "thread:tots", - thread: { - threadId: callerThread, - providerSessionId: "session", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, + thread: + callerThread === "person" + ? undefined + : { + threadId: callerThread, + providerSessionId: "session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: + callerThread === "person" + ? { sessionId: "session", label: "Claude Code", access: "full-access" as const } + : undefined, issuedAt: 0, capabilities: new Set(["orchestration" as const]), }), @@ -106,6 +116,11 @@ const harness = (callerThread: ThreadId) => { : Option.none(), ), setTheme: (id, patch) => Effect.sync(() => saveTheme(id, patch)), + update: (input) => + Effect.sync(() => { + if (input.instructions !== undefined) instructions.set(input.id, input.instructions); + return stored([home, scopedYui].find((tot) => tot.id === input.id)!); + }), create: (input) => created.some((tot) => tot.name === input.name) || input.name === "Yui" ? Effect.fail(new TotError({ message: "A Tot named like this already exists." })) @@ -169,7 +184,8 @@ const harness = (callerThread: ThreadId) => { | "t3_tot_create" | "t3_tot_webhook_listener" | "t3_tot_theme_set" - | "t3_tot_theme_read", + | "t3_tot_theme_read" + | "t3_tot_instructions", params: Record, ) => Effect.gen(function* () { @@ -183,7 +199,7 @@ const harness = (callerThread: ThreadId) => { .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); return result.at(-1)?.result; }); - return { watches, created, removed, listeners, themePatches, call }; + return { watches, created, removed, listeners, themePatches, instructions, call }; }; it.effect("lists the Tots with a link to each one's thread", () => @@ -385,3 +401,57 @@ it.effect("only a Tot can read or set a theme", () => { expect(themePatches).toHaveLength(0); }); }); + +it.effect("a Tot reads and replaces its own instructions, but not another's", () => { + const { call, instructions } = harness(scopedThread); + return Effect.gen(function* () { + expect(yield* call("t3_tot_instructions", {})).toMatchObject({ + totId: "yui", + instructions: "", + updated: false, + }); + expect(yield* call("t3_tot_instructions", { instructions: "Be brief." })).toMatchObject({ + totId: "yui", + instructions: "Be brief.", + updated: true, + }); + expect(yield* call("t3_tot_instructions", { tot: "home", instructions: "x" })).toMatchObject({ + code: "capability_denied", + }); + expect(yield* call("t3_tot_instructions", { tot: "home" })).toMatchObject({ + code: "capability_denied", + }); + expect([...instructions]).toEqual([["yui", "Be brief."]]); + }); +}); + +it.effect("Home and the user can change any Tot's instructions; other agents cannot", () => + Effect.gen(function* () { + const home = harness(homeThread); + expect( + yield* home.call("t3_tot_instructions", { tot: "yui", instructions: "From Home." }), + ).toMatchObject({ totId: "yui", updated: true }); + const person = harness("person"); + expect( + yield* person.call("t3_tot_instructions", { tot: "yui", instructions: "From the user." }), + ).toMatchObject({ totId: "yui", instructions: "From the user." }); + expect(yield* person.call("t3_tot_instructions", {})).toMatchObject({ + code: "invalid_request", + }); + const agent = harness(ThreadId.make("thread:ordinary")); + expect( + yield* agent.call("t3_tot_instructions", { tot: "yui", instructions: "Hijack." }), + ).toMatchObject({ code: "capability_denied" }); + expect(agent.instructions.size).toBe(0); + }), +); + +it.effect("refuses instructions over the cap", () => { + const { call, instructions } = harness(scopedThread); + return Effect.gen(function* () { + // The schema refuses it before the handler runs. + const refused = yield* call("t3_tot_instructions", { instructions: "a".repeat(20_001) }); + expect(refused).toMatchObject({ reason: { _tag: "ToolParameterValidationError" } }); + expect(instructions.size).toBe(0); + }); +}); diff --git a/apps/server/src/mcp/toolkits/tots/handlers.ts b/apps/server/src/mcp/toolkits/tots/handlers.ts index 2ce113d54adaa..70aa774d8934a 100644 --- a/apps/server/src/mcp/toolkits/tots/handlers.ts +++ b/apps/server/src/mcp/toolkits/tots/handlers.ts @@ -1,5 +1,6 @@ import { DEFAULT_HOME_TOT, + HOME_TOT_ID, OrchestratorMcpFailure, type Tot, type TotThemePatch, @@ -16,8 +17,8 @@ import * as GroupChatService from "../../../tots/GroupChatService.ts"; import * as TotService from "../../../tots/TotService.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; -import { requireTotChange } from "../../totCaller.ts"; -import { readCaller } from "../../threadAccess.ts"; +import { readTotCaller, requireTotChange } from "../../totCaller.ts"; +import { assertFullAccess, readCaller } from "../../threadAccess.ts"; import { TotToolkit } from "./tools.ts"; /** Sizes and a summary only: the stored CSS and opaque effect text are never echoed. */ @@ -35,6 +36,32 @@ const themeResult = (tot: Tot) => { }; }; +/** + * Who may reach Tot instructions: a Tot here, its own or (Home) any, or a person + * at a client outside any thread. Agents in other threads may not. + */ +const instructionsCaller = Effect.fn("mcp.totInstructionsCaller")(function* (writing: boolean) { + const tot = yield* readTotCaller(); + if (Option.isSome(tot)) { + const caller = writing ? yield* requireTotChange() : tot.value; + if (caller.via !== "local") + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Your instructions live with you here; change them from your own environment.", + }); + return Option.some(caller.totId); + } + const context = yield* readCaller(); + if (context.scope.thread !== undefined || context.scope.client?.linked === true) + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Only a Tot or the user can read or change Tot instructions.", + }); + if (writing) + yield* assertFullAccess(context, "Changing Tot instructions needs a full-access client."); + return Option.none(); +}); + export const layer = McpToolAccess.toLayer(TotToolkit, { t3_tot_list: McpToolAccess.reads(() => Effect.gen(function* () { @@ -300,6 +327,38 @@ export const layer = McpToolAccess.toLayer(TotToolkit, { }; }), ), + t3_tot_instructions: McpToolAccess.reads((input) => + Effect.gen(function* () { + const writing = input.instructions !== undefined; + const caller = yield* instructionsCaller(writing); + const targetId = input.tot ?? Option.getOrUndefined(caller); + if (targetId === undefined) + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: "Pass `tot`: you are not a Tot.", + }); + if (Option.isSome(caller) && caller.value !== targetId && caller.value !== HOME_TOT_ID) + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "A Tot can reach only its own instructions; Home and the user can reach any.", + }); + const tots = yield* TotService.TotService; + const invalid = (error: { readonly message: string }) => + new OrchestratorMcpFailure({ code: "invalid_request", message: error.message }); + const tot = + input.instructions === undefined + ? (yield* tots.list).find((candidate) => candidate.id === targetId) + : yield* tots + .update({ id: targetId, instructions: input.instructions }) + .pipe(Effect.mapError(invalid)); + if (tot === undefined) + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: `There is no Tot "${targetId}".`, + }); + return { totId: tot.id, name: tot.name, instructions: tot.instructions, updated: writing }; + }), + ), t3_tot_watch: McpToolAccess.reads((input) => Effect.gen(function* () { const tot = yield* requireTotChange(); diff --git a/apps/server/src/mcp/toolkits/tots/tools.ts b/apps/server/src/mcp/toolkits/tots/tools.ts index 11cc3c8ab619d..89140c6b72c27 100644 --- a/apps/server/src/mcp/toolkits/tots/tools.ts +++ b/apps/server/src/mcp/toolkits/tots/tools.ts @@ -191,6 +191,26 @@ const TotCreateTool = Tool.make("t3_tot_create", { }), }).annotate(Tool.Destructive, false); +const TotInstructionsTool = Tool.make("t3_tot_instructions", { + ...shared, + description: + "Read a Tot's personality and instructions, or replace them by passing `instructions`. They render into its AGENTS.md, so edit them here, not by hand. A Tot reaches only its own, unless it is Home.", + parameters: Schema.Struct({ + tot: Schema.optional(TotId).annotate({ description: "Default: you." }), + instructions: Schema.optional( + Tot.fields.instructions.annotate({ + description: "The whole new text, in Markdown, up to 20,000 characters. Omit to read.", + }), + ), + }), + success: Schema.Struct({ + totId: TotId, + name: Schema.String, + instructions: Schema.String, + updated: Schema.Boolean, + }), +}).annotate(Tool.Destructive, false); + export const TotToolkit = Toolkit.make( TotListTool, TotWatchTool, @@ -200,4 +220,5 @@ export const TotToolkit = Toolkit.make( TotThemeReadTool, TotWebhookListenerTool, TotCreateTool, + TotInstructionsTool, ); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index f43ae5e0248a1..76a17d462e677 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -120,6 +120,7 @@ import Migration0109 from "./Migrations/109_AgentFeedback.ts"; import Migration0110 from "./Migrations/110_IssueTrackerAccounts.ts"; import Migration0111 from "./Migrations/111_Workflows.ts"; import Migration0112 from "./Migrations/112_SupersededRunAttemptIndex.ts"; +import Migration0113 from "./Migrations/113_ScheduledTaskModelPinned.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -237,6 +238,7 @@ const migrationEntries = [ [110, "IssueTrackerAccounts", Migration0110], [111, "Workflows", Migration0111], [112, "SupersededRunAttemptIndex", Migration0112], + [113, "ScheduledTaskModelPinned", Migration0113], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.test.ts b/apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.test.ts new file mode 100644 index 0000000000000..a27a5f5d719eb --- /dev/null +++ b/apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.test.ts @@ -0,0 +1,50 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import Migration0113 from "./113_ScheduledTaskModelPinned.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" }))); + +layer("113_ScheduledTaskModelPinned", (it) => { + it.effect("keeps existing scheduled tasks unpinned and replays safely", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 112 }); + yield* sql`INSERT INTO scheduled_tasks ${sql.insert({ + task_id: "existing", + title: "task", + prompt: "Run", + enabled: 1, + schedule_json: '{"type":"interval","everyMs":60000}', + project_id: "project", + thread_id: null, + thread_mode: "new_thread", + workspace_strategy_json: '{"type":"root"}', + model_selection_json: '{"instanceId":"codex","model":"gpt-5"}', + runtime_mode: "full-access", + interaction_mode: "default", + created_by: "user", + creation_source: "web", + created_at: "2026-10-01T00:00:00.000Z", + updated_at: "2026-10-01T00:00:00.000Z", + next_run_at: null, + last_run_at: null, + last_run_status: "never", + last_run_error: null, + run_count: 0, + })}`; + yield* runMigrations({ toMigrationInclusive: 113 }); + yield* Migration0113; + + const rows = yield* sql<{ + task_id: string; + model_pinned: number; + }>`SELECT task_id, model_pinned FROM scheduled_tasks`; + assert.deepEqual(rows, [{ task_id: "existing", model_pinned: 0 }]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.ts b/apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.ts new file mode 100644 index 0000000000000..eeaf5fd456d70 --- /dev/null +++ b/apps/server/src/persistence/Migrations/113_ScheduledTaskModelPinned.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // A task can pin its model, so bound runs stop following the thread's current one. + // Idempotent: a history that recorded it at another id replays it (see Migrations.ts). + const existing = yield* sql` + SELECT 1 FROM pragma_table_info('scheduled_tasks') WHERE name = 'model_pinned' + `; + if (existing.length > 0) return; + yield* sql`ALTER TABLE scheduled_tasks ADD COLUMN model_pinned INTEGER NOT NULL DEFAULT 0`; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 3af4762626283..b7381cf020e52 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -92,6 +92,7 @@ describe("V2 preview upgrade", () => { [110, "IssueTrackerAccounts"], [111, "Workflows"], [112, "SupersededRunAttemptIndex"], + [113, "ScheduledTaskModelPinned"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -227,6 +228,7 @@ describe("V2 preview upgrade", () => { [110, "IssueTrackerAccounts"], [111, "Workflows"], [112, "SupersededRunAttemptIndex"], + [113, "ScheduledTaskModelPinned"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index eec35dbc7d9e8..76fca50915f08 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 71469 + "mcpToolListJsonBytes": 72116 } diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.failure.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.failure.test.ts index e1b28fab4a55d..ce27e59d57297 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.failure.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.failure.test.ts @@ -262,3 +262,28 @@ it.effect("a run replaces a bound task's stale stored model with the one its thr }).pipe(Effect.provide(layer)); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("a bound task that pins its model keeps that model across saves and runs", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z")); + const { layer, settled } = yield* harness({ + first: "failed", + retry: null, + threadModel: flash, + }); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert({ + ...onceTask, + schedule: { type: "interval", everyMs: 60 * 60 * 1_000 }, + modelPinned: true, + }); + assert.deepEqual(task.modelSelection, glm); + yield* service.runNow({ id: task.id }); + // The failure notice is sent after the bound-model refresh would have run. + yield* Deferred.await(settled); + const stored = (yield* service.list()).tasks.find((entry) => entry.id === task.id); + assert.deepEqual(stored?.modelSelection, glm); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index de37b8bc435e0..6f214ca80cf40 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -5,6 +5,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, it, vi } from "@effect/vitest"; import { CommandId, + type ModelSelection, ProjectId, ProviderInstanceId, ScheduledTaskError, @@ -935,6 +936,69 @@ it.effect("remembers the Tot that created a task across later edits", () => }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); +it.effect("a bound run sends the model only when the task pins it, and edits keep the pin", () => + Effect.gen(function* () { + const project = ProjectId.make("project:pinned"); + const sent = yield* Ref.make>([]); + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + sendToThread: (input) => + Ref.update(sent, (all) => [...all, input.modelSelection]).pipe( + Effect.as({} as never), + ), + getThreadShell: () => Effect.succeed(threadShell(project)), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }), + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const flash = { instanceId: ProviderInstanceId.make("opencode"), model: "glm-5.3-flash" }; + const base = { + title: "Check in", + prompt: "Check progress", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 } as const, + projectId: project, + threadId: ThreadId.make("thread:pinned"), + workspaceStrategy: { type: "root" } as const, + modelSelection: flash, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + }; + const pinned = yield* service.upsert({ + ...base, + id: ScheduledTaskId.make("task:pinned"), + modelPinned: true, + }); + const following = yield* service.upsert({ + ...base, + id: ScheduledTaskId.make("task:following"), + }); + // A client save that does not know the pin keeps it. + yield* service.upsert({ ...base, id: pinned.task.id, title: "Check in, edited" }); + const stored = (yield* service.list()).tasks.find((task) => task.id === pinned.task.id); + assert.equal(stored?.modelPinned, true); + assert.isUndefined(following.task.modelPinned); + + yield* service.runNow({ id: pinned.task.id }); + yield* service.runNow({ id: following.task.id }); + assert.deepEqual(yield* Ref.get(sent), [flash, undefined]); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + it.effect("a first run whose thread was deleted before it bound removes the task", () => Effect.gen(function* () { const layer = ScheduledTaskService.layer.pipe( diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 5079c93c08e8e..77b008bd6669e 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -252,6 +252,7 @@ interface ScheduledTaskRow { readonly thread_mode: string; readonly workspace_strategy_json: string; readonly model_selection_json: string; + readonly model_pinned: number; readonly runtime_mode: string; readonly interaction_mode: string; readonly created_by: string; @@ -444,6 +445,7 @@ const decodeRow = Effect.fnUntraced( threadMode: row.thread_mode, workspaceStrategy, modelSelection, + ...(row.model_pinned === 1 ? { modelPinned: true } : {}), runtimeMode: row.runtime_mode, interactionMode: row.interaction_mode, createdBy: row.created_by, @@ -574,6 +576,7 @@ export const layer = Layer.effect( thread_mode, workspace_strategy_json, model_selection_json, + model_pinned, runtime_mode, interaction_mode, created_by, @@ -617,6 +620,7 @@ export const layer = Layer.effect( thread_mode, workspace_strategy_json, model_selection_json, + model_pinned, runtime_mode, interaction_mode, created_by, @@ -698,6 +702,7 @@ export const layer = Layer.effect( thread_mode, workspace_strategy_json, model_selection_json, + model_pinned, runtime_mode, interaction_mode, created_by, @@ -724,6 +729,7 @@ export const layer = Layer.effect( ${scheduledTaskThreadMode(task)}, ${JSON.stringify(task.workspaceStrategy)}, ${JSON.stringify(task.modelSelection)}, + ${task.modelPinned === true ? 1 : 0}, ${task.runtimeMode}, ${task.interactionMode}, ${task.createdBy}, @@ -757,6 +763,7 @@ export const layer = Layer.effect( thread_mode = excluded.thread_mode, workspace_strategy_json = excluded.workspace_strategy_json, model_selection_json = excluded.model_selection_json, + model_pinned = excluded.model_pinned, runtime_mode = excluded.runtime_mode, interaction_mode = excluded.interaction_mode, creation_source = excluded.creation_source, @@ -1005,15 +1012,16 @@ export const layer = Layer.effect( if (retried !== null) outcome = (yield* awaitRunOutcome(thread, retried.messageId)) ?? outcome; } - // A bound run uses its thread's model, not the stored one, so keep the stored one true. - if (scheduledTaskThreadMode(task) !== "new_thread") { + // An unpinned bound run uses its thread's model, not the stored one, so keep the stored one + // true. A pinned task's stored model is what its runs send, so it is never overwritten. + if (scheduledTaskThreadMode(task) !== "new_thread" && task.modelPinned !== true) { yield* Effect.gen(function* () { const current = yield* threadManagement.getThreadShell(threadId); if (current === null) return; const json = yield* encodeModelSelectionJson(current.modelSelection); yield* sql` UPDATE scheduled_tasks SET model_selection_json = ${json} - WHERE task_id = ${taskId} AND thread_id = ${threadId} + WHERE task_id = ${taskId} AND thread_id = ${threadId} AND model_pinned = 0 AND model_selection_json IS NOT ${json} `; }).pipe( @@ -1185,6 +1193,7 @@ export const layer = Layer.effect( text: prompt, attachments: [], mode: "queue", + ...(active.modelPinned === true ? { modelSelection: active.modelSelection } : {}), ...(threadMode === "fresh_session" ? { freshContext: true } : {}), createdBy: active.createdBy, creationSource: active.creationSource, @@ -1236,7 +1245,7 @@ export const layer = Layer.effect( ) : yield* Effect.exit( // The stored selection only seeds fresh threads. A bound run - // follows the thread's current provider, so it passes none. + // follows the thread's current provider unless the task pins its model. sendBound(ThreadId.make(active.threadId), active.projectId, 2).pipe( Effect.as(ThreadId.make(active.threadId)), ), @@ -1610,8 +1619,8 @@ export const layer = Layer.effect( keptThreadId === existingTask.threadId; const threadId = threadMode === "new_thread" || movedOffThread ? null : keptThreadId; // An unchanged destination is not rechecked, so a task on an archived thread stays editable. - // A bound run uses its thread's model, so a new binding stores that one rather than a - // selection it ignores; each run refreshes it after that. + // An unpinned bound run uses its thread's model, so a new binding stores that one rather + // than a selection it ignores; each run refreshes it after that. A pin keeps the input's. const boundModel = threadId !== null && threadId !== existingTask?.threadId ? (yield* requireDestinationThread(threadId, input.projectId, id)).modelSelection @@ -1760,6 +1769,7 @@ export const layer = Layer.effect( if (!scheduleUnchanged) yield* requireFutureOnce({ enabled: input.enabled, schedule }, now, id); const createdByTotId = existingTask?.createdByTotId ?? input.createdByTotId; + const modelPinned = input.modelPinned ?? existingTask?.modelPinned ?? false; const task: ScheduledTask = { id, title: input.title, @@ -1770,7 +1780,8 @@ export const layer = Layer.effect( threadId, threadMode, workspaceStrategy, - modelSelection: boundModel ?? input.modelSelection, + modelSelection: modelPinned ? input.modelSelection : (boundModel ?? input.modelSelection), + ...(modelPinned ? { modelPinned: true } : {}), runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, createdBy: existingTask?.createdBy ?? input.createdBy ?? "user", diff --git a/apps/server/src/tots/totAgents.ts b/apps/server/src/tots/totAgents.ts index 3c723a5762e31..5901668bb3479 100644 --- a/apps/server/src/tots/totAgents.ts +++ b/apps/server/src/tots/totAgents.ts @@ -65,6 +65,8 @@ const instructionsBlock = (tot: Tot): string => INSTRUCTIONS_START, "## Your personality and instructions", "", + "T3 Code rewrites this block from your settings. Change it with `t3_tot_instructions`; edits made here by hand are lost.", + "", tot.instructions.trim() === "" ? "(None yet.)" : tot.instructions.trim(), INSTRUCTIONS_END, ].join("\n"); diff --git a/docs/internals/tots.md b/docs/internals/tots.md index f566144bc05ff..17caab80ed81b 100644 --- a/docs/internals/tots.md +++ b/docs/internals/tots.md @@ -59,3 +59,7 @@ A Tot stores its own theme on its record: `theme?: { css?: string; effect?: stri - `css` is applied like an environment theme, not as one: the server refuses what [`themeCssLoadsRemoteFiles`](../../packages/shared/src/themeCss.ts) catches, and [`totThemeCss.ts`](../../apps/web/src/components/tots/totThemeCss.ts) parses it into its own constructed sheet, runs the same `stripFetches` guard, and rewrites each selector to start at `[data-tot-id=""]`. Bare `:root`, `html` and `body` steps become the scope; a qualified step such as `:root.dark` stays as ancestor context so appearance rules still work. `@keyframes` and `@font-face` stay global on purpose. The sheet exists only while that Tot's thread is open, and it never touches the app's own theme sheet. - `effect` is opaque text. T3 Code stores and returns it, and the client's effect layer reads it; nothing here parses, runs, or renders it. - The conversation root carries `data-tot-id` and `data-thread-id` ([`totThreadScope.ts`](../../apps/web/src/components/tots/totThreadScope.ts)), whether or not the thread has messages, so CSS never needs `:has()`. + +## Instructions + +Instructions follow a looser rule because Home looks after the others: `t3_tot_instructions` lets a Tot read and replace its own, Home any Tot's, and a person at a client outside any thread any Tot's. Other agent threads are refused. The write goes through `TotService.update`, which re-renders `AGENTS.md`, so hand edits to the instructions block never stick. diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index bab30865fedf5..138b10ba4eaa3 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -43,6 +43,7 @@ import { OrchestrationV2TurnItemStatus, } from "./orchestrationV2.ts"; import { ProviderOptionSelection, ProviderOptionSelectionValue } from "./model.ts"; +import { ModelSelection } from "./modelSelection.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; const OrchestratorMcpPrompt = TrimmedNonEmptyString.check(Schema.isMaxLength(120_000)); @@ -755,6 +756,12 @@ export const OrchestratorMcpScheduleTaskInput = Schema.Struct({ "Runs share one thread but each starts a fresh session. Unbound: the first run makes the thread.", }), ), + modelSelection: Schema.optional( + ModelSelection.annotate({ + description: + "Model for every run, bound or not. Default: this thread's model, which bound runs then follow as it changes.", + }), + ), clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), }); export type OrchestratorMcpScheduleTaskInput = typeof OrchestratorMcpScheduleTaskInput.Type; @@ -777,6 +784,7 @@ export const OrchestratorMcpScheduledTask = Schema.Struct({ projectId: ProjectId, boundThreadId: Schema.NullOr(ThreadId), freshSession: Schema.Boolean, + modelSelection: ModelSelection, schedule: ScheduledTaskSchedule, nextRunAt: Schema.NullOr(IsoDateTime), lastRunStatus: ScheduledTaskRunStatus, @@ -798,7 +806,8 @@ export const OrchestratorMcpListScheduledTasksInput = Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, projectId: Schema.optional( ProjectId.annotate({ - description: "Default: your thread's project, or all outside a thread.", + description: + "Default: your thread's project, or all outside a thread. A Tot also gets the projects it owns.", }), ), scheduledTaskId: Schema.optional(ScheduledTaskId), @@ -808,6 +817,8 @@ export type OrchestratorMcpListScheduledTasksInput = export const OrchestratorMcpListScheduledTasksResult = Schema.Struct({ tasks: Schema.Array(OrchestratorMcpScheduledTask), + /** Why a default listing may not be everything, such as projects it did not cover. */ + note: Schema.optional(Schema.String), }); export type OrchestratorMcpListScheduledTasksResult = typeof OrchestratorMcpListScheduledTasksResult.Type; @@ -821,6 +832,7 @@ export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({ enabled: Schema.optional(Schema.Boolean), bindToCurrentThread: Schema.optional(Schema.Boolean), freshSession: Schema.optional(Schema.Boolean), + modelSelection: Schema.optional(ModelSelection), }); export type OrchestratorMcpUpdateScheduledTaskInput = typeof OrchestratorMcpUpdateScheduledTaskInput.Type; diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts index 133481094b977..d5dd2fba18a4d 100644 --- a/packages/contracts/src/scheduledTask.ts +++ b/packages/contracts/src/scheduledTask.ts @@ -315,6 +315,8 @@ export const ScheduledTask = Schema.Struct({ threadMode: Schema.optional(ScheduledTaskThreadMode), workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy, modelSelection: ModelSelection, + /** Bound runs use `modelSelection` instead of following the thread's current model. */ + modelPinned: Schema.optional(Schema.Boolean), runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, createdBy: OrchestrationV2Actor, @@ -364,6 +366,8 @@ export const ScheduledTaskUpsertInput = Schema.Struct({ threadMode: Schema.optional(ScheduledTaskThreadMode), workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy, modelSelection: ModelSelection, + /** Omitted: keep the stored pin, so a client that does not know it leaves it alone. */ + modelPinned: Schema.optional(Schema.Boolean), runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, createdBy: Schema.optional(OrchestrationV2Actor),