Skip to content

An open-source, faster Devin alternative

TypeScript

Add code-defined schedules (#642)

Mohamed Habib213e76838a6c
diff --git a/agent/package-lock.json b/agent/package-lock.json
index b13d2d19..909dacdd 100644
--- a/agent/package-lock.json
+++ b/agent/package-lock.json
@@ -1,12 +1,15 @@
{
"name": "@opencomputer/agent",
- "version": "0.5.0",
+ "version": "0.5.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/agent",
- "version": "0.5.0",
+ "version": "0.5.1",
+ "dependencies": {
+ "croner": "^9.1.0"
+ },
"devDependencies": {
"typescript": "^5.9.0"
},
@@ -14,6 +17,15 @@
"node": ">=22.0.0"
}
},
+ "node_modules/croner": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/croner/-/croner-9.1.0.tgz",
+ "integrity": "sha512-p9nwwR4qyT5W996vBZhdvBCnMhicY5ytZkR4D1Xj0wuTDEiMnjwR57Q3RXYY/s0EpX6Ay3vgIcfaR+ewGHsi+g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0"
+ }
+ },
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
diff --git a/agent/package.json b/agent/package.json
index 06753496..11fd14a8 100644
--- a/agent/package.json
+++ b/agent/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/agent",
- "version": "0.5.0",
+ "version": "0.5.1",
"description": "Reactive agent authoring API for OpenComputer.",
"type": "module",
"main": "./dist/index.js",
@@ -11,17 +11,29 @@
"import": "./dist/index.js"
}
},
- "files": ["dist", "README.md"],
+ "files": [
+ "dist",
+ "README.md"
+ ],
"scripts": {
"build": "tsc -p tsconfig.json",
"prepack": "npm run build"
},
- "engines": { "node": ">=22.0.0" },
- "publishConfig": { "access": "public" },
+ "engines": {
+ "node": ">=22.0.0"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
"repository": {
"type": "git",
"url": "git+https://github.com/diggerhq/opencomputer.git",
"directory": "agent"
},
- "devDependencies": { "typescript": "^5.9.0" }
+ "devDependencies": {
+ "typescript": "^5.9.0"
+ },
+ "dependencies": {
+ "croner": "^9.1.0"
+ }
}
diff --git a/agent/src/index.ts b/agent/src/index.ts
index 4912cb30..99155b41 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -1,3 +1,5 @@
+import { Cron } from "croner";
+
export type DataValue =
| null
| boolean
@@ -14,12 +16,27 @@ export type InputSource =
| "subagent"
| "system";
-export interface AgentInput {
- readonly source: InputSource;
+export interface ScheduleRunContext {
+ readonly id: string;
+ readonly runId: string;
+ readonly scheduledAt: string;
+ readonly timezone: string;
+ readonly attempt: number;
+ readonly manual: boolean;
+}
+
+interface BasicAgentInput {
readonly text?: string;
readonly payload?: DataValue;
}
+export type AgentInput =
+ | (BasicAgentInput & { readonly source: Exclude<InputSource, "schedule"> })
+ | (BasicAgentInput & {
+ readonly source: "schedule";
+ readonly schedule: Readonly<ScheduleRunContext>;
+ });
+
export interface ResourceReference {
readonly id: string;
}
@@ -119,6 +136,21 @@ export interface OutboxRegistrationDefinition extends ResourceReference {
readonly outboxId: string;
}
+export type ScheduleEnvironment = "development" | "production";
+
+export interface ScheduleDefinition extends ResourceReference {
+ readonly kind: "schedule";
+ readonly version: 1;
+ readonly cron: string;
+ readonly timezone: string;
+ readonly enabled: readonly ScheduleEnvironment[];
+ readonly overlap: "skip" | "allow";
+ readonly dispatch: {
+ readonly text?: string;
+ readonly payload?: DataValue;
+ };
+}
+
function outboxEventType(value: string): string {
const type = value.trim();
if (!/^[a-z0-9]+(?:[a-z0-9.-]*[a-z0-9])?$/.test(type)) {
@@ -401,6 +433,79 @@ function resourceIdentifier(value: string, kind: string): string {
return id;
}
+function schedulePayload(value: DataValue | undefined): DataValue | undefined {
+ if (value === undefined) return undefined;
+ let serialized: string | undefined;
+ try {
+ serialized = JSON.stringify(value);
+ } catch {
+ throw new Error("Schedule payloads must be JSON-compatible");
+ }
+ if (serialized === undefined || serialized.length > 32 * 1024) {
+ throw new Error("Schedule payloads must be JSON-compatible and at most 32 KiB");
+ }
+ return JSON.parse(serialized) as DataValue;
+}
+
+export function defineSchedule(input: {
+ id: string;
+ cron: string;
+ timezone?: string;
+ enabled?: readonly ScheduleEnvironment[];
+ overlap?: "skip" | "allow";
+ dispatch: {
+ text?: string;
+ payload?: DataValue;
+ };
+}): ScheduleDefinition {
+ const id = resourceIdentifier(input.id, "defineSchedule");
+ const cron = input.cron.trim().replace(/\s+/g, " ");
+ if (cron.split(" ").length !== 5) {
+ throw new Error("Schedule cron expressions must contain exactly five fields");
+ }
+ const timezone = input.timezone?.trim() || "UTC";
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
+ } catch {
+ throw new Error(`Schedule ${id} has an invalid IANA timezone`);
+ }
+ try {
+ new Cron(cron, { timezone, paused: true });
+ } catch {
+ throw new Error(`Schedule ${id} has an invalid cron expression`);
+ }
+ const enabled = [...new Set(input.enabled ?? ["production"])] as ScheduleEnvironment[];
+ if (
+ !enabled.length ||
+ enabled.some(
+ (environment) =>
+ environment !== "development" && environment !== "production",
+ )
+ ) {
+ throw new Error(
+ "Schedule enabled environments must contain development or production",
+ );
+ }
+ const text = input.dispatch.text?.trim();
+ const payload = schedulePayload(input.dispatch.payload);
+ if (!text && payload === undefined) {
+ throw new Error("Schedule dispatch requires text or payload");
+ }
+ return Object.freeze({
+ kind: "schedule" as const,
+ version: 1 as const,
+ id,
+ cron,
+ timezone,
+ enabled: Object.freeze(enabled),
+ overlap: input.overlap ?? "skip",
+ dispatch: Object.freeze({
+ ...(text ? { text } : {}),
+ ...(payload === undefined ? {} : { payload }),
+ }),
+ });
+}
+
export function defineChannel(input: {
id: string;
type: "slack";
diff --git a/cli/package-lock.json b/cli/package-lock.json
index 756eadf6..4e890cc3 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,15 +1,16 @@
{
"name": "@opencomputer/cli",
- "version": "0.5.3",
+ "version": "0.5.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.5.3",
+ "version": "0.5.4",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
+ "croner": "^9.1.0",
"opencode-ai": "1.18.4",
"react": "^19.2.8",
"typescript": "^5.9.0"
@@ -54,6 +55,7 @@
"version": "2.0.21",
"resolved": "https://registry.npmjs.org/@ai-sdk/mcp/-/mcp-2.0.21.tgz",
"integrity": "sha512-IC7mhtIX551SGp3jyFveNpwWpvzju/2ah4+Wsmsj4OMXOVCBChdwNpanZTGGfTaugqUoqtRgsOZ7dS2jJ4ix7Q==",
+ "dev": true,
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/provider": "4.0.4",
@@ -723,6 +725,15 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/croner": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/croner/-/croner-9.1.0.tgz",
+ "integrity": "sha512-p9nwwR4qyT5W996vBZhdvBCnMhicY5ytZkR4D1Xj0wuTDEiMnjwR57Q3RXYY/s0EpX6Ay3vgIcfaR+ewGHsi+g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -2821,7 +2832,6 @@
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
- "dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
diff --git a/cli/package.json b/cli/package.json
index b7164792..517f134c 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.5.3",
+ "version": "0.5.4",
"description": "Build, test, deploy, and share OpenComputer agents as code.",
"type": "module",
"bin": {
@@ -44,6 +44,7 @@
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
+ "croner": "^9.1.0",
"opencode-ai": "1.18.4",
"react": "^19.2.8",
"typescript": "^5.9.0"
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index 851aa024..e910acbd 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -208,12 +208,59 @@ export default registerOutbox(reviewRequests);
outboxRegistrations: [
{ agentId: "hello-world", outboxId: "review-requests" },
],
+ schedules: [],
});
} finally {
await rm(parent, { recursive: true, force: true });
}
});
+test("the compiler normalizes code-defined agent schedules", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-schedules-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root, undefined, { spa: false });
+ await mkdir(resolve(initialized.agentRoot, "schedules"), { recursive: true });
+ await writeFile(
+ resolve(initialized.agentRoot, "schedules", "weekday-hygiene.ts"),
+ `import { defineSchedule } from "@opencomputer/agent";
+export default defineSchedule({
+ id: "weekday-hygiene",
+ cron: "0 9 * * 1-5",
+ timezone: "America/Los_Angeles",
+ enabled: ["development", "production"],
+ overlap: "skip",
+ dispatch: {
+ text: "Run feature flag hygiene.",
+ payload: { repository: "acme/widgets", dryRun: false, labels: ["cleanup"] },
+ },
+});
+`,
+ );
+ const built = await readProjectResources(root);
+ assert.deepEqual(built.manifest.schedules, [
+ {
+ id: "weekday-hygiene",
+ agentId: "hello-world",
+ cron: "0 9 * * 1-5",
+ timezone: "America/Los_Angeles",
+ enabled: ["development", "production"],
+ overlap: "skip",
+ dispatch: {
+ text: "Run feature flag hygiene.",
+ payload: {
+ repository: "acme/widgets",
+ dryRun: false,
+ labels: ["cleanup"],
+ },
+ },
+ },
+ ]);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
test("init can create an agent-only project", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-agent-only-"));
const root = resolve(parent, "hello-agent");
diff --git a/cli/src/project.ts b/cli/src/project.ts
index 9d12332b..88723bc2 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -9,6 +9,7 @@ import {
writeFile,
} from "node:fs/promises";
import { basename, dirname, relative, resolve } from "node:path";
+import { Cron } from "croner";
import ts from "typescript";
export interface AgentManifest {
@@ -78,12 +79,26 @@ export interface OutboxRegistrationManifest {
outboxId: string;
}
+export interface ScheduleDefinitionManifest {
+ id: string;
+ agentId: string;
+ cron: string;
+ timezone: string;
+ enabled: Array<"development" | "production">;
+ overlap: "skip" | "allow";
+ dispatch: {
+ text?: string;
+ payload?: unknown;
+ };
+}
+
export interface ProjectResourceManifest {
version: 1;
channels: ChannelDefinitionManifest[];
channelRegistrations: ChannelRegistrationManifest[];
outboxes: OutboxDefinitionManifest[];
outboxRegistrations: OutboxRegistrationManifest[];
+ schedules: ScheduleDefinitionManifest[];
}
export interface BuiltProjectResources {
@@ -1123,6 +1138,133 @@ function outboxRegistration(
return { agentId, outboxId };
}
+function staticJsonValue(expression: ts.Expression, label: string): unknown {
+ if (ts.isStringLiteralLike(expression)) return expression.text;
+ if (ts.isNumericLiteral(expression)) return Number(expression.text);
+ if (
+ ts.isPrefixUnaryExpression(expression) &&
+ expression.operator === ts.SyntaxKind.MinusToken &&
+ ts.isNumericLiteral(expression.operand)
+ ) {
+ return -Number(expression.operand.text);
+ }
+ if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
+ if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
+ if (expression.kind === ts.SyntaxKind.NullKeyword) return null;
+ if (ts.isArrayLiteralExpression(expression)) {
+ return expression.elements.map((element) => {
+ if (ts.isSpreadElement(element)) {
+ throw new Error(`${label} cannot use spreads`);
+ }
+ return staticJsonValue(element, label);
+ });
+ }
+ if (ts.isObjectLiteralExpression(expression)) {
+ const value: Record<string, unknown> = {};
+ for (const property of expression.properties) {
+ if (!ts.isPropertyAssignment(property)) {
+ throw new Error(`${label} cannot use methods or spreads`);
+ }
+ value[staticPropertyName(property.name, label)] = staticJsonValue(
+ property.initializer,
+ label,
+ );
+ }
+ return value;
+ }
+ throw new Error(`${label} must be a static JSON value`);
+}
+
+function scheduleDefinition(
+ source: string,
+ path: string,
+ agentId: string,
+): ScheduleDefinitionManifest {
+ const call = defaultExportCall(source, path, "defineSchedule");
+ const input = call.arguments[0];
+ if (!input || !ts.isObjectLiteralExpression(input)) {
+ throw new Error(`${path} defineSchedule() requires an object literal`);
+ }
+ const id = literalStringValue(objectProperty(input, "id"), `${path} schedule id`);
+ if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
+ throw new Error(`${path} filename must match its valid schedule id`);
+ }
+ const cron = literalStringValue(objectProperty(input, "cron"), `${path} cron`)
+ .trim()
+ .replace(/\s+/g, " ");
+ if (cron.split(" ").length !== 5) {
+ throw new Error(`${path} cron must contain exactly five fields`);
+ }
+ const timezoneExpression = objectProperty(input, "timezone");
+ const timezone = timezoneExpression
+ ? literalStringValue(timezoneExpression, `${path} timezone`)
+ : "UTC";
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
+ } catch {
+ throw new Error(`${path} timezone must be a valid IANA timezone`);
+ }
+ try {
+ new Cron(cron, { timezone, paused: true });
+ } catch {
+ throw new Error(`${path} cron is invalid`);
+ }
+ const enabledExpression = objectProperty(input, "enabled");
+ const enabled = [
+ ...new Set(
+ enabledExpression
+ ? literalStringArray(enabledExpression, `${path} enabled environments`)
+ : ["production"],
+ ),
+ ].sort();
+ if (
+ !enabled.length ||
+ enabled.some(
+ (environment) =>
+ environment !== "development" && environment !== "production",
+ )
+ ) {
+ throw new Error(`${path} enabled environments are invalid`);
+ }
+ const overlapExpression = objectProperty(input, "overlap");
+ const overlap = overlapExpression
+ ? literalStringValue(overlapExpression, `${path} overlap`)
+ : "skip";
+ if (overlap !== "skip" && overlap !== "allow") {
+ throw new Error(`${path} overlap must be "skip" or "allow"`);
+ }
+ const dispatchExpression = objectProperty(input, "dispatch");
+ if (!dispatchExpression || !ts.isObjectLiteralExpression(dispatchExpression)) {
+ throw new Error(`${path} dispatch must be an object literal`);
+ }
+ const textExpression = objectProperty(dispatchExpression, "text");
+ const text = textExpression
+ ? literalStringValue(textExpression, `${path} dispatch text`).trim()
+ : undefined;
+ const payloadExpression = objectProperty(dispatchExpression, "payload");
+ const payload = payloadExpression
+ ? staticJsonValue(payloadExpression, `${path} dispatch payload`)
+ : undefined;
+ if (!text && payload === undefined) {
+ throw new Error(`${path} dispatch requires text or payload`);
+ }
+ if (payload !== undefined && JSON.stringify(payload).length > 32 * 1024) {
+ throw new Error(`${path} dispatch payload cannot exceed 32 KiB`);
+ }
+ return {
+ id,
+ agentId,
+ cron,
+ timezone,
+ enabled: enabled as ScheduleDefinitionManifest["enabled"],
+ overlap,
+ dispatch: {
+ ...(text ? { text } : {}),
+ ...(payload === undefined ? {} : { payload }),
+ },
+ };
+}
+
async function typescriptFiles(directory: string): Promise<string[]> {
if (!(await exists(directory))) return [];
return (await readdir(directory, { withFileTypes: true }))
@@ -1156,6 +1298,7 @@ export async function readProjectResources(
const agents = await readProjectAgents(projectRoot);
const channelRegistrations: ChannelRegistrationManifest[] = [];
const outboxRegistrations: OutboxRegistrationManifest[] = [];
+ const schedules: ScheduleDefinitionManifest[] = [];
for (const agent of agents) {
for (const path of await typescriptFiles(resolve(agent.root, "channels"))) {
channelRegistrations.push(
@@ -1177,6 +1320,15 @@ export async function readProjectResources(
),
);
}
+ for (const path of await typescriptFiles(resolve(agent.root, "schedules"))) {
+ schedules.push(
+ scheduleDefinition(await readFile(path, "utf8"), path, agent.localId),
+ );
+ }
+ }
+ const scheduleKeys = schedules.map(({ agentId, id }) => `${agentId}:${id}`);
+ if (new Set(scheduleKeys).size !== scheduleKeys.length) {
+ throw new Error("Agent schedule IDs must be unique within each agent");
}
const manifest: ProjectResourceManifest = {
version: 1,
@@ -1188,6 +1340,9 @@ export async function readProjectResources(
outboxRegistrations: outboxRegistrations.sort((left, right) =>
`${left.outboxId}:${left.agentId}`.localeCompare(`${right.outboxId}:${right.agentId}`),
),
+ schedules: schedules.sort((left, right) =>
+ `${left.agentId}:${left.id}`.localeCompare(`${right.agentId}:${right.id}`),
+ ),
};
const serialized = JSON.stringify(manifest);
return {
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 5a7bbac0..b1138277 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -483,6 +483,110 @@ describe("managed agents proxy", () => {
});
});
+ it("lists schedules and exposes only a public run failure", async () => {
+ const fetchSpy = vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json({
+ accountId: "private_org",
+ schedules: [
+ {
+ id: "weekday-hygiene",
+ projectId: "prj_test",
+ environment: "development",
+ agentId: "hygiene-agent",
+ deploymentId: "hygiene-agent:digest",
+ cron: "0 9 * * 1-5",
+ timezone: "America/Los_Angeles",
+ overlap: "skip",
+ dispatch: { text: "Review flags", payload: { mode: "async" } },
+ nextRunAt: "2026-08-17T16:00:00.000Z",
+ status: "manual",
+ userId: "private_user",
+ },
+ ],
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json(
+ {
+ run: {
+ id: "run_test",
+ scheduleId: "weekday-hygiene",
+ projectId: "prj_test",
+ environment: "development",
+ deploymentId: "hygiene-agent:digest",
+ scheduledAt: "2026-08-16T20:00:00.000Z",
+ manual: true,
+ attempt: 1,
+ outcome: "failed",
+ error: "Runtime secret and topology details",
+ createdAt: "2026-08-16T20:00:00.000Z",
+ },
+ },
+ { status: 201 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ const env = {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ };
+ const caller = { orgID: "org_test", userID: "user_test" };
+
+ const schedules = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/schedules?projectId=prj_test&agentId=hygiene-agent&environment=development",
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(await schedules.json()).toEqual({
+ schedules: [
+ {
+ id: "weekday-hygiene",
+ projectId: "prj_test",
+ environment: "development",
+ agentId: "hygiene-agent",
+ deploymentId: "hygiene-agent:digest",
+ cron: "0 9 * * 1-5",
+ timezone: "America/Los_Angeles",
+ overlap: "skip",
+ dispatch: { text: "Review flags", payload: { mode: "async" } },
+ nextRunAt: "2026-08-17T16:00:00.000Z",
+ status: "manual",
+ },
+ ],
+ });
+
+ const run = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/schedules/weekday-hygiene/run?projectId=prj_test&agentId=hygiene-agent&environment=development",
+ { method: "POST" },
+ ),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ expect(run.status).toBe(201);
+ expect(await run.json()).toEqual({
+ run: {
+ id: "run_test",
+ scheduleId: "weekday-hygiene",
+ projectId: "prj_test",
+ environment: "development",
+ deploymentId: "hygiene-agent:digest",
+ scheduledAt: "2026-08-16T20:00:00.000Z",
+ manual: true,
+ attempt: 1,
+ outcome: "failed",
+ error: "The scheduled run could not be started.",
+ createdAt: "2026-08-16T20:00:00.000Z",
+ },
+ });
+ });
+
it("returns a public per-agent Slack manifest", async () => {
const fetchSpy = vi.fn().mockResolvedValue(
Response.json({
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index 6e451dc1..2f8b5577 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -273,6 +273,42 @@ function publicOutbox(value: unknown): Record<string, unknown> {
};
}
+function publicSchedule(value: unknown): Record<string, unknown> {
+ const schedule = record(value) ?? {};
+ return {
+ id: schedule.id,
+ projectId: schedule.projectId,
+ environment: schedule.environment,
+ agentId: schedule.agentId,
+ deploymentId: schedule.deploymentId,
+ cron: schedule.cron,
+ timezone: schedule.timezone,
+ overlap: schedule.overlap,
+ dispatch: stripPrivateValues(schedule.dispatch),
+ nextRunAt: schedule.nextRunAt,
+ lastRunAt: schedule.lastRunAt,
+ status: schedule.status,
+ };
+}
+
+function publicScheduleRun(value: unknown): Record<string, unknown> {
+ const run = record(value) ?? {};
+ return {
+ id: run.id,
+ scheduleId: run.scheduleId,
+ projectId: run.projectId,
+ environment: run.environment,
+ deploymentId: run.deploymentId,
+ scheduledAt: run.scheduledAt,
+ manual: run.manual,
+ attempt: run.attempt,
+ outcome: run.outcome,
+ sessionId: run.sessionId,
+ ...(run.error ? { error: "The scheduled run could not be started." } : {}),
+ createdAt: run.createdAt,
+ };
+}
+
function stripPrivateValues(value: unknown): unknown {
if (Array.isArray(value)) return value.map(stripPrivateValues);
const source = record(value);
@@ -436,6 +472,21 @@ function publicSuccessBody(
: [],
};
}
+ if (method === "GET" && suffix === "/schedules") {
+ return {
+ schedules: Array.isArray(body.schedules)
+ ? body.schedules.map(publicSchedule)
+ : [],
+ };
+ }
+ if (method === "GET" && suffix === "/schedule-runs") {
+ return {
+ runs: Array.isArray(body.runs) ? body.runs.map(publicScheduleRun) : [],
+ };
+ }
+ if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix)) {
+ return { run: publicScheduleRun(body.run) };
+ }
if (method === "POST" && suffix === "/channels/slack/connections") {
return {
connection: publicChannel(body.connection),
@@ -672,6 +723,9 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
if (method === "GET" && suffix === "/deployments") return true;
if (method === "GET" && /^\/deployments\/[^/]+$/.test(suffix)) return true;
if (method === "GET" && suffix === "/outboxes") return true;
+ if (method === "GET" && suffix === "/schedules") return true;
+ if (method === "GET" && suffix === "/schedule-runs") return true;
+ if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix)) return true;
if (
(method === "GET" &&
(/^\/connections(?:\/.*)?$/.test(suffix) ||
diff --git a/create-start/package.json b/create-start/package.json
index 51328794..a5f2d097 100644
--- a/create-start/package.json
+++ b/create-start/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/create-start",
- "version": "0.5.3",
+ "version": "0.5.4",
"description": "Create a hello-world OpenComputer agent application.",
"type": "module",
"bin": {
@@ -18,7 +18,7 @@
"node": ">=22.0.0"
},
"dependencies": {
- "@opencomputer/cli": "0.5.3"
+ "@opencomputer/cli": "0.5.4"
},
"publishConfig": {
"access": "public"
diff --git a/docs/agents/projects.mdx b/docs/agents/projects.mdx
index 0d04b255..f81a720c 100644
--- a/docs/agents/projects.mdx
+++ b/docs/agents/projects.mdx
@@ -24,7 +24,8 @@ my-agent/
│ ├── channels/ # optional inbound registrations
│ ├── outboxes/ # optional publish registrations
│ ├── tools/ # optional
-│ └── skills/ # optional
+│ ├── skills/ # optional
+│ └── schedules/ # optional
├── src/
│ ├── App.tsx
│ └── main.tsx
@@ -103,6 +104,7 @@ The current project dashboard provides:
- **Agent playground** for creating and resuming test sessions
- **Deployments** for immutable version history and active aliases
- **Sessions** created through the dashboard, React client, or API
+- **Schedules** deployed from each agent's source directory
- **Channels** for environment-specific Slack installation and destination
binding
- **Outboxes** for inspecting proactive notification delivery
diff --git a/docs/agents/schedules.mdx b/docs/agents/schedules.mdx
new file mode 100644
index 00000000..aa8bfdae
--- /dev/null
+++ b/docs/agents/schedules.mdx
@@ -0,0 +1,107 @@
+---
+title: "Schedules"
+description: "Run an agent from a code-defined cron schedule"
+---
+
+Schedules start durable agent sessions at recurring times. Their timing,
+timezone, target agent, and input are defined in source control and deployed
+with the project.
+
+## Define a schedule
+
+Create a TypeScript file under an agent's `schedules/` directory. The filename
+must match the schedule ID:
+
+```text
+opencomputer/
+└── agents/
+ └── feature-flag-hygiene/
+ ├── agent.ts
+ └── schedules/
+ └── weekday-hygiene.ts
+```
+
+```ts weekday-hygiene.ts
+import { defineSchedule } from "@opencomputer/agent";
+
+export default defineSchedule({
+ id: "weekday-hygiene",
+ cron: "0 9 * * 1-5",
+ timezone: "America/Los_Angeles",
+ enabled: ["production"],
+ overlap: "skip",
+ dispatch: {
+ text: "Review stale feature flags.",
+ payload: {
+ mode: "async",
+ repository: "acme/widgets",
+ dryRun: true,
+ },
+ },
+});
+```
+
+Schedules use five-field cron expressions. `timezone` is an IANA timezone such
+as `UTC`, `America/Los_Angeles`, or `Europe/London`. The dispatch payload must
+be JSON-compatible and must not contain secrets.
+
+## Development and Production
+
+When `enabled` is omitted, it defaults to `["production"]`.
+
+- Development displays every deployed schedule and supports **Run now**.
+ Schedules that do not enable Development are marked **Manual only** and never
+ recur there.
+- Production automatically runs schedules that enable Production.
+- Add `"development"` to `enabled` only when you intentionally want automatic
+ Development recurrence.
+
+Development and Production have separate schedule state, run history,
+sessions, secrets, and channel bindings.
+
+## Receive scheduled input
+
+Each run starts a fresh session pinned to the deployment that was active when
+the run was claimed. `useInput()` includes the static dispatch and execution
+metadata:
+
+```tsx
+import { useInput } from "@opencomputer/agent";
+
+export default function Agent() {
+ const input = useInput();
+ const payload =
+ input.payload &&
+ typeof input.payload === "object" &&
+ !Array.isArray(input.payload)
+ ? input.payload
+ : {};
+
+ if (payload.mode === "async") {
+ return "Complete the unattended hygiene workflow and publish its result.";
+ }
+
+ return "Ask the user which repository they want to inspect.";
+}
+```
+
+Use payload fields such as `mode` to select business behavior. The platform
+sets `input.source` to `"schedule"` as provenance, but transport provenance
+should not be the agent's business-mode switch.
+
+After narrowing `input.source === "schedule"`, `input.schedule` contains the
+schedule ID, run ID, intended time, timezone, attempt number, and whether the
+run was started manually.
+
+## Overlap and run history
+
+`overlap` defaults to `"skip"`. If an earlier run is still starting or running,
+the next occurrence is recorded as skipped. Use `"allow"` only when concurrent
+runs are safe.
+
+The project's **Schedules** tab shows the next and previous run, current
+activation state, recent outcomes, and linked sessions. **Run now** uses the
+same deployment and dispatch payload as an automatic occurrence.
+
+Schedule timing and payload remain code-owned. Redeploy the project after
+changing a definition.
diff --git a/docs/docs.json b/docs/docs.json
index 92110a50..a2a98cdd 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -41,6 +41,7 @@
"pages": [
"agents/reactive-agents",
"agents/sessions",
+ "agents/schedules",
"agents/capabilities",
"agents/channels",
"agents/outboxes",
diff --git a/web/src/components/status-badge.tsx b/web/src/components/status-badge.tsx
index 271092d7..040508f3 100644
--- a/web/src/components/status-badge.tsx
+++ b/web/src/components/status-badge.tsx
@@ -5,6 +5,7 @@ import {
Moon,
Clock,
Loader2,
+ Play,
type LucideIcon,
} from 'lucide-react'
import { cn } from '@/lib/utils'
@@ -27,8 +28,10 @@ const STATUS: Record<string, Meta> = {
running: { tone: 'running', label: 'Running', icon: CircleCheck },
ready: { tone: 'running', label: 'Ready', icon: CircleCheck },
active: { tone: 'running', label: 'Active', icon: CircleCheck },
+ manual: { tone: 'hibernated', label: 'Manual only', icon: Play },
connected: { tone: 'running', label: 'Connected', icon: CircleCheck },
success: { tone: 'running', label: 'Success', icon: CircleCheck },
+ enacted: { tone: 'running', label: 'Session started', icon: CircleCheck },
resolved: { tone: 'running', label: 'Resolved', icon: CircleCheck },
stopped: { tone: 'stopped', label: 'Stopped', icon: CircleSlash },
disconnected: {
diff --git a/web/src/managed-agents/AgentMarkdown.tsx b/web/src/managed-agents/AgentMarkdown.tsx
new file mode 100644
index 00000000..7883d5da
--- /dev/null
+++ b/web/src/managed-agents/AgentMarkdown.tsx
@@ -0,0 +1,98 @@
+import ReactMarkdown from 'react-markdown'
+import remarkGfm from 'remark-gfm'
+
+export function AgentMarkdown({ children }: { children: string }) {
+ return (
+ <div className="text-sm leading-6">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={{
+ h1: ({ children, ...props }) => (
+ <h1
+ className="mt-6 mb-3 text-xl font-semibold first:mt-0"
+ {...props}
+ >
+ {children}
+ </h1>
+ ),
+ h2: ({ children, ...props }) => (
+ <h2
+ className="mt-5 mb-2 text-lg font-semibold first:mt-0"
+ {...props}
+ >
+ {children}
+ </h2>
+ ),
+ h3: ({ children, ...props }) => (
+ <h3
+ className="mt-4 mb-2 text-base font-semibold first:mt-0"
+ {...props}
+ >
+ {children}
+ </h3>
+ ),
+ p: (props) => <p className="mb-3 last:mb-0" {...props} />,
+ ul: (props) => (
+ <ul
+ className="mb-3 list-disc space-y-1 pl-5 last:mb-0"
+ {...props}
+ />
+ ),
+ ol: (props) => (
+ <ol
+ className="mb-3 list-decimal space-y-1 pl-5 last:mb-0"
+ {...props}
+ />
+ ),
+ li: (props) => <li className="pl-0.5" {...props} />,
+ blockquote: (props) => (
+ <blockquote
+ className="text-muted-foreground my-3 border-l-2 pl-4 italic"
+ {...props}
+ />
+ ),
+ a: ({ children, ...props }) => (
+ <a
+ className="underline underline-offset-4"
+ target="_blank"
+ rel="noreferrer"
+ {...props}
+ >
+ {children}
+ </a>
+ ),
+ code: (props) => (
+ <code
+ className="bg-muted rounded px-1 py-0.5 font-mono text-[0.85em]"
+ {...props}
+ />
+ ),
+ pre: (props) => (
+ <pre
+ className="bg-muted my-3 overflow-x-auto rounded-md border p-3 text-xs leading-5 [&_code]:bg-transparent [&_code]:p-0"
+ {...props}
+ />
+ ),
+ hr: (props) => <hr className="my-5" {...props} />,
+ table: (props) => (
+ <div className="my-3 overflow-x-auto rounded-md border">
+ <table
+ className="w-full border-collapse text-left text-xs"
+ {...props}
+ />
+ </div>
+ ),
+ th: (props) => (
+ <th
+ className="bg-muted border-b px-3 py-2 font-medium"
+ {...props}
+ />
+ ),
+ td: (props) => <td className="border-b px-3 py-2" {...props} />,
+ }}
+ >
+ {children}
+ </ReactMarkdown>
+ </div>
+ )
+}
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index b2e45819..8be0d302 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -9,8 +9,6 @@ import {
useParams,
useSearchParams,
} from 'react-router-dom'
-import ReactMarkdown from 'react-markdown'
-import remarkGfm from 'remark-gfm'
import {
Bot,
Check,
@@ -67,6 +65,8 @@ import {
import { ManagedProjectSecrets } from './Secrets'
import { ManagedSlackWizard } from './SlackWizard'
import { ManagedAgentOutboxes } from './Outboxes'
+import { ManagedAgentSchedules } from './Schedules'
+import { AgentMarkdown } from './AgentMarkdown'
type DetailTab =
| 'playground'
@@ -85,102 +85,6 @@ function eventText(event: ManagedAgentEvent) {
return typeof event.data.text === 'string' ? event.data.text : ''
}
-function AgentMarkdown({ children }: { children: string }) {
- return (
- <div className="text-sm leading-6">
- <ReactMarkdown
- remarkPlugins={[remarkGfm]}
- components={{
- h1: ({ children, ...props }) => (
- <h1
- className="mt-6 mb-3 text-xl font-semibold first:mt-0"
- {...props}
- >
- {children}
- </h1>
- ),
- h2: ({ children, ...props }) => (
- <h2
- className="mt-5 mb-2 text-lg font-semibold first:mt-0"
- {...props}
- >
- {children}
- </h2>
- ),
- h3: ({ children, ...props }) => (
- <h3
- className="mt-4 mb-2 text-base font-semibold first:mt-0"
- {...props}
- >
- {children}
- </h3>
- ),
- p: (props) => <p className="mb-3 last:mb-0" {...props} />,
- ul: (props) => (
- <ul
- className="mb-3 list-disc space-y-1 pl-5 last:mb-0"
- {...props}
- />
- ),
- ol: (props) => (
- <ol
- className="mb-3 list-decimal space-y-1 pl-5 last:mb-0"
- {...props}
- />
- ),
- li: (props) => <li className="pl-0.5" {...props} />,
- blockquote: (props) => (
- <blockquote
- className="text-muted-foreground my-3 border-l-2 pl-4 italic"
- {...props}
- />
- ),
- a: ({ children, ...props }) => (
- <a
- className="underline underline-offset-4"
- target="_blank"
- rel="noreferrer"
- {...props}
- >
- {children}
- </a>
- ),
- code: (props) => (
- <code
- className="bg-muted rounded px-1 py-0.5 font-mono text-[0.85em]"
- {...props}
- />
- ),
- pre: (props) => (
- <pre
- className="bg-muted my-3 overflow-x-auto rounded-md border p-3 text-xs leading-5 [&_code]:bg-transparent [&_code]:p-0"
- {...props}
- />
- ),
- hr: (props) => <hr className="my-5" {...props} />,
- table: (props) => (
- <div className="my-3 overflow-x-auto rounded-md border">
- <table
- className="w-full border-collapse text-left text-xs"
- {...props}
- />
- </div>
- ),
- th: (props) => (
- <th
- className="bg-muted border-b px-3 py-2 font-medium"
- {...props}
- />
- ),
- td: (props) => <td className="border-b px-3 py-2" {...props} />,
- }}
- >
- {children}
- </ReactMarkdown>
- </div>
- )
-}
-
function historicalMessages(
session: ManagedAgentSession | undefined,
events: ManagedAgentEvent[],
@@ -1111,11 +1015,12 @@ export default function ManagedAgentDetail({
/>
) : null}
- {activeTab === 'schedules' && project ? (
- <ProjectResourcePanel
- title="Schedules"
- description="Functions in this project that run on a cron schedule."
- values={project.schedules}
+ {activeTab === 'schedules' && project && agent ? (
+ <ManagedAgentSchedules
+ projectId={project.project.id}
+ agentId={agent.id}
+ environment={environment}
+ deployed={Boolean(projectEnvironment?.activeDeploymentId)}
/>
) : null}
@@ -1129,33 +1034,3 @@ export default function ManagedAgentDetail({
</div>
)
}
-
-function ProjectResourcePanel({
- title,
- description,
- values,
-}: {
- title: string
- description: string
- values: unknown[]
-}) {
- return (
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>{title}</PanelTitle>
- <PanelDescription className="mt-1">{description}</PanelDescription>
- </div>
- </PanelHeader>
- <PanelContent>
- {values.length ? (
- <pre className="bg-muted overflow-x-auto rounded-md border p-4 text-xs leading-5">
- {JSON.stringify(values.length === 1 ? values[0] : values, null, 2)}
- </pre>
- ) : (
- <p className="text-muted-foreground text-sm">Nothing here yet.</p>
- )}
- </PanelContent>
- </Panel>
- )
-}
diff --git a/web/src/managed-agents/Schedules.tsx b/web/src/managed-agents/Schedules.tsx
new file mode 100644
index 00000000..499280bb
--- /dev/null
+++ b/web/src/managed-agents/Schedules.tsx
@@ -0,0 +1,258 @@
+import { useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { CalendarClock, Loader2, Play } from 'lucide-react'
+import { Link } from 'react-router-dom'
+import { EmptyState } from '@/components/empty-state'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { ResourceTable, type Column } from '@/components/resource-table'
+import { StatusBadge } from '@/components/status-badge'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { notifyError } from '@/lib/errors'
+import {
+ getManagedAgentScheduleRuns,
+ getManagedAgentSchedules,
+ runManagedAgentSchedule,
+ type ManagedAgentSchedule,
+} from './api'
+import { projectContextSearch } from './project-context'
+
+function formatDate(value?: string) {
+ return value ? new Date(value).toLocaleString() : 'Never'
+}
+
+export function ManagedAgentSchedules({
+ projectId,
+ agentId,
+ environment,
+ deployed,
+}: {
+ projectId: string
+ agentId: string
+ environment: 'development' | 'production'
+ deployed: boolean
+}) {
+ const queryClient = useQueryClient()
+ const [selected, setSelected] = useState<ManagedAgentSchedule>()
+ const schedules = useQuery({
+ queryKey: ['managed-agent-schedules', projectId, agentId, environment],
+ queryFn: () => getManagedAgentSchedules(projectId, agentId, environment),
+ enabled: deployed,
+ refetchInterval: 10_000,
+ })
+ const runs = useQuery({
+ queryKey: ['managed-agent-schedule-runs', projectId, agentId, environment],
+ queryFn: () => getManagedAgentScheduleRuns(projectId, agentId, environment),
+ enabled: deployed,
+ refetchInterval: 5_000,
+ })
+ const runNow = useMutation({
+ mutationFn: (scheduleId: string) =>
+ runManagedAgentSchedule(projectId, agentId, environment, scheduleId),
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: [
+ 'managed-agent-schedule-runs',
+ projectId,
+ agentId,
+ environment,
+ ],
+ }),
+ queryClient.invalidateQueries({
+ queryKey: ['managed-agent-sessions', agentId],
+ }),
+ ])
+ },
+ onError: (error) => notifyError("Couldn't run that schedule.", error),
+ })
+
+ if (!deployed) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={CalendarClock}
+ title={`No active ${environment} deployment`}
+ description="Deploy this project to activate its schedules in this environment."
+ />
+ </Panel>
+ )
+ }
+ if (schedules.isError || runs.isError) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={CalendarClock}
+ title="Schedules are temporarily unavailable"
+ description="Try loading this environment again."
+ />
+ </Panel>
+ )
+ }
+
+ const columns: Column<ManagedAgentSchedule>[] = [
+ {
+ key: 'schedule',
+ header: 'Schedule',
+ cell: (schedule) => (
+ <div>
+ <p className="text-sm font-medium">{schedule.id}</p>
+ <p className="text-muted-foreground mt-1 font-mono text-xs">
+ {schedule.cron} · {schedule.timezone}
+ </p>
+ </div>
+ ),
+ },
+ {
+ key: 'next',
+ header: 'Next run',
+ cell: (schedule) => (
+ <span className="text-muted-foreground text-xs">
+ {formatDate(schedule.nextRunAt)}
+ </span>
+ ),
+ },
+ {
+ key: 'last',
+ header: 'Last run',
+ cell: (schedule) => (
+ <span className="text-muted-foreground text-xs">
+ {formatDate(schedule.lastRunAt)}
+ </span>
+ ),
+ },
+ {
+ key: 'status',
+ header: 'Status',
+ cell: (schedule) => <StatusBadge status={schedule.status} />,
+ },
+ {
+ key: 'actions',
+ header: '',
+ align: 'right',
+ cell: (schedule) => (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={runNow.isPending}
+ onClick={(event) => {
+ event.stopPropagation()
+ runNow.mutate(schedule.id)
+ }}
+ >
+ {runNow.isPending && runNow.variables === schedule.id ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <Play />
+ )}
+ Run now
+ </Button>
+ ),
+ },
+ ]
+ const selectedRuns = (runs.data ?? []).filter(
+ (run) => run.scheduleId === selected?.id,
+ )
+
+ return (
+ <>
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Schedules</PanelTitle>
+ <PanelDescription>
+ {environment === 'development'
+ ? 'Development schedules run only when you choose Run now.'
+ : 'Production schedules run automatically. Each run starts a fresh session.'}
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ <PanelContent className="p-0">
+ <ResourceTable
+ columns={columns}
+ rows={schedules.data ?? []}
+ rowKey={(schedule) => schedule.id}
+ loading={schedules.isLoading}
+ onRowClick={setSelected}
+ empty={
+ <EmptyState
+ icon={CalendarClock}
+ title={`No ${environment} schedules`}
+ description="Add a schedule under this agent's schedules folder and deploy it."
+ />
+ }
+ />
+ </PanelContent>
+ </Panel>
+
+ <Dialog
+ open={Boolean(selected)}
+ onOpenChange={(open) => !open && setSelected(undefined)}
+ >
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{selected?.id}</DialogTitle>
+ <DialogDescription>
+ {selected?.cron} · {selected?.timezone} · overlap{' '}
+ {selected?.overlap}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="max-h-[26rem] overflow-y-auto rounded-md border">
+ {selectedRuns.length ? (
+ <div className="divide-y">
+ {selectedRuns.map((run) => (
+ <div
+ key={run.id}
+ className="flex items-center justify-between gap-4 p-3"
+ >
+ <div>
+ <p className="text-sm">{formatDate(run.scheduledAt)}</p>
+ <p className="text-muted-foreground mt-1 text-xs">
+ {run.manual ? 'Manual run' : 'Scheduled run'} · attempt{' '}
+ {run.attempt}
+ </p>
+ </div>
+ <div className="flex items-center gap-3">
+ <StatusBadge status={run.outcome} />
+ {run.sessionId ? (
+ <Link
+ className="font-mono text-xs underline underline-offset-2"
+ to={{
+ pathname: `/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(run.sessionId)}`,
+ search: projectContextSearch(
+ '',
+ agentId,
+ environment,
+ ),
+ }}
+ >
+ Session
+ </Link>
+ ) : null}
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-muted-foreground p-6 text-sm">
+ No runs recorded yet.
+ </p>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
diff --git a/web/src/managed-agents/Session.tsx b/web/src/managed-agents/Session.tsx
index c561ff24..ec31e3f3 100644
--- a/web/src/managed-agents/Session.tsx
+++ b/web/src/managed-agents/Session.tsx
@@ -1,3 +1,4 @@
+import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { ArrowLeft, Bot, Clock3, Loader2, TerminalSquare } from 'lucide-react'
import { Link, useParams, useSearchParams } from 'react-router-dom'
@@ -17,6 +18,7 @@ import {
getManagedAgentSessionEvents,
getManagedProject,
} from './api'
+import { AgentMarkdown } from './AgentMarkdown'
function formatDate(value: string) {
return new Date(value).toLocaleString()
@@ -25,6 +27,9 @@ function formatDate(value: string) {
export default function ManagedSessionDetail() {
const { projectId = '', sessionId = '' } = useParams()
const [searchParams] = useSearchParams()
+ const [activeTab, setActiveTab] = useState<'conversation' | 'events'>(
+ 'conversation',
+ )
const project = useQuery({
queryKey: ['managed-project', projectId],
queryFn: () => getManagedProject(projectId),
@@ -119,83 +124,116 @@ export default function ManagedSessionDetail() {
</Panel>
</div>
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>Conversation</PanelTitle>
- <PanelDescription className="mt-1">
- Durable turn history for this session.
- </PanelDescription>
- </div>
- </PanelHeader>
- <PanelContent className="space-y-6">
- {session.data.turns.length === 0 ? (
- <p className="text-muted-foreground text-sm">No turns yet.</p>
- ) : (
- session.data.turns.map((turn) => {
- const response = replies.find((event) => event.turnId === turn.id)
- return (
- <div
- key={turn.id}
- className="space-y-4 border-b pb-6 last:border-0 last:pb-0"
- >
- <div>
- <p className="text-muted-foreground mb-2 text-[10px] font-medium tracking-wider uppercase">
- You · {formatDate(turn.createdAt)}
- </p>
- <p className="bg-muted ml-auto max-w-3xl rounded-lg px-4 py-3 text-sm whitespace-pre-wrap">
- {turn.input}
- </p>
- </div>
- <div>
- <p className="text-muted-foreground mb-2 flex items-center gap-1.5 text-[10px] font-medium tracking-wider uppercase">
- <Bot className="size-3" /> Agent · {turn.status}
- </p>
- <p className="max-w-3xl text-sm leading-6 whitespace-pre-wrap">
- {response && typeof response.data.text === 'string'
- ? response.data.text
- : 'No completed response recorded.'}
- </p>
- </div>
- </div>
- )
- })
- )}
- </PanelContent>
- </Panel>
-
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>Durable log</PanelTitle>
- <PanelDescription className="mt-1">
- Runtime events persisted for inspection and debugging.
- </PanelDescription>
- </div>
- <span className="text-muted-foreground flex items-center gap-1.5 text-xs">
- <Clock3 className="size-3.5" /> {events.data?.length ?? 0} events
+ <div
+ role="tablist"
+ aria-label="Session detail"
+ className="flex w-fit items-center gap-1 rounded-lg border p-1"
+ >
+ <Button
+ role="tab"
+ aria-selected={activeTab === 'conversation'}
+ variant={activeTab === 'conversation' ? 'default' : 'ghost'}
+ size="sm"
+ onClick={() => setActiveTab('conversation')}
+ >
+ Conversation
+ </Button>
+ <Button
+ role="tab"
+ aria-selected={activeTab === 'events'}
+ variant={activeTab === 'events' ? 'default' : 'ghost'}
+ size="sm"
+ onClick={() => setActiveTab('events')}
+ >
+ Events
+ <span className="text-[10px] opacity-70">
+ {events.data?.length ?? 0}
</span>
- </PanelHeader>
- <div className="divide-y font-mono text-xs">
- {(events.data ?? []).map((event) => (
- <div
- key={event.id ?? event.seq}
- className="grid gap-2 px-5 py-3 md:grid-cols-[5rem_12rem_1fr]"
- >
- <span className="text-muted-foreground">#{event.seq}</span>
- <span>{event.type}</span>
- <pre className="overflow-x-auto whitespace-pre-wrap">
- {JSON.stringify(event.data, null, 2)}
- </pre>
+ </Button>
+ </div>
+
+ {activeTab === 'conversation' ? (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Conversation</PanelTitle>
+ <PanelDescription className="mt-1">
+ Durable turn history for this session.
+ </PanelDescription>
</div>
- ))}
- {!events.isLoading && (events.data ?? []).length === 0 ? (
- <p className="text-muted-foreground px-5 py-4">
- No events recorded.
- </p>
- ) : null}
- </div>
- </Panel>
+ </PanelHeader>
+ <PanelContent className="space-y-8 px-6 py-7">
+ {session.data.turns.length === 0 ? (
+ <p className="text-muted-foreground text-sm">No turns yet.</p>
+ ) : (
+ session.data.turns.map((turn) => {
+ const response = replies.find(
+ (event) => event.turnId === turn.id,
+ )
+ return (
+ <div key={turn.id} className="space-y-6">
+ <div>
+ <p className="text-muted-foreground mb-1.5 text-[10px] font-semibold tracking-wider uppercase">
+ You
+ </p>
+ <p className="bg-muted ml-auto max-w-2xl rounded-xl rounded-br-sm px-3.5 py-2.5 text-sm leading-6 whitespace-pre-wrap">
+ {turn.input}
+ </p>
+ </div>
+ <div className="max-w-3xl">
+ <p className="text-muted-foreground mb-1.5 flex items-center gap-1.5 text-[10px] font-semibold tracking-wider uppercase">
+ <Bot className="size-3" /> Agent
+ </p>
+ {response && typeof response.data.text === 'string' ? (
+ <AgentMarkdown>{response.data.text}</AgentMarkdown>
+ ) : (
+ <p className="text-muted-foreground text-sm">
+ {turn.status === 'completed'
+ ? 'No completed response recorded.'
+ : `Turn ${turn.status.replace(/_/g, ' ')}.`}
+ </p>
+ )}
+ </div>
+ </div>
+ )
+ })
+ )}
+ </PanelContent>
+ </Panel>
+ ) : (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Durable log</PanelTitle>
+ <PanelDescription className="mt-1">
+ Runtime events persisted for inspection and debugging.
+ </PanelDescription>
+ </div>
+ <span className="text-muted-foreground flex items-center gap-1.5 text-xs">
+ <Clock3 className="size-3.5" /> {events.data?.length ?? 0} events
+ </span>
+ </PanelHeader>
+ <div className="divide-y font-mono text-xs">
+ {(events.data ?? []).map((event) => (
+ <div
+ key={event.id ?? event.seq}
+ className="grid gap-2 px-5 py-3 md:grid-cols-[5rem_12rem_1fr]"
+ >
+ <span className="text-muted-foreground">#{event.seq}</span>
+ <span>{event.type}</span>
+ <pre className="overflow-x-auto whitespace-pre-wrap">
+ {JSON.stringify(event.data, null, 2)}
+ </pre>
+ </div>
+ ))}
+ {!events.isLoading && (events.data ?? []).length === 0 ? (
+ <p className="text-muted-foreground px-5 py-4">
+ No events recorded.
+ </p>
+ ) : null}
+ </div>
+ </Panel>
+ )}
</div>
)
}
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 1e585f09..f0eddb00 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -38,6 +38,23 @@ const deploymentSchema = z.object({
),
}),
),
+ schedules: z
+ .array(
+ z.object({
+ id: z.string(),
+ agentId: z.string(),
+ cron: z.string(),
+ timezone: z.string(),
+ enabled: z.array(z.enum(['development', 'production'])),
+ overlap: z.enum(['skip', 'allow']),
+ dispatch: z.object({
+ text: z.string().optional(),
+ payload: z.unknown().optional(),
+ }),
+ }),
+ )
+ .optional()
+ .default([]),
}),
})
.optional(),
@@ -182,6 +199,45 @@ const outboxesResponseSchema = z.object({
outboxes: z.array(outboxSchema),
})
+const scheduleSchema = z.object({
+ id: z.string(),
+ projectId: z.string(),
+ environment: z.enum(['development', 'production']),
+ agentId: z.string(),
+ deploymentId: z.string(),
+ cron: z.string(),
+ timezone: z.string(),
+ overlap: z.enum(['skip', 'allow']),
+ dispatch: z.object({
+ text: z.string().optional(),
+ payload: z.unknown().optional(),
+ }),
+ nextRunAt: z.string(),
+ lastRunAt: z.string().optional(),
+ status: z.enum(['active', 'manual', 'paused']),
+})
+
+const scheduleRunSchema = z.object({
+ id: z.string(),
+ scheduleId: z.string(),
+ projectId: z.string(),
+ environment: z.enum(['development', 'production']),
+ deploymentId: z.string(),
+ scheduledAt: z.string(),
+ manual: z.boolean(),
+ attempt: z.number(),
+ outcome: z.enum(['pending', 'enacted', 'skipped', 'failed']),
+ sessionId: z.string().optional(),
+ error: z.string().optional(),
+ createdAt: z.string(),
+})
+
+const schedulesResponseSchema = z.object({ schedules: z.array(scheduleSchema) })
+const scheduleRunsResponseSchema = z.object({
+ runs: z.array(scheduleRunSchema),
+})
+const scheduleRunResponseSchema = z.object({ run: scheduleRunSchema })
+
const slackManifestResponseSchema = z.object({
connection: channelSchema,
manifest: z.record(z.string(), z.unknown()),
@@ -238,7 +294,10 @@ const sessionSchema = z.object({
agentId: z.string(),
deploymentId: z.string(),
status: z.string(),
- source: z.enum(['api', 'channel', 'playground']).optional().default('api'),
+ source: z
+ .enum(['api', 'channel', 'playground', 'schedule'])
+ .optional()
+ .default('api'),
microvmState: z.string().optional(),
createdAt: z.string(),
updatedAt: z.string(),
@@ -283,6 +342,8 @@ export type ManagedAgentConnection = z.infer<typeof connectionSchema>
export type ManagedAgentChannel = z.infer<typeof channelSchema>
export type ManagedAgentOutbox = z.infer<typeof outboxSchema>
export type ManagedAgentOutboxItem = z.infer<typeof outboxItemSchema>
+export type ManagedAgentSchedule = z.infer<typeof scheduleSchema>
+export type ManagedAgentScheduleRun = z.infer<typeof scheduleRunSchema>
export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>
export type ManagedProjectSecret = z.infer<typeof secretSchema>
@@ -435,6 +496,52 @@ export async function getManagedAgentOutboxes(
)
}
+export async function getManagedAgentSchedules(
+ projectId: string,
+ agentId: string,
+ environment: 'development' | 'production',
+) {
+ const query = new URLSearchParams({ projectId, agentId, environment })
+ return (
+ await apiFetch(
+ `/managed-agents/schedules?${query.toString()}`,
+ undefined,
+ schedulesResponseSchema,
+ )
+ ).schedules
+}
+
+export async function getManagedAgentScheduleRuns(
+ projectId: string,
+ agentId: string,
+ environment: 'development' | 'production',
+) {
+ const query = new URLSearchParams({ projectId, agentId, environment })
+ return (
+ await apiFetch(
+ `/managed-agents/schedule-runs?${query.toString()}`,
+ undefined,
+ scheduleRunsResponseSchema,
+ )
+ ).runs
+}
+
+export async function runManagedAgentSchedule(
+ projectId: string,
+ agentId: string,
+ environment: 'development' | 'production',
+ scheduleId: string,
+) {
+ const query = new URLSearchParams({ projectId, agentId, environment })
+ return (
+ await apiFetch(
+ `/managed-agents/schedules/${encodeURIComponent(scheduleId)}/run?${query.toString()}`,
+ { method: 'POST' },
+ scheduleRunResponseSchema,
+ )
+ ).run
+}
+
export async function startManagedAgentSlack(
agentId: string,
name: string,