Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions CUSTOM.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
97 changes: 97 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<ReadonlyArray<ScheduledTaskUpsertInput>>([]);
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
Effect.provide(
service(
masterRepository,
yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]),
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",
Expand Down
52 changes: 48 additions & 4 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProjectId>;
/** Sidebar groups in its scope, which this server cannot resolve to projects. */
readonly hasGroups: boolean;
}

export interface OrchestratorMcpServiceShape {
readonly capabilities: (
scope: McpInvocationScope,
Expand Down Expand Up @@ -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<OrchestratorMcpListScheduledTasksResult, OrchestratorMcpFailure>;
readonly updateScheduledTask: (
scope: McpInvocationScope,
Expand Down Expand Up @@ -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<string> = 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,
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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(
Expand All @@ -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.",
}
: {}),
};
},
),
Expand All @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
38 changes: 36 additions & 2 deletions apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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* () {
Expand Down Expand Up @@ -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;
Expand All @@ -134,6 +167,7 @@ const handlers = {
enabled,
freshSession,
bindToCurrentThread,
modelSelection,
});
}),
),
Expand All @@ -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) =>
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading