Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add creator-owned schedule subscriptions (#3566)

Colton Paddenbc101b508c2a
diff --git a/.changeset/calm-schedules-collect.md b/.changeset/calm-schedules-collect.md
new file mode 100644
index 000000000..85da90141
--- /dev/null
+++ b/.changeset/calm-schedules-collect.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Add experimental `defineDynamicSchedules` with direct operation tools, optional `preparePayload` creation preparation, top-level per-operation approval, and creator-bound execution. Create approval receives prepared data and rejects changed results before writing; `ctx.session.schedule` exposes scheduled-turn provenance without auth attributes.
diff --git a/e2e/fixtures/agent-workflow-tools/dynamic-skill-context-audit.ts b/e2e/fixtures/agent-workflow-tools/dynamic-skill-context-audit.ts
index 6062387f4..ccd3acfe3 100644
--- a/e2e/fixtures/agent-workflow-tools/dynamic-skill-context-audit.ts
+++ b/e2e/fixtures/agent-workflow-tools/dynamic-skill-context-audit.ts
@@ -8,6 +8,7 @@ function snapshot(ctx: DynamicResolveContext) {
session: {
id: ctx.session.id,
auth: ctx.session.auth,
+ schedule: ctx.session.schedule ?? null,
} satisfies Record<keyof DynamicResolveContext["session"], unknown>,
channel: {
kind: ctx.channel.kind ?? null,
diff --git a/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts
index e9311c270..3bb177aa1 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts
@@ -89,6 +89,7 @@ export default (["direct", "waiting"] as const).map((mode) =>
model: { id: "eve-mock/model" },
session: {
id: started.sessionId,
+ schedule: null,
auth: {
current: expectedAuth(last ? "bob" : "alice"),
initiator: expectedAuth("alice"),
diff --git a/packages/eve/extension-contracts/compatibility/channel/v51.ts b/packages/eve/extension-contracts/compatibility/channel/v51.ts
new file mode 100644
index 000000000..4a15cbd69
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v51.ts
@@ -0,0 +1,12 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+export default defineChannel({
+ routes: [POST("/report", async () => new Response("ok"))],
+ state: { reply: "" },
+ context: (state) => state,
+ events: {
+ "message.completed"({ message }, channel, ctx) {
+ channel.reply = `${ctx.session.id}: ${message}`;
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/connection/v40.ts b/packages/eve/extension-contracts/compatibility/connection/v40.ts
new file mode 100644
index 000000000..3728132ac
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v40.ts
@@ -0,0 +1,8 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+export default defineMcpClientConnection({
+ description: "Specialist tools.",
+ url: "https://specialist.example.test/eve/v1/mcp",
+ protocolVersionDiscovery: false,
+ approval: ({ session }) => (session.auth.current === null ? "denied" : "user-approval"),
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v33.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v33.ts
new file mode 100644
index 000000000..94a203bc4
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v33.ts
@@ -0,0 +1,8 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineInstructions({ markdown: `Review evidence for session ${ctx.session.id}.` }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v32.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v32.ts
new file mode 100644
index 000000000..ace1b41bc
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v32.ts
@@ -0,0 +1,11 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineSkill({
+ description: `Review evidence for session ${ctx.session.id}.`,
+ markdown: "Check claims against sources.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v72.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v72.ts
new file mode 100644
index 000000000..0afec7680
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v72.ts
@@ -0,0 +1,12 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineTool({
+ description: "Report the current session.",
+ inputSchema: { type: "object", properties: {} },
+ execute: () => ({ sessionId: ctx.session.id }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v38.ts b/packages/eve/extension-contracts/compatibility/hook/v38.ts
new file mode 100644
index 000000000..a224fb6ee
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v38.ts
@@ -0,0 +1,9 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "authorization.required": (event, ctx) => {
+ console.info("Sign-in required", { name: event.data.name, sessionId: ctx.session.id });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/state/v9.ts b/packages/eve/extension-contracts/compatibility/state/v9.ts
new file mode 100644
index 000000000..5c774760c
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/state/v9.ts
@@ -0,0 +1,7 @@
+import { defineState } from "#public/context/index.js";
+
+export const visits = defineState("compatibility.visits", () => ({ count: 0 }));
+export function recordVisit(): number {
+ visits.update((current) => ({ count: current.count + 1 }));
+ return visits.get().count;
+}
diff --git a/packages/eve/extension-contracts/compatibility/subagent/v30.ts b/packages/eve/extension-contracts/compatibility/subagent/v30.ts
new file mode 100644
index 000000000..baad189d4
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/subagent/v30.ts
@@ -0,0 +1,13 @@
+import { defineAgent, defineDynamic } from "#public/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ ctx.session.auth.current === null
+ ? null
+ : defineAgent({
+ description: "Investigate the authenticated request.",
+ model: "openai/gpt-5.6-sol",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v77.ts b/packages/eve/extension-contracts/compatibility/tool/v77.ts
new file mode 100644
index 000000000..fae115795
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v77.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Report the authenticated caller.",
+ inputSchema: z.object({}),
+ outputSchema: z.object({ principalId: z.string().nullable() }),
+ execute: (_input, ctx) => ({ principalId: ctx.session.auth.current?.principalId ?? null }),
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v52.json b/packages/eve/extension-contracts/reports/channel/v52.json
new file mode 100644
index 000000000..88bcd87d1
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v52.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 52,
+ "sha256": "19f4c3dd37fdbdfff6373a8f708cdc9cdd20fcf7f0fcd5edd88ec96fd6d9bba5",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v41.json b/packages/eve/extension-contracts/reports/connection/v41.json
new file mode 100644
index 000000000..446014e78
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v41.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 41,
+ "sha256": "ee2e387ccecb692eb6612b0822f0d10dfaf391117c2e64e75c1d87f3dae8682c",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v34.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v34.json
new file mode 100644
index 000000000..914dd0501
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v34.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 34,
+ "sha256": "21cc0a7ae2e731202e2700e37c5698a2ada60350a2ff7bfdd769ed1c22990c76",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v33.json b/packages/eve/extension-contracts/reports/dynamicSkill/v33.json
new file mode 100644
index 000000000..98d3f61aa
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v33.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 33,
+ "sha256": "4ae76610f88f4cc3991b43ed95d02ccc48514bed30e46762dcced6d50b5b34e2",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v73.json b/packages/eve/extension-contracts/reports/dynamicTool/v73.json
new file mode 100644
index 000000000..d944ae827
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v73.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 73,
+ "sha256": "227b9ace0970ceea5a7e0faf1004d9fd2262e3f1c3162da2c50de3619c3a4127",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v39.json b/packages/eve/extension-contracts/reports/hook/v39.json
new file mode 100644
index 000000000..ae413f90d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v39.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 39,
+ "sha256": "51308e82e2d4b8d19420e686b1966a12e9c20eb038814022552bf04b16d01f4b",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/state/v10.json b/packages/eve/extension-contracts/reports/state/v10.json
new file mode 100644
index 000000000..563311ea0
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/state/v10.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "state",
+ "epoch": 10,
+ "sha256": "065773df9c3dbc933180ab7a7bbcf7f94865107c183b5d14ba47c39209a6af36",
+ "exports": [
+ "Session",
+ "SessionAuth",
+ "SessionAuthContext",
+ "SessionContext",
+ "SessionParent",
+ "SessionTurn",
+ "defineState"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/subagent/v31.json b/packages/eve/extension-contracts/reports/subagent/v31.json
new file mode 100644
index 000000000..8286d7ca9
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/subagent/v31.json
@@ -0,0 +1,23 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "subagent",
+ "epoch": 31,
+ "sha256": "5daeb6cea48ce3e5a2db1f965f33606663e18ada9be4a50ae428a6b75fd44c3f",
+ "exports": [
+ "AgentCompactionDefinition",
+ "AgentDefinition",
+ "AgentModelDefinition",
+ "AgentStaticModelDefinition",
+ "DefinedAgent",
+ "DynamicLocalSubagentDefinition",
+ "DynamicSubagentDefinition",
+ "RemoteAgentDefinition",
+ "RemoteAgentDefinitionInput",
+ "WorkspaceAgentDefinition",
+ "WorkspaceAgentTransport",
+ "defineAgent",
+ "defineDynamic",
+ "defineRemoteAgent",
+ "defineWorkspaceAgent"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v78.json b/packages/eve/extension-contracts/reports/tool/v78.json
new file mode 100644
index 000000000..552dbba14
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v78.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 78,
+ "sha256": "f6875930ec12deecce460acbffd42b08ac2d9e0115f75088e00cac04dcdc4e63",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 661b1e926..d6835807b 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -424,6 +424,18 @@
"import": "./dist/src/public/server/index.js",
"default": "./dist/src/public/server/index.js"
},
+ "./experimental/schedules/testing": {
+ "eve-source": "./src/public/experimental/schedules/testing.ts",
+ "types": "./dist/src/public/experimental/schedules/testing.d.ts",
+ "import": "./dist/src/public/experimental/schedules/testing.js",
+ "default": "./dist/src/public/experimental/schedules/testing.js"
+ },
+ "./experimental/schedules": {
+ "eve-source": "./src/public/experimental/schedules/index.ts",
+ "types": "./dist/src/public/experimental/schedules/index.d.ts",
+ "import": "./dist/src/public/experimental/schedules/index.js",
+ "default": "./dist/src/public/experimental/schedules/index.js"
+ },
"./channels": {
"types": "./dist/src/public/channels/index.d.ts",
"import": "./dist/src/public/channels/index.js",
diff --git a/packages/eve/src/channel/schedule.ts b/packages/eve/src/channel/schedule.ts
index 70e15407f..9875aa0ad 100644
--- a/packages/eve/src/channel/schedule.ts
+++ b/packages/eve/src/channel/schedule.ts
@@ -1,16 +1,27 @@
+import { randomUUID } from "node:crypto";
+import { scheduleDisplayName } from "#runtime/schedules/record.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";
import { createCrossChannelToFn, toCrossChannelTargets } from "#channel/cross-channel-receive.js";
import { createSession, type Session } from "#channel/session.js";
import type { Runtime } from "#channel/types.js";
import { ContextContainer, contextStorage } from "#context/container.js";
-import { ScheduleIdKey } from "#context/keys.js";
+import { AuthKey, OccurrenceIdKey, ScheduleIdKey, ScheduleInstanceKey } from "#context/keys.js";
import { expectFunction } from "#internal/authored-module.js";
import type {
ScheduleDefinition,
ScheduleHandlerArgs,
ScheduleRunHandler,
} from "#public/definitions/schedule.js";
+import type {
+ DynamicSchedulesDefinition,
+ ScheduleOccurrenceIdentity,
+} from "#public/schedules/subscription.js";
+import {
+ parseSchedulePayload,
+ validateSchedulePayload,
+ type ScheduleCollectionPayload,
+} from "#runtime/schedules/payload.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
export { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";
@@ -28,16 +39,27 @@ export const SCHEDULE_ADAPTER_KIND = "schedule";
export const SCHEDULE_ADAPTER: ChannelAdapter = {
kind: SCHEDULE_ADAPTER_KIND,
};
-
/**
* Loaded shape of one schedule for the dispatcher. Either `run` is
* defined (authored handler) or `markdown` is defined (fire-and-forget).
*/
-interface ScheduleDispatchInput {
+export interface ScheduleDispatchInput {
readonly scheduleId: string;
readonly run?: ScheduleRunHandler;
readonly markdown?: string;
}
+/** Sessions started by dispatch and background work registered by the handler. */
+export interface ScheduleDispatchResult {
+ readonly sessions: readonly Session[];
+ readonly waitUntilTasks: readonly Promise<unknown>[];
+}
+export interface ScheduleCollectionDispatchInput {
+ readonly collectionId: string;
+ readonly definition: DynamicSchedulesDefinition<any, any, any>;
+ readonly payload: ScheduleCollectionPayload<unknown>;
+ readonly occurrence: ScheduleOccurrenceIdentity;
+ readonly verifyDelivery?: () => Promise<void>;
+}
/**
* Dispatches scheduled task execution.
@@ -54,17 +76,13 @@ interface ScheduleDispatchInput {
*
* Returns a {@link ScheduleDispatchResult} carrying any sessions the
* handler started (for telemetry / task-result observability) and the
- * `waitUntil` promises the handler registered.
+ * `waitUntil` promises the handler registered. Subscription callbacks resolve
+ * creator auth and await their registered work before returning; their channel
+ * sends start fresh, unattended sessions rather than resume a conversation.
*/
-interface ScheduleDispatchResult {
- readonly sessions: readonly Session[];
- readonly waitUntilTasks: readonly Promise<unknown>[];
-}
-
export class ScheduleDispatcher {
private readonly runtime: Runtime;
private readonly channels: readonly ResolvedChannelDefinition[];
-
constructor(config: {
readonly runtime: Runtime;
readonly channels: readonly ResolvedChannelDefinition[];
@@ -79,42 +97,122 @@ export class ScheduleDispatcher {
return await contextStorage.run(scope, () => this.triggerInScope(input));
}
- private async triggerInScope(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult> {
- const sessions: Session[] = [];
- const waitUntilTasks: Promise<unknown>[] = [];
- const toChannel = createCrossChannelToFn(this.runtime, toCrossChannelTargets(this.channels));
-
- const args: ScheduleHandlerArgs = {
- appAuth: SCHEDULE_APP_AUTH,
- to(channel, target) {
- const destination = toChannel(channel, target);
- return {
- async send(message, options) {
- const session = await destination.send(message, options);
- sessions.push(session);
- return session;
- },
- };
- },
- waitUntil(task) {
- waitUntilTasks.push(task);
- },
+ async triggerCollection(input: ScheduleCollectionDispatchInput): Promise<ScheduleDispatchResult> {
+ const parsed = parseSchedulePayload<unknown>(input.payload, {
+ application: input.payload.eve.application,
+ collection: input.collectionId,
+ });
+ const { envelope } = parsed;
+ const { definition } = input;
+ const occurrence = {
+ ...input.occurrence,
+ displayName: scheduleDisplayName(input.occurrence.name),
};
+ const payload =
+ definition.preparePayload === undefined
+ ? await validateSchedulePayload(definition.inputSchema, envelope.payload)
+ : envelope.payload;
+ await input.verifyDelivery?.();
+ const resolvedAuth = await definition.auth({
+ principal: envelope.principal,
+ payload,
+ occurrence,
+ });
+ if (resolvedAuth === null) throw new Error("Scheduled execution is no longer authorized.");
+ if (
+ resolvedAuth.principalId !== envelope.principal.principalId ||
+ resolvedAuth.principalType !== envelope.principal.type ||
+ resolvedAuth.authenticator !== envelope.principal.authenticator ||
+ resolvedAuth.issuer !== envelope.principal.issuer ||
+ resolvedAuth.subject !== envelope.principal.subject
+ )
+ throw new Error("Scheduled execution auth must resolve the schedule creator.");
+ const auth = resolvedAuth;
+ const scope = new ContextContainer();
+ scope.set(ScheduleIdKey, input.collectionId);
+ scope.set(AuthKey, auth);
+ scope.set(OccurrenceIdKey, occurrence.executionId);
+ scope.set(ScheduleInstanceKey, occurrence.name);
+ return await contextStorage.run(scope, async () => {
+ const runtime: Runtime = {
+ ...this.runtime,
+ // A scheduled send must not steer an existing conversation or inherit interactive input.
+ resolveContinuation: async () => undefined,
+ dispatchContinuation: async <TCommand extends import("#channel/types.js").SessionCommand>(
+ delivery: import("#channel/types.js").DispatchContinuationInput<TCommand>,
+ ) => {
+ if (delivery.command.kind !== "send")
+ throw new Error("Scheduled channel receive can only start a fresh session.");
+ return {
+ status: "session_not_active",
+ } as import("#channel/types.js").SessionCommandResult<TCommand>;
+ },
+ createSession: async (run) =>
+ await this.runtime.createSession({
+ ...run,
+ auth,
+ initiatorAuth: auth,
+ capabilities: { requestInput: false },
+ continuationToken: `eve-scheduled-send:${randomUUID()}`,
+ continuationConflictCommand: undefined,
+ }),
+ };
+ const { args, sessions, waitUntilTasks } = this.createHandlerContext(runtime);
+ await definition.run({
+ payload,
+ occurrence,
+ auth,
+ to: (channel, target) => ({
+ send: (message) => args.to(channel, target).send(message, { auth }),
+ }),
+ waitUntil: args.waitUntil,
+ });
+ await Promise.all(waitUntilTasks);
+ return { sessions, waitUntilTasks };
+ });
+ }
- if (input.run) {
- await input.run(args);
- } else if (input.markdown !== undefined) {
- const session = await this.runMarkdown(input.markdown);
- sessions.push(session);
- } else {
+ private async triggerInScope(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult> {
+ const { args, sessions, waitUntilTasks } = this.createHandlerContext();
+ if (input.run) await input.run(args);
+ else if (input.markdown !== undefined) sessions.push(await this.runMarkdown(input.markdown));
+ else
throw new Error(
`Schedule "${input.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`,
);
- }
-
return { sessions, waitUntilTasks };
}
+ private createHandlerContext(runtime = this.runtime): {
+ args: ScheduleHandlerArgs;
+ sessions: Session[];
+ waitUntilTasks: Promise<unknown>[];
+ } {
+ const sessions: Session[] = [];
+ const waitUntilTasks: Promise<unknown>[] = [];
+ const toChannel = createCrossChannelToFn(runtime, toCrossChannelTargets(this.channels));
+ return {
+ args: {
+ appAuth: SCHEDULE_APP_AUTH,
+ to(channel, target) {
+ const destination = toChannel(channel, target);
+ return {
+ async send(message, options) {
+ const session = await destination.send(message, options);
+ sessions.push(session);
+ return session;
+ },
+ };
+ },
+ waitUntil(task) {
+ waitUntilTasks.push(task);
+ },
+ },
+ sessions,
+ waitUntilTasks,
+ };
+ }
+
private async runMarkdown(markdown: string): Promise<Session> {
const handle = await this.runtime.createSession({
adapter: SCHEDULE_ADAPTER,
@@ -136,11 +234,10 @@ export function expectScheduleRun(
exportName: string | undefined,
): ScheduleRunHandler {
const definition = value as ScheduleDefinition;
- if (definition === null || typeof definition !== "object") {
+ if (definition === null || typeof definition !== "object")
throw new Error(
`Schedule export "${exportName ?? "default"}" from "${logicalPath}" must be an object.`,
);
- }
return expectFunction(
definition.run,
`Expected the schedule export "${exportName ?? "default"}" from "${logicalPath}" to export a \`run\` handler function.`,
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 8159f1c40..b9384d49b 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -191,6 +191,7 @@ export type SessionCommand =
/** Initial workflow title when delivering to a prewarmed session. */
readonly title?: string;
readonly kind: "send";
+ readonly schedule?: import("#context/session-schedule.js").SessionSchedule;
readonly payload: DeliverPayload;
readonly delivery?: ChannelDeliveryMetadata;
readonly requestId?: string;
@@ -249,6 +250,7 @@ export interface DispatchSessionInput<TCommand extends SessionCommand = SessionC
* metadata so both cross the durable hook boundary outside adapter-owned data.
*/
export interface DeliverHookPayload {
+ readonly schedule?: import("#context/session-schedule.js").SessionSchedule;
/** Initial workflow title; ignored once session initialization has run. */
readonly title?: string;
readonly auth?: SessionAuthContext | null;
@@ -424,6 +426,8 @@ export interface SessionCapabilities {
* subagent tool wrapper).
*/
export interface RunInput {
+ /** Server-supplied provenance inherited by locally delegated scheduled work. */
+ readonly schedule?: import("#context/session-schedule.js").SessionSchedule;
readonly adapter: ChannelAdapter<any>;
/**
* Registered channel name for root sessions started from an authored
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 6baadb041..3ef2df526 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 77,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77],
+ current: 78,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
15: "TaskExec replaces stageEffect with send",
@@ -84,10 +84,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 72,
+ current: 73,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
- 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72,
+ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -127,10 +127,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 51,
+ current: 52,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, 47, 48, 49, 50, 51,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -163,8 +163,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
subagent: {
- current: 30,
- supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23, 24, 25, 26, 27, 28, 29, 30],
+ current: 31,
+ supported: [
+ 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+ ],
dropped: {
1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",
2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",
@@ -177,10 +179,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 40,
+ current: 41,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,
- 35, 36, 37, 38, 39, 40,
+ 35, 36, 37, 38, 39, 40, 41,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
@@ -195,8 +197,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
hook: {
- current: 38,
- supported: [20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38],
+ current: 39,
+ supported: [20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
2: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -226,10 +228,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
skill: { current: 2, supported: [1, 2], dropped: {} },
dynamicSkill: {
- current: 32,
+ current: 33,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 25, 26, 27, 28, 29, 30,
- 31, 32,
+ 31, 32, 33,
],
dropped: {
13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -240,10 +242,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
instructions: { current: 2, supported: [1, 2], dropped: {} },
dynamicInstructions: {
- current: 33,
+ current: 34,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 26, 27, 28, 29, 30,
- 31, 32, 33,
+ 31, 32, 33, 34,
],
dropped: {
14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -254,8 +256,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
config: { current: 1, supported: [1], dropped: {} },
state: {
- current: 9,
- supported: [1, 2, 3, 4, 5, 7, 9],
+ current: 10,
+ supported: [1, 2, 3, 4, 5, 7, 9, 10],
dropped: {
6: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",
8: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 1cdb6c669..055621876 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -196,6 +196,9 @@ export type CompiledSkillDefinition = NamedSkillDefinition &
* Normalized authored schedule preserved in the compiled manifest.
*/
export type CompiledScheduleDefinition = z.infer<typeof compiledScheduleDefinitionSchema>;
+export type CompiledScheduleCollectionDefinition = z.infer<
+ typeof compiledScheduleCollectionDefinitionSchema
+>;
/**
* Normalized authored sandbox metadata preserved in the compiled manifest.
@@ -744,6 +747,18 @@ const compiledScheduleDefinitionSchema = z.discriminatedUnion("sourceKind", [
.strict(),
]);
+const compiledScheduleCollectionDefinitionSchema = z
+ .object({
+ description: z.string().optional(),
+ logicalPath: z.string(),
+ name: z.string(),
+ providerKind: z.string(),
+ sourceId: z.string(),
+ sourceKind: z.literal("module"),
+ tools: z.boolean().optional(),
+ })
+ .strict();
+
const compiledSandboxDefinitionSchema = z
.object({
/** Stable provider name from the exported environment. */
@@ -982,6 +997,7 @@ const compiledAgentResourceFields = {
sandbox: compiledSandboxDefinitionSchema,
sandboxWorkspaces: z.array(compiledSandboxWorkspaceSchema),
schedules: z.array(compiledScheduleDefinitionSchema),
+ scheduleCollections: z.array(compiledScheduleCollectionDefinitionSchema).default([]),
remoteAgents: z.array(compiledRemoteAgentNodeSchema),
skills: z.array(compiledSkillSourceSchema).readonly(),
instructions: z.array(compiledInstructionsSchema).readonly().default([]),
@@ -1090,6 +1106,7 @@ export const compiledAgentManifestSchema = z
sandbox: compiledSandboxDefinitionSchema,
sandboxWorkspaces: z.array(compiledSandboxWorkspaceSchema),
schedules: z.array(compiledScheduleDefinitionSchema),
+ scheduleCollections: z.array(compiledScheduleCollectionDefinitionSchema).default([]),
skills: z.array(compiledSkillSourceSchema).readonly(),
subagents: z.array(compiledSubagentNodeSchema),
instructions: z.array(compiledInstructionsSchema).readonly().default([]),
@@ -1118,6 +1135,7 @@ export interface CreateCompiledAgentResourcesInput {
readonly sandbox: CompiledSandboxDefinition;
readonly sandboxWorkspaces?: readonly CompiledSandboxWorkspace[];
readonly schedules?: readonly CompiledScheduleDefinition[];
+ readonly scheduleCollections?: readonly CompiledScheduleCollectionDefinition[];
readonly skills?: readonly CompiledSkillDefinition[];
readonly instructions?: readonly CompiledInstructionsDefinition[];
readonly tools?: readonly CompiledToolDefinition[];
@@ -1157,6 +1175,7 @@ export function createCompiledAgentResources(
sandbox: input.sandbox,
sandboxWorkspaces: [...(input.sandboxWorkspaces ?? [])],
schedules: [...(input.schedules ?? [])],
+ scheduleCollections: [...(input.scheduleCollections ?? [])],
skills: [...(input.skills ?? [])],
tools: [...(input.tools ?? [])],
workspaceResourceRoot: input.workspaceResourceRoot ?? {
@@ -1300,6 +1319,7 @@ export function createCompiledAgentManifest(input: {
readonly sandbox: CompiledSandboxDefinition;
readonly sandboxWorkspaces?: readonly CompiledSandboxWorkspace[];
readonly schedules?: readonly CompiledScheduleDefinition[];
+ readonly scheduleCollections?: readonly CompiledScheduleCollectionDefinition[];
readonly skills?: readonly CompiledSkillDefinition[];
readonly subagents?: readonly CompiledSubagentNode[];
readonly instructions?: readonly CompiledInstructionsDefinition[];
diff --git a/packages/eve/src/compiler/memory-wrapper-candidates.ts b/packages/eve/src/compiler/memory-wrapper-candidates.ts
new file mode 100644
index 000000000..267c05bb7
--- /dev/null
+++ b/packages/eve/src/compiler/memory-wrapper-candidates.ts
@@ -0,0 +1,33 @@
+import { deriveMemorySlot } from "#compiler/normalize-memory.js";
+import {
+ canonicalSourceSlot,
+ instantiateProgrammaticTemplate,
+ type AgentModuleCandidate,
+ type AgentSourceCandidate,
+} from "#compiler/source-graph.js";
+import { memoryWrapperTemplate } from "#framework/sources/registry.js";
+
+export function createMemoryWrapperCandidates(candidates: readonly AgentSourceCandidate[]) {
+ return candidates
+ .filter(
+ (candidate): candidate is AgentModuleCandidate =>
+ candidate.backing.kind !== "resource" &&
+ (canonicalSourceSlot(candidate.logicalPath) === "memory" ||
+ canonicalSourceSlot(candidate.logicalPath).startsWith("memory/")),
+ )
+ .map((candidate) => {
+ const slot = deriveMemorySlot(candidate.logicalPath);
+ return instantiateProgrammaticTemplate({
+ anchor: candidate,
+ dependencies: { memory: candidate },
+ logicalPath: `tools/${slot}.ts`,
+ owner: { feature: "memory", kind: "framework" },
+ parameters: {
+ memoryExportName: candidate.exportName ?? "default",
+ memoryLogicalPath: candidate.logicalPath,
+ slot,
+ },
+ template: memoryWrapperTemplate,
+ });
+ });
+}
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index fef4af341..05b61f270 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -525,7 +525,7 @@ describe("compileAgentManifest source graph", () => {
"instructions/dynamic.ts": { compile: true, runtimeEntry: true },
"instructions/static.ts": { compile: true, runtimeEntry: false },
"schedules/handler.ts": { compile: true, runtimeEntry: true },
- "schedules/prompt.ts": { compile: true, runtimeEntry: false },
+ "schedules/prompt.ts": { compile: true, runtimeEntry: true },
"skills/dynamic.ts": { compile: true, runtimeEntry: true },
"skills/static.ts": { compile: true, runtimeEntry: false },
"tools/dynamic.ts": { compile: true, runtimeEntry: true },
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index 35f0e242c..a3d7a4fab 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -20,6 +20,7 @@ import {
type CompiledHookDefinition,
type CompiledRemoteAgentNode,
type CompiledSkillDefinition,
+ type CompiledScheduleCollectionDefinition,
type CompiledScheduleDefinition,
type CompiledSandboxDefinition,
type CompiledSubagentNode,
@@ -41,14 +42,21 @@ import {
assertFrameworkToolPolicy,
canDisableToolWithoutSelectedSource,
} from "#compiler/default-tool-policy.js";
-import type { ManifestCompileContext } from "#compiler/normalize-helpers.js";
+import {
+ loadModuleBackedDefinition,
+ type ManifestCompileContext,
+} from "#compiler/normalize-helpers.js";
import { resolveWorkspaceSubagentDefinition } from "#compiler/resolve-workspace-subagent.js";
import { workspaceSubagentName } from "#public/definitions/workspace-agent.js";
import { compileHookEntry } from "#compiler/normalize-hook.js";
import { compileInstructionsEntry } from "#compiler/normalize-instructions.js";
-import { compileMemoryDefinition, deriveMemorySlot } from "#compiler/normalize-memory.js";
+import { compileMemoryDefinition } from "#compiler/normalize-memory.js";
+import { createMemoryWrapperCandidates } from "#compiler/memory-wrapper-candidates.js";
import { compileSandboxDefinition } from "#compiler/normalize-sandbox.js";
import { compileScheduleDefinition } from "#compiler/normalize-schedule.js";
+import { compileScheduleCollectionDefinition } from "#compiler/normalize-schedule-collection.js";
+import { isScheduleCollectionDefinition } from "#shared/schedule-collection-definition.js";
+import { createScheduleCollectionWrapperCandidates } from "#compiler/schedule-collection-wrapper-candidates.js";
import { compileSkillSource } from "#compiler/normalize-skill.js";
import {
assertRemoteAgentDefinitionHasNoLocalPackageEntries,
@@ -85,17 +93,12 @@ import {
createAgentModuleBinding,
createProgrammaticModuleCandidates,
disableComposedCandidate,
- instantiateProgrammaticTemplate,
isAgentModuleCandidate,
type AgentModuleCandidate,
type AgentSourceCandidate,
type AgentSourceRegistry,
- canonicalSourceSlot,
} from "#compiler/source-graph.js";
-import {
- frameworkAgentSourceRegistry,
- memoryWrapperTemplate,
-} from "#framework/sources/registry.js";
+import { frameworkAgentSourceRegistry } from "#framework/sources/registry.js";
import {
noDevelopmentExtensions,
prepareDevelopmentExtensions,
@@ -390,33 +393,15 @@ class AgentGraphCompiler {
(framework ? frameworkCandidates : applicationCandidates).push(...candidates);
}
}
- const memoryWrapperCandidates = [...projected.candidates, ...applicationCandidates]
- .filter(
- (candidate): candidate is AgentModuleCandidate =>
- candidate.backing.kind !== "resource" &&
- (canonicalSourceSlot(candidate.logicalPath) === "memory" ||
- canonicalSourceSlot(candidate.logicalPath).startsWith("memory/")),
- )
- .map((candidate) => {
- const slot = deriveMemorySlot(candidate.logicalPath);
- return instantiateProgrammaticTemplate({
- anchor: candidate,
- dependencies: { memory: candidate },
- logicalPath: `tools/${slot}.ts`,
- owner: { feature: "memory", kind: "framework" },
- parameters: {
- memoryExportName: candidate.exportName ?? "default",
- memoryLogicalPath: candidate.logicalPath,
- slot,
- },
- template: memoryWrapperTemplate,
- });
- });
const orderedCandidates: AgentSourceCandidate[] = [
...frameworkCandidates,
...(input.developmentExtensionCandidates ?? []),
...projected.candidates,
- ...memoryWrapperCandidates,
+ ...createMemoryWrapperCandidates([...projected.candidates, ...applicationCandidates]),
+ ...createScheduleCollectionWrapperCandidates(
+ [...projected.candidates, ...applicationCandidates],
+ input.manifest.agentId,
+ ),
...applicationCandidates,
];
const composed = composeAgentModuleCandidates(orderedCandidates);
@@ -477,6 +462,7 @@ class AgentGraphCompiler {
const memories: CompiledMemoryDefinition[] = [];
const hooks: CompiledHookDefinition[] = [];
const schedules: CompiledScheduleDefinition[] = [];
+ const scheduleCollections: CompiledScheduleCollectionDefinition[] = [];
const channels: CompiledChannelDefinition[] = [];
let sandbox: CompiledSandboxDefinition | undefined;
const selectedSourceIds = collectSelectedSourceIds(state.composed);
@@ -561,10 +547,25 @@ class AgentGraphCompiler {
}
break;
case "schedule": {
- const schedule = await compileScheduleDefinition(
+ const value =
+ entry.source.sourceKind === "module"
+ ? await loadModuleBackedDefinition({
+ binding: binding!,
+ loadNamespace,
+ kind: "schedule",
+ source: entry.source,
+ })
+ : entry.source.definition;
+ if (isScheduleCollectionDefinition(value)) {
+ scheduleCollections.push(compileScheduleCollectionDefinition(entry.source, value));
+ state.evaluation.requireRuntimeEntry(candidate.sourceId);
+ break;
+ }
+ const schedule = compileScheduleDefinition(
input.manifest.agentRoot,
entry.source,
- options,
+ value,
+ options.owner,
);
schedules.push(schedule);
if (schedule.sourceKind === "module" && schedule.hasRun) {
@@ -650,6 +651,7 @@ class AgentGraphCompiler {
sourcePath: workspace.sourcePath,
})),
schedules,
+ scheduleCollections,
skills,
sourceComposition: state.composed.composition,
tools,
diff --git a/packages/eve/src/compiler/normalize-schedule-collection.ts b/packages/eve/src/compiler/normalize-schedule-collection.ts
new file mode 100644
index 000000000..cd3dc7ab9
--- /dev/null
+++ b/packages/eve/src/compiler/normalize-schedule-collection.ts
@@ -0,0 +1,28 @@
+import type { CompiledScheduleCollectionDefinition } from "#compiler/manifest.js";
+import { stripLogicalPathExtension } from "#discover/filesystem.js";
+import type { ScheduleSourceRef } from "#discover/manifest.js";
+import { normalizeScheduleCollectionDefinition } from "#internal/authored-definition/schedule-collection.js";
+
+export function compileScheduleCollectionDefinition(
+ source: ScheduleSourceRef,
+ value: unknown,
+): CompiledScheduleCollectionDefinition {
+ if (source.sourceKind !== "module") {
+ throw new Error(`Schedule collections must be authored as modules: "${source.logicalPath}".`);
+ }
+ const definition = normalizeScheduleCollectionDefinition(
+ value,
+ `Expected the schedule collection export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
+ );
+
+ const compiled: CompiledScheduleCollectionDefinition = {
+ logicalPath: source.logicalPath,
+ name: stripLogicalPathExtension(source.logicalPath).replace(/^schedules\//u, ""),
+ providerKind: definition.provider.kind,
+ sourceId: source.sourceId,
+ sourceKind: "module",
+ };
+ if (definition.description !== undefined) compiled.description = definition.description;
+ if (definition.tool !== undefined) compiled.tools = definition.tool;
+ return compiled;
+}
diff --git a/packages/eve/src/compiler/normalize-schedule.ts b/packages/eve/src/compiler/normalize-schedule.ts
index 6542bbedd..877da239a 100644
--- a/packages/eve/src/compiler/normalize-schedule.ts
+++ b/packages/eve/src/compiler/normalize-schedule.ts
@@ -5,11 +5,7 @@ import type { ScheduleDefinition } from "#public/definitions/schedule.js";
import type { CompiledScheduleDefinition } from "#compiler/manifest.js";
import { readWorkflowFunctionId } from "#internal/workflow/reference.js";
import { workflowCallbackErrorMessage } from "#shared/workflow-tool-context.js";
-import {
- loadModuleBackedDefinition,
- requireModuleBackedDefinitionLoadOptions,
- type SourceDefinitionCompileOptions,
-} from "#compiler/normalize-helpers.js";
+import type { AgentSourceOwner } from "#compiler/source-graph.js";
/**
* Compiles one authored schedule into the normalized shape consumed by
@@ -22,25 +18,18 @@ import {
* path under `schedules/` minus the extension
* (`schedules/billing/invoice-sweep.ts` → `"billing/invoice-sweep"`).
*/
-export async function compileScheduleDefinition(
+export function compileScheduleDefinition(
_agentRoot: string,
source: ScheduleSourceRef,
- options: SourceDefinitionCompileOptions,
-): Promise<CompiledScheduleDefinition> {
- const definition: ScheduleDefinition =
+ value: unknown,
+ owner: AgentSourceOwner,
+): CompiledScheduleDefinition {
+ const definition: ScheduleDefinition = normalizeScheduleDefinition(
+ value,
source.sourceKind === "markdown"
- ? normalizeScheduleDefinition(
- source.definition,
- `Expected the compiled schedule definition at "${source.logicalPath}" to match the public eve shape.`,
- )
- : normalizeScheduleDefinition(
- await loadModuleBackedDefinition({
- ...requireModuleBackedDefinitionLoadOptions(options, source.logicalPath),
- kind: "schedule",
- source,
- }),
- `Expected the schedule export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
- );
+ ? `Expected the compiled schedule definition at "${source.logicalPath}" to match the public eve shape.`
+ : `Expected the schedule export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
+ );
if (readWorkflowFunctionId(definition.run) !== undefined) {
throw new Error(`${source.logicalPath}: ${workflowCallbackErrorMessage("schedule")}`);
@@ -62,7 +51,7 @@ export async function compileScheduleDefinition(
return source.sourceKind === "module"
? { ...withMarkdown, sourceKind: "module" }
- : { ...withMarkdown, owner: options.owner, sourceKind: "markdown" };
+ : { ...withMarkdown, owner, sourceKind: "markdown" };
}
function deriveScheduleName(logicalPath: string): string {
diff --git a/packages/eve/src/compiler/schedule-collection-wrapper-candidates.ts b/packages/eve/src/compiler/schedule-collection-wrapper-candidates.ts
new file mode 100644
index 000000000..056f8be0d
--- /dev/null
+++ b/packages/eve/src/compiler/schedule-collection-wrapper-candidates.ts
@@ -0,0 +1,39 @@
+import {
+ canonicalSourceSlot,
+ instantiateProgrammaticTemplate,
+ type AgentModuleCandidate,
+ type AgentSourceCandidate,
+} from "#compiler/source-graph.js";
+import { stripLogicalPathExtension } from "#discover/filesystem.js";
+import { scheduleCollectionWrapperTemplate } from "#framework/sources/registry.js";
+import { scheduleCollectionToolPrefix } from "#shared/schedule-collection-tools.js";
+
+export function createScheduleCollectionWrapperCandidates(
+ candidates: readonly AgentSourceCandidate[],
+ application: string,
+) {
+ return candidates
+ .filter(
+ (candidate): candidate is AgentModuleCandidate =>
+ candidate.backing.kind !== "resource" &&
+ canonicalSourceSlot(candidate.logicalPath).startsWith("schedules/"),
+ )
+ .map((candidate) => {
+ const collection = stripLogicalPathExtension(candidate.logicalPath).slice(
+ "schedules/".length,
+ );
+ return instantiateProgrammaticTemplate({
+ anchor: candidate,
+ dependencies: { collection: candidate },
+ logicalPath: `tools/${scheduleCollectionToolPrefix(collection)}.ts`,
+ owner: { feature: "schedule-collection", kind: "framework" },
+ parameters: {
+ application,
+ collection,
+ collectionExportName: candidate.exportName ?? "default",
+ collectionLogicalPath: candidate.logicalPath,
+ },
+ template: scheduleCollectionWrapperTemplate,
+ });
+ });
+}
diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.ts
index 0e408f08a..6b4f63151 100644
--- a/packages/eve/src/compiler/validate-artifact.ts
+++ b/packages/eve/src/compiler/validate-artifact.ts
@@ -185,6 +185,13 @@ export function validateCompiledAgentResources(
node.schedules.map((entry) => ({ identity: entry.name, kind: "schedule" })),
"schedule name",
);
+ validateUniqueIdentities(
+ node.scheduleCollections.map((entry) => ({
+ identity: entry.name,
+ kind: "schedule collection",
+ })),
+ "schedule collection name",
+ );
const referencedModuleSources = collectReferencedModuleSources(node);
for (const source of options.additionalModuleSources ?? []) {
referencedModuleSources.set(source.sourceId, { logicalPath: source.logicalPath });
@@ -350,6 +357,7 @@ function collectReferencedModuleSources(
for (const value of node.instructions) if (value.sourceKind === "module") add(value);
for (const value of node.skills) if (value.sourceKind === "module") add(value);
for (const value of node.schedules) if (value.sourceKind === "module") add(value);
+ for (const value of node.scheduleCollections) add(value);
add(node.sandbox);
for (const mount of node.extensionMounts) {
add({ logicalPath: mount.mountLogicalPath, sourceId: mount.mountSourceId });
diff --git a/packages/eve/src/context/build-callback-context.ts b/packages/eve/src/context/build-callback-context.ts
index 1d138ba63..2bdd3167f 100644
--- a/packages/eve/src/context/build-callback-context.ts
+++ b/packages/eve/src/context/build-callback-context.ts
@@ -1,6 +1,7 @@
import type { SessionContext } from "#context/session-context.js";
import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js";
import type { RuntimeSandboxSession, SandboxSession } from "#shared/sandbox-session.js";
+import { readSessionSchedule } from "#context/session-schedule.js";
import { loadContext } from "#context/container.js";
import { DynamicSkillSandboxKey, SandboxKey, SessionKey } from "#context/keys.js";
@@ -20,6 +21,7 @@ export function buildCallbackContext(): SessionContext {
auth: session.auth,
turn: session.turn,
parent: session.parent,
+ schedule: readSessionSchedule(ctx),
},
getSandbox(environment?: SandboxEnvironmentIdentity): Promise<RuntimeSandboxSession> {
diff --git a/packages/eve/src/context/dynamic-resolve-context.ts b/packages/eve/src/context/dynamic-resolve-context.ts
index aecb1acbd..7bdb649ab 100644
--- a/packages/eve/src/context/dynamic-resolve-context.ts
+++ b/packages/eve/src/context/dynamic-resolve-context.ts
@@ -12,6 +12,7 @@ import {
} from "#context/keys.js";
import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getAdapterKind } from "#channel/adapter.js";
+import { readSessionSchedule } from "#context/session-schedule.js";
import { ConversationContextKey } from "#shared/conversation-context.js";
type ReadableContext = Pick<AlsContext, "get">;
@@ -38,6 +39,7 @@ export function buildResolveContext(
model: effectiveModel === null ? null : { id: effectiveModel.reference.id },
session: {
id: sessionId,
+ schedule: readSessionSchedule(ctx),
auth: {
current: currentAuth,
initiator: initiatorAuth,
diff --git a/packages/eve/src/context/key-names.ts b/packages/eve/src/context/key-names.ts
index 512c237a5..a54e1f77a 100644
--- a/packages/eve/src/context/key-names.ts
+++ b/packages/eve/src/context/key-names.ts
@@ -9,5 +9,6 @@
* silently drift apart.
*/
+export const BUNDLE_CONTEXT_KEY_NAME = "eve.bundle";
export const CHANNEL_CONTEXT_KEY_NAME = "eve.channel";
export const SESSION_CALLBACK_CONTEXT_KEY_NAME = "eve.sessionCallback";
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 2266fb0f1..01e8d47b0 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -101,8 +101,10 @@ export interface LocalDevRequestProvenance {
export const LocalDevRequestKey = new ContextKey<LocalDevRequestProvenance>(
"eve.internal.localDevRequest",
);
+export const OccurrenceIdKey = new ContextKey<string>("eve.scheduleOccurrenceId");
/** Authored schedule whose dispatch created this session. */
export const ScheduleIdKey = new ContextKey<string>("eve.scheduleId");
+export const ScheduleInstanceKey = new ContextKey<string>("eve.scheduleInstance");
/** Display title derived from the session's initial input. */
export const SessionTitleKey = new ContextKey<string>("eve.sessionTitle");
export const ChannelDeliveryKey = new ContextKey<ChannelDeliveryMetadata>("eve.channelDelivery");
diff --git a/packages/eve/src/context/schedule-collection-tools.ts b/packages/eve/src/context/schedule-collection-tools.ts
new file mode 100644
index 000000000..4abdac582
--- /dev/null
+++ b/packages/eve/src/context/schedule-collection-tools.ts
@@ -0,0 +1,311 @@
+import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
+import { z } from "#compiled/zod/index.js";
+import { isDeepStrictEqual } from "node:util";
+import type {
+ ApprovalContext,
+ ApprovalPolicy,
+ ApprovalResponsePolicy,
+} from "#approval/definition.js";
+import { loadContext, contextStorage } from "#context/container.js";
+import { ContextKey } from "#context/key.js";
+import { readSessionSchedule } from "#context/session-schedule.js";
+import { defineDynamic } from "#dynamic/definition.js";
+import { isApprovalRecheck } from "#harness/approval-recheck.js";
+import { markDynamicCallbackRebind } from "#internal/dynamic-tool-rebind.js";
+import { bindScheduleCollection, schedules } from "#public/experimental/schedules/client.js";
+import type {
+ ScheduleOperation,
+ DynamicSchedulesDefinition,
+} from "#public/schedules/subscription.js";
+import {
+ assertScheduleManagementAllowed,
+ type PreparedScheduleCreate,
+} from "#runtime/schedules/collection-client.js";
+import { scheduleDisplayName } from "#runtime/schedules/record.js";
+import { MAX_SCHEDULE_DELAY_MINUTES } from "#runtime/schedules/validation.js";
+import { parseJsonObject } from "#shared/json.js";
+import { scheduleCollectionToolPrefix } from "#shared/schedule-collection-tools.js";
+import { always } from "#tools/approval/policies.js";
+import { defineTool, type ToolDefinition } from "#tools/definition.js";
+import type { DynamicToolEntry } from "#tools/dynamic.js";
+import {
+ readDurableDynamicToolCallbacks,
+ stampDurableDynamicToolCallbacks,
+} from "#tools/durable-callbacks.js";
+
+// Approval must retain prepared data across durable suspension, not in a resolver closure.
+const PreparedCreatesKey = new ContextKey<Readonly<Record<string, PreparedScheduleCreate>>>(
+ "eve.schedulePreparedCreates",
+);
+const nameSchema = z
+ .string()
+ .min(1)
+ .max(256)
+ .regex(/^[0-9A-Za-z][0-9A-Za-z._-]*$/)
+ .describe("Readable display label; it may repeat. Creation returns a unique management name.");
+const nameInput = z
+ .object({
+ name: z
+ .string()
+ .min(1)
+ .max(256)
+ .describe("Exact unique management name returned by create/get/list, not the display label."),
+ })
+ .strict();
+const timezoneSchema = z
+ .string()
+ .describe("IANA timezone; omission means UTC. Delays need no timezone.");
+const expressionSchema = z.discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal("cron"),
+ cron: z.string().describe("Five-field cron: minute hour day-of-month month day-of-week."),
+ timezone: timezoneSchema.optional(),
+ jitter: z.number().int().min(1).max(15).optional(),
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("single"),
+ at: z.string().describe("Local YYYY-MM-DDTHH:mm, without offset or fractions."),
+ timezone: timezoneSchema.optional(),
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("delay"),
+ minutes: z.number().int().min(1).max(MAX_SCHEDULE_DELAY_MINUTES),
+ })
+ .strict(),
+]);
+const timingGuidance =
+ "For relative requests use expression { type: 'delay', minutes: 1 }; eve resolves timing after approval and rounds up to minute precision (up to 59 seconds later). Do not guess the clock or ask for a timezone for delays.";
+
+export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared = TInput>(
+ definition: DynamicSchedulesDefinition<TInput, StandardSchemaV1<unknown, TInput>, TPrepared>,
+ identity: { readonly application: string; readonly collection: string },
+) {
+ return markDynamicCallbackRebind(
+ defineDynamic({
+ events: {
+ "turn.started": async (_event, context) => {
+ const scope = contextStorage.getStore();
+ if (
+ definition.tool === false ||
+ context.session.schedule !== undefined ||
+ (scope !== undefined && readSessionSchedule(scope) !== undefined)
+ )
+ return null;
+ const prefix = `${scheduleCollectionToolPrefix(identity.collection)}__`;
+ const keyFor = (callId: string) => `${prefix}create:${callId}`;
+ const createSchema = z
+ .object({
+ name: nameSchema,
+ expression: expressionSchema,
+ payload: definition.inputSchema,
+ })
+ .strict();
+ const createPolicy = definition.approval?.create ?? always();
+ const createApproval: { request: ApprovalPolicy; response?: ApprovalResponsePolicy } = {
+ request: async (context) => {
+ try {
+ const input = await createSchema.parseAsync(context.toolInput);
+ const prepared = await (
+ await bindScheduleCollection(definition as never)
+ ).prepareCreate(input);
+ const key = keyFor(context.callId);
+ const previous = loadContext().get(PreparedCreatesKey) ?? {};
+ if (isApprovalRecheck(context)) {
+ if (previous[key] === undefined || !isDeepStrictEqual(previous[key], prepared))
+ return {
+ type: "denied",
+ reason:
+ "The prepared schedule changed or its approval expired. Request a new creation approval.",
+ };
+ } else {
+ const snapshots = {
+ ...Object.fromEntries(
+ Object.entries(previous)
+ .filter(([existing]) => existing !== key)
+ .slice(-31),
+ ),
+ [key]: prepared,
+ };
+ // Evicted approvals fail closed instead of blocking future creation forever.
+ while (Buffer.byteLength(JSON.stringify(snapshots)) > 512 * 1024)
+ delete snapshots[Object.keys(snapshots)[0]!];
+ loadContext().set(PreparedCreatesKey, snapshots);
+ }
+ const routed = {
+ ...context,
+ toolInput: { ...input, payload: prepared.envelope.payload },
+ payload: prepared.envelope.payload as NoInfer<TPrepared>,
+ };
+ return typeof createPolicy === "function"
+ ? await createPolicy(routed)
+ : await createPolicy.request(routed);
+ } catch (error) {
+ return {
+ type: "denied",
+ reason: error instanceof Error ? error.message : "Schedule preparation failed.",
+ };
+ }
+ },
+ };
+ if (typeof createPolicy !== "function" && createPolicy.response !== undefined) {
+ createApproval.response = async (context) => {
+ const prepared =
+ loadContext().get(PreparedCreatesKey)?.[keyFor(context.request.callId)];
+ if (prepared === undefined)
+ return {
+ status: "rejected",
+ reason: "The prepared schedule approval expired. Request creation again.",
+ };
+ return await createPolicy.response!({
+ ...context,
+ request: {
+ ...context.request,
+ toolInput: { ...context.request.toolInput, payload: prepared.envelope.payload },
+ },
+ payload: prepared.envelope.payload as NoInfer<TPrepared>,
+ });
+ };
+ }
+ const define = (
+ operation: ScheduleOperation,
+ action: string,
+ description: string,
+ inputSchema: any,
+ execute: ToolDefinition<any, unknown>["execute"],
+ ) => {
+ const approval =
+ operation === "create"
+ ? createApproval
+ : (definition.approval?.[operation] ??
+ (operation === "get" || operation === "list" ? undefined : always()));
+ const tool = defineTool({
+ description: `${definition.description ? `${definition.description}\n\n` : ""}${description}`,
+ inputSchema,
+ approval,
+ label: {
+ start: (input: { name?: string }) =>
+ input.name ? `${action}: ${scheduleDisplayName(input.name)}` : action,
+ },
+ execute: (input: any, context) => {
+ assertScheduleManagementAllowed();
+ return execute(input, context);
+ },
+ });
+ stampCallbacks(tool);
+ return tool as DynamicToolEntry;
+ };
+ return {
+ [`${prefix}create`]: define(
+ "create",
+ "Create schedule",
+ `Create future work, not an immediate action. The display name may repeat; use the returned unique name for management. ${timingGuidance} Preparation validates the destination before approval; a changed prepared payload requires fresh approval.`,
+ createSchema,
+ async (input, context) => {
+ const key = keyFor(context.callId);
+ const approved = loadContext().get(PreparedCreatesKey)?.[key];
+ if (approved === undefined)
+ throw new Error(
+ "Schedule creation has no prepared approval snapshot. Request creation again.",
+ );
+ const created = await (
+ await bindScheduleCollection(definition as never)
+ ).create(input, approved);
+ const snapshots = { ...loadContext().get(PreparedCreatesKey) };
+ delete snapshots[key];
+ loadContext().set(PreparedCreatesKey, snapshots);
+ return created;
+ },
+ ),
+ [`${prefix}get`]: define(
+ "get",
+ "Read schedule",
+ "Read timing/state; stored payload is not returned.",
+ nameInput,
+ async ({ name }) => await (await schedules(definition as never)).get(name),
+ ),
+ [`${prefix}list`]: define(
+ "list",
+ "List schedules",
+ "List identity, timing/state, and timestamps; payload is not returned.",
+ z
+ .object({
+ cursor: z.string().optional(),
+ limit: z.number().int().min(1).max(100).optional(),
+ })
+ .strict(),
+ async (input) => await (await schedules(definition as never)).list(input),
+ ),
+ [`${prefix}enable`]: define(
+ "enable",
+ "Enable schedule",
+ "Enable future occurrences.",
+ nameInput,
+ async ({ name }) => await (await schedules(definition as never)).enable(name),
+ ),
+ [`${prefix}disable`]: define(
+ "disable",
+ "Disable schedule",
+ "Disable future occurrences; already started work is not cancelled.",
+ nameInput,
+ async ({ name }) => await (await schedules(definition as never)).disable(name),
+ ),
+ [`${prefix}invoke`]: define(
+ "invoke",
+ "Run schedule",
+ "Enqueue an extra occurrence as the original creator; acceptance is not execution success.",
+ nameInput,
+ async ({ name }) => {
+ await (await schedules(definition as never)).invoke(name);
+ return { accepted: true };
+ },
+ ),
+ [`${prefix}delete`]: define(
+ "delete",
+ "Delete schedule",
+ "Delete a schedule; already started work is not cancelled.",
+ nameInput,
+ async ({ name }) => ({
+ deleted: await (await schedules(definition as never)).delete(name),
+ }),
+ ),
+ };
+ },
+ },
+ }),
+ );
+}
+
+function stampCallbacks(tool: ToolDefinition<any, unknown>): void {
+ const closure = parseJsonObject({});
+ const existing = readDurableDynamicToolCallbacks(tool);
+ const callbacks: Parameters<typeof stampDurableDynamicToolCallbacks>[1] = {
+ ...existing,
+ execute: {
+ callback: async (_closure, input, context) => await tool.execute(input, context),
+ closure,
+ },
+ inputSchema: { callback: () => tool.inputSchema, closure },
+ label: { start: { callback: (_closure, input) => tool.label!.start(input), closure } },
+ };
+ if (tool.approval !== undefined) {
+ const approval = tool.approval;
+ callbacks.approvalRequest = {
+ callback: async (_closure, context) =>
+ typeof approval === "function"
+ ? await approval(context as ApprovalContext)
+ : await approval.request(context as ApprovalContext),
+ closure,
+ };
+ if (typeof approval !== "function" && approval.response !== undefined)
+ callbacks.approvalResponse = {
+ callback: async (_closure, context) => await approval.response!(context),
+ closure,
+ };
+ }
+ stampDurableDynamicToolCallbacks(tool, callbacks);
+}
diff --git a/packages/eve/src/context/session-context.ts b/packages/eve/src/context/session-context.ts
index 493aacb3c..364667e65 100644
--- a/packages/eve/src/context/session-context.ts
+++ b/packages/eve/src/context/session-context.ts
@@ -6,7 +6,8 @@ import type {
} from "#shared/sandbox-session.js";
import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";
-export type { SessionAuth, SessionParent, SessionTurn };
+import type { SessionSchedule } from "#context/session-schedule.js";
+export type { SessionAuth, SessionParent, SessionTurn, SessionSchedule };
/**
* Shared runtime context available to all authored callbacks that run
@@ -25,6 +26,8 @@ export interface SessionContext {
readonly auth: SessionAuth;
readonly turn: SessionTurn;
readonly parent?: SessionParent;
+ /** Present only for scheduled work; not an application-supplied auth attribute. */
+ readonly schedule?: SessionSchedule;
};
/**
diff --git a/packages/eve/src/context/session-schedule.ts b/packages/eve/src/context/session-schedule.ts
new file mode 100644
index 000000000..b08322d1c
--- /dev/null
+++ b/packages/eve/src/context/session-schedule.ts
@@ -0,0 +1,35 @@
+import type { ContextReader } from "#context/key.js";
+import { ScheduleIdKey, ScheduleInstanceKey, OccurrenceIdKey } from "#context/keys.js";
+
+/** Framework-owned provenance for the scheduled work that started the current turn. */
+export interface SessionSchedule {
+ readonly definition: string;
+ readonly instance?: string;
+ readonly occurrenceId?: string;
+}
+
+export function readSerializedSessionSchedule(
+ values: Readonly<Record<string, unknown>>,
+): SessionSchedule | undefined {
+ const definition = values[ScheduleIdKey.name];
+ if (typeof definition !== "string") return undefined;
+ const instance = values[ScheduleInstanceKey.name];
+ const occurrenceId = values[OccurrenceIdKey.name];
+ return {
+ definition,
+ instance: typeof instance === "string" ? instance : undefined,
+ occurrenceId: typeof occurrenceId === "string" ? occurrenceId : undefined,
+ };
+}
+
+export function readSessionSchedule(
+ context: Pick<ContextReader, "get">,
+): SessionSchedule | undefined {
+ const definition = context.get(ScheduleIdKey);
+ if (definition === undefined) return undefined;
+ return {
+ definition,
+ instance: context.get(ScheduleInstanceKey),
+ occurrenceId: context.get(OccurrenceIdKey),
+ };
+}
diff --git a/packages/eve/src/dynamic/definition.ts b/packages/eve/src/dynamic/definition.ts
index 7853a1c31..37022f7d3 100644
--- a/packages/eve/src/dynamic/definition.ts
+++ b/packages/eve/src/dynamic/definition.ts
@@ -53,6 +53,7 @@ export interface DynamicResolveContext {
readonly session: {
readonly id: string;
readonly auth: SessionAuth;
+ readonly schedule?: import("#context/session-schedule.js").SessionSchedule;
};
/** Channel metadata for the request that triggered this resolve. */
readonly channel: {
diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.ts
index 4dc079946..065e9df0c 100644
--- a/packages/eve/src/execution/agent-sessions/context.ts
+++ b/packages/eve/src/execution/agent-sessions/context.ts
@@ -6,6 +6,7 @@ import type {
SessionTraceRoot,
} from "#channel/types.js";
import type { LocalDevRequestProvenance } from "#context/keys.js";
+import { readSerializedSessionSchedule, type SessionSchedule } from "#context/session-schedule.js";
import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";
import type { PreparedCoordinationDispatch } from "#execution/coordination-dispatch-shared.js";
import {
@@ -38,6 +39,7 @@ export interface AgentSessionContext {
readonly bundle: AgentSessionBundle;
/** Forwarded unchanged, so a session asks a person only when its caller can. */
readonly capabilities?: SessionCapabilities;
+ readonly schedule?: SessionSchedule;
readonly channelMetadata?: ChannelInstrumentationProjection;
readonly conversation?: ConversationContext;
/** Dynamic agents the calling turn selected, by node id. */
@@ -113,6 +115,7 @@ export function captureAgentSessionContext(
source: serializeDurableCompiledArtifactsSource(caller.bundle.compiledArtifactsSource),
},
capabilities: caller.capabilities,
+ schedule: readSerializedSessionSchedule(caller.serializedContext),
channelMetadata: caller.channelMetadata,
conversation: caller.inheritedConversation,
dynamicSelections: caller.dynamicSubagentSelections,
diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.ts
index 3dbea8133..e6c576be6 100644
--- a/packages/eve/src/execution/agent-sessions/steps.ts
+++ b/packages/eve/src/execution/agent-sessions/steps.ts
@@ -148,6 +148,7 @@ export async function sendAgentSessionMessageStep(
const result = await dispatchWorkflowSessionCommand({
command: {
auth: input.auth.current,
+ schedule: context.schedule,
caller: {
callId: context.parent.callId,
replyTo: { kind: "hook", token: input.replyTo },
@@ -233,6 +234,7 @@ async function startLocalSession(
action,
auth: auth.current,
capabilities: context.capabilities,
+ schedule: context.schedule,
channelMetadata: context.channelMetadata,
continuationKey: input.key,
graph: bundle.graph,
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index d4763be27..a3a86d0ba 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -12,9 +12,11 @@ import {
ConversationIdKey,
DynamicSubagentAgentConfigKey,
InitiatorAuthKey,
+ OccurrenceIdKey,
ParentSessionKey,
ParentTraceContextKey,
ScheduleIdKey,
+ ScheduleInstanceKey,
SessionCallbackKey,
LegacyRemoteAgentCallerKey,
SessionTitleKey,
@@ -66,6 +68,9 @@ export function buildRunContext(input: {
ctx.set(ContinuationTokenKey, run.continuationToken);
ctx.set(ContinuationHookTokensKey, [run.continuationToken]);
}
+ const occurrenceId =
+ run.schedule?.occurrenceId ?? contextStorage.getStore()?.get(OccurrenceIdKey);
+ if (occurrenceId !== undefined) ctx.set(OccurrenceIdKey, occurrenceId);
ctx.set(AuthKey, auth);
if (run.initiatorAuth !== undefined || run.input.message !== undefined) {
ctx.set(InitiatorAuthKey, run.initiatorAuth ?? auth);
@@ -83,7 +88,9 @@ export function buildRunContext(input: {
ctx.set(ChannelRequestIdKey, run.requestId);
}
- const scheduleId = contextStorage.getStore()?.get(ScheduleIdKey);
+ const instance = run.schedule?.instance ?? contextStorage.getStore()?.get(ScheduleInstanceKey);
+ if (instance !== undefined) ctx.set(ScheduleInstanceKey, instance);
+ const scheduleId = run.schedule?.definition ?? contextStorage.getStore()?.get(ScheduleIdKey);
if (scheduleId !== undefined) {
ctx.set(ScheduleIdKey, scheduleId);
}
diff --git a/packages/eve/src/execution/session-inbox/protocol.ts b/packages/eve/src/execution/session-inbox/protocol.ts
index 548214c91..f2264e04b 100644
--- a/packages/eve/src/execution/session-inbox/protocol.ts
+++ b/packages/eve/src/execution/session-inbox/protocol.ts
@@ -31,6 +31,7 @@ export function decodeSessionInboxPayload(value: unknown): DecodedSessionInbox {
const command = value as Extract<SessionCommand, { readonly kind: "send" }>;
return {
auth: command.auth,
+ schedule: command.schedule,
title: command.title,
caller: command.caller,
deliveryMetadata:
diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.ts
index 3fd273a2b..7b09a9550 100644
--- a/packages/eve/src/execution/session/entry.integration.test.ts
+++ b/packages/eve/src/execution/session/entry.integration.test.ts
@@ -26,7 +26,12 @@ import { always } from "#tools/approval/policies.js";
import { defineTool } from "#tools/definition.js";
import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";
import { defineInteractiveAuthorization } from "#shared/connection-types.js";
-import { SessionTitleKey } from "#context/keys.js";
+import {
+ SessionTitleKey,
+ ScheduleIdKey,
+ ScheduleInstanceKey,
+ OccurrenceIdKey,
+} from "#context/keys.js";
import {
buildSerializedContext,
captureEvents,
@@ -43,6 +48,57 @@ afterEach(() => {
});
describe("workflowEntry integration", () => {
+ it("preserves scheduled provenance in the first turn so unattended tools need no approval", async () => {
+ const executions: unknown[] = [];
+ const runtime = await createTestRuntime({
+ agent: { name: "scheduled-first-turn" },
+ modules: [
+ {
+ logicalPath: "tools/inspect_schedule.ts",
+ loadNamespace: async () => ({
+ default: defineTool({
+ description: "Report this turn's schedule provenance.",
+ inputSchema: {},
+ approval: ({ session }) =>
+ session.schedule === undefined ? "user-approval" : "not-applicable",
+ execute: (_input, context) => {
+ executions.push(context.session.schedule);
+ return { inspected: true };
+ },
+ }),
+ }),
+ },
+ ],
+ });
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: { message: "Use inspect_schedule exactly once." },
+ serializedContext: {
+ ...buildSerializedContext({ channelKind: "schedule" }),
+ [ScheduleIdKey.name]: "tasks",
+ [ScheduleInstanceKey.name]: "joke--id",
+ [OccurrenceIdKey.name]: "exec-1",
+ "eve.capabilities": { requestInput: false },
+ },
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ try {
+ const events = await stream.nextTurn();
+ expect(filterEventsByType(events, "input.requested")).toHaveLength(0);
+ expect(filterEventsByType(events, "turn.failed")).toHaveLength(0);
+ expect(executions).toEqual([
+ { definition: "tasks", instance: "joke--id", occurrenceId: "exec-1" },
+ ]);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ });
it("registers first-turn abort hooks before a prewarmed session receives a message", async () => {
const runtime = await createTestRuntime({ agent: { name: "workflow-entry-turn-prewarm" } });
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index 948b9f639..d22edf42a 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -1,3 +1,4 @@
+import { readSerializedSessionSchedule } from "#context/session-schedule.js";
import { failSession, runPreparedSession, type SessionBoot } from "#execution/session/program.js";
import { getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";
@@ -317,6 +318,7 @@ function createInitialDelivery(
): DeliverHookPayload | undefined {
if (input.input.message === undefined) return undefined;
return {
+ schedule: readSerializedSessionSchedule(serializedContext),
deliveryMetadata:
serializedContext["eve.channelDelivery"] === undefined
? undefined
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index 427c6afc6..70869ad7c 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -13,6 +13,9 @@ import {
} from "#context/dynamic-tool-lifecycle.js";
import {
AuthKey,
+ ScheduleIdKey,
+ ScheduleInstanceKey,
+ OccurrenceIdKey,
InitiatorAuthKey,
SessionTitleKey,
ParentSessionKey,
@@ -169,6 +172,20 @@ async function runSessionStepBody(
}
}
+ // A new inbound message is a new caller action, not a scheduled occurrence.
+ // Approval/input responses alone keep the parked turn's provenance.
+ if (delivery?.payloads.some((payload) => payload.message !== undefined)) {
+ ctx.delete(ScheduleIdKey);
+ ctx.delete(ScheduleInstanceKey);
+ ctx.delete(OccurrenceIdKey);
+ if (delivery.schedule !== undefined) {
+ ctx.set(ScheduleIdKey, delivery.schedule.definition);
+ if (delivery.schedule.instance !== undefined)
+ ctx.set(ScheduleInstanceKey, delivery.schedule.instance);
+ if (delivery.schedule.occurrenceId !== undefined)
+ ctx.set(OccurrenceIdKey, delivery.schedule.occurrenceId);
+ }
+ }
const previousAuth = ctx.get(AuthKey);
const hadInitiator = ctx.has(InitiatorAuthKey);
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index f404ddbc4..a0a11dedc 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -63,7 +63,7 @@ export function hasDelegatedCallerContext(serializedContext: Record<string, unkn
const NO_INPUT_CAPABILITY_ERROR_MESSAGE =
"This session cannot request human input, so it cannot wait for a tool approval or question. " +
- "Sessions started without `capabilities.requestInput`, such as schedules, must not use approval-gated tools.";
+ "Configure unattended tools with an approval policy that does not require human input.";
export interface SessionExecutionInput {
readonly capabilities?: SessionCapabilities;
diff --git a/packages/eve/src/framework/sources/modules/schedule-collection-wrapper.ts b/packages/eve/src/framework/sources/modules/schedule-collection-wrapper.ts
new file mode 100644
index 000000000..7dc74a9a9
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/schedule-collection-wrapper.ts
@@ -0,0 +1,55 @@
+import type { ProgrammaticModuleLoadContext } from "#compiler/source-graph.js";
+import { createScheduleCollectionToolDynamicDefinition } from "#context/schedule-collection-tools.js";
+import {
+ getAuthoredModuleExport,
+ materializeAuthoredModuleExport,
+} from "#internal/authored-module.js";
+import { normalizeScheduleCollectionDefinition } from "#internal/authored-definition/schedule-collection.js";
+import { defineDynamic } from "#dynamic/definition.js";
+import {
+ isScheduleCollectionDefinition,
+ stampScheduleCollectionSource,
+} from "#shared/schedule-collection-definition.js";
+
+export async function loadScheduleCollectionWrapperNamespace(
+ context: ProgrammaticModuleLoadContext,
+): Promise<Readonly<Record<string, unknown>>> {
+ const application = context.parameters.application;
+ const collection = context.parameters.collection;
+ const logicalPath = context.parameters.collectionLogicalPath;
+ const exportName = context.parameters.collectionExportName;
+ const dependency = context.dependencies.collection;
+ if (
+ typeof application !== "string" ||
+ typeof collection !== "string" ||
+ typeof logicalPath !== "string" ||
+ typeof exportName !== "string" ||
+ dependency === undefined
+ ) {
+ throw new Error(
+ "The compiled schedule collection wrapper is missing its selected collection source.",
+ );
+ }
+ const value = await materializeAuthoredModuleExport(
+ getAuthoredModuleExport(dependency, { exportName, logicalPath }),
+ );
+ if (!isScheduleCollectionDefinition(value)) {
+ return { default: defineDynamic({ events: { "turn.started": () => null } }) };
+ }
+ const definition = normalizeScheduleCollectionDefinition(
+ value,
+ `Expected the schedule collection export "${exportName}" from "${logicalPath}" to be created with defineDynamicSchedules().`,
+ );
+ stampScheduleCollectionSource(value as object, {
+ application,
+ collection,
+ logicalPath,
+ sourceId: String(context.parameters.collectionSourceId ?? ""),
+ });
+ return {
+ default: createScheduleCollectionToolDynamicDefinition(definition, {
+ application,
+ collection,
+ }),
+ };
+}
diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.ts
index b0443ef8c..6053c1d67 100644
--- a/packages/eve/src/framework/sources/registry.ts
+++ b/packages/eve/src/framework/sources/registry.ts
@@ -71,6 +71,21 @@ const rootDefaults = defineProgrammaticAgentSource({
],
});
+const scheduleCollectionWrapperTemplateSource = defineProgrammaticAgentSource({
+ id: "eve:schedule-collection-wrapper",
+ revision,
+ modules: [
+ {
+ logicalPath: "tools/schedule-collection-wrapper.ts",
+ loadNamespace: async (context) => {
+ const { loadScheduleCollectionWrapperNamespace } =
+ await import("#framework/sources/modules/schedule-collection-wrapper.js");
+ return await loadScheduleCollectionWrapperNamespace(context);
+ },
+ },
+ ],
+});
+
const memoryWrapperTemplateSource = defineProgrammaticAgentSource({
id: "eve:memory-wrapper",
revision,
@@ -91,12 +106,15 @@ export const frameworkAgentSourceRegistry: AgentSourceRegistry = createAgentSour
{ applyTo: "all-local-nodes", source: localDefaults },
{ applyTo: "root", source: rootDefaults },
],
- { templates: [memoryWrapperTemplateSource] },
+ { templates: [memoryWrapperTemplateSource, scheduleCollectionWrapperTemplateSource] },
);
export const memoryWrapperTemplate = frameworkAgentSourceRegistry.templates.get(
memoryWrapperTemplateSource.id,
)!;
+export const scheduleCollectionWrapperTemplate = frameworkAgentSourceRegistry.templates.get(
+ scheduleCollectionWrapperTemplateSource.id,
+)!;
export async function loadFrameworkProgrammaticModule(
backing: Extract<AgentModuleBacking, { readonly kind: "programmatic" }>,
diff --git a/packages/eve/src/internal/authored-definition/schedule-collection.ts b/packages/eve/src/internal/authored-definition/schedule-collection.ts
new file mode 100644
index 000000000..d11e2ade9
--- /dev/null
+++ b/packages/eve/src/internal/authored-definition/schedule-collection.ts
@@ -0,0 +1,119 @@
+import { expectObjectRecord, expectOnlyKnownKeys } from "#internal/authored-module.js";
+import type {
+ DynamicSchedulesDefinition,
+ ScheduleProvider,
+} from "#public/schedules/subscription.js";
+import { isScheduleCollectionDefinition } from "#shared/schedule-collection-definition.js";
+
+const SCHEDULE_OPERATIONS = [
+ "create",
+ "get",
+ "list",
+ "enable",
+ "disable",
+ "invoke",
+ "delete",
+] as const;
+
+const PROVIDER_KEYS = [
+ "kind",
+ "create",
+ "list",
+ "get",
+ "enable",
+ "disable",
+ "invoke",
+ "delete",
+] as const satisfies readonly (keyof ScheduleProvider)[];
+const PROVIDER_METHODS = PROVIDER_KEYS.filter(
+ (key): key is Exclude<(typeof PROVIDER_KEYS)[number], "kind"> => key !== "kind",
+);
+const DEFINITION_KEYS = [
+ "description",
+ "provider",
+ "scope",
+ "inputSchema",
+ "preparePayload",
+ "run",
+ "auth",
+ "events",
+ "tool",
+ "approval",
+] as const;
+
+export function normalizeScheduleCollectionDefinition(
+ value: unknown,
+ message: string,
+): DynamicSchedulesDefinition {
+ if (!isScheduleCollectionDefinition(value)) throw new Error(message);
+ const record = expectObjectRecord(value, message);
+ expectOnlyKnownKeys(record, DEFINITION_KEYS, message);
+ if (
+ record.description !== undefined &&
+ (typeof record.description !== "string" || record.description.trim() === "")
+ )
+ throw new Error(`${message} "description" must be a non-empty string when provided.`);
+ const schema = expectObjectRecord(
+ record.inputSchema,
+ `${message} "inputSchema" is required and must be a Standard Schema.`,
+ );
+ const standard = expectObjectRecord(
+ schema["~standard"],
+ `${message} "inputSchema" must be a Standard Schema.`,
+ );
+ if (typeof standard.validate !== "function")
+ throw new Error(`${message} "inputSchema" must supply a Standard Schema validate function.`);
+ if (record.preparePayload !== undefined && typeof record.preparePayload !== "function")
+ throw new Error(`${message} "preparePayload" must be a function when provided.`);
+ if (typeof record.run !== "function")
+ throw new Error(`${message} "run" is required and must be a function.`);
+ if (record.scope !== undefined && typeof record.scope !== "function")
+ throw new Error(`${message} "scope" must be a function when provided.`);
+ if (typeof record.auth !== "function")
+ throw new Error(
+ `${message} "auth" is required and must be a function that resolves the schedule creator to execution auth.`,
+ );
+ if (record.events !== undefined) {
+ const events = expectObjectRecord(record.events, `${message} "events" must be an object.`);
+ expectOnlyKnownKeys(
+ events,
+ ["occurrence.dispatched", "occurrence.failed"],
+ `${message} "events"`,
+ );
+ for (const [name, handler] of Object.entries(events))
+ if (handler !== undefined && typeof handler !== "function")
+ throw new Error(`${message} "events.${name}" must be a function.`);
+ }
+ const provider = expectObjectRecord(record.provider, `${message} "provider" must be an object.`);
+ expectOnlyKnownKeys(provider, PROVIDER_KEYS, `${message} "provider"`);
+ if (typeof provider.kind !== "string" || provider.kind.trim() === "")
+ throw new Error(`${message} provider.kind must be a non-empty string.`);
+ for (const method of PROVIDER_METHODS)
+ if (typeof provider[method] !== "function")
+ throw new Error(`${message} provider.${method} must be a function.`);
+ if (record.tool !== undefined && typeof record.tool !== "boolean")
+ throw new Error(
+ `${message} "tool" must be true or false; deferred tools are not supported yet.`,
+ );
+ if (record.tool === false && record.approval !== undefined)
+ throw new Error(`${message} "approval" cannot be configured when tool is false.`);
+ if (record.approval !== undefined) {
+ const approval = expectObjectRecord(
+ record.approval,
+ `${message} "approval" must be an object.`,
+ );
+ expectOnlyKnownKeys(approval, SCHEDULE_OPERATIONS, `${message} "approval"`);
+ for (const [operation, policy] of Object.entries(approval)) {
+ if (
+ typeof policy !== "function" &&
+ (typeof policy !== "object" ||
+ policy === null ||
+ typeof Reflect.get(policy, "request") !== "function" ||
+ (Reflect.get(policy, "response") !== undefined &&
+ typeof Reflect.get(policy, "response") !== "function"))
+ )
+ throw new Error(`${message} "approval.${operation}" must be an approval policy.`);
+ }
+ }
+ return value as DynamicSchedulesDefinition;
+}
diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.ts
index 482f162cc..ac1c50dff 100644
--- a/packages/eve/src/public/channels/slack/index.ts
+++ b/packages/eve/src/public/channels/slack/index.ts
@@ -74,6 +74,7 @@ export {
export { type SlackFetch, type SlackTransportOptions } from "#public/channels/slack/transport.js";
export { defaultSlackAuth } from "#public/channels/slack/defaults.js";
+export { buildSlackAuthContext } from "#public/channels/slack/auth.js";
export {
postCompletedSlackReply,
diff --git a/packages/eve/src/public/experimental/schedules/client.ts b/packages/eve/src/public/experimental/schedules/client.ts
new file mode 100644
index 000000000..bcd09a29f
--- /dev/null
+++ b/packages/eve/src/public/experimental/schedules/client.ts
@@ -0,0 +1,59 @@
+import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
+import { loadContext } from "#context/container.js";
+import { normalizeScheduleCollectionDefinition } from "#internal/authored-definition/schedule-collection.js";
+import { readScheduleCollectionSource } from "#shared/schedule-collection-definition.js";
+import {
+ AuthKey,
+ InitiatorAuthKey,
+ SessionIdKey,
+ ContinuationTokenKey,
+ ChannelInstrumentationKey,
+} from "#context/keys.js";
+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+import { getAdapterKind } from "#channel/adapter.js";
+import type { DefinedDynamicSchedules, ScheduleClient } from "#public/schedules/subscription.js";
+import { readSessionSchedule } from "#context/session-schedule.js";
+import {
+ createScheduleCollectionClient,
+ type ScheduleCollectionClient,
+} from "#runtime/schedules/collection-client.js";
+
+/** Binds a registered subscription to a scope authorized on every operation. */
+export async function schedules<TPayload, TPrepared = TPayload>(
+ collection: DefinedDynamicSchedules<TPayload, StandardSchemaV1<unknown, TPayload>, TPrepared>,
+): Promise<ScheduleClient<TPayload>> {
+ return await bindScheduleCollection(collection);
+}
+
+/** Shared binding for model approval preview and code-only client access. */
+export async function bindScheduleCollection<TPayload, TPrepared = TPayload>(
+ collection: DefinedDynamicSchedules<TPayload, StandardSchemaV1<unknown, TPayload>, TPrepared>,
+): Promise<ScheduleCollectionClient<TPayload, TPrepared>> {
+ const identity = readScheduleCollectionSource(collection);
+ if (identity === undefined)
+ throw new Error("schedules(): subscription must be a stamped agent/schedules module export.");
+ const definition = normalizeScheduleCollectionDefinition(
+ collection,
+ `Invalid schedule subscription ${identity.logicalPath}.`,
+ ) as DefinedDynamicSchedules<TPayload, StandardSchemaV1<unknown, TPayload>, TPrepared>;
+ const context = loadContext();
+ const channel = context.get(ChannelKey);
+ return createScheduleCollectionClient(definition, {
+ abortSignal: new AbortController().signal,
+ session: {
+ id: context.get(SessionIdKey) ?? "",
+ schedule: readSessionSchedule(context),
+ auth: {
+ current: context.get(AuthKey) ?? null,
+ initiator: context.get(InitiatorAuthKey) ?? null,
+ },
+ },
+ channel: {
+ kind: channel === undefined ? undefined : getAdapterKind(channel),
+ continuationToken: context.get(ContinuationTokenKey),
+ metadata: context.get(ChannelInstrumentationKey)?.metadata,
+ },
+ application: identity.application,
+ collection: identity.collection,
+ });
+}
diff --git a/packages/eve/src/public/experimental/schedules/index.ts b/packages/eve/src/public/experimental/schedules/index.ts
new file mode 100644
index 000000000..090368cd7
--- /dev/null
+++ b/packages/eve/src/public/experimental/schedules/index.ts
@@ -0,0 +1,34 @@
+/** Experimental dynamic schedule subscriptions. APIs may change without notice. */
+export { schedules } from "#public/experimental/schedules/client.js";
+export {
+ defineDynamicSchedules,
+ type DefinedDynamicSchedules,
+ type DynamicSchedulesDefinition,
+ type DynamicSchedulesRunArgs,
+ type DynamicSchedulesToFn,
+ type ScheduleCreateApproval,
+ type ScheduleApprovals,
+ type ScheduleClient,
+ type ScheduleClientCreate,
+ type ScheduleCreate,
+ type ScheduleExpression,
+ type ScheduleTiming,
+ type ScheduleList,
+ type ScheduleOccurrence,
+ type ScheduleOccurrenceIdentity,
+ type SchedulePrincipalReference,
+ type ScheduleOccurrenceEvent,
+ type SchedulePage,
+ type ScheduleProvider,
+ type ScheduleRecord,
+ type ScheduleScopeContext,
+ type ScheduleScopeResolverResult,
+ type ScheduleOperation,
+ type ScheduleState,
+} from "#public/schedules/subscription.js";
+export type {
+ ScheduleDelivery,
+ ScheduleDeliveryTarget,
+ ScheduleProviderContext,
+} from "#runtime/schedules/provider-types.js";
+export { byPrincipal } from "#public/schedules/scope.js";
diff --git a/packages/eve/src/public/experimental/schedules/testing.ts b/packages/eve/src/public/experimental/schedules/testing.ts
new file mode 100644
index 000000000..1677fdc99
--- /dev/null
+++ b/packages/eve/src/public/experimental/schedules/testing.ts
@@ -0,0 +1,5 @@
+/** Experimental in-memory dynamic schedule collections for tests. */
+export {
+ inMemoryScheduleProvider,
+ type InMemoryScheduleProviderOptions,
+} from "#public/schedules/providers/in-memory.js";
diff --git a/packages/eve/src/public/memory/scope.ts b/packages/eve/src/public/memory/scope.ts
index bb4834ef5..6a27be2ed 100644
--- a/packages/eve/src/public/memory/scope.ts
+++ b/packages/eve/src/public/memory/scope.ts
@@ -1,15 +1,6 @@
import type { MemoryScopeContext } from "#public/memory/index.js";
-
-const DISABLED_PRINCIPAL_TYPES = new Set(["anonymous", "runtime"]);
+import { principalScope } from "#shared/principal-scope.js";
export function byPrincipal(context: MemoryScopeContext): string | null {
- const principal = context.session.auth.current;
- if (principal === null || DISABLED_PRINCIPAL_TYPES.has(principal.principalType)) return null;
- if (principal.principalType === "local-dev") return "local-dev";
- return JSON.stringify([
- principal.principalType,
- principal.authenticator,
- principal.issuer ?? null,
- principal.principalId,
- ]);
+ return principalScope(context.session.auth);
}
diff --git a/packages/eve/src/public/schedules/provider-types.ts b/packages/eve/src/public/schedules/provider-types.ts
new file mode 100644
index 000000000..e76079bb4
--- /dev/null
+++ b/packages/eve/src/public/schedules/provider-types.ts
@@ -0,0 +1,19 @@
+import type { ScheduleOccurrence } from "#public/schedules/subscription.js";
+
+export interface ScheduleDelivery<TPayload = unknown> {
+ readonly payload: TPayload;
+ readonly occurrence: ScheduleOccurrence;
+}
+
+export interface ScheduleDeliveryTarget {
+ readonly key: string;
+ readonly deliver?: (delivery: ScheduleDelivery<any>) => Promise<void>;
+}
+
+export interface ScheduleProviderContext {
+ readonly abortSignal: AbortSignal;
+ readonly collection: string;
+ readonly namespace: string;
+ readonly operationId: string;
+ readonly target: ScheduleDeliveryTarget;
+}
diff --git a/packages/eve/src/public/schedules/providers/in-memory.ts b/packages/eve/src/public/schedules/providers/in-memory.ts
new file mode 100644
index 000000000..0498c6b37
--- /dev/null
+++ b/packages/eve/src/public/schedules/providers/in-memory.ts
@@ -0,0 +1,246 @@
+import { createHash, randomUUID } from "node:crypto";
+
+import type {
+ ScheduleCreate,
+ ScheduleExpression,
+ ScheduleList,
+ SchedulePage,
+ ScheduleProvider,
+ ScheduleRecord,
+} from "#public/schedules/subscription.js";
+import type { ScheduleProviderContext } from "#runtime/schedules/provider-types.js";
+
+export interface InMemoryScheduleProviderOptions {
+ readonly now?: () => Date;
+}
+
+interface StoredSchedule extends ScheduleRecord {
+ readonly payload: unknown;
+ readonly target: ScheduleProviderContext["target"];
+}
+
+export function inMemoryScheduleProvider(
+ options: InMemoryScheduleProviderOptions = {},
+): ScheduleProvider {
+ const schedules = new Map<string, StoredSchedule>();
+ const operationResults = new Map<string, unknown>();
+ const scheduleIds = new Map<string, string>();
+ const usedScheduleIds = new Set<string>();
+ const usedOccurrenceIds = new Set<string>();
+ const now = options.now ?? (() => new Date());
+
+ return {
+ kind: "in-memory",
+
+ async create<TPayload>(context: ScheduleProviderContext, schedule: ScheduleCreate<TPayload>) {
+ return withOperationResult(operationResults, context.operationId, () => {
+ const key = scheduleKey(context, schedule.name);
+ if (schedules.has(key)) {
+ throw new Error(`Schedule ${JSON.stringify(schedule.name)} already exists.`);
+ }
+ const timestamp = now().getTime();
+ const record: StoredSchedule = {
+ createdAt: timestamp,
+ expression: normalizeExpression(schedule.expression),
+ payload: schedule.payload,
+ name: schedule.name,
+ scheduleId: allocateScheduleId(context, schedule.name, scheduleIds, usedScheduleIds),
+ state:
+ schedule.expression.type === "single" && Date.parse(schedule.expression.at) <= timestamp
+ ? "completed"
+ : (schedule.state ?? "active"),
+ target: context.target,
+ updatedAt: timestamp,
+ };
+ schedules.set(key, record);
+ return publicRecord(record);
+ });
+ },
+
+ async list(context: ScheduleProviderContext, query: ScheduleList): Promise<SchedulePage> {
+ const records = [...schedules.entries()]
+ .filter(([key]) => key.startsWith(collectionPrefix(context)))
+ .map(([, record]) => publicRecord(record))
+ .sort((left, right) => left.name.localeCompare(right.name));
+ const start = decodeCursor(query.cursor);
+ const limit = normalizeLimit(query.limit);
+ const data = records.slice(start, start + limit);
+ const next = start + data.length;
+ return { cursor: next < records.length ? String(next) : null, data };
+ },
+
+ async get(context: ScheduleProviderContext, name: string) {
+ const record = schedules.get(scheduleKey(context, name));
+ return record === undefined ? null : publicRecord(record);
+ },
+
+ async enable(context: ScheduleProviderContext, name: string) {
+ return setState(schedules, operationResults, context, name, "active", now);
+ },
+
+ async disable(context: ScheduleProviderContext, name: string) {
+ return setState(schedules, operationResults, context, name, "inactive", now);
+ },
+
+ async invoke(context: ScheduleProviderContext, name: string) {
+ const replay = operationResults.get(context.operationId) as
+ | {
+ readonly payload: unknown;
+ readonly occurrence: ScheduleRecord & { executionId: string; scheduledAt: string };
+ }
+ | undefined;
+ if (replay !== undefined) {
+ if (context.target.deliver !== undefined) await context.target.deliver(replay);
+ return;
+ }
+ const schedule = requireSchedule(schedules, scheduleKey(context, name), name);
+ if (schedule.state === "completed")
+ throw new Error(`Completed schedule ${JSON.stringify(name)} cannot be invoked.`);
+ const scheduledAt = now().toISOString();
+ const delivery = {
+ payload: schedule.payload,
+ occurrence: {
+ executionId: allocateOccurrenceId(context.operationId, usedOccurrenceIds),
+ name: schedule.name,
+ scheduleId: schedule.scheduleId,
+ scheduledAt,
+ },
+ };
+ operationResults.set(context.operationId, delivery);
+ if (schedule.target.deliver !== undefined) await schedule.target.deliver(delivery);
+ },
+
+ async delete(context: ScheduleProviderContext, name: string) {
+ return withOperationResult(operationResults, context.operationId, () => {
+ const key = scheduleKey(context, name);
+ const deleted = schedules.delete(key);
+ if (deleted) scheduleIds.delete(key);
+ return deleted;
+ });
+ },
+ };
+}
+
+async function setState(
+ schedules: Map<string, StoredSchedule>,
+ operationResults: Map<string, unknown>,
+ context: ScheduleProviderContext,
+ name: string,
+ state: ScheduleRecord["state"],
+ now: () => Date,
+): Promise<ScheduleRecord> {
+ return withOperationResult(operationResults, context.operationId, () => {
+ const key = scheduleKey(context, name);
+ const current = requireSchedule(schedules, key, name);
+ const updated = { ...current, state, updatedAt: now().getTime() };
+ schedules.set(key, updated);
+ return publicRecord(updated);
+ });
+}
+
+function requireSchedule(
+ schedules: Map<string, StoredSchedule>,
+ key: string,
+ name: string,
+): StoredSchedule {
+ const schedule = schedules.get(key);
+ if (schedule === undefined) {
+ throw new Error(`Schedule ${JSON.stringify(name)} was not found.`);
+ }
+ return schedule;
+}
+
+function withOperationResult<TResult>(
+ results: Map<string, unknown>,
+ operationId: string,
+ operation: () => TResult,
+): TResult {
+ if (results.has(operationId)) return results.get(operationId) as TResult;
+ const result = operation();
+ results.set(operationId, result);
+ return result;
+}
+
+function allocateOccurrenceId(operationId: string, usedOccurrenceIds: Set<string>): string {
+ const base = `manual_${createHash("sha256").update(operationId).digest("base64url")}`;
+ let occurrenceId = base;
+ let suffix = 0;
+ while (usedOccurrenceIds.has(occurrenceId)) occurrenceId = `${base}_${++suffix}`;
+ usedOccurrenceIds.add(occurrenceId);
+ return occurrenceId;
+}
+
+function normalizeExpression(expression: ScheduleExpression): ScheduleExpression {
+ if (expression.type === "cron") {
+ const normalized: {
+ type: "cron";
+ cron: string;
+ timezone?: string;
+ jitter?: number;
+ } = {
+ type: "cron",
+ cron: expression.cron.trim().replace(/\s+/gu, " "),
+ };
+ if (expression.timezone !== undefined) normalized.timezone = expression.timezone;
+ if (expression.jitter !== undefined) normalized.jitter = expression.jitter;
+ return normalized;
+ }
+ const normalized: { type: "single"; at: string; timezone?: string } = {
+ type: "single",
+ at: expression.at,
+ };
+ if (expression.timezone !== undefined) normalized.timezone = expression.timezone;
+ return normalized;
+}
+
+function publicRecord(record: StoredSchedule): ScheduleRecord {
+ return {
+ createdAt: record.createdAt,
+ expression: record.expression,
+ name: record.name,
+ scheduleId: record.scheduleId,
+ state: record.state,
+ updatedAt: record.updatedAt,
+ };
+}
+
+function collectionPrefix(context: ScheduleProviderContext): string {
+ return `${context.collection}\0${context.namespace}\0`;
+}
+
+function scheduleKey(context: ScheduleProviderContext, name: string): string {
+ return `${collectionPrefix(context)}${name}`;
+}
+
+function allocateScheduleId(
+ context: ScheduleProviderContext,
+ name: string,
+ scheduleIds: Map<string, string>,
+ usedScheduleIds: Set<string>,
+): string {
+ const key = scheduleKey(context, name);
+ const existing = scheduleIds.get(key);
+ if (existing !== undefined) return existing;
+ let scheduleId: string;
+ do {
+ scheduleId = `mem_${createHash("sha256").update(`${key}:${randomUUID()}`).digest("hex")}`;
+ } while (usedScheduleIds.has(scheduleId));
+ scheduleIds.set(key, scheduleId);
+ usedScheduleIds.add(scheduleId);
+ return scheduleId;
+}
+
+function normalizeLimit(limit: number | undefined): number {
+ if (limit === undefined) return 20;
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
+ throw new Error("Schedule list limit must be an integer from 1 through 100.");
+ }
+ return limit;
+}
+
+function decodeCursor(cursor: string | undefined): number {
+ if (cursor === undefined) return 0;
+ const value = Number(cursor);
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid schedule cursor.");
+ return value;
+}
diff --git a/packages/eve/src/public/schedules/scope.ts b/packages/eve/src/public/schedules/scope.ts
new file mode 100644
index 000000000..55d7f62d4
--- /dev/null
+++ b/packages/eve/src/public/schedules/scope.ts
@@ -0,0 +1,6 @@
+import type { ScheduleScopeContext } from "#public/schedules/subscription.js";
+import { principalScope } from "#shared/principal-scope.js";
+
+export function byPrincipal(context: ScheduleScopeContext): string | null {
+ return principalScope(context.session.auth);
+}
diff --git a/packages/eve/src/public/schedules/subscription.ts b/packages/eve/src/public/schedules/subscription.ts
new file mode 100644
index 000000000..f6ab22766
--- /dev/null
+++ b/packages/eve/src/public/schedules/subscription.ts
@@ -0,0 +1,329 @@
+import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
+import type { SessionSchedule } from "#context/session-schedule.js";
+import type { SessionAuth } from "#context/keys.js";
+import type { SessionAuthContext } from "#channel/types.js";
+import type { ScheduleHandlerArgs } from "#public/definitions/schedule.js";
+import type { ExactDefinition } from "#public/definitions/exact.js";
+import type {
+ Approval,
+ ApprovalContext,
+ ApprovalStatus,
+ ApprovalResponseContext,
+ ApprovalResponseDecision,
+} from "#approval/definition.js";
+import type { UserContent } from "ai";
+import type { ChannelReference } from "#channel/compiled-channel.js";
+import type { InferReceiveTarget } from "#channel/receive-target.js";
+import type { Session } from "#channel/session.js";
+import { SCHEDULE_COLLECTION_DEFINITION_BRAND } from "#shared/schedule-collection-definition.js";
+import type { ScheduleProviderContext } from "#runtime/schedules/provider-types.js";
+
+/** A provider namespace scope, represented by one key or a hierarchical key path. */
+export type ScheduleScopeValue = string | readonly string[];
+/** Return `null` to deny the current schedule operation. */
+export type ScheduleScopeResolverResult = ScheduleScopeValue | null;
+export type ScheduleOperation =
+ | "create"
+ | "get"
+ | "list"
+ | "enable"
+ | "disable"
+ | "invoke"
+ | "delete";
+
+/** Trusted caller context used to authorize each management operation. */
+export interface ScheduleScopeContext {
+ readonly abortSignal: AbortSignal;
+ readonly operation?: ScheduleOperation;
+ readonly name?: string;
+ readonly session: {
+ readonly id: string;
+ readonly auth: SessionAuth;
+ readonly schedule?: SessionSchedule;
+ };
+ readonly channel: {
+ readonly kind?: string;
+ readonly continuationToken?: string;
+ readonly metadata?: Readonly<Record<string, unknown>>;
+ };
+}
+
+/** Stable creator reference; never a snapshot of credentials or permissions. */
+export interface SchedulePrincipalReference {
+ readonly type: string;
+ readonly authenticator: string;
+ readonly issuer?: string;
+ readonly principalId: string;
+ readonly subject?: string;
+}
+
+/** Framework-owned envelope stored alongside timing with the provider. */
+export interface ScheduleEnvelope<TPayload = unknown> {
+ readonly version: 3;
+ readonly payload: TPayload;
+ readonly scope: ScheduleScopeValue;
+ readonly principal: SchedulePrincipalReference;
+}
+
+export interface ScheduleOccurrenceIdentity {
+ /** Readable schedule label; name remains the unique management identifier. */
+ readonly displayName?: string;
+ readonly collection: string;
+ readonly scheduleId: string;
+ readonly name: string;
+ readonly executionId: string;
+ readonly scheduledAt: string;
+}
+
+/** Callback completion is distinct from completion of the agent sessions it starts. */
+export interface ScheduleOccurrenceEvent<TPayload = unknown> {
+ readonly type: "occurrence.dispatched" | "occurrence.failed";
+ readonly collection: string;
+ readonly executionId: string;
+ readonly name: string;
+ readonly scheduleId: string;
+ readonly scheduledAt: string;
+ readonly occurrence: ScheduleOccurrenceIdentity;
+ readonly sessionIds?: readonly string[];
+ readonly reason?: string;
+ readonly schedule?: ScheduleEnvelope<TPayload>;
+}
+
+export type ScheduleOccurrenceEventHandler<TPayload = unknown> = (
+ event: ScheduleOccurrenceEvent<TPayload>,
+) => void | Promise<void>;
+
+export type ScheduleExpression =
+ | {
+ readonly type: "cron";
+ readonly cron: string;
+ readonly timezone?: string;
+ readonly jitter?: number;
+ }
+ | { readonly type: "single"; readonly at: string; readonly timezone?: string };
+/** Relative delays are resolved once at the client call boundary using eve's clock. */
+export type ScheduleTiming =
+ | ScheduleExpression
+ | { readonly type: "delay"; readonly minutes: number };
+export type ScheduleState = "active" | "inactive" | "completed";
+
+/** Provider projection; payload and creator data are not read back. */
+export interface ScheduleRecord {
+ /** Human-readable label; multiple schedules may share it. */
+ readonly displayName?: string;
+ readonly createdAt: number;
+ readonly expression: ScheduleExpression;
+ readonly name: string;
+ readonly scheduleId: string;
+ readonly state: ScheduleState;
+ readonly updatedAt: number;
+}
+export interface SchedulePage {
+ readonly cursor: string | null;
+ readonly data: readonly ScheduleRecord[];
+}
+export interface ScheduleCreate<TPayload> {
+ readonly expression: ScheduleExpression;
+ readonly payload: TPayload;
+ readonly name: string;
+ readonly state?: ScheduleState;
+}
+export interface ScheduleList {
+ readonly cursor?: string;
+ readonly limit?: number;
+}
+export interface ScheduleOccurrence {
+ readonly executionId: string;
+ readonly name: string;
+ readonly scheduleId: string;
+ readonly scheduledAt: string;
+}
+
+/** Storage and occurrence transport supplied by a schedule backend. */
+export interface ScheduleProvider {
+ readonly kind: string;
+ create<TPayload>(
+ context: ScheduleProviderContext,
+ schedule: ScheduleCreate<TPayload>,
+ ): Promise<ScheduleRecord>;
+ list(context: ScheduleProviderContext, query: ScheduleList): Promise<SchedulePage>;
+ get(context: ScheduleProviderContext, name: string): Promise<ScheduleRecord | null>;
+ enable(context: ScheduleProviderContext, name: string): Promise<ScheduleRecord>;
+ disable(context: ScheduleProviderContext, name: string): Promise<ScheduleRecord>;
+ invoke(context: ScheduleProviderContext, name: string): Promise<void>;
+ delete(context: ScheduleProviderContext, name: string): Promise<boolean>;
+}
+
+export interface ScheduleClientCreate<TPayload> {
+ readonly expression: ScheduleTiming;
+ /** Display label. Creation allocates a unique management name returned in the receipt. */
+ readonly name: string;
+ readonly payload: TPayload;
+}
+export interface SchedulePageResult {
+ readonly cursor: string | null;
+ readonly data: readonly ScheduleRecord[];
+}
+
+/** Authenticated client; payload and creator identity are immutable after creation. */
+export interface ScheduleClient<TPayload> {
+ create(input: ScheduleClientCreate<TPayload>): Promise<ScheduleRecord>;
+ delete(name: string): Promise<boolean>;
+ disable(name: string): Promise<ScheduleRecord>;
+ enable(name: string): Promise<ScheduleRecord>;
+ get(name: string): Promise<ScheduleRecord | null>;
+ invoke(name: string): Promise<void>;
+ list(input?: ScheduleList): Promise<SchedulePageResult>;
+}
+
+/** Starts fresh unattended work bound to the resolved creator; callers cannot choose another identity. */
+export type DynamicSchedulesToFn = <TChannel extends ChannelReference<unknown>>(
+ channel: TChannel,
+ target: InferReceiveTarget<TChannel>,
+) => { send(message: string | UserContent): Promise<Session> };
+
+export type ScheduleCreateApproval<TPrepared> =
+ | ((
+ context: ApprovalContext & { readonly payload: TPrepared },
+ ) => ApprovalStatus | Promise<ApprovalStatus>)
+ | {
+ readonly request: (
+ context: ApprovalContext & { readonly payload: TPrepared },
+ ) => ApprovalStatus | Promise<ApprovalStatus>;
+ readonly response?: (
+ context: ApprovalResponseContext & { readonly payload: TPrepared },
+ ) => ApprovalResponseDecision | Promise<ApprovalResponseDecision>;
+ };
+export type ScheduleApprovals<TPrepared> = Partial<
+ Record<Exclude<ScheduleOperation, "create">, Approval>
+> & {
+ readonly create?: ScheduleCreateApproval<TPrepared>;
+};
+
+/** Execution context; `to` starts fresh, unattended sessions as the resolved creator. */
+export interface DynamicSchedulesRunArgs<TPayload> extends Pick<ScheduleHandlerArgs, "waitUntil"> {
+ readonly to: DynamicSchedulesToFn;
+ readonly payload: TPayload;
+ readonly occurrence: ScheduleOccurrenceIdentity;
+ readonly auth: SessionAuthContext;
+}
+
+/** Defines dynamically created schedules whose occurrences invoke authored code. */
+export interface DynamicSchedulesDefinition<
+ TPayload = unknown,
+ TSchema extends StandardSchemaV1<unknown, TPayload> = StandardSchemaV1<unknown, TPayload>,
+ TPrepared = TPayload,
+> {
+ readonly description?: string;
+ /** Model-facing payload schema. Destination intent may be resolved by `run`. */
+ readonly inputSchema: TSchema;
+ /** Backend used to store schedules and deliver occurrences. */
+ readonly provider: ScheduleProvider;
+ /**
+ * Validates application policy and enriches a creation payload before the provider write.
+ * The caller constructs input; eve validates it with `inputSchema`, authorizes creation
+ * through `scope`, then calls `preparePayload` with trusted creation context. eve checks that the
+ * result is bounded JSON and persists it; `inputSchema` describes caller input, not stored prepared output.
+ * Throw an actionable error to reject creation without writing a schedule.
+ *
+ * A common use is capturing the current channel destination: derive channel/workspace
+ * references from verified caller context, replace any model-supplied references, and
+ * return them with the task. Keep captured fields out of the input schema.
+ * Channel-less or delegated callers may lack that context; reject those cases explicitly.
+ *
+ * Runs only on creation. Model calls invoke preparePayload before approval and again before
+ * writing; execution fails if the prepared result differs from the approved snapshot.
+ * Authenticated clients invoke preparePayload once before writing without model approval. Reads, enable/disable operations, and occurrence execution do not call it. Omission
+ * stores validated input unchanged. Creation retries may call it again, so avoid
+ * irreversible side effects; state changes never recapture a different destination.
+ * `auth`, `run`, and occurrence events receive the inferred return type. Declare `preparePayload`
+ * before those callbacks for contextual inference, or annotate its return type explicitly.
+ * Prepared application data is not revalidated against the input schema at execution;
+ * validate the application's persisted contract in authored code when necessary.
+ */
+ readonly preparePayload?: (
+ payload: TPayload,
+ context: ScheduleScopeContext & { readonly operation: "create"; readonly name: string },
+ ) => TPrepared | Promise<TPrepared>;
+ /** Authorizes every management operation. Defaults to `byPrincipal`. */
+ readonly scope?: (
+ context: ScheduleScopeContext & { readonly operation: ScheduleOperation },
+ ) => ScheduleScopeResolverResult | Promise<ScheduleScopeResolverResult>;
+ /** Resolves the captured creator to current execution auth; return `null` to deny. */
+ readonly auth: (context: {
+ readonly principal: SchedulePrincipalReference;
+ readonly payload: NoInfer<TPrepared>;
+ readonly occurrence: ScheduleOccurrenceIdentity;
+ }) => SessionAuthContext | null | Promise<SessionAuthContext | null>;
+ /** May repeat on provider retries. Key external effects on the occurrence identity. */
+ readonly run: (args: DynamicSchedulesRunArgs<NoInfer<TPrepared>>) => void | Promise<void>;
+ readonly events?: {
+ /** After `run` and registered `waitUntil` work succeed; may repeat on retries. */
+ readonly "occurrence.dispatched"?: ScheduleOccurrenceEventHandler<NoInfer<TPrepared>>;
+ /** On a permanent provider failure or after its retry budget is exhausted. */
+ readonly "occurrence.failed"?: ScheduleOccurrenceEventHandler<NoInfer<TPrepared>>;
+ };
+ /** Expose operation tools directly (default true), or false for code-only scheduling. */
+ readonly tool?: boolean;
+ /** Model-call policies keyed by operation. Create receives the validated prepared payload. */
+ readonly approval?: ScheduleApprovals<NoInfer<TPrepared>>;
+}
+
+export type DefinedDynamicSchedules<
+ TPayload = unknown,
+ TSchema extends StandardSchemaV1<unknown, TPayload> = StandardSchemaV1<unknown, TPayload>,
+ TPrepared = TPayload,
+> = DynamicSchedulesDefinition<TPayload, TSchema, TPrepared> & {
+ readonly [SCHEDULE_COLLECTION_DEFINITION_BRAND]: true;
+};
+
+type DynamicSchedulesOptions<
+ TInput,
+ TSchema extends StandardSchemaV1<unknown, TInput>,
+ TPrepared = TInput,
+> = Omit<
+ DynamicSchedulesDefinition<TInput, TSchema, TPrepared>,
+ "provider" | "tool" | "approval"
+> & {
+ /** Backend used by this definition. */
+ readonly provider: ScheduleProvider;
+} & (
+ | { readonly tool: false; readonly approval?: never }
+ | { readonly tool?: true; readonly approval?: ScheduleApprovals<NoInfer<TPrepared>> }
+ );
+
+/**
+ * Defines a dynamic schedule subscription. Export it from `agent/schedules/`;
+ * identity comes from the module path. inputSchema validates caller input,
+ * while eve captures creator identity separately and re-resolves it on every attempt.
+ * `run` chooses destinations and starts work; no creation conversation is implicitly captured.
+ */
+export function defineDynamicSchedules<TInput, TPrepared>(
+ definition: Omit<
+ DynamicSchedulesOptions<TInput, StandardSchemaV1<unknown, TInput>, TPrepared>,
+ "preparePayload"
+ > & {
+ readonly preparePayload: (
+ payload: TInput,
+ context: ScheduleScopeContext & { readonly operation: "create"; readonly name: string },
+ ) => TPrepared | Promise<TPrepared>;
+ },
+): DefinedDynamicSchedules<TInput, StandardSchemaV1<unknown, TInput>, TPrepared>;
+export function defineDynamicSchedules<TSchema extends StandardSchemaV1<unknown, unknown>>(
+ definition: ExactDefinition<
+ DynamicSchedulesOptions<StandardSchemaV1.InferOutput<TSchema>, TSchema>,
+ DynamicSchedulesOptions<StandardSchemaV1.InferOutput<TSchema>, TSchema>
+ >,
+): DefinedDynamicSchedules<StandardSchemaV1.InferOutput<TSchema>, TSchema>;
+export function defineDynamicSchedules(
+ definition: Omit<DynamicSchedulesDefinition<any, any, any>, "provider"> & {
+ readonly provider: ScheduleProvider;
+ },
+): DefinedDynamicSchedules<any, any, any> {
+ Object.assign(definition, {
+ provider: definition.provider,
+ tool: definition.tool ?? true,
+ [SCHEDULE_COLLECTION_DEFINITION_BRAND]: true,
+ });
+ return definition as DefinedDynamicSchedules<any, any, any>;
+}
diff --git a/packages/eve/src/public/schedules/testing.ts b/packages/eve/src/public/schedules/testing.ts
new file mode 100644
index 000000000..95707f15f
--- /dev/null
+++ b/packages/eve/src/public/schedules/testing.ts
@@ -0,0 +1,4 @@
+export {
+ inMemoryScheduleProvider,
+ type InMemoryScheduleProviderOptions,
+} from "#public/schedules/providers/in-memory.js";
diff --git a/packages/eve/src/runtime/channels/registry.test.ts b/packages/eve/src/runtime/channels/registry.test.ts
index 6dbad307b..4b5e962ce 100644
--- a/packages/eve/src/runtime/channels/registry.test.ts
+++ b/packages/eve/src/runtime/channels/registry.test.ts
@@ -55,7 +55,7 @@ describe("createRuntimeAdapterRegistry", () => {
// channel-less schedule (i.e. every markdown schedule, which is
// forbidden from declaring a channel). Locks the framework
// registration so that rehydrating a serialized schedule adapter
- // returns the bare discriminator instead of throwing.
+ // restores its kind and state instead of throwing.
it("rehydrates a serialized schedule adapter through the framework registry", () => {
const registry = createRuntimeAdapterRegistry({ channels: [] });
@@ -64,7 +64,7 @@ describe("createRuntimeAdapterRegistry", () => {
state: {},
});
- expect(rehydrated).toEqual({ kind: SCHEDULE_ADAPTER_KIND, state: {} });
+ expect(rehydrated).toMatchObject({ kind: SCHEDULE_ADAPTER_KIND, state: {} });
});
// Mirror of the schedule rehydration regression — proves the
diff --git a/packages/eve/src/runtime/schedules/collection-client.ts b/packages/eve/src/runtime/schedules/collection-client.ts
new file mode 100644
index 000000000..a07780ce2
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/collection-client.ts
@@ -0,0 +1,267 @@
+import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
+import { createHash, randomUUID } from "node:crypto";
+import { isDeepStrictEqual } from "node:util";
+import { readSessionSchedule } from "#context/session-schedule.js";
+import { loadContext, contextStorage } from "#context/container.js";
+import type { SessionSchedule } from "#context/session-schedule.js";
+import { dispatchScheduledOccurrence } from "#runtime/schedules/dispatch-occurrence.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import type {
+ ScheduleClient,
+ ScheduleClientCreate,
+ DynamicSchedulesDefinition,
+ ScheduleEnvelope,
+ SchedulePageResult,
+ SchedulePrincipalReference,
+ ScheduleScopeContext,
+ ScheduleScopeValue,
+} from "#public/schedules/subscription.js";
+import { projectScheduleRecord } from "#runtime/schedules/record.js";
+import { byPrincipal } from "#public/schedules/scope.js";
+import type { ScheduleProviderContext } from "#runtime/schedules/provider-types.js";
+import {
+ createScheduleCollectionPayload,
+ validateSchedulePayload,
+ type ScheduleCollectionPayload,
+} from "#runtime/schedules/payload.js";
+import {
+ resolveScheduleTiming,
+ validateScheduleListLimit,
+ validateScheduleName,
+} from "#runtime/schedules/validation.js";
+
+export interface ScheduleBoundCallContext extends ScheduleScopeContext {
+ readonly application: string;
+ readonly collection: string;
+ readonly operationId?: () => string;
+}
+
+export interface PreparedScheduleCreate<TPrepared = unknown> {
+ readonly displayName: string;
+ readonly expression: import("#public/schedules/subscription.js").ScheduleTiming;
+ readonly envelope: ScheduleEnvelope<TPrepared>;
+}
+
+/** Internal capabilities used by generated create approval; authored clients expose only create. */
+export interface ScheduleCollectionClient<TInput, TPrepared> extends ScheduleClient<TInput> {
+ prepareCreate(
+ input: ScheduleClientCreate<TInput>,
+ ): Promise<PreparedScheduleCreate<TInput | TPrepared>>;
+ create(
+ input: ScheduleClientCreate<TInput>,
+ approved?: PreparedScheduleCreate,
+ ): Promise<import("#public/schedules/subscription.js").ScheduleRecord>;
+}
+
+export function createScheduleCollectionClient<TPayload, TPrepared = TPayload>(
+ definition: DynamicSchedulesDefinition<TPayload, StandardSchemaV1<unknown, TPayload>, TPrepared>,
+ callContext: ScheduleBoundCallContext,
+): ScheduleCollectionClient<TPayload, TPrepared> {
+ const nextOperationId = callContext.operationId ?? randomUUID;
+
+ const contextFor = (
+ operation: NonNullable<ScheduleScopeContext["operation"]>,
+ name?: string,
+ ): ScheduleScopeContext & {
+ readonly operation: NonNullable<ScheduleScopeContext["operation"]>;
+ } => {
+ const context = { ...callContext, operation } as ScheduleScopeContext & {
+ operation: NonNullable<ScheduleScopeContext["operation"]>;
+ name?: string;
+ };
+ if (name !== undefined) context.name = name;
+ return context;
+ };
+ const resolveNamespace = async (
+ operation: NonNullable<ScheduleScopeContext["operation"]>,
+ name?: string,
+ ): Promise<{ scope: ScheduleScopeValue; provider: ScheduleProviderContext }> => {
+ assertScheduleManagementAllowed(callContext.session.schedule);
+ const context = contextFor(operation, name);
+ const scope =
+ definition.scope === undefined
+ ? byPrincipal(context)
+ : await definition.scope({ ...context, operation });
+ if (scope === null) throw new Error(`Schedule ${operation} is not available in this context.`);
+ validateScope(scope);
+ const provider: ScheduleProviderContext = {
+ abortSignal: callContext.abortSignal,
+ collection: callContext.collection,
+ namespace: deriveScheduleNamespace(callContext.application, callContext.collection, scope),
+ operationId: nextOperationId(),
+ target: {
+ key: callContext.application,
+ deliver: async ({ payload, occurrence }) => {
+ await dispatchScheduledOccurrence({
+ bundle: loadContext().require(BundleKey),
+ collection: callContext.collection,
+ definition,
+ occurrence: { ...occurrence, collection: callContext.collection },
+ payload: payload as ScheduleCollectionPayload<unknown>,
+ });
+ },
+ },
+ };
+ return { scope, provider };
+ };
+
+ const prepareCreation = async (input: ScheduleClientCreate<TPayload>) => {
+ const displayName = validateScheduleName(input.name);
+ // Validate timing before preparation; relative delays are resolved again at the write boundary.
+ resolveScheduleTiming(input.expression);
+ const { scope, provider } = await resolveNamespace("create", displayName);
+ const creator = principalReference(callContext.session.auth.current);
+ if (creator === null)
+ throw new Error("Creating a schedule requires an authenticated principal.");
+ const validated = await validateSchedulePayload<TPayload>(
+ definition.inputSchema,
+ input.payload,
+ );
+ const preparedPayload =
+ definition.preparePayload === undefined
+ ? validated
+ : await definition.preparePayload(validated, {
+ ...contextFor("create", displayName),
+ operation: "create",
+ name: displayName,
+ });
+ const envelope: ScheduleEnvelope<TPayload | TPrepared> = {
+ version: 3,
+ payload: preparedPayload,
+ scope,
+ principal: creator,
+ };
+ const payload = createScheduleCollectionPayload({
+ application: callContext.application,
+ collection: callContext.collection,
+ envelope,
+ });
+ const prepared = {
+ displayName,
+ expression: JSON.parse(
+ JSON.stringify(input.expression),
+ ) as import("#public/schedules/subscription.js").ScheduleTiming,
+ envelope: payload.envelope,
+ };
+ if (Buffer.byteLength(JSON.stringify(prepared)) > 64 * 1024)
+ throw new Error(
+ "Prepared schedule creation exceeds the 64 KB limit, including timing and payload.",
+ );
+ return { prepared, provider };
+ };
+
+ return {
+ async prepareCreate(input) {
+ return (await prepareCreation(input)).prepared;
+ },
+ async create(input, approved) {
+ const { prepared, provider } = await prepareCreation(input);
+ if (approved !== undefined && !isDeepStrictEqual(prepared, approved))
+ throw new Error(
+ "Schedule creation changed after approval. Request a new creation approval; no schedule was written.",
+ );
+ const name = `${prepared.displayName.slice(0, 218)}--${randomUUID()}`;
+ const expression = resolveScheduleTiming(input.expression);
+ const payload = createScheduleCollectionPayload({
+ application: callContext.application,
+ collection: callContext.collection,
+ envelope: prepared.envelope,
+ });
+ return projectScheduleRecord(
+ await definition.provider.create(provider, { expression, name, payload }),
+ );
+ },
+ async delete(name) {
+ const normalized = validateScheduleName(name);
+ const { provider } = await resolveNamespace("delete", normalized);
+ return await definition.provider.delete(provider, normalized);
+ },
+ async disable(name) {
+ const normalized = validateScheduleName(name);
+ const { provider } = await resolveNamespace("disable", normalized);
+ return projectScheduleRecord(await definition.provider.disable(provider, normalized));
+ },
+ async enable(name) {
+ const normalized = validateScheduleName(name);
+ const { provider } = await resolveNamespace("enable", normalized);
+ return projectScheduleRecord(await definition.provider.enable(provider, normalized));
+ },
+ async get(name) {
+ const normalized = validateScheduleName(name);
+ const { provider } = await resolveNamespace("get", normalized);
+ const record = await definition.provider.get(provider, normalized);
+ return record === null ? null : projectScheduleRecord(record);
+ },
+ async invoke(name) {
+ const normalized = validateScheduleName(name);
+ const { provider } = await resolveNamespace("invoke", normalized);
+ await definition.provider.invoke(provider, normalized);
+ },
+ async list(input = {}): Promise<SchedulePageResult> {
+ const limit = validateScheduleListLimit(input.limit);
+ const { provider } = await resolveNamespace("list");
+ const query: { cursor?: string; limit?: number } = {};
+ if (input.cursor?.trim()) query.cursor = input.cursor.trim();
+ if (limit !== undefined) query.limit = limit;
+ const page = await definition.provider.list(provider, query);
+ return { ...page, data: page.data.map(projectScheduleRecord) };
+ },
+ };
+}
+
+export function assertScheduleManagementAllowed(schedule?: SessionSchedule): void {
+ const context = contextStorage.getStore();
+ if (
+ schedule !== undefined ||
+ (context !== undefined && readSessionSchedule(context) !== undefined)
+ )
+ throw new Error("Schedule management is unavailable during scheduled execution.");
+}
+
+function principalReference(
+ auth: {
+ readonly principalType: string;
+ readonly authenticator: string;
+ readonly issuer?: string;
+ readonly principalId: string;
+ readonly subject?: string;
+ } | null,
+): SchedulePrincipalReference | null {
+ if (auth === null || auth.principalType === "anonymous" || auth.principalType === "runtime")
+ return null;
+ const reference: {
+ type: string;
+ authenticator: string;
+ issuer?: string;
+ principalId: string;
+ subject?: string;
+ } = {
+ type: auth.principalType,
+ authenticator: auth.authenticator,
+ principalId: auth.principalId,
+ };
+ if (auth.issuer !== undefined) reference.issuer = auth.issuer;
+ if (auth.subject !== undefined) reference.subject = auth.subject;
+ return reference;
+}
+
+function validateScope(scope: ScheduleScopeValue): void {
+ const values = typeof scope === "string" ? [scope] : scope;
+ if (
+ values.length === 0 ||
+ values.some((value) => typeof value !== "string" || value.trim().length === 0)
+ )
+ throw new Error("Schedule scope must be a non-empty string or tuple of non-empty strings.");
+}
+
+function deriveScheduleNamespace(
+ application: string,
+ collection: string,
+ scope: ScheduleScopeValue,
+): string {
+ if (application.trim().length === 0) throw new Error("Schedule application must not be empty.");
+ const digest = createHash("sha256")
+ .update(JSON.stringify(["eve-schedule-namespace-v2", application, collection, scope]))
+ .digest("base64url");
+ return `eve-${digest}`;
+}
diff --git a/packages/eve/src/runtime/schedules/dispatch-occurrence.ts b/packages/eve/src/runtime/schedules/dispatch-occurrence.ts
new file mode 100644
index 000000000..af43baf4f
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/dispatch-occurrence.ts
@@ -0,0 +1,47 @@
+import { scheduleDisplayName } from "#runtime/schedules/record.js";
+import { ScheduleDispatcher } from "#channel/schedule.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import type {
+ DynamicSchedulesDefinition,
+ ScheduleOccurrenceIdentity,
+} from "#public/schedules/subscription.js";
+import type { ScheduleCollectionPayload } from "#runtime/schedules/payload.js";
+import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+
+/** Dispatches an at-least-once callback and reports the sessions it started, if any. */
+export async function dispatchScheduledOccurrence(input: {
+ readonly bundle: Pick<CompiledRuntimeAgentBundle, "compiledArtifactsSource" | "graph">;
+ readonly collection: string;
+ readonly definition: DynamicSchedulesDefinition<any, any, any>;
+ readonly occurrence: ScheduleOccurrenceIdentity;
+ readonly payload: ScheduleCollectionPayload<unknown>;
+ readonly verifyDelivery?: () => Promise<void>;
+}): Promise<void> {
+ const occurrence = {
+ ...input.occurrence,
+ displayName: scheduleDisplayName(input.occurrence.name),
+ };
+ const result = await new ScheduleDispatcher({
+ runtime: createWorkflowRuntime({
+ compiledArtifactsSource: input.bundle.compiledArtifactsSource,
+ }),
+ channels: input.bundle.graph.root.channels,
+ }).triggerCollection({
+ collectionId: input.collection,
+ definition: input.definition,
+ occurrence,
+ payload: input.payload,
+ verifyDelivery: input.verifyDelivery,
+ });
+ await input.definition.events?.["occurrence.dispatched"]?.({
+ collection: input.collection,
+ executionId: input.occurrence.executionId,
+ name: occurrence.name,
+ occurrence,
+ scheduledAt: input.occurrence.scheduledAt,
+ scheduleId: input.occurrence.scheduleId,
+ sessionIds: result.sessions.map((session) => session.id),
+ schedule: input.payload.envelope,
+ type: "occurrence.dispatched",
+ });
+}
diff --git a/packages/eve/src/runtime/schedules/load-collection.ts b/packages/eve/src/runtime/schedules/load-collection.ts
new file mode 100644
index 000000000..f13248622
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/load-collection.ts
@@ -0,0 +1,42 @@
+import type { CompiledAgentManifest } from "#compiler/manifest.js";
+import { normalizeScheduleCollectionDefinition } from "#internal/authored-definition/schedule-collection.js";
+import type { DynamicSchedulesDefinition } from "#public/schedules/subscription.js";
+import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
+import { loadResolvedModuleExport } from "#runtime/resolve-helpers.js";
+import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+
+/** The agent does not deploy the named collection, or not with the expected provider. */
+export class ScheduleCollectionNotDeployedError extends Error {}
+
+/**
+ * Reloads a collection's authored definition inside a durable step or queue
+ * callback, where the closure that created the occurrence no longer exists.
+ */
+export async function loadScheduleCollectionDefinition(
+ bundle: Pick<CompiledRuntimeAgentBundle, "compiledArtifactsSource" | "moduleMap" | "nodeId">,
+ collection: string,
+ options: { readonly manifest?: CompiledAgentManifest; readonly providerKind?: string } = {},
+): Promise<DynamicSchedulesDefinition<unknown>> {
+ const manifest =
+ options.manifest ??
+ (await loadCompiledManifest({ compiledArtifactsSource: bundle.compiledArtifactsSource }));
+ const compiled = manifest.scheduleCollections.find(
+ (item) =>
+ item.name === collection &&
+ (options.providerKind === undefined || item.providerKind === options.providerKind),
+ );
+ if (compiled === undefined)
+ throw new ScheduleCollectionNotDeployedError(
+ `Schedule collection "${collection}" is not deployed by this agent.`,
+ );
+ const exported = await loadResolvedModuleExport({
+ definition: compiled,
+ kindLabel: "schedule collection",
+ moduleMap: bundle.moduleMap,
+ nodeId: bundle.nodeId,
+ });
+ return normalizeScheduleCollectionDefinition(
+ exported,
+ `Invalid schedule collection ${collection}.`,
+ ) as DynamicSchedulesDefinition<unknown>;
+}
diff --git a/packages/eve/src/runtime/schedules/payload.ts b/packages/eve/src/runtime/schedules/payload.ts
new file mode 100644
index 000000000..fffd83c4a
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/payload.ts
@@ -0,0 +1,85 @@
+import { z } from "#compiled/zod/index.js";
+import type { ScheduleEnvelope } from "#public/schedules/subscription.js";
+
+const referenceSchema = z.string().min(1).max(2048);
+const principalReferenceSchema = z
+ .object({
+ type: referenceSchema,
+ authenticator: referenceSchema,
+ issuer: referenceSchema.optional(),
+ principalId: referenceSchema,
+ subject: referenceSchema.optional(),
+ })
+ .strict();
+const payloadSchema = z
+ .object({
+ eve: z
+ .object({ application: referenceSchema, collection: referenceSchema, version: z.literal(3) })
+ .strict(),
+ envelope: z
+ .object({
+ version: z.literal(3),
+ payload: z.json(),
+ scope: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
+ principal: principalReferenceSchema,
+ })
+ .strict(),
+ })
+ .strict();
+
+export interface ScheduleCollectionPayload<TPayload = unknown> {
+ readonly eve: { readonly application: string; readonly collection: string; readonly version: 3 };
+ readonly envelope: ScheduleEnvelope<TPayload>;
+}
+
+export function createScheduleCollectionPayload<TPayload>(input: {
+ readonly application: string;
+ readonly collection: string;
+ readonly envelope: ScheduleEnvelope<TPayload>;
+}): ScheduleCollectionPayload<TPayload> {
+ return parseSchedulePayload({
+ eve: { application: input.application, collection: input.collection, version: 3 },
+ envelope: input.envelope,
+ });
+}
+
+export function parseSchedulePayload<TPayload = unknown>(
+ value: unknown,
+ expected?: { readonly application: string; readonly collection: string },
+): ScheduleCollectionPayload<TPayload> {
+ let snapshot: unknown;
+ try {
+ const json = JSON.stringify(value);
+ if (json === undefined || Buffer.byteLength(json) > 64 * 1024) throw new Error();
+ snapshot = JSON.parse(json);
+ } catch {
+ throw new Error("Invalid scheduled collection payload; recreate the schedule.");
+ }
+ const parsed = payloadSchema.safeParse(snapshot);
+ if (!parsed.success)
+ throw new Error("Invalid scheduled collection payload; recreate the schedule.");
+ if (
+ expected !== undefined &&
+ (parsed.data.eve.application !== expected.application ||
+ parsed.data.eve.collection !== expected.collection)
+ ) {
+ throw new Error("Schedule identity changed; recreate the schedule.");
+ }
+ return parsed.data as ScheduleCollectionPayload<TPayload>;
+}
+
+/** Shared validation for client writes and delivered occurrences. */
+export async function validateSchedulePayload<T>(
+ schema: { readonly "~standard": { validate(value: unknown): unknown } },
+ value: unknown,
+): Promise<T> {
+ const result = (await schema["~standard"].validate(value)) as {
+ readonly issues?: readonly { readonly message: string }[];
+ readonly value?: T;
+ };
+ if (result.issues !== undefined || !("value" in result))
+ throw new Error(
+ `Invalid schedule payload: ${result.issues?.map((issue) => issue.message).join("; ") ?? "schema validation failed"}.`,
+ );
+ return result.value as T;
+}
diff --git a/packages/eve/src/runtime/schedules/provider-types.ts b/packages/eve/src/runtime/schedules/provider-types.ts
new file mode 100644
index 000000000..b5a01f390
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/provider-types.ts
@@ -0,0 +1,5 @@
+export type {
+ ScheduleDelivery,
+ ScheduleDeliveryTarget,
+ ScheduleProviderContext,
+} from "#public/schedules/provider-types.js";
diff --git a/packages/eve/src/runtime/schedules/queue-namespace.ts b/packages/eve/src/runtime/schedules/queue-namespace.ts
new file mode 100644
index 000000000..7fbb0b521
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/queue-namespace.ts
@@ -0,0 +1,9 @@
+import { createHash } from "node:crypto";
+
+/** Derives the private Vercel Queues topic used by one eve agent's schedule collections. */
+export function deriveEveScheduleQueueTopic(application: string): string {
+ const normalized = application.trim();
+ if (normalized.length === 0) throw new Error("Schedule application must not be empty.");
+ const digest = createHash("sha256").update(normalized).digest("hex").slice(0, 32);
+ return `__eve_schedule_${digest}`;
+}
diff --git a/packages/eve/src/runtime/schedules/record.ts b/packages/eve/src/runtime/schedules/record.ts
new file mode 100644
index 000000000..7307b4bf6
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/record.ts
@@ -0,0 +1,13 @@
+import type { ScheduleRecord } from "#public/schedules/subscription.js";
+
+/** Provider names retain the readable label so get/list need no payload read-back. */
+export function scheduleDisplayName(name: string): string {
+ return name.replace(
+ /--[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
+ "",
+ );
+}
+
+export function projectScheduleRecord(record: ScheduleRecord): ScheduleRecord {
+ return { ...record, displayName: scheduleDisplayName(record.name) };
+}
diff --git a/packages/eve/src/runtime/schedules/validation.ts b/packages/eve/src/runtime/schedules/validation.ts
new file mode 100644
index 000000000..a9d37ae72
--- /dev/null
+++ b/packages/eve/src/runtime/schedules/validation.ts
@@ -0,0 +1,102 @@
+import type { ScheduleExpression, ScheduleTiming } from "#public/schedules/subscription.js";
+
+const SCHEDULE_IDENTIFIER = /^[0-9A-Za-z][0-9A-Za-z._-]{0,255}$/u;
+const LOCAL_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::00)?$/u;
+
+export function validateScheduleName(name: string): string {
+ const normalized = name.trim();
+ if (!SCHEDULE_IDENTIFIER.test(normalized)) {
+ throw new Error(
+ "Schedule name must be 1–256 characters, start with an ASCII letter or digit, and contain only letters, digits, '.', '_', and '-'.",
+ );
+ }
+ return normalized;
+}
+
+export const MAX_SCHEDULE_DELAY_MINUTES = 525_600;
+
+export function resolveScheduleTiming(
+ timing: ScheduleTiming,
+ now = Date.now(),
+): ScheduleExpression {
+ if (timing.type !== "delay") return validateScheduleExpression(timing);
+ if (
+ !Number.isSafeInteger(timing.minutes) ||
+ timing.minutes < 1 ||
+ timing.minutes > MAX_SCHEDULE_DELAY_MINUTES
+ ) {
+ throw new Error(
+ `Schedule delay must be a whole number from 1 through ${MAX_SCHEDULE_DELAY_MINUTES} minutes.`,
+ );
+ }
+ if (Object.keys(timing).some((key) => key !== "type" && key !== "minutes")) {
+ throw new Error(
+ "Relative schedule delays accept only type and minutes; no timezone is needed.",
+ );
+ }
+ const at = new Date(Math.ceil((now + timing.minutes * 60_000) / 60_000) * 60_000);
+ return { type: "single", at: at.toISOString().slice(0, 16), timezone: "UTC" };
+}
+
+export function validateScheduleExpression(expression: ScheduleExpression): ScheduleExpression {
+ if (expression.type === "cron") {
+ const cron = expression.cron.trim().replace(/\s+/gu, " ");
+ if (cron.split(" ").length !== 5) {
+ throw new Error("Schedule cron expressions must contain exactly five fields.");
+ }
+ const normalized: {
+ type: "cron";
+ cron: string;
+ timezone?: string;
+ jitter?: number;
+ } = { type: "cron", cron };
+ if (expression.timezone !== undefined) {
+ normalized.timezone = validateTimezone(expression.timezone);
+ }
+ if (expression.jitter !== undefined) {
+ if (
+ !Number.isSafeInteger(expression.jitter) ||
+ expression.jitter < 1 ||
+ expression.jitter > 15
+ ) {
+ throw new Error("Schedule jitter must be an integer from 1 through 15 minutes.");
+ }
+ normalized.jitter = expression.jitter;
+ }
+ return normalized;
+ }
+
+ if (!LOCAL_DATE_TIME.test(expression.at)) {
+ throw new Error(
+ 'One-time schedules require a minute-precision local datetime in "YYYY-MM-DDTHH:mm" or "YYYY-MM-DDTHH:mm:00" format without an offset or fractional seconds.',
+ );
+ }
+ const normalized: { type: "single"; at: string; timezone?: string } = {
+ type: "single",
+ at: expression.at,
+ };
+ if (expression.timezone !== undefined)
+ normalized.timezone = validateTimezone(expression.timezone);
+ return normalized;
+}
+
+export function validateScheduleListLimit(limit: number | undefined): number | undefined {
+ if (limit === undefined) return undefined;
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
+ throw new Error("Schedule list limit must be an integer from 1 through 100.");
+ }
+ return limit;
+}
+
+function validateTimezone(timezone: string): string {
+ const normalized = timezone.trim();
+ if (normalized.length === 0 || normalized.length > 50) {
+ throw new Error("Schedule timezone must be a valid IANA timezone.");
+ }
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: normalized }).format(0);
+ } catch {
+ throw new Error(`Invalid IANA timezone: ${normalized}`);
+ }
+ return normalized;
+}
diff --git a/packages/eve/src/runtime/sessions/runtime-context-keys.ts b/packages/eve/src/runtime/sessions/runtime-context-keys.ts
index 3a0b37af9..86d5fff7f 100644
--- a/packages/eve/src/runtime/sessions/runtime-context-keys.ts
+++ b/packages/eve/src/runtime/sessions/runtime-context-keys.ts
@@ -6,7 +6,7 @@
import type { ChannelAdapter } from "#channel/adapter.js";
import { getAdapterKind } from "#channel/adapter.js";
import { ContextKey } from "#context/key.js";
-import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
+import { BUNDLE_CONTEXT_KEY_NAME, CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
import { deserializeRuntimeAdapter } from "#runtime/channels/registry.js";
import {
type DurableCompiledArtifactsSource,
@@ -54,7 +54,7 @@ export const ChannelKey = new ContextKey<ChannelAdapter>(CHANNEL_CONTEXT_KEY_NAM
},
});
-export const BundleKey = new ContextKey<CompiledBundle>("eve.bundle", {
+export const BundleKey = new ContextKey<CompiledBundle>(BUNDLE_CONTEXT_KEY_NAME, {
codec: {
serialize: (bundle): SerializedBundle => ({
nodeId: bundle.nodeId,
diff --git a/packages/eve/src/shared/principal-scope.ts b/packages/eve/src/shared/principal-scope.ts
new file mode 100644
index 000000000..004d869d7
--- /dev/null
+++ b/packages/eve/src/shared/principal-scope.ts
@@ -0,0 +1,15 @@
+import type { SessionAuth } from "#context/keys.js";
+
+const DISABLED_PRINCIPAL_TYPES = new Set(["anonymous", "runtime"]);
+
+export function principalScope(auth: SessionAuth): string | null {
+ const principal = auth.current;
+ if (principal === null || DISABLED_PRINCIPAL_TYPES.has(principal.principalType)) return null;
+ if (principal.principalType === "local-dev") return "local-dev";
+ return JSON.stringify([
+ principal.principalType,
+ principal.authenticator,
+ principal.issuer ?? null,
+ principal.principalId,
+ ]);
+}
diff --git a/packages/eve/src/shared/schedule-collection-definition.ts b/packages/eve/src/shared/schedule-collection-definition.ts
new file mode 100644
index 000000000..d672e130c
--- /dev/null
+++ b/packages/eve/src/shared/schedule-collection-definition.ts
@@ -0,0 +1,50 @@
+export const SCHEDULE_COLLECTION_DEFINITION_BRAND = Symbol.for(
+ "eve:schedule-collection-definition",
+);
+export const SCHEDULE_COLLECTION_SOURCE = Symbol.for("eve:schedule-collection-source");
+
+export interface ScheduleCollectionSourceIdentity {
+ readonly application: string;
+ readonly collection: string;
+ readonly logicalPath: string;
+ readonly sourceId: string;
+}
+
+export function stampScheduleCollectionSource(
+ value: object,
+ identity: ScheduleCollectionSourceIdentity,
+): void {
+ const existing = readScheduleCollectionSource(value);
+ if (existing !== undefined) {
+ if (
+ existing.application !== identity.application ||
+ existing.collection !== identity.collection ||
+ existing.logicalPath !== identity.logicalPath ||
+ existing.sourceId !== identity.sourceId
+ ) {
+ throw new Error("Schedule collection source identity does not match its compiled module.");
+ }
+ return;
+ }
+ Object.defineProperty(value, SCHEDULE_COLLECTION_SOURCE, {
+ configurable: false,
+ enumerable: false,
+ value: Object.freeze({ ...identity }),
+ });
+}
+
+export function readScheduleCollectionSource(
+ value: object,
+): ScheduleCollectionSourceIdentity | undefined {
+ return Reflect.get(value, SCHEDULE_COLLECTION_SOURCE) as
+ | ScheduleCollectionSourceIdentity
+ | undefined;
+}
+
+export function isScheduleCollectionDefinition(value: unknown): boolean {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ Reflect.get(value, SCHEDULE_COLLECTION_DEFINITION_BRAND) === true
+ );
+}
diff --git a/packages/eve/src/shared/schedule-collection-tools.ts b/packages/eve/src/shared/schedule-collection-tools.ts
new file mode 100644
index 000000000..e0f5e5692
--- /dev/null
+++ b/packages/eve/src/shared/schedule-collection-tools.ts
@@ -0,0 +1,3 @@
+export function scheduleCollectionToolPrefix(collection: string): string {
+ return `schedule__${collection.replaceAll("/", "-")}`;
+}
diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.ts
index 70ad2a222..d39b0298e 100644
--- a/packages/eve/src/subagents/tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -63,6 +63,7 @@ export function buildSubagentRunInput(input: {
* parent capabilities produce an undefined child capability set.
*/
readonly capabilities?: SessionCapabilities;
+ readonly schedule?: import("#context/session-schedule.js").SessionSchedule;
readonly channelMetadata?: ChannelInstrumentationProjection;
/** Replay-stable key the child's continuation token derives from. */
readonly continuationKey: string;
@@ -120,6 +121,7 @@ export function buildSubagentRunInput(input: {
},
auth,
capabilities,
+ schedule: input.schedule,
channelMetadata,
inheritedConversation,
continuationToken: childContinuationToken,
diff --git a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
index 3f62260f7..3926b10f4 100644
--- a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
+++ b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
@@ -420,11 +420,12 @@ describe("runtime compiled artifact loaders", () => {
expect(resolvedChannel.urlPath).toBe("/slack");
expect(typeof resolvedChannel.fetch).toBe("function");
expect(resolvedAgent.channels.filter((channel) => channel.name === "slack")).toHaveLength(1);
- // The runtime module map excludes compile-only config, instructions,
- // skills, and prompt schedules while retaining executable entries.
+ // The schedule wrapper loads its authored source to distinguish static
+ // schedules from collections; static schedules still execute via Cron.
const rootModuleIds = Object.keys(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules ?? {});
expect(rootModuleIds.filter((moduleId) => !moduleId.startsWith("eve:"))).toEqual([
"channels/slack.mjs",
+ "schedules/daily-digest.mjs",
"tools/get_weather.mjs",
]);
expect(rootModuleIds.some((moduleId) => moduleId.startsWith("eve:"))).toBe(true);
diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
index 230275a22..908ea3a2c 100644
--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
@@ -168,7 +168,7 @@ describe("schedule trigger end-to-end (channel-less schedules)", () => {
// \"schedule\"".
const rehydrated = await simulateStepBoundary(captured[0]!.adapter, bundle);
- expect(rehydrated).toEqual({ kind: SCHEDULE_ADAPTER_KIND, state: {} });
+ expect(rehydrated).toMatchObject({ kind: SCHEDULE_ADAPTER_KIND, state: {} });
});
});
@@ -224,7 +224,7 @@ describe("schedule trigger end-to-end (channel-less schedules)", () => {
const rehydrated = await simulateStepBoundary(captured[0]!.adapter, bundle);
- expect(rehydrated).toEqual({ kind: SCHEDULE_ADAPTER_KIND, state: {} });
+ expect(rehydrated).toMatchObject({ kind: SCHEDULE_ADAPTER_KIND, state: {} });
});
});