Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): support updating dynamic schedule timing and payload (#4535)

Colton Padden14f2af0f993a
diff --git a/.changeset/fresh-reminder-updates.md b/.changeset/fresh-reminder-updates.md
new file mode 100644
index 000000000..ae5785934
--- /dev/null
+++ b/.changeset/fresh-reminder-updates.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Add dynamic schedule updates for timing and complete payload replacement, with prepared-payload approval for model calls. Payload replacement makes the updating caller the new creator; custom schedule providers must implement `update`, and `preparePayload` now receives a `create` or `update` operation.
diff --git a/e2e/fixtures/agent-schedules/agent/lib/mock-responder.ts b/e2e/fixtures/agent-schedules/agent/lib/mock-responder.ts
index 2d932c123..ae1ac43a0 100644
--- a/e2e/fixtures/agent-schedules/agent/lib/mock-responder.ts
+++ b/e2e/fixtures/agent-schedules/agent/lib/mock-responder.ts
@@ -2,6 +2,11 @@ import type { MockModelRequest, MockModelResponse } from "eve/evals";
const SCHEDULE = "collection-email";
const EMAIL = { to: "[email protected]", subject: "Scheduled note", body: "A fixture note." };
+const UPDATED_EMAIL = {
+ subject: "Updated note",
+ body: "A revised fixture note.",
+};
/**
* Scripted mock for the world suites. Each `schedule-collection` eval prompt
@@ -11,7 +16,8 @@ const EMAIL = { to: "[email protected]", subject: "Scheduled note", body: "A fi
export function respond(request: MockModelRequest): MockModelResponse | string {
const message = request.lastUserMessage ?? "";
if (message.includes("This scheduled occurrence is firing now")) {
- return once(request, "record-email", EMAIL, () => `Sent "${EMAIL.subject}" to ${EMAIL.to}.`);
+ const email = message.includes(UPDATED_EMAIL.subject) ? UPDATED_EMAIL : EMAIL;
+ return once(request, "record-email", email, () => `Sent "${email.subject}" to ${email.to}.`);
}
if (message.includes(`Create the schedule named ${SCHEDULE}`)) {
const input = {
@@ -24,6 +30,23 @@ export function respond(request: MockModelRequest): MockModelResponse | string {
};
return once(request, "schedule__requests__create", input, () => `Saved ${SCHEDULE}.`);
}
+ if (message.includes("Update the schedule using management name")) {
+ const name = /management name ([0-9A-Za-z._-]+)\./u.exec(message)?.[1];
+ if (!name) throw new Error("The update prompt needs a management name.");
+ return once(
+ request,
+ "schedule__requests__update",
+ {
+ name,
+ expression: { type: "single", at: "2030-01-02T09:00", timezone: "UTC" },
+ payload: {
+ task: `Send a fixture email with subject "${UPDATED_EMAIL.subject}" and body "${UPDATED_EMAIL.body}".`,
+ destination: "creator-email",
+ },
+ },
+ () => `Updated ${SCHEDULE}.`,
+ );
+ }
for (const operation of ["get", "invoke", "delivery"] as const) {
if (message.includes("share-schedule") && message.includes(OPERATION_PROMPTS[operation])) {
return once(request, "share-schedule", { operation, name: SCHEDULE }, (output) => output);
diff --git a/e2e/fixtures/agent-schedules/evals/schedule-collection.eval.ts b/e2e/fixtures/agent-schedules/evals/schedule-collection.eval.ts
index 4423b272b..106f6cfde 100644
--- a/e2e/fixtures/agent-schedules/evals/schedule-collection.eval.ts
+++ b/e2e/fixtures/agent-schedules/evals/schedule-collection.eval.ts
@@ -29,6 +29,39 @@ export default defineEval({
);
client.succeeded();
client.calledTool("share-schedule", { input: { operation: "get", name: "collection-email" } });
+ const record = client.toolCalls.find((call) => call.name === "share-schedule")?.output;
+ const managementName = Reflect.get(Object(record), "name");
+ if (typeof managementName !== "string") throw new Error("The schedule has no management name.");
+ const edit = await t.send(
+ `Alice wants to revise her saved reminder. Update the schedule using management name ${managementName}. Set its one-time timing to January 2, 2030 at 09:00 UTC and replace its complete payload with a task to send a fixture email with subject Updated note and body A revised fixture note., and destination creator-email. Save the change without sending the email now.`,
+ );
+ edit.expectOk();
+ const updateApproval = edit.session.requireInputRequest({
+ display: "confirmation",
+ toolName: "schedule__requests__update",
+ });
+ const updated = await edit.session.respond([
+ { optionId: "approve", requestId: updateApproval.requestId },
+ ]);
+ updated.expectOk();
+ updated.session.calledTool("schedule__requests__update", {
+ input: {
+ name: managementName,
+ expression: { type: "single", at: "2030-01-02T09:00", timezone: "UTC" },
+ payload: { destination: "creator-email" },
+ },
+ status: "completed",
+ });
+ const inspected = await t.send(
+ "Inspect the schedule named collection-email with share-schedule using its get operation.",
+ );
+ inspected.succeeded();
+ inspected.calledTool("share-schedule", {
+ output: {
+ name: managementName,
+ expression: { type: "single", at: "2030-01-02T09:00", timezone: "UTC" },
+ },
+ });
const manual = await t.send("Use share-schedule to invoke collection-email once.");
manual.succeeded();
manual.calledTool("share-schedule", {
@@ -46,7 +79,7 @@ export default defineEval({
const scheduled = await t.target.attachSession(sessionId);
scheduled.succeeded();
scheduled.calledTool("record-email", {
- input: { to: "[email protected]", subject: "Scheduled note" },
+ input: { to: "[email protected]", subject: "Updated note" },
output: { recipient: "[email protected]", accepted: true },
});
// The authored outbox channel records the scheduled session's reply.
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index 566a488b9..3eded0de1 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -446,7 +446,7 @@ describe("compileAgentManifest source graph", () => {
messages: [],
});
expect(Object.keys(tools as object).sort()).toEqual(
- ["create", "delete", "disable", "enable", "get", "invoke", "list"].map(
+ ["create", "delete", "disable", "enable", "get", "invoke", "list", "update"].map(
(operation) => `schedule__billing-requests__${operation}`,
),
);
diff --git a/packages/eve/src/context/schedule-collection-tools.ts b/packages/eve/src/context/schedule-collection-tools.ts
index 4abdac582..0eb8a997c 100644
--- a/packages/eve/src/context/schedule-collection-tools.ts
+++ b/packages/eve/src/context/schedule-collection-tools.ts
@@ -3,6 +3,7 @@ import { z } from "#compiled/zod/index.js";
import { isDeepStrictEqual } from "node:util";
import type {
ApprovalContext,
+ Approval,
ApprovalPolicy,
ApprovalResponsePolicy,
} from "#approval/definition.js";
@@ -14,12 +15,13 @@ 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,
+ DefinedDynamicSchedules,
DynamicSchedulesDefinition,
+ ScheduleCreateApproval,
} from "#public/schedules/subscription.js";
import {
assertScheduleManagementAllowed,
- type PreparedScheduleCreate,
+ type PreparedScheduleWrite,
} from "#runtime/schedules/collection-client.js";
import { scheduleDisplayName } from "#runtime/schedules/record.js";
import { MAX_SCHEDULE_DELAY_MINUTES } from "#runtime/schedules/validation.js";
@@ -34,8 +36,8 @@ import {
} 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 PreparedWritesKey = new ContextKey<Readonly<Record<string, PreparedScheduleWrite>>>(
+ "eve.schedulePreparedWrites",
);
const nameSchema = z
.string()
@@ -85,6 +87,10 @@ export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared
definition: DynamicSchedulesDefinition<TInput, StandardSchemaV1<unknown, TInput>, TPrepared>,
identity: { readonly application: string; readonly collection: string },
) {
+ const bind = () =>
+ bindScheduleCollection(
+ definition as DefinedDynamicSchedules<TInput, StandardSchemaV1<unknown, TInput>, TPrepared>,
+ );
return markDynamicCallbackRebind(
defineDynamic({
events: {
@@ -97,7 +103,8 @@ export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared
)
return null;
const prefix = `${scheduleCollectionToolPrefix(identity.collection)}__`;
- const keyFor = (callId: string) => `${prefix}create:${callId}`;
+ const keyFor = (operation: "create" | "update", callId: string) =>
+ `${prefix}${operation}:${callId}`;
const createSchema = z
.object({
name: nameSchema,
@@ -105,84 +112,37 @@ export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared
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.",
- };
- }
+ const updateSchema = createSchema
+ .partial({ expression: true, payload: true })
+ .extend({ name: nameInput.shape.name })
+ .refine((input) => input.expression !== undefined || input.payload !== undefined, {
+ message: "Schedule update requires an expression or replacement payload.",
+ });
+ const createApproval = writeApproval(
+ definition.approval?.create ?? always(),
+ (callId) => keyFor("create", callId),
+ async (input) => (await bind()).prepareCreate(await createSchema.parseAsync(input)),
+ (prepared) => prepared.envelope.payload,
+ );
+ const updateApproval = writeApproval(
+ definition.approval?.update ?? always(),
+ (callId) => keyFor("update", callId),
+ async (input) => {
+ const { name, expression, payload } = await updateSchema.parseAsync(input);
+ const client = await bind();
+ return expression === undefined
+ ? client.prepareUpdate(name, { payload })
+ : client.prepareUpdate(name, { expression, payload });
},
- };
- 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>,
- });
- };
- }
+ (prepared) => prepared.envelope?.payload,
+ );
const define = (
- operation: ScheduleOperation,
action: string,
description: string,
inputSchema: any,
execute: ToolDefinition<any, unknown>["execute"],
+ approval?: Approval,
) => {
- 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,
@@ -201,35 +161,55 @@ export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared
};
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)
+ const key = keyFor("create", context.callId);
+ const approved = loadContext().get(PreparedWritesKey)?.[key];
+ if (approved === undefined || !("displayName" in approved))
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) };
+ const snapshots = { ...loadContext().get(PreparedWritesKey) };
delete snapshots[key];
- loadContext().set(PreparedCreatesKey, snapshots);
+ loadContext().set(PreparedWritesKey, snapshots);
return created;
},
+ createApproval,
+ ),
+ [`${prefix}update`]: define(
+ "Update schedule",
+ `Replace timing and/or the complete payload of an existing schedule. A payload replacement prepares new work and makes the updating caller its creator; timing-only updates preserve ownership. State and dispatch target are unchanged. Already started work is not cancelled. ${timingGuidance}`,
+ updateSchema,
+ async ({ name, ...patch }, context) => {
+ const key = keyFor("update", context.callId);
+ const approved = loadContext().get(PreparedWritesKey)?.[key];
+ if (approved === undefined || !("name" in approved))
+ throw new Error(
+ "Schedule update has no prepared approval snapshot. Request update again.",
+ );
+ const updated = await (
+ await bindScheduleCollection(definition as never)
+ ).update(name, patch, approved);
+ const snapshots = { ...loadContext().get(PreparedWritesKey) };
+ delete snapshots[key];
+ loadContext().set(PreparedWritesKey, snapshots);
+ return updated;
+ },
+ updateApproval,
),
[`${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),
+ definition.approval?.get,
),
[`${prefix}list`]: define(
- "list",
"List schedules",
"List identity, timing/state, and timestamps; payload is not returned.",
z
@@ -239,39 +219,40 @@ export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared
})
.strict(),
async (input) => await (await schedules(definition as never)).list(input),
+ definition.approval?.list,
),
[`${prefix}enable`]: define(
- "enable",
"Enable schedule",
"Enable future occurrences.",
nameInput,
async ({ name }) => await (await schedules(definition as never)).enable(name),
+ definition.approval?.enable ?? always(),
),
[`${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),
+ definition.approval?.disable ?? always(),
),
[`${prefix}invoke`]: define(
- "invoke",
"Run schedule",
- "Enqueue an extra occurrence as the original creator; acceptance is not execution success.",
+ "Enqueue an extra occurrence as the stored creator; acceptance is not execution success.",
nameInput,
async ({ name }) => {
await (await schedules(definition as never)).invoke(name);
return { accepted: true };
},
+ definition.approval?.invoke ?? always(),
),
[`${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),
}),
+ definition.approval?.delete ?? always(),
),
};
},
@@ -280,6 +261,76 @@ export function createScheduleCollectionToolDynamicDefinition<TInput, TPrepared
);
}
+function writeApproval<TWrite extends PreparedScheduleWrite, TPayload>(
+ policy: ScheduleCreateApproval<TPayload>,
+ keyFor: (callId: string) => string,
+ prepare: (input: unknown) => Promise<TWrite>,
+ payloadFor: (prepared: TWrite) => TPayload,
+) {
+ const approval: { request: ApprovalPolicy; response?: ApprovalResponsePolicy } = {
+ request: async (context) => {
+ try {
+ const prepared = await prepare(context.toolInput);
+ const key = keyFor(context.callId);
+ const previous = loadContext().get(PreparedWritesKey) ?? {};
+ 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 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(PreparedWritesKey, snapshots);
+ }
+ const payload = payloadFor(prepared);
+ const routed = {
+ ...context,
+ toolInput: { ...context.toolInput, payload },
+ payload,
+ };
+ return typeof policy === "function" ? await policy(routed) : await policy.request(routed);
+ } catch (error) {
+ return {
+ type: "denied",
+ reason: error instanceof Error ? error.message : "Schedule preparation failed.",
+ };
+ }
+ },
+ };
+ if (typeof policy !== "function" && policy.response !== undefined) {
+ approval.response = async (context) => {
+ // Each key family is written by one typed preparer; restore that type after durable suspension.
+ const prepared = loadContext().get(PreparedWritesKey)?.[keyFor(context.request.callId)] as
+ | TWrite
+ | undefined;
+ if (prepared === undefined)
+ return {
+ status: "rejected",
+ reason: "The prepared schedule approval expired. Request approval again.",
+ };
+ const payload = payloadFor(prepared);
+ return await policy.response!({
+ ...context,
+ request: { ...context.request, toolInput: { ...context.request.toolInput, payload } },
+ payload,
+ });
+ };
+ }
+ return approval;
+}
+
function stampCallbacks(tool: ToolDefinition<any, unknown>): void {
const closure = parseJsonObject({});
const existing = readDurableDynamicToolCallbacks(tool);
diff --git a/packages/eve/src/internal/authored-definition/schedule-collection.test.ts b/packages/eve/src/internal/authored-definition/schedule-collection.test.ts
index ddb0d31c3..4e2d65c62 100644
--- a/packages/eve/src/internal/authored-definition/schedule-collection.test.ts
+++ b/packages/eve/src/internal/authored-definition/schedule-collection.test.ts
@@ -23,9 +23,9 @@ describe("normalizeScheduleCollectionDefinition", () => {
'"preparePayload" must be a function',
],
[
- "approval for the removed update tool",
- { approval: { update: () => "user-approval" } },
- "update",
+ "approval for an unsupported operation",
+ { approval: { rename: () => "user-approval" } },
+ "rename",
],
["unsupported deferral", { tool: "deferred" }, "deferred tools are not supported"],
["the removed capture hook", { resolvePayload: () => ({}) }, "resolvePayload"],
diff --git a/packages/eve/src/internal/authored-definition/schedule-collection.ts b/packages/eve/src/internal/authored-definition/schedule-collection.ts
index d11e2ade9..ad2ca5a0c 100644
--- a/packages/eve/src/internal/authored-definition/schedule-collection.ts
+++ b/packages/eve/src/internal/authored-definition/schedule-collection.ts
@@ -9,6 +9,7 @@ const SCHEDULE_OPERATIONS = [
"create",
"get",
"list",
+ "update",
"enable",
"disable",
"invoke",
@@ -20,6 +21,7 @@ const PROVIDER_KEYS = [
"create",
"list",
"get",
+ "update",
"enable",
"disable",
"invoke",
diff --git a/packages/eve/src/public/experimental/schedules/index.ts b/packages/eve/src/public/experimental/schedules/index.ts
index 090368cd7..d1c3b8033 100644
--- a/packages/eve/src/public/experimental/schedules/index.ts
+++ b/packages/eve/src/public/experimental/schedules/index.ts
@@ -10,6 +10,8 @@ export {
type ScheduleApprovals,
type ScheduleClient,
type ScheduleClientCreate,
+ type ScheduleClientUpdate,
+ type SchedulePatch,
type ScheduleCreate,
type ScheduleExpression,
type ScheduleTiming,
diff --git a/packages/eve/src/public/schedules/providers/in-memory.ts b/packages/eve/src/public/schedules/providers/in-memory.ts
index ea7a57e77..f242a85a3 100644
--- a/packages/eve/src/public/schedules/providers/in-memory.ts
+++ b/packages/eve/src/public/schedules/providers/in-memory.ts
@@ -4,6 +4,7 @@ import type {
ScheduleCreate,
ScheduleExpression,
ScheduleList,
+ SchedulePatch,
SchedulePage,
ScheduleProvider,
ScheduleRecord,
@@ -74,6 +75,28 @@ export function inMemoryScheduleProvider(
return record === undefined ? null : publicRecord(record);
},
+ async update<TPayload>(
+ context: ScheduleProviderContext,
+ name: string,
+ patch: SchedulePatch<TPayload>,
+ ) {
+ return withOperationResult(operationResults, context.operationId, () => {
+ const key = scheduleKey(context, name);
+ const current = requireSchedule(schedules, key, name);
+ const updated: StoredSchedule = {
+ ...current,
+ expression:
+ patch.expression === undefined
+ ? current.expression
+ : normalizeExpression(patch.expression),
+ payload: patch.payload === undefined ? current.payload : patch.payload,
+ updatedAt: now().getTime(),
+ };
+ schedules.set(key, updated);
+ return publicRecord(updated);
+ });
+ },
+
async enable(context: ScheduleProviderContext, name: string) {
return setState(schedules, operationResults, context, name, "active", now);
},
diff --git a/packages/eve/src/public/schedules/providers/vercel.test.ts b/packages/eve/src/public/schedules/providers/vercel.test.ts
index 5b3a5aeba..fb0ed155f 100644
--- a/packages/eve/src/public/schedules/providers/vercel.test.ts
+++ b/packages/eve/src/public/schedules/providers/vercel.test.ts
@@ -72,6 +72,34 @@ describe("vercelScheduleProvider", () => {
expect(new Headers(init?.headers).get("Authorization")).toBe(`Bearer ${oidcToken}`);
});
+ it("patches only supplied configuration, wraps replacement payloads, and clears omitted timing options", async () => {
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_ENV", "production");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", oidcToken);
+ const fetchImpl = vi.fn<typeof fetch>(async () => Response.json(schedule()));
+ const provider = vercelScheduleProvider({ fetch: fetchImpl });
+ await provider.update(context, "review-prs-daily", { payload: { task: "Updated" } });
+ await provider.update(context, "review-prs-daily", {
+ expression: { type: "cron", cron: "0 9 * * *" },
+ });
+ const [url, payloadRequest] = fetchImpl.mock.calls[0]!;
+ expect(String(url)).toBe(
+ "https://vercel-schedules.com/v1/schedules/review-prs-daily?namespace=eve-namespace",
+ );
+ expect(payloadRequest?.method).toBe("PATCH");
+ expect(JSON.parse(String(payloadRequest?.body))).toEqual({
+ payload: {
+ eve: { application: "dynamic-schedules", collection: "collection", version: 1 },
+ payload: { task: "Updated" },
+ },
+ });
+ expect(JSON.parse(String(fetchImpl.mock.calls[1]![1]?.body))).toEqual({
+ expression: { type: "cron", cron: "0 9 * * *" },
+ timezone: "UTC",
+ jitter: null,
+ });
+ });
+
it("omits a blank first-page cursor", async () => {
vi.stubEnv("VERCEL", "1");
vi.stubEnv("VERCEL_ENV", "production");
diff --git a/packages/eve/src/public/schedules/providers/vercel.ts b/packages/eve/src/public/schedules/providers/vercel.ts
index 212ab868e..d2bfe2f2f 100644
--- a/packages/eve/src/public/schedules/providers/vercel.ts
+++ b/packages/eve/src/public/schedules/providers/vercel.ts
@@ -1,6 +1,7 @@
import type {
Schedule as VercelSchedule,
SchedulesClient,
+ UpdateScheduleParams,
} from "#compiled/@vercel/schedules/index.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
@@ -71,6 +72,19 @@ export function vercelScheduleProvider(
);
return response === null ? null : fromVercelSchedule(response);
},
+ async update(context, name, patch) {
+ const expression = patch.expression;
+ const params: UpdateScheduleParams = { name, namespace: context.namespace };
+ if (expression !== undefined) {
+ params.expression = toVercelExpression(expression);
+ params.timezone = expression.timezone ?? "UTC";
+ params.jitter = expression.type === "cron" ? (expression.jitter ?? null) : null;
+ }
+ if (patch.payload !== undefined)
+ params.payload = createDispatchPayload(context, patch.payload);
+ const schedule = await (await client(context.abortSignal)).update(params);
+ return fromVercelSchedule(schedule);
+ },
async enable(context, name) {
return fromVercelSchedule(
await (await client(context.abortSignal)).enable({ name, namespace: context.namespace }),
diff --git a/packages/eve/src/public/schedules/subscription.ts b/packages/eve/src/public/schedules/subscription.ts
index 8814d9786..1acce1fe3 100644
--- a/packages/eve/src/public/schedules/subscription.ts
+++ b/packages/eve/src/public/schedules/subscription.ts
@@ -27,6 +27,7 @@ export type ScheduleOperation =
| "create"
| "get"
| "list"
+ | "update"
| "enable"
| "disable"
| "invoke"
@@ -128,6 +129,10 @@ export interface ScheduleCreate<TPayload> {
readonly payload: TPayload;
readonly name: string;
}
+export interface SchedulePatch<TPayload> {
+ readonly expression?: ScheduleExpression;
+ readonly payload?: TPayload;
+}
export interface ScheduleList {
readonly cursor?: string;
readonly limit?: number;
@@ -148,6 +153,12 @@ export interface ScheduleProvider {
): Promise<ScheduleRecord>;
list(context: ScheduleProviderContext, query: ScheduleList): Promise<SchedulePage>;
get(context: ScheduleProviderContext, name: string): Promise<ScheduleRecord | null>;
+ /** Patch supplied fields; preserve identity, state, target, and omitted fields. */
+ update<TPayload>(
+ context: ScheduleProviderContext,
+ name: string,
+ patch: SchedulePatch<TPayload>,
+ ): Promise<ScheduleRecord>;
enable(context: ScheduleProviderContext, name: string): Promise<ScheduleRecord>;
disable(context: ScheduleProviderContext, name: string): Promise<ScheduleRecord>;
invoke(context: ScheduleProviderContext, name: string): Promise<void>;
@@ -165,7 +176,12 @@ export interface SchedulePageResult {
readonly data: readonly ScheduleRecord[];
}
-/** Authenticated client; payload and creator identity are immutable after creation. */
+/** Requires timing or complete replacement input, which captures the updating caller as creator. */
+export type ScheduleClientUpdate<TPayload> =
+ | { readonly expression: ScheduleTiming; readonly payload?: TPayload }
+ | { readonly expression?: ScheduleTiming; readonly payload: TPayload };
+
+/** Authenticated client; timing-only updates preserve payload and creator identity. */
export interface ScheduleClient<TPayload> {
create(input: ScheduleClientCreate<TPayload>): Promise<ScheduleRecord>;
delete(name: string): Promise<boolean>;
@@ -174,6 +190,8 @@ export interface ScheduleClient<TPayload> {
get(name: string): Promise<ScheduleRecord | null>;
invoke(name: string): Promise<void>;
list(input?: ScheduleList): Promise<SchedulePageResult>;
+ /** Requires timing or payload. Payload replacement captures the updating caller as creator. */
+ update(name: string, patch: ScheduleClientUpdate<TPayload>): Promise<ScheduleRecord>;
}
/** Starts fresh unattended work bound to the resolved creator; callers cannot choose another identity. */
@@ -182,7 +200,7 @@ export type DynamicSchedulesToFn = <TChannel extends ChannelReference<unknown>>(
target: InferReceiveTarget<TChannel>,
) => { send(message: string | UserContent): Promise<Session> };
-export type ScheduleCreateApproval<TPrepared> =
+type SchedulePayloadApproval<TPrepared> =
| ((
context: ApprovalContext & { readonly payload: TPrepared },
) => ApprovalStatus | Promise<ApprovalStatus>)
@@ -194,10 +212,14 @@ export type ScheduleCreateApproval<TPrepared> =
context: ApprovalResponseContext & { readonly payload: TPrepared },
) => ApprovalResponseDecision | Promise<ApprovalResponseDecision>;
};
+export type ScheduleCreateApproval<TPrepared> = SchedulePayloadApproval<TPrepared>;
+
export type ScheduleApprovals<TPrepared> = Partial<
- Record<Exclude<ScheduleOperation, "create">, Approval>
+ Record<Exclude<ScheduleOperation, "create" | "update">, Approval>
> & {
readonly create?: ScheduleCreateApproval<TPrepared>;
+ /** Prepared replacement payload, or undefined for timing-only updates. */
+ readonly update?: SchedulePayloadApproval<TPrepared | undefined>;
};
/** Execution context; `to` starts fresh, unattended sessions as the resolved creator. */
@@ -220,22 +242,23 @@ export interface DynamicSchedulesDefinition<
/** Resolved backend. defineDynamicSchedules defaults omitted providers to Vercel Schedules. */
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
+ * Validates application policy and enriches a creation or replacement payload before the provider write.
+ * The caller constructs input; eve validates it with `inputSchema`, authorizes the write
+ * through `scope`, then calls `preparePayload` with trusted caller 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.
+ * Throw an actionable error to reject the write without changing 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.
+ * Runs on creation and payload replacement. 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, timing-only updates, state changes, and occurrence execution do not call it. Omission
+ * stores validated input unchanged. Write retries may call it again, so avoid irreversible
+ * side effects. Payload replacement recaptures the destination and creator from the updating caller.
* `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;
@@ -243,7 +266,10 @@ export interface DynamicSchedulesDefinition<
*/
readonly preparePayload?: (
payload: TPayload,
- context: ScheduleScopeContext & { readonly operation: "create"; readonly name: string },
+ context: ScheduleScopeContext & {
+ readonly operation: "create" | "update";
+ readonly name: string;
+ },
) => TPrepared | Promise<TPrepared>;
/** Authorizes every management operation. Defaults to `byPrincipal`. */
readonly scope?: (
@@ -265,7 +291,7 @@ export interface DynamicSchedulesDefinition<
};
/** 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. */
+ /** Model-call policies keyed by operation. Create and update receive the prepared payload. */
readonly approval?: ScheduleApprovals<NoInfer<TPrepared>>;
}
@@ -307,7 +333,10 @@ export function defineDynamicSchedules<TInput, TPrepared>(
> & {
readonly preparePayload: (
payload: TInput,
- context: ScheduleScopeContext & { readonly operation: "create"; readonly name: string },
+ context: ScheduleScopeContext & {
+ readonly operation: "create" | "update";
+ readonly name: string;
+ },
) => TPrepared | Promise<TPrepared>;
},
): DefinedDynamicSchedules<TInput, StandardSchemaV1<unknown, TInput>, TPrepared>;
diff --git a/packages/eve/src/runtime/schedules/collection-client.test.ts b/packages/eve/src/runtime/schedules/collection-client.test.ts
index 2d3256937..f0fb0ed7d 100644
--- a/packages/eve/src/runtime/schedules/collection-client.test.ts
+++ b/packages/eve/src/runtime/schedules/collection-client.test.ts
@@ -112,6 +112,7 @@ describe("schedule subscription client", () => {
});
await expect(bob.get(created.name)).resolves.toBeNull();
await expect(bob.list()).resolves.toEqual({ cursor: null, data: [] });
+ await expect(bob.update(created.name, { payload })).rejects.toThrow("not found");
const scope = vi.fn(() => null);
const prepare = vi.fn(
(value: { task: string; destination: "my-dm" | "team-channel" }) => value,
@@ -123,12 +124,35 @@ describe("schedule subscription client", () => {
const get = vi.spyOn(provider, "get");
await expect(denied.get(created.name)).rejects.toThrow("not available");
await expect(denied.delete(created.name)).rejects.toThrow("not available");
+ await expect(denied.update(created.name, { payload })).rejects.toThrow("not available");
await expect(denied.create(input)).rejects.toThrow("not available");
- expect(scope.mock.calls).toHaveLength(3);
+ expect(scope.mock.calls).toHaveLength(4);
expect(prepare).not.toHaveBeenCalled();
expect(get).not.toHaveBeenCalled();
});
+ it("rejects empty, unsupported, invalid, and missing schedule updates without writing", async () => {
+ const { client, provider } = setup();
+ const created = await client.create(input);
+ const update = vi.spyOn(provider, "update");
+ // @ts-expect-error TypeScript callers must supply timing or replacement payload.
+ await expect(client.update(created.name, {})).rejects.toThrow(
+ "requires an expression or replacement payload",
+ );
+ await expect(client.update(created.name, { name: "renamed" } as never)).rejects.toThrow(
+ "does not support",
+ );
+ await expect(
+ client.update(created.name, { payload: { ...payload, task: "" } }),
+ ).rejects.toThrow("Invalid schedule payload");
+ await expect(client.update("missing", { payload })).rejects.toThrow("not found");
+ await expect(
+ client.update(created.name, { expression: { type: "delay", minutes: 0 } }),
+ ).rejects.toThrow();
+ expect(update).not.toHaveBeenCalled();
+ await expect(client.get(created.name)).resolves.toEqual(created);
+ });
+
it("refuses scheduled-execution management through the custom client too", async () => {
const { definition, create } = setup();
const scheduled = createScheduleCollectionClient(definition, {
@@ -139,6 +163,9 @@ describe("schedule subscription client", () => {
},
});
await expect(scheduled.create(input)).rejects.toThrow("unavailable during scheduled execution");
+ await expect(scheduled.update("report", { payload })).rejects.toThrow(
+ "unavailable during scheduled execution",
+ );
expect(create).not.toHaveBeenCalled();
});
});
diff --git a/packages/eve/src/runtime/schedules/collection-client.ts b/packages/eve/src/runtime/schedules/collection-client.ts
index a07780ce2..c0a772893 100644
--- a/packages/eve/src/runtime/schedules/collection-client.ts
+++ b/packages/eve/src/runtime/schedules/collection-client.ts
@@ -9,6 +9,8 @@ import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import type {
ScheduleClient,
ScheduleClientCreate,
+ ScheduleClientUpdate,
+ SchedulePatch,
DynamicSchedulesDefinition,
ScheduleEnvelope,
SchedulePageResult,
@@ -42,15 +44,31 @@ export interface PreparedScheduleCreate<TPrepared = unknown> {
readonly envelope: ScheduleEnvelope<TPrepared>;
}
-/** Internal capabilities used by generated create approval; authored clients expose only create. */
+export interface PreparedScheduleUpdate<TPrepared = unknown> {
+ readonly name: string;
+ readonly namespace: string;
+ readonly expression?: import("#public/schedules/subscription.js").ScheduleTiming;
+ readonly envelope?: ScheduleEnvelope<TPrepared>;
+}
+
+export type PreparedScheduleWrite = PreparedScheduleCreate | PreparedScheduleUpdate;
+
+/** Internal preparation capabilities used by generated write approval. */
export interface ScheduleCollectionClient<TInput, TPrepared> extends ScheduleClient<TInput> {
- prepareCreate(
- input: ScheduleClientCreate<TInput>,
- ): Promise<PreparedScheduleCreate<TInput | TPrepared>>;
+ prepareCreate(input: ScheduleClientCreate<unknown>): Promise<PreparedScheduleCreate<TPrepared>>;
create(
input: ScheduleClientCreate<TInput>,
approved?: PreparedScheduleCreate,
): Promise<import("#public/schedules/subscription.js").ScheduleRecord>;
+ prepareUpdate(
+ name: string,
+ patch: ScheduleClientUpdate<unknown>,
+ ): Promise<PreparedScheduleUpdate<TPrepared>>;
+ update(
+ name: string,
+ patch: ScheduleClientUpdate<TInput>,
+ approved?: PreparedScheduleUpdate,
+ ): Promise<import("#public/schedules/subscription.js").ScheduleRecord>;
}
export function createScheduleCollectionClient<TPayload, TPrepared = TPayload>(
@@ -105,48 +123,68 @@ export function createScheduleCollectionClient<TPayload, TPrepared = TPayload>(
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 prepareEnvelope = async (
+ value: unknown,
+ scope: ScheduleScopeValue,
+ operation: "create" | "update",
+ name: string,
+ ) => {
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 =
+ throw new Error("Writing a schedule payload requires an authenticated principal.");
+ const validated = await validateSchedulePayload<TPayload>(definition.inputSchema, value);
+ // Definitions without preparation default TPrepared to the validated input type.
+ 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({
+ ...contextFor(operation, name),
+ operation,
+ name,
+ })
+ ) as TPrepared;
+ return 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,
+ envelope: { version: 3, payload: preparedPayload, scope, principal: creator },
+ }).envelope;
+ };
+
+ const prepareUpdate = async (name: string, patch: ScheduleClientUpdate<unknown>) => {
+ const unsupported = Object.keys(patch).filter(
+ (key) => key !== "expression" && key !== "payload",
+ );
+ if (unsupported.length > 0)
+ throw new Error(`Schedule update does not support: ${unsupported.join(", ")}.`);
+ if (patch.expression === undefined && patch.payload === undefined)
+ throw new Error("Schedule update requires an expression or replacement payload.");
+ const normalized = validateScheduleName(name);
+ if (patch.expression !== undefined) resolveScheduleTiming(patch.expression);
+ const { scope, provider } = await resolveNamespace("update", normalized);
+ if ((await definition.provider.get(provider, normalized)) === null)
+ throw new Error("Schedule was not found in the authorized scope.");
+ const prepared: PreparedScheduleUpdate<TPrepared> = {
+ name: normalized,
+ namespace: provider.namespace,
+ expression: patch.expression,
+ envelope:
+ patch.payload === undefined
+ ? undefined
+ : await prepareEnvelope(patch.payload, scope, "update", normalized),
};
- 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: snapshotPreparedWrite(prepared), provider };
+ };
+
+ const prepareCreation = async (input: ScheduleClientCreate<unknown>) => {
+ 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 prepared = snapshotPreparedWrite({
+ displayName,
+ expression: input.expression,
+ envelope: await prepareEnvelope(input.payload, scope, "create", displayName),
+ });
return { prepared, provider };
};
@@ -171,6 +209,33 @@ export function createScheduleCollectionClient<TPayload, TPrepared = TPayload>(
await definition.provider.create(provider, { expression, name, payload }),
);
},
+ async prepareUpdate(name, patch) {
+ return (await prepareUpdate(name, patch)).prepared;
+ },
+ async update(name, patch, approved) {
+ const { prepared, provider } = await prepareUpdate(name, patch);
+ if (approved !== undefined && !isDeepStrictEqual(prepared, approved))
+ throw new Error(
+ "Schedule update changed after approval. Request a new update approval; no schedule was written.",
+ );
+ const update: SchedulePatch<ScheduleCollectionPayload<TPrepared>> = {
+ expression:
+ prepared.expression === undefined
+ ? undefined
+ : resolveScheduleTiming(prepared.expression),
+ payload:
+ prepared.envelope === undefined
+ ? undefined
+ : createScheduleCollectionPayload({
+ application: callContext.application,
+ collection: callContext.collection,
+ envelope: prepared.envelope,
+ }),
+ };
+ return projectScheduleRecord(
+ await definition.provider.update(provider, prepared.name, update),
+ );
+ },
async delete(name) {
const normalized = validateScheduleName(name);
const { provider } = await resolveNamespace("delete", normalized);
@@ -209,6 +274,15 @@ export function createScheduleCollectionClient<TPayload, TPrepared = TPayload>(
};
}
+function snapshotPreparedWrite<T extends PreparedScheduleWrite>(prepared: T): T {
+ const json = JSON.stringify(prepared);
+ if (Buffer.byteLength(json) > 64 * 1024)
+ throw new Error(
+ "Prepared schedule write exceeds the 64 KB limit, including timing and payload.",
+ );
+ return JSON.parse(json) as T;
+}
+
export function assertScheduleManagementAllowed(schedule?: SessionSchedule): void {
const context = contextStorage.getStore();
if (
diff --git a/packages/eve/src/runtime/schedules/subscription.integration.test.ts b/packages/eve/src/runtime/schedules/subscription.integration.test.ts
index f0dfa1add..2e0606434 100644
--- a/packages/eve/src/runtime/schedules/subscription.integration.test.ts
+++ b/packages/eve/src/runtime/schedules/subscription.integration.test.ts
@@ -37,6 +37,7 @@ describe("schedule creation and invocation", () => {
let destination = "C123";
const provider = inMemoryScheduleProvider();
const write = vi.spyOn(provider, "create");
+ const updateWrite = vi.spyOn(provider, "update");
const approvedTargets: string[] = [];
const responseTargets: string[] = [];
const dispatched = vi.fn();
@@ -57,6 +58,16 @@ describe("schedule creation and invocation", () => {
return { status: "allowed" };
},
},
+ update: {
+ request: ({ payload }) => {
+ approvedTargets.push(payload?.target ?? "timing-only");
+ return "user-approval";
+ },
+ response: ({ payload }) => {
+ responseTargets.push(payload?.target ?? "timing-only");
+ return { status: "allowed" };
+ },
+ },
invoke: once(),
},
auth: () => alice,
@@ -84,7 +95,7 @@ describe("schedule creation and invocation", () => {
messages: [],
})) as Record<string, DynamicToolEntry>;
expect(Object.keys(tools).sort()).toEqual(
- ["create", "delete", "disable", "enable", "get", "invoke", "list"].map(
+ ["create", "delete", "disable", "enable", "get", "invoke", "list", "update"].map(
(operation) => `schedule__requests__${operation}`,
),
);
@@ -135,6 +146,40 @@ describe("schedule creation and invocation", () => {
await expect(tools.schedule__requests__list!.execute({}, {} as never)).resolves.toMatchObject(
{ data: [{ name: created.name }] },
);
+ const update = tools.schedule__requests__update!;
+ const updateInput = { name: created.name, payload: { task: "A new joke" } };
+ const updateRequest = resolveApprovalPolicy(update.approval!);
+ const updateResponse = (update.approval as ApprovalConfiguration).response!;
+ await expect(
+ updateRequest(policyContext("empty-update", { name: created.name })),
+ ).resolves.toMatchObject({ type: "denied" });
+ expect(updateWrite).not.toHaveBeenCalled();
+ await expect(updateRequest(policyContext("update-changed", updateInput))).resolves.toBe(
+ "user-approval",
+ );
+ await updateResponse({ request: { callId: "update-changed" } } as never);
+ expect(responseTargets.at(-1)).toBe("C999");
+ destination = "C456";
+ await expect(
+ update.execute(updateInput, { callId: "update-changed" } as never),
+ ).rejects.toThrow("changed after approval");
+ expect(updateWrite).not.toHaveBeenCalled();
+ await expect(updateRequest(policyContext("update-accepted", updateInput))).resolves.toBe(
+ "user-approval",
+ );
+ await update.execute(updateInput, { callId: "update-accepted" } as never);
+ expect(updateWrite.mock.calls[0]![2].payload).toMatchObject({
+ envelope: { payload: { task: "A new joke", target: "C456" } },
+ });
+ const timingInput = { name: created.name, expression: { type: "delay", minutes: 10 } };
+ await expect(updateRequest(policyContext("timing", timingInput))).resolves.toBe(
+ "user-approval",
+ );
+ expect(approvedTargets.at(-1)).toBe("timing-only");
+ await updateResponse({ request: { callId: "timing" } } as never);
+ expect(responseTargets.at(-1)).toBe("timing-only");
+ await update.execute(timingInput, { callId: "timing" } as never);
+ expect(updateWrite.mock.calls[1]![2].payload).toBeUndefined();
const invoke = tools.schedule__requests__invoke!;
const invoked = { name: created.name };
const invokeContext = {
@@ -155,21 +200,26 @@ describe("schedule creation and invocation", () => {
});
});
- it("prepares code-only creation once and revalidates the creator on each occurrence", async () => {
+ it("prepares payload replacements as the updating caller while timing-only updates preserve the creator", async () => {
let allowed = true;
let preparations = 0;
+ const operations: string[] = [];
const messages: string[] = [];
const outcomes: ScheduleOccurrenceEvent[] = [];
const subscription = defineDynamicSchedules({
inputSchema: z.object({ task: z.string() }).strict(),
provider: inMemoryScheduleProvider(),
tool: false,
+ scope: () => "shared",
async preparePayload(input, context) {
preparations += 1;
+ operations.push(context.operation);
return { message: input.task, author: context.session.auth.current!.principalId };
},
auth: ({ principal, payload }) =>
- allowed && payload.author === principal.principalId ? alice : null,
+ allowed && payload.author === principal.principalId
+ ? { ...alice, principalId: principal.principalId }
+ : null,
run: ({ payload }) => {
messages.push(payload.message);
},
@@ -212,6 +262,34 @@ describe("schedule creation and invocation", () => {
await expect(client.invoke(created.name)).rejects.toThrow("no longer authorized");
expect(messages).toHaveLength(2);
expect(outcomes).toHaveLength(2);
+ allowed = true;
+ loadContext().set(AuthKey, { ...alice, principalId: "bob" });
+ const bobClient = await schedules(subscription);
+ await bobClient.disable(created.name);
+ const retimed = await bobClient.update(created.name, {
+ expression: { type: "delay", minutes: 10 },
+ });
+ expect(retimed).toMatchObject({
+ name: created.name,
+ scheduleId: created.scheduleId,
+ state: "inactive",
+ });
+ await bobClient.invoke(created.name);
+ expect(preparations).toBe(1);
+ expect(outcomes.at(-1)!.schedule!.principal.principalId).toBe("alice");
+ await bobClient.update(created.name, {
+ expression: { type: "delay", minutes: 15 },
+ payload: { task: "Bob's reminder" },
+ });
+ await bobClient.invoke(created.name);
+ expect(preparations).toBe(2);
+ expect(operations).toEqual(["create", "update"]);
+ expect(messages.at(-1)).toBe("Bob's reminder");
+ expect(outcomes.at(-1)!.schedule).toMatchObject({
+ principal: { principalId: "bob" },
+ payload: { author: "bob", message: "Bob's reminder" },
+ scope: "shared",
+ });
});
});
});