Skip to content

Commit e32cce2

Browse files
committed
feat(server): agents can schedule prompts in their threads
1 parent 5cc99e1 commit e32cce2

20 files changed

Lines changed: 913 additions & 29 deletions

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ import {
4141
DeviceScreenshotToolkit,
4242
DeviceStandardToolkit,
4343
} from "./toolkits/device/tools.ts";
44+
import { SchedulingToolkit } from "./toolkits/scheduling/tools.ts";
45+
import { SchedulingToolkitHandlersLive } from "./toolkits/scheduling/handlers.ts";
4446

4547
const unauthorized = HttpServerResponse.jsonUnsafe(
4648
{
@@ -670,5 +672,6 @@ const McpTransportLive = McpServer.layerHttp({
670672
export const layer = Layer.mergeAll(
671673
PreviewToolkitRegistrationLive,
672674
PullRequestsToolkitRegistrationLive,
675+
McpServer.toolkit(SchedulingToolkit).pipe(Layer.provide(SchedulingToolkitHandlersLive)),
673676
DeviceToolkitRegistrationLive,
674677
).pipe(Layer.provideMerge(McpTransportLive));

‎apps/server/src/mcp/McpInvocationContext.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import * as Context from "effect/Context";
99
import * as Effect from "effect/Effect";
1010

11-
export type McpCapability = "preview" | "device" | "pull-requests";
11+
export type McpCapability = "preview" | "device" | "pull-requests" | "scheduling";
1212

1313
export interface McpInvocationScope {
1414
readonly environmentId: EnvironmentId;

‎apps/server/src/mcp/McpSessionRegistry.test.ts‎

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -56,33 +56,39 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
5656
}),
5757
);
5858

59-
it.effect("always grants pull-requests and gates browser and device access independently", () =>
60-
Effect.gen(function* () {
61-
const registry = yield* makeRegistry(() => 1_000);
62-
const withPreview = yield* registry.issue({
63-
threadId: ThreadId.make("thread-preview"),
64-
providerInstanceId: ProviderInstanceId.make("codex"),
65-
capabilities: new Set(["preview"]),
66-
});
67-
const withoutPreview = yield* registry.issue({
68-
threadId: ThreadId.make("thread-no-preview"),
69-
providerInstanceId: ProviderInstanceId.make("codex"),
70-
capabilities: new Set(),
71-
});
72-
const withDevice = yield* registry.issue({
73-
threadId: ThreadId.make("thread-device"),
74-
providerInstanceId: ProviderInstanceId.make("codex"),
75-
capabilities: new Set(["device"]),
76-
});
77-
const capabilitiesOf = (issued: typeof withPreview) =>
78-
registry
79-
.resolve(issued.config.authorizationHeader.replace(/^Bearer\s+/, ""))
80-
.pipe(Effect.map((scope) => [...(scope?.capabilities ?? [])].sort()));
81-
82-
expect(yield* capabilitiesOf(withPreview)).toEqual(["preview", "pull-requests"]);
83-
expect(yield* capabilitiesOf(withoutPreview)).toEqual(["pull-requests"]);
84-
expect(yield* capabilitiesOf(withDevice)).toEqual(["device", "pull-requests"]);
85-
}),
59+
it.effect(
60+
"always grants pull-requests and scheduling and gates browser and device access independently",
61+
() =>
62+
Effect.gen(function* () {
63+
const registry = yield* makeRegistry(() => 1_000);
64+
const withPreview = yield* registry.issue({
65+
threadId: ThreadId.make("thread-preview"),
66+
providerInstanceId: ProviderInstanceId.make("codex"),
67+
capabilities: new Set(["preview"]),
68+
});
69+
const withoutPreview = yield* registry.issue({
70+
threadId: ThreadId.make("thread-no-preview"),
71+
providerInstanceId: ProviderInstanceId.make("codex"),
72+
capabilities: new Set(),
73+
});
74+
const withDevice = yield* registry.issue({
75+
threadId: ThreadId.make("thread-device"),
76+
providerInstanceId: ProviderInstanceId.make("codex"),
77+
capabilities: new Set(["device"]),
78+
});
79+
const capabilitiesOf = (issued: typeof withPreview) =>
80+
registry
81+
.resolve(issued.config.authorizationHeader.replace(/^Bearer\s+/, ""))
82+
.pipe(Effect.map((scope) => [...(scope?.capabilities ?? [])].sort()));
83+
84+
expect(yield* capabilitiesOf(withPreview)).toEqual([
85+
"preview",
86+
"pull-requests",
87+
"scheduling",
88+
]);
89+
expect(yield* capabilitiesOf(withoutPreview)).toEqual(["pull-requests", "scheduling"]);
90+
expect(yield* capabilitiesOf(withDevice)).toEqual(["device", "pull-requests", "scheduling"]);
91+
}),
8692
);
8793

8894
it.effect("builds MCP endpoints from the bound server host", () =>

‎apps/server/src/mcp/McpSessionRegistry.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
127127
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
128128
capabilities: new Set<McpInvocationContext.McpCapability>([
129129
"pull-requests",
130+
"scheduling",
130131
...request.capabilities,
131132
]),
132133
issuedAt,
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import * as Effect from "effect/Effect";
2+
import * as McpInvocationContext from "../../McpInvocationContext.ts";
3+
import * as ScheduledPrompts from "../../../scheduling/ScheduledPrompts.ts";
4+
import { SchedulingToolkit } from "./tools.ts";
5+
6+
const make = Effect.gen(function* () {
7+
const schedules = yield* ScheduledPrompts.ScheduledPrompts;
8+
return SchedulingToolkit.of({
9+
schedule_prompt: (input) =>
10+
Effect.gen(function* () {
11+
const scope = yield* McpInvocationContext.requireMcpCapability("scheduling");
12+
return yield* schedules.create(scope.threadId, input);
13+
}),
14+
list_scheduled_prompts: () =>
15+
Effect.gen(function* () {
16+
const scope = yield* McpInvocationContext.requireMcpCapability("scheduling");
17+
return { schedules: yield* schedules.list(scope.threadId) };
18+
}),
19+
update_scheduled_prompt: (input) =>
20+
Effect.gen(function* () {
21+
const scope = yield* McpInvocationContext.requireMcpCapability("scheduling");
22+
return yield* schedules.update(scope.threadId, input.id, input.action);
23+
}),
24+
});
25+
});
26+
export const SchedulingToolkitHandlersLive = SchedulingToolkit.toLayer(make);
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import {
2+
CreateScheduledPromptInput,
3+
McpCapabilityUnavailableError,
4+
ScheduledPrompt,
5+
ScheduledPromptError,
6+
TrimmedNonEmptyString,
7+
} from "@t3tools/contracts";
8+
import * as Schema from "effect/Schema";
9+
import * as Tool from "effect/unstable/ai/Tool";
10+
import * as Toolkit from "effect/unstable/ai/Toolkit";
11+
import * as McpInvocationContext from "../../McpInvocationContext.ts";
12+
import * as ScheduledPrompts from "../../../scheduling/ScheduledPrompts.ts";
13+
14+
const dependencies = [McpInvocationContext.McpInvocationContext, ScheduledPrompts.ScheduledPrompts];
15+
const failure = Schema.Union([ScheduledPromptError, McpCapabilityUnavailableError]);
16+
17+
export const SchedulingToolkit = Toolkit.make(
18+
Tool.make("schedule_prompt", {
19+
description:
20+
"Schedule a future user prompt that starts a new agent turn in this same chat. Use when the user asks to check later, at a specific time, or repeatedly. Supports once (ISO timestamp with offset), delay (seconds), interval (seconds, optional startAt), and cron (five fields, explicit IANA timeZone). Minimum delay/interval is 60 seconds. The environment server must be running; schedules persist across restarts and missed occurrences run once. Busy threads wait. Confirm the returned nextRunAt to the user. Do not schedule work unless the user requests it.",
21+
parameters: CreateScheduledPromptInput,
22+
success: ScheduledPrompt,
23+
failure,
24+
dependencies,
25+
})
26+
.annotate(Tool.Readonly, false)
27+
.annotate(Tool.Destructive, false)
28+
.annotate(Tool.OpenWorld, false)
29+
.annotate(Tool.Idempotent, false),
30+
Tool.make("list_scheduled_prompts", {
31+
description:
32+
"List the latest 100 schedules in this chat, including their IDs, next run, status, last run, and any delivery error. Use to inspect scheduled work before changing it.",
33+
success: Schema.Struct({ schedules: Schema.Array(ScheduledPrompt) }),
34+
failure,
35+
dependencies,
36+
})
37+
.annotate(Tool.Readonly, true)
38+
.annotate(Tool.Destructive, false)
39+
.annotate(Tool.OpenWorld, false)
40+
.annotate(Tool.Idempotent, true),
41+
Tool.make("update_scheduled_prompt", {
42+
description:
43+
"Pause, resume, or cancel a schedule in this chat by its ID. Resume runs an overdue prompt once. Cancel permanently stops future runs; completed or cancelled schedules cannot resume. To change the prompt or timing, cancel it and create a replacement.",
44+
parameters: Schema.Struct({
45+
id: TrimmedNonEmptyString,
46+
action: Schema.Literals(["pause", "resume", "cancel"]),
47+
}),
48+
success: ScheduledPrompt,
49+
failure,
50+
dependencies,
51+
})
52+
.annotate(Tool.Readonly, false)
53+
.annotate(Tool.Destructive, false)
54+
.annotate(Tool.OpenWorld, false)
55+
.annotate(Tool.Idempotent, true),
56+
);

‎apps/server/src/orchestration/decider.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1399,6 +1399,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
13991399
command,
14001400
threadId: command.threadId,
14011401
});
1402+
if (
1403+
command.requireIdleAt !== undefined &&
1404+
(targetThread.archivedAt !== null ||
1405+
targetThread.latestTurn?.state === "running" ||
1406+
targetThread.session?.status === "starting" ||
1407+
(targetThread.session?.activeTurnId !== null &&
1408+
targetThread.session?.activeTurnId !== undefined) ||
1409+
openRequests(targetThread).size > 0 ||
1410+
hasQueuedTurnStartForThread(targetThread, command.requireIdleAt))
1411+
) {
1412+
return yield* new OrchestrationCommandInvariantError({
1413+
commandType: command.type,
1414+
detail: "Scheduled prompts require an idle, unarchived thread.",
1415+
});
1416+
}
14021417
const sourceProposedPlan = command.sourceProposedPlan;
14031418
const sourceThread = sourceProposedPlan
14041419
? yield* requireThread({

‎apps/server/src/orchestration/decider.userMessageAppend.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,50 @@ it.layer(NodeServices.layer)("thread.message.user.append", (it) => {
135135
}),
136136
);
137137
});
138+
139+
it.effect("scheduled turn starts cannot steer running or queued work", () =>
140+
Effect.gen(function* () {
141+
const readModel = yield* readModelWithThread;
142+
const target = readModel.threads[0]!;
143+
const starting = {
144+
...target,
145+
session: {
146+
threadId,
147+
status: "starting" as const,
148+
providerName: "codex",
149+
runtimeMode: "full-access" as const,
150+
activeTurnId: null,
151+
lastError: null,
152+
updatedAt: createdAt,
153+
},
154+
};
155+
const archived = { ...target, archivedAt: createdAt };
156+
for (const blocked of [starting, archived]) {
157+
const error = yield* decideOrchestrationCommand({
158+
readModel: { ...readModel, threads: [blocked] },
159+
command: { ...turnStartCommand, requireIdleAt: createdAt },
160+
}).pipe(Effect.flip);
161+
expect(error).toMatchObject({ _tag: "OrchestrationCommandInvariantError" });
162+
}
163+
const queuedEvents = yield* decideOrchestrationCommand({ readModel, command: appendCommand });
164+
let queuedModel = readModel;
165+
for (const [index, event] of (Array.isArray(queuedEvents)
166+
? queuedEvents
167+
: [queuedEvents]
168+
).entries()) {
169+
queuedModel = yield* projectEvent(queuedModel, { ...event, sequence: index + 3 });
170+
}
171+
const error = yield* decideOrchestrationCommand({
172+
readModel: queuedModel,
173+
command: { ...turnStartCommand, requireIdleAt: createdAt },
174+
}).pipe(Effect.flip);
175+
expect(error).toMatchObject({ _tag: "OrchestrationCommandInvariantError" });
176+
const accepted = yield* decideOrchestrationCommand({
177+
readModel,
178+
command: { ...turnStartCommand, requireIdleAt: createdAt },
179+
});
180+
expect((Array.isArray(accepted) ? accepted : [accepted]).map((event) => event.type)).toContain(
181+
"thread.turn-start-requested",
182+
);
183+
}).pipe(Effect.provide(NodeServices.layer)),
184+
);

‎apps/server/src/persistence/Migrations.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import Migration0051 from "./Migrations/051_ProjectionThreadMessageContext.ts";
6666
import Migration0052 from "./Migrations/052_ProjectionThreadTitleState.ts";
6767
import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts";
6868
import Migration0054 from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts";
69+
import Migration0055 from "./Migrations/055_ScheduledPrompts.ts";
6970

7071
/**
7172
* Migration loader with all migrations defined inline.
@@ -132,6 +133,7 @@ const migrationEntries = [
132133
[52, "ProjectionThreadTitleState", Migration0052],
133134
[53, "PullRequestFilesViewed", Migration0053],
134135
[54, "ProjectionThreadsAutoSettleDisabledAt", Migration0054],
136+
[55, "ScheduledPrompts", Migration0055],
135137
] as const;
136138

137139
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import * as Effect from "effect/Effect";
2+
import * as SqlClient from "effect/unstable/sql/SqlClient";
3+
4+
export default Effect.gen(function* () {
5+
const sql = yield* SqlClient.SqlClient;
6+
yield* sql`CREATE TABLE scheduled_prompts (
7+
id TEXT PRIMARY KEY,
8+
thread_id TEXT NOT NULL,
9+
prompt TEXT NOT NULL,
10+
schedule_json TEXT NOT NULL,
11+
next_run_at TEXT NOT NULL,
12+
eligible_at TEXT NOT NULL,
13+
status TEXT NOT NULL CHECK (status IN ('active', 'paused', 'completed', 'cancelled')),
14+
last_run_at TEXT,
15+
last_error TEXT,
16+
delivery_command_id TEXT,
17+
delivery_created_at TEXT,
18+
created_at TEXT NOT NULL
19+
)`;
20+
yield* sql`CREATE INDEX scheduled_prompts_due ON scheduled_prompts(status, eligible_at, next_run_at)`;
21+
yield* sql`CREATE INDEX scheduled_prompts_thread ON scheduled_prompts(thread_id, created_at)`;
22+
});

0 commit comments

Comments
 (0)