Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(routines): add agent-managed scheduled routines (#103)

Leod6c61a0e042f
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 8c2d2f82f..a4edc1b31 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -69,6 +69,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.portabilityExport]: AuthOrchestrationReadScope,
[WS_METHODS.portabilityPreviewImport]: AuthOrchestrationReadScope,
[WS_METHODS.portabilityApplyImport]: AuthOrchestrationOperateScope,
+ [WS_METHODS.routinesListRuns]: AuthOrchestrationReadScope,
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
[WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.test.ts b/apps/server/src/orchestration/ActivityPayloadProjection.test.ts
index 2cdfef19f..8e3dd8bbd 100644
--- a/apps/server/src/orchestration/ActivityPayloadProjection.test.ts
+++ b/apps/server/src/orchestration/ActivityPayloadProjection.test.ts
@@ -21,6 +21,17 @@ function activity(payload: Record<string, unknown>): OrchestrationThreadActivity
* assertions are the tripwire.
*/
describe("projectActivityPayload", () => {
+ it("keeps a Mastra command while dropping its unused arguments", () => {
+ const projected = projectActivityPayload(
+ activity({
+ itemType: "command_execution",
+ data: { args: { command: 'printf "hi\\n"', cwd: null, background: null } },
+ }),
+ );
+ const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
+ expect(data).toEqual({ command: 'printf "hi\\n"' });
+ });
+
it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {
const projected = projectActivityPayload(
activity({
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.ts
index 32f249c25..930934488 100644
--- a/apps/server/src/orchestration/ActivityPayloadProjection.ts
+++ b/apps/server/src/orchestration/ActivityPayloadProjection.ts
@@ -130,6 +130,11 @@ function projectCommandValue(data: Record<string, unknown>): unknown {
return data.command;
}
+ const args = asRecord(data.args);
+ if (args?.command !== undefined) {
+ return args.command;
+ }
+
const input = asRecord(data.input);
if (input?.command !== undefined) {
return input.command;
diff --git a/apps/server/src/orchestration/Layers/BotPersistence.test.ts b/apps/server/src/orchestration/Layers/BotPersistence.test.ts
index 806db488f..64fdc3ed1 100644
--- a/apps/server/src/orchestration/Layers/BotPersistence.test.ts
+++ b/apps/server/src/orchestration/Layers/BotPersistence.test.ts
@@ -7,6 +7,7 @@ import {
MessageId,
ProjectId,
ProviderInstanceId,
+ RoutineId,
ThreadId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -55,6 +56,7 @@ it.layer(TestLayer)("bot persistence", (it) => {
const sql = yield* SqlClient.SqlClient;
const botId = BotId.make("bot-1");
const groupId = GroupId.make("group-1");
+ const routineId = RoutineId.make("routine-1");
const createdAt = "2026-01-01T00:00:00.000Z";
yield* engine.dispatch({
@@ -73,6 +75,36 @@ it.layer(TestLayer)("bot persistence", (it) => {
groupId: null,
createdAt,
});
+ yield* engine.dispatch({
+ type: "routine.draft",
+ commandId: CommandId.make("cmd-routine-draft"),
+ routineId,
+ botId,
+ targetThreadId: ThreadId.make("thread-routine"),
+ projectId: ProjectId.make("project-1"),
+ job: "Morning research",
+ procedure: "Prepare the morning research brief.",
+ schedule: { kind: "daily", time: "09:00" },
+ timezone: "America/New_York",
+ skillAssignmentIds: [],
+ connectorDependencies: [],
+ sandbox: "local",
+ approvalPolicy: "approval-required",
+ createdAt,
+ });
+ yield* engine.dispatch({
+ type: "routine.approve",
+ commandId: CommandId.make("cmd-routine-approve"),
+ routineId,
+ procedureVersion: 1,
+ createdAt,
+ });
+ yield* engine.dispatch({
+ type: "routine.enable",
+ commandId: CommandId.make("cmd-routine-enable"),
+ routineId,
+ createdAt,
+ });
yield* engine.dispatch({
type: "bot.update",
commandId: CommandId.make("cmd-bot-update"),
@@ -98,6 +130,9 @@ it.layer(TestLayer)("bot persistence", (it) => {
const archived = yield* snapshots.getShellSnapshot();
assert.equal(archived.bots.length, 1);
assert.notEqual(archived.bots[0]?.archivedAt, null);
+ assert.equal(archived.routines?.[0]?.lifecycle, "paused");
+ assert.equal(archived.routines?.[0]?.enabled, false);
+ assert.equal(archived.routines?.[0]?.nextRunAt, null);
yield* engine.dispatch({
type: "bot.restore",
@@ -120,6 +155,8 @@ it.layer(TestLayer)("bot persistence", (it) => {
});
const restored = yield* snapshots.getShellSnapshot();
+ assert.equal(restored.routines?.[0]?.lifecycle, "paused");
+ assert.equal(restored.routines?.[0]?.enabled, false);
assert.deepEqual(restored.bots, [
{
id: botId,
diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts
index f43005ecc..f7f7cd32c 100644
--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts
+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts
@@ -113,6 +113,29 @@ function commandToAggregateRef(command: OrchestrationCommand): {
aggregateKind: "delegation",
aggregateId: command.delegationId,
};
+ case "routine.create-approved":
+ case "routine.draft":
+ case "routine.approve":
+ case "routine.enable":
+ case "routine.pause":
+ case "routine.run":
+ case "routine.run.scheduled":
+ case "routine.run.start":
+ case "routine.run.block":
+ case "routine.run.fail":
+ case "routine.run.complete":
+ case "routine.run.cancel":
+ case "routine.delete":
+ return {
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ };
+ case "routine.skill.assign":
+ case "routine.skill.unassign":
+ return {
+ aggregateKind: "skill-assignment",
+ aggregateId: command.assignmentId,
+ };
default:
return {
aggregateKind: "thread",
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index cf124fdd5..1463d2356 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1,6 +1,11 @@
import {
ApprovalRequestId,
isGroupBotMember,
+ McpServerId,
+ RoutineRunFailure,
+ RoutineRunResult,
+ RoutineSchedule,
+ SkillAssignmentId,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
@@ -11,6 +16,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -68,6 +74,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
groups: "projection.groups",
delegations: "projection.delegations",
mcpServers: "projection.mcp-servers",
+ routines: "projection.routines",
threads: "projection.threads",
threadMessages: "projection.thread-messages",
threadProposedPlans: "projection.thread-proposed-plans",
@@ -81,6 +88,14 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
type ProjectorName =
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
+const encodeRoutineSchedule = Schema.encodeSync(Schema.fromJsonString(RoutineSchedule));
+const encodeSkillAssignmentIds = Schema.encodeSync(
+ Schema.fromJsonString(Schema.Array(SkillAssignmentId)),
+);
+const encodeMcpServerIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(McpServerId)));
+const encodeRoutineResult = Schema.encodeSync(Schema.fromJsonString(RoutineRunResult));
+const encodeRoutineFailure = Schema.encodeSync(Schema.fromJsonString(RoutineRunFailure));
+
/**
* Turn state to settle still-running turns with when their session leaves the
* "running" status, or null while the session is (re)starting or running and
@@ -832,6 +847,118 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
Effect.asVoid,
);
});
+
+ const applyRoutinesProjection: ProjectorDefinition["apply"] = Effect.fn(
+ "applyRoutinesProjection",
+ )(function* (event, _attachmentSideEffects) {
+ if (event.type === "skill-assignment.assigned") {
+ const assignment = event.payload.assignment;
+ yield* sql`
+ INSERT INTO projection_routine_skill_assignments (
+ assignment_id, bot_id, skill_id, name, description, created_at, updated_at
+ ) VALUES (
+ ${assignment.id}, ${assignment.botId}, ${assignment.skillId}, ${assignment.name},
+ ${assignment.description}, ${assignment.createdAt}, ${assignment.updatedAt}
+ ) ON CONFLICT (assignment_id) DO UPDATE SET
+ bot_id = excluded.bot_id,
+ skill_id = excluded.skill_id,
+ name = excluded.name,
+ description = excluded.description,
+ updated_at = excluded.updated_at
+ `.pipe(Effect.mapError(toPersistenceSqlError("ProjectionPipeline.routines:assignment")));
+ return;
+ }
+ if (event.type === "skill-assignment.unassigned") {
+ yield* sql`
+ DELETE FROM projection_routine_skill_assignments
+ WHERE assignment_id = ${event.payload.assignmentId}
+ `.pipe(Effect.mapError(toPersistenceSqlError("ProjectionPipeline.routines:unassign")));
+ return;
+ }
+
+ switch (event.type) {
+ case "routine.drafted":
+ case "routine.approved":
+ case "routine.enabled":
+ case "routine.running":
+ case "routine.paused":
+ case "routine.blocked":
+ case "routine.failed":
+ case "routine.completed":
+ case "routine.run-canceled":
+ case "routine.deleted":
+ break;
+ default:
+ return;
+ }
+
+ const routine = event.payload.routine;
+ yield* sql`
+ INSERT INTO projection_routines (
+ routine_id, bot_id, target_thread_id, project_id, job, procedure, procedure_version,
+ approval_version, schedule_json, timezone, skill_assignment_ids_json,
+ connector_dependencies_json, sandbox, approval_policy, enabled, lifecycle,
+ next_run_at, last_run_at, latest_result_json, latest_failure_json,
+ created_at, updated_at, deleted_at
+ ) VALUES (
+ ${routine.id}, ${routine.botId}, ${routine.targetThreadId}, ${routine.projectId}, ${routine.job},
+ ${routine.procedure}, ${routine.procedureVersion}, ${routine.approvalVersion},
+ ${encodeRoutineSchedule(routine.schedule)}, ${routine.timezone},
+ ${encodeSkillAssignmentIds(routine.skillAssignmentIds)},
+ ${encodeMcpServerIds(routine.connectorDependencies)}, ${routine.sandbox},
+ ${routine.approvalPolicy}, ${routine.enabled ? 1 : 0}, ${routine.lifecycle},
+ ${routine.nextRunAt}, ${routine.lastRunAt},
+ ${routine.latestResult === null ? null : encodeRoutineResult(routine.latestResult)},
+ ${routine.latestFailure === null ? null : encodeRoutineFailure(routine.latestFailure)},
+ ${routine.createdAt}, ${routine.updatedAt}, ${routine.deletedAt}
+ ) ON CONFLICT (routine_id) DO UPDATE SET
+ bot_id = excluded.bot_id,
+ target_thread_id = excluded.target_thread_id,
+ project_id = excluded.project_id,
+ job = excluded.job,
+ procedure = excluded.procedure,
+ procedure_version = excluded.procedure_version,
+ approval_version = excluded.approval_version,
+ schedule_json = excluded.schedule_json,
+ timezone = excluded.timezone,
+ skill_assignment_ids_json = excluded.skill_assignment_ids_json,
+ connector_dependencies_json = excluded.connector_dependencies_json,
+ sandbox = excluded.sandbox,
+ approval_policy = excluded.approval_policy,
+ enabled = excluded.enabled,
+ lifecycle = excluded.lifecycle,
+ next_run_at = excluded.next_run_at,
+ last_run_at = excluded.last_run_at,
+ latest_result_json = excluded.latest_result_json,
+ latest_failure_json = excluded.latest_failure_json,
+ updated_at = excluded.updated_at,
+ deleted_at = excluded.deleted_at
+ `.pipe(Effect.mapError(toPersistenceSqlError("ProjectionPipeline.routines:routine")));
+
+ if (!("run" in event.payload)) return;
+ const run = event.payload.run;
+ yield* sql`
+ INSERT INTO projection_routine_runs (
+ run_id, routine_id, procedure_version, trigger, scheduled_for, status,
+ thread_ref, result_json, failure_json, usage_ref, started_at, completed_at,
+ created_at, updated_at
+ ) VALUES (
+ ${run.id}, ${run.routineId}, ${run.procedureVersion}, ${run.trigger},
+ ${run.scheduledFor}, ${run.status}, ${run.threadRef},
+ ${run.result === null ? null : encodeRoutineResult(run.result)},
+ ${run.failure === null ? null : encodeRoutineFailure(run.failure)},
+ ${run.usageRef}, ${run.startedAt}, ${run.completedAt}, ${run.createdAt}, ${run.updatedAt}
+ ) ON CONFLICT (run_id) DO UPDATE SET
+ status = excluded.status,
+ thread_ref = excluded.thread_ref,
+ result_json = excluded.result_json,
+ failure_json = excluded.failure_json,
+ usage_ref = excluded.usage_ref,
+ started_at = excluded.started_at,
+ completed_at = excluded.completed_at,
+ updated_at = excluded.updated_at
+ `.pipe(Effect.mapError(toPersistenceSqlError("ProjectionPipeline.routines:run")));
+ });
const applyMcpServersProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyMcpServersProjection",
)(function* (event, _attachmentSideEffects) {
@@ -1961,6 +2088,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
name: ORCHESTRATION_PROJECTOR_NAMES.mcpServers,
apply: applyMcpServersProjection,
},
+ {
+ name: ORCHESTRATION_PROJECTOR_NAMES.routines,
+ apply: applyRoutinesProjection,
+ },
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
apply: applyThreadMessagesProjection,
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index 12e86146f..e8385767a 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -60,6 +60,8 @@ import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheck
import { ProjectionGroup } from "../../persistence/Services/ProjectionGroups.ts";
import { ProjectionMcpServerRepository } from "../../persistence/Services/ProjectionMcpServers.ts";
import { ProjectionMcpServerRepositoryLive } from "../../persistence/Layers/ProjectionMcpServers.ts";
+import { RoutineRepository } from "../../routines/Repository.ts";
+import { RoutineRepositoryLive } from "../../routines/RepositoryLive.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
@@ -238,6 +240,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.groups,
ORCHESTRATION_PROJECTOR_NAMES.delegations,
ORCHESTRATION_PROJECTOR_NAMES.mcpServers,
+ ORCHESTRATION_PROJECTOR_NAMES.routines,
ORCHESTRATION_PROJECTOR_NAMES.threads,
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
@@ -433,6 +436,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const projectionMcpServerRepository = yield* ProjectionMcpServerRepository;
+ const routineRepository = yield* RoutineRepository;
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const threadPlanProgress = yield* ThreadPlanProgressService;
const sql = yield* SqlClient.SqlClient;
@@ -1658,6 +1662,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
projectionMcpServerRepository.listAll(),
+ routineRepository.listAll,
+ routineRepository.listAllRuns,
+ routineRepository.listSkillAssignments,
listThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -1732,6 +1739,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
groupRows,
delegationRows,
mcpServers,
+ routines,
+ routineRuns,
+ skillAssignments,
threadRows,
messageRows,
proposedPlanRows,
@@ -1917,6 +1927,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
groups: groupRows.map(mapGroupRow),
delegations: delegationRows.map((row) => row.delegation),
mcpServers,
+ routines,
+ routineRuns,
+ skillAssignments,
threads,
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
@@ -1973,6 +1986,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
projectionMcpServerRepository.listAll(),
+ routineRepository.listAll,
+ routineRepository.listAllRuns,
+ routineRepository.listSkillAssignments,
listThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2023,6 +2039,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
groupRows,
delegationRows,
mcpServers,
+ routines,
+ routineRuns,
+ skillAssignments,
threadRows,
proposedPlanRows,
sessionRows,
@@ -2184,6 +2203,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
groups: groupRows.map(mapGroupRow),
delegations: delegationRows.map((row) => row.delegation),
mcpServers,
+ routines,
+ routineRuns,
+ skillAssignments,
threads,
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel;
@@ -2234,6 +2256,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
projectionMcpServerRepository.listAll(),
+ routineRepository.listAll,
+ routineRepository.listAllRuns,
+ routineRepository.listSkillAssignments,
listActiveThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2276,6 +2301,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
groupRows,
delegationRows,
mcpServers,
+ routines,
+ routineRuns,
+ skillAssignments,
threadRows,
sessionRows,
latestTurnRows,
@@ -2339,6 +2367,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
groups: groupRows.map(mapGroupRow),
delegations: delegationRows.map((row) => row.delegation),
mcpServers,
+ routines: routines.filter((routine) => routine.deletedAt === null),
+ routineRuns,
+ skillAssignments,
threads: Arr.filterMap(threadRows, (row) =>
row.deletedAt === null
? Result.succeed({
@@ -3214,4 +3245,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
export const OrchestrationProjectionSnapshotQueryLive = Layer.effect(
ProjectionSnapshotQuery,
makeProjectionSnapshotQuery,
-).pipe(Layer.provideMerge(ProjectionMcpServerRepositoryLive));
+).pipe(
+ Layer.provideMerge(ProjectionMcpServerRepositoryLive),
+ Layer.provideMerge(RoutineRepositoryLive),
+);
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
index 54bb80758..4eb9a2a8e 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
@@ -3408,6 +3408,7 @@ describe("ProviderCommandReactor", () => {
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
+ harness.respondToUserInput.mockImplementation(() => Effect.never);
await Effect.runPromise(
harness.engine.dispatch({
@@ -3441,6 +3442,14 @@ describe("ProviderCommandReactor", () => {
);
await waitFor(() => harness.respondToUserInput.mock.calls.length === 1);
+ const readModel = await harness.readModel();
+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
+ expect(thread?.messages.filter((message) => message.role === "user")).toEqual([
+ expect.objectContaining({
+ id: MessageId.make("user-input:thread-1:user-input-request-1"),
+ text: "workspace-write",
+ }),
+ ]);
expect(harness.respondToUserInput.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
requestId: "user-input-request-1",
@@ -3543,6 +3552,16 @@ describe("ProviderCommandReactor", () => {
(activity.payload as Record<string, unknown>).requestId === "approval-request-1",
);
expect(resolvedActivity).toBeUndefined();
+ expect(thread?.messages).toContainEqual(
+ expect.objectContaining({
+ role: "assistant",
+ text: "I could not continue that approval because the agent session restarted. Send it again.",
+ }),
+ );
+ expect(thread?.session).toMatchObject({
+ status: "error",
+ activeTurnId: null,
+ });
});
it("surfaces non-resumable provider user-input callbacks as stale failures", async () => {
@@ -3652,6 +3671,16 @@ describe("ProviderCommandReactor", () => {
(activity.payload as Record<string, unknown>).requestId === "user-input-request-1",
);
expect(resolvedActivity).toBeUndefined();
+ expect(thread?.messages).toContainEqual(
+ expect.objectContaining({
+ role: "assistant",
+ text: "I could not continue that request because the agent session restarted. Send it again.",
+ }),
+ );
+ expect(thread?.session).toMatchObject({
+ status: "error",
+ activeTurnId: null,
+ });
});
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index 1edfdb07c..d75a42651 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -5,6 +5,7 @@ import {
type ChatAttachment,
CommandId,
EventId,
+ MessageId,
type ModelSelection,
type McpServer,
type OrchestrationEvent,
@@ -425,6 +426,76 @@ const make = Effect.gen(function* () {
),
);
+ const appendUserInputFailureReply = Effect.fn("appendUserInputFailureReply")(function* (input: {
+ readonly threadId: ThreadId;
+ readonly requestId: string;
+ readonly createdAt: string;
+ }) {
+ const thread = yield* resolveThread(input.threadId);
+ if (!thread) return;
+ const messageId = MessageId.make(
+ `assistant:user-input-response-failed:${input.threadId}:${input.requestId}`,
+ );
+ if (thread.messages.some((message) => message.id === messageId)) return;
+ const turnId = thread.session?.activeTurnId ?? undefined;
+ const text =
+ "I could not continue that request because the agent session restarted. Send it again.";
+
+ const deltaCommandId = yield* serverCommandId("user-input-failure-reply-delta");
+ yield* orchestrationEngine.dispatch({
+ type: "thread.message.assistant.delta",
+ commandId: deltaCommandId,
+ threadId: input.threadId,
+ messageId,
+ delta: text,
+ ...(turnId ? { turnId } : {}),
+ createdAt: input.createdAt,
+ });
+ const completeCommandId = yield* serverCommandId("user-input-failure-reply-complete");
+ yield* orchestrationEngine.dispatch({
+ type: "thread.message.assistant.complete",
+ commandId: completeCommandId,
+ threadId: input.threadId,
+ messageId,
+ ...(turnId ? { turnId } : {}),
+ createdAt: input.createdAt,
+ });
+ });
+
+ const appendApprovalFailureReply = Effect.fn("appendApprovalFailureReply")(function* (input: {
+ readonly threadId: ThreadId;
+ readonly requestId: string;
+ readonly createdAt: string;
+ }) {
+ const thread = yield* resolveThread(input.threadId);
+ if (!thread) return;
+ const messageId = MessageId.make(
+ `assistant:approval-response-failed:${input.threadId}:${input.requestId}`,
+ );
+ if (thread.messages.some((message) => message.id === messageId)) return;
+ const turnId = thread.session?.activeTurnId ?? undefined;
+ const text =
+ "I could not continue that approval because the agent session restarted. Send it again.";
+
+ yield* orchestrationEngine.dispatch({
+ type: "thread.message.assistant.delta",
+ commandId: yield* serverCommandId("approval-failure-reply-delta"),
+ threadId: input.threadId,
+ messageId,
+ delta: text,
+ ...(turnId ? { turnId } : {}),
+ createdAt: input.createdAt,
+ });
+ yield* orchestrationEngine.dispatch({
+ type: "thread.message.assistant.complete",
+ commandId: yield* serverCommandId("approval-failure-reply-complete"),
+ threadId: input.threadId,
+ messageId,
+ ...(turnId ? { turnId } : {}),
+ createdAt: input.createdAt,
+ });
+ });
+
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
const capError = isBotUsageCapExceeded(failReason?.error) ? failReason.error : undefined;
@@ -957,6 +1028,7 @@ const make = Effect.gen(function* () {
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly modelSelection?: ModelSelection;
readonly interactionMode?: "default" | "plan";
+ readonly timezone?: string;
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
@@ -1013,6 +1085,7 @@ const make = Effect.gen(function* () {
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
+ ...(input.timezone !== undefined ? { timezone: input.timezone } : {}),
};
});
@@ -1446,6 +1519,7 @@ const make = Effect.gen(function* () {
? { modelSelection: event.payload.modelSelection }
: {}),
interactionMode: event.payload.interactionMode,
+ ...(event.payload.timezone !== undefined ? { timezone: event.payload.timezone } : {}),
createdAt: event.payload.createdAt,
}).pipe(
Effect.map(Option.some),
@@ -1605,17 +1679,22 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
- const hasSession = thread.session && thread.session.status !== "stopped";
- if (!hasSession) {
- return yield* appendProviderFailureActivity({
+ const session = thread.session;
+ if (!session || session.status === "stopped") {
+ yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
- detail: "No active provider session is bound to this thread.",
+ detail: stalePendingRequestDetail("approval", event.payload.requestId),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
+ return yield* appendApprovalFailureReply({
+ threadId: event.payload.threadId,
+ requestId: event.payload.requestId,
+ createdAt: event.payload.createdAt,
+ });
}
yield* agentController
@@ -1625,19 +1704,38 @@ const make = Effect.gen(function* () {
decision: event.payload.decision,
})
.pipe(
- Effect.catchCause((cause) =>
- appendProviderFailureActivity({
- threadId: event.payload.threadId,
- kind: "provider.approval.respond.failed",
- summary: "Provider approval response failed",
- detail: isUnknownPendingApprovalRequestError(cause)
- ? stalePendingRequestDetail("approval", event.payload.requestId)
- : Cause.pretty(cause),
- turnId: null,
- createdAt: event.payload.createdAt,
- requestId: event.payload.requestId,
- }),
- ),
+ Effect.catchCause((cause) => {
+ const detail = isUnknownPendingApprovalRequestError(cause)
+ ? stalePendingRequestDetail("approval", event.payload.requestId)
+ : Cause.pretty(cause);
+ return Effect.gen(function* () {
+ yield* appendProviderFailureActivity({
+ threadId: event.payload.threadId,
+ kind: "provider.approval.respond.failed",
+ summary: "Provider approval response failed",
+ detail,
+ turnId: null,
+ createdAt: event.payload.createdAt,
+ requestId: event.payload.requestId,
+ });
+ yield* appendApprovalFailureReply({
+ threadId: event.payload.threadId,
+ requestId: event.payload.requestId,
+ createdAt: event.payload.createdAt,
+ });
+ yield* setThreadSession({
+ threadId: event.payload.threadId,
+ session: {
+ ...session,
+ status: "error",
+ activeTurnId: null,
+ lastError: detail,
+ updatedAt: event.payload.createdAt,
+ },
+ createdAt: event.payload.createdAt,
+ });
+ });
+ }),
);
});
@@ -1651,15 +1749,20 @@ const make = Effect.gen(function* () {
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
- return yield* appendProviderFailureActivity({
+ yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
- detail: "No active provider session is bound to this thread.",
+ detail: stalePendingRequestDetail("user-input", event.payload.requestId),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
+ return yield* appendUserInputFailureReply({
+ threadId: event.payload.threadId,
+ requestId: event.payload.requestId,
+ createdAt: event.payload.createdAt,
+ });
}
yield* agentController
@@ -1669,19 +1772,40 @@ const make = Effect.gen(function* () {
answers: event.payload.answers,
})
.pipe(
- Effect.catchCause((cause) =>
- appendProviderFailureActivity({
- threadId: event.payload.threadId,
- kind: "provider.user-input.respond.failed",
- summary: "Provider user input response failed",
- detail: isUnknownPendingUserInputRequestError(cause)
- ? stalePendingRequestDetail("user-input", event.payload.requestId)
- : Cause.pretty(cause),
- turnId: null,
- createdAt: event.payload.createdAt,
- requestId: event.payload.requestId,
- }),
- ),
+ Effect.catchCause((cause) => {
+ const detail = isUnknownPendingUserInputRequestError(cause)
+ ? stalePendingRequestDetail("user-input", event.payload.requestId)
+ : Cause.pretty(cause);
+ return Effect.gen(function* () {
+ yield* appendProviderFailureActivity({
+ threadId: event.payload.threadId,
+ kind: "provider.user-input.respond.failed",
+ summary: "Provider user input response failed",
+ detail,
+ turnId: null,
+ createdAt: event.payload.createdAt,
+ requestId: event.payload.requestId,
+ });
+ yield* appendUserInputFailureReply({
+ threadId: event.payload.threadId,
+ requestId: event.payload.requestId,
+ createdAt: event.payload.createdAt,
+ });
+ if (thread.session) {
+ yield* setThreadSession({
+ threadId: event.payload.threadId,
+ session: {
+ ...thread.session,
+ status: "error",
+ activeTurnId: null,
+ lastError: detail,
+ updatedAt: event.payload.createdAt,
+ },
+ createdAt: event.payload.createdAt,
+ });
+ }
+ });
+ }),
);
},
);
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
index 453bcdb57..3a396da57 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
@@ -682,6 +682,48 @@ describe("ProviderRuntimeIngestion", () => {
});
});
+ it("adds a visible reply when a completed turn emitted only whitespace", async () => {
+ const harness = await createHarness();
+ const turnId = asTurnId("turn-whitespace-only");
+
+ harness.emit({
+ type: "turn.started",
+ eventId: asEventId("evt-turn-whitespace-started"),
+ provider: ProviderDriverKind.make("codex"),
+ threadId: asThreadId("thread-1"),
+ createdAt: "2026-01-01T00:00:01.000Z",
+ turnId,
+ });
+ harness.emit({
+ type: "content.delta",
+ eventId: asEventId("evt-turn-whitespace-delta"),
+ provider: ProviderDriverKind.make("codex"),
+ threadId: asThreadId("thread-1"),
+ createdAt: "2026-01-01T00:00:02.000Z",
+ turnId,
+ itemId: asItemId("item-whitespace-only"),
+ payload: { streamKind: "assistant_text", delta: " \n" },
+ });
+ harness.emit({
+ type: "turn.completed",
+ eventId: asEventId("evt-turn-whitespace-completed"),
+ provider: ProviderDriverKind.make("codex"),
+ threadId: asThreadId("thread-1"),
+ createdAt: "2026-01-01T00:00:03.000Z",
+ turnId,
+ payload: { state: "completed" },
+ });
+
+ const thread = await waitForThread(harness.readModel, (entry) =>
+ entry.messages.some(
+ (message) =>
+ message.turnId === turnId &&
+ message.text === "I finished without a text response. Please try again.",
+ ),
+ );
+ expect(thread.messages.filter((message) => message.turnId === turnId)).toHaveLength(1);
+ });
+
it("applies provider session.state.changed transitions directly", async () => {
const harness = await createHarness();
const waitingAt = "2026-01-01T00:00:00.000Z";
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
index b0185d7af..e1aad7925 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
@@ -1,6 +1,8 @@
import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
ChatAttachment,
+ AkeruCreateRoutineInput,
ApprovalRequestId,
type AssistantDeliveryMode,
CommandId,
@@ -130,11 +132,21 @@ function runtimeChatAttachment(event: ProviderRuntimeEvent) {
const data = decodeRuntimeChatAttachment(event.payload.data);
return Option.isSome(data) ? data.value.chatAttachment : undefined;
}
+const decodeCreateRoutineInput = Schema.decodeUnknownExit(AkeruCreateRoutineInput, {
+ onExcessProperty: "error",
+});
-function boundedFeedbackArgs(toolName: string | undefined, args: unknown): unknown {
- if (toolName !== AKERU_PRODUCT_FEEDBACK_TOOL_NAME || args === undefined) return undefined;
- const decoded = decodeProductFeedbackToolDraft(args);
- return Exit.isSuccess(decoded) ? decoded.value : undefined;
+function boundedApprovalArgs(toolName: string | undefined, args: unknown): unknown {
+ if (args === undefined) return undefined;
+ if (toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME) {
+ const decoded = decodeProductFeedbackToolDraft(args);
+ return Exit.isSuccess(decoded) ? decoded.value : undefined;
+ }
+ if (toolName === AKERU_CREATE_ROUTINE_TOOL_NAME) {
+ const decoded = decodeCreateRoutineInput(args);
+ return Exit.isSuccess(decoded) ? decoded.value : undefined;
+ }
+ return undefined;
}
type TurnStartRequestedDomainEvent = Extract<
@@ -413,7 +425,7 @@ export function runtimeEventToActivities(
return [];
}
const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);
- const feedbackArgs = boundedFeedbackArgs(event.payload.toolName, event.payload.args);
+ const approvalArgs = boundedApprovalArgs(event.payload.toolName, event.payload.args);
return [
{
id: event.eventId,
@@ -438,7 +450,7 @@ export function runtimeEventToActivities(
...(event.payload.target ? { target: event.payload.target } : {}),
...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),
...(event.payload.action ? { action: event.payload.action } : {}),
- ...(feedbackArgs !== undefined ? { args: feedbackArgs } : {}),
+ ...(approvalArgs !== undefined ? { args: approvalArgs } : {}),
...(event.payload.detail ? { detail: event.payload.detail } : {}),
...(event.payload.appName ? { appName: event.payload.appName } : {}),
...(event.payload.options ? { options: event.payload.options } : {}),
@@ -1361,6 +1373,7 @@ const make = Effect.gen(function* () {
});
}
yield* clearAssistantMessageState(input.messageId);
+ return Boolean(input.hasProjectedMessage || hasRenderableText);
});
const finalizeActiveAssistantSegmentForTurn = (input: {
@@ -2061,7 +2074,7 @@ const make = Effect.gen(function* () {
const turnId = toTurnId(event.turnId);
if (turnId) {
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
- yield* Effect.forEach(
+ const finalizedReplyVisibility = yield* Effect.forEach(
assistantMessageIds,
(assistantMessageId) =>
finalizeAssistantMessage({
@@ -2075,7 +2088,7 @@ const make = Effect.gen(function* () {
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
}),
{ concurrency: 1 },
- ).pipe(Effect.asVoid);
+ );
yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
yield* clearAssistantSegmentStateForTurn(thread.id, turnId);
@@ -2087,6 +2100,27 @@ const make = Effect.gen(function* () {
turnId,
updatedAt: now,
});
+
+ const hasVisibleAssistantReply = messages.some(
+ (message) => message.role === "assistant" && sameId(message.turnId, turnId),
+ );
+ if (!hasVisibleAssistantReply && !finalizedReplyVisibility.some(Boolean)) {
+ const fallbackText =
+ event.payload.state === "failed"
+ ? "I could not complete that request. Check the error details and try again."
+ : "I finished without a text response. Please try again.";
+ yield* finalizeAssistantMessage({
+ event,
+ threadId: thread.id,
+ messageId: MessageId.make(`assistant:${event.eventId}:fallback`),
+ turnId,
+ createdAt: now,
+ commandTag: "assistant-empty-turn-complete",
+ finalDeltaCommandTag: "assistant-empty-turn-delta",
+ hasProjectedMessage: false,
+ fallbackText,
+ });
+ }
}
}
diff --git a/apps/server/src/orchestration/decider.routine.test.ts b/apps/server/src/orchestration/decider.routine.test.ts
new file mode 100644
index 000000000..67202710e
--- /dev/null
+++ b/apps/server/src/orchestration/decider.routine.test.ts
@@ -0,0 +1,168 @@
+import {
+ BotId,
+ CommandId,
+ EventId,
+ ProjectId,
+ RoutineId,
+ RoutineRunId,
+ ThreadId,
+} from "@t3tools/contracts";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+
+import { decideOrchestrationCommand } from "./decider.ts";
+import { createEmptyReadModel, projectEvent } from "./projector.ts";
+
+const NOW = "2026-08-31T13:00:00.000Z";
+
+it.layer(NodeServices.layer)("routine decider", (it) => {
+ it.effect("creates an already-approved routine atomically", () =>
+ Effect.gen(function* () {
+ const event = yield* decideOrchestrationCommand({
+ command: {
+ type: "routine.create-approved",
+ commandId: CommandId.make("command-routine-approved"),
+ routineId: RoutineId.make("routine-approved"),
+ botId: BotId.make("bot-1"),
+ targetThreadId: ThreadId.make("thread-1"),
+ job: "Daily brief",
+ procedure: "Summarize this chat.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ timezone: "America/New_York",
+ skillAssignmentIds: [],
+ connectorDependencies: [],
+ projectId: ProjectId.make("project-1"),
+ sandbox: "local",
+ approvalPolicy: "approval-required",
+ createdAt: NOW,
+ },
+ readModel: createEmptyReadModel(NOW),
+ });
+ const events = Array.isArray(event) ? event : [event];
+
+ expect(events).toHaveLength(1);
+ expect(events[0]?.type).toBe("routine.approved");
+ if (events[0]?.type === "routine.approved") {
+ expect(events[0].payload.routine).toMatchObject({
+ lifecycle: "approved",
+ procedureVersion: 1,
+ approvalVersion: 1,
+ enabled: false,
+ });
+ }
+ }),
+ );
+
+ it.effect("deletes a routine and disables future runs", () =>
+ Effect.gen(function* () {
+ const readModel = createEmptyReadModel(NOW);
+ const created = yield* decideOrchestrationCommand({
+ command: {
+ type: "routine.create-approved",
+ commandId: CommandId.make("command-routine-create-for-delete"),
+ routineId: RoutineId.make("routine-delete"),
+ botId: BotId.make("bot-1"),
+ targetThreadId: ThreadId.make("thread-1"),
+ job: "Daily brief",
+ procedure: "Summarize this chat.",
+ schedule: { kind: "daily", time: "09:00" },
+ timezone: "America/New_York",
+ skillAssignmentIds: [],
+ connectorDependencies: [],
+ projectId: ProjectId.make("project-1"),
+ sandbox: "local",
+ approvalPolicy: "approval-required",
+ createdAt: NOW,
+ },
+ readModel,
+ });
+ const createdEvent = Array.isArray(created) ? created[0] : created;
+ const withRoutine = yield* projectEvent(readModel, {
+ ...createdEvent,
+ sequence: 1,
+ eventId: EventId.make("event-routine-created-for-delete"),
+ });
+ const started = yield* decideOrchestrationCommand({
+ command: {
+ type: "routine.run",
+ commandId: CommandId.make("command-routine-run-before-delete"),
+ routineId: RoutineId.make("routine-delete"),
+ runId: RoutineRunId.make("run-before-delete"),
+ trigger: "manual",
+ createdAt: NOW,
+ },
+ readModel: withRoutine,
+ });
+ const startedEvent = Array.isArray(started) ? started[0] : started;
+ const withRun = yield* projectEvent(withRoutine, {
+ ...startedEvent,
+ sequence: 2,
+ eventId: EventId.make("event-routine-run-before-delete"),
+ });
+ const deletedAt = "2026-08-31T14:00:00.000Z";
+
+ const deleted = yield* decideOrchestrationCommand({
+ command: {
+ type: "routine.delete",
+ commandId: CommandId.make("command-routine-delete"),
+ routineId: RoutineId.make("routine-delete"),
+ createdAt: deletedAt,
+ },
+ readModel: withRun,
+ });
+ const deletedEvent = Array.isArray(deleted) ? deleted[0] : deleted;
+
+ expect(deletedEvent?.type).toBe("routine.deleted");
+ if (deletedEvent?.type === "routine.deleted") {
+ expect(deletedEvent.payload.routine).toMatchObject({
+ id: RoutineId.make("routine-delete"),
+ enabled: false,
+ lifecycle: "deleted",
+ nextRunAt: null,
+ updatedAt: deletedAt,
+ deletedAt,
+ });
+ }
+ const afterDelete = yield* projectEvent(withRun, {
+ ...deletedEvent,
+ sequence: 3,
+ eventId: EventId.make("event-routine-deleted"),
+ });
+ const completionError = yield* Effect.flip(
+ decideOrchestrationCommand({
+ command: {
+ type: "routine.run.complete",
+ commandId: CommandId.make("command-routine-complete-after-delete"),
+ routineId: RoutineId.make("routine-delete"),
+ runId: RoutineRunId.make("run-before-delete"),
+ result: { summary: "Late completion" },
+ usageRef: null,
+ nextRunAt: null,
+ createdAt: "2026-08-31T14:01:00.000Z",
+ },
+ readModel: afterDelete,
+ }),
+ );
+ expect(completionError.message).toContain("does not exist");
+ }),
+ );
+
+ it.effect("rejects deletion when the routine does not exist", () =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(
+ decideOrchestrationCommand({
+ command: {
+ type: "routine.delete",
+ commandId: CommandId.make("command-missing-routine-delete"),
+ routineId: RoutineId.make("routine-missing"),
+ createdAt: NOW,
+ },
+ readModel: createEmptyReadModel(NOW),
+ }),
+ );
+
+ expect(error.message).toContain("Routine 'routine-missing' does not exist.");
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index 73968b0d7..de7b10b73 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -9,6 +9,7 @@ import {
EventId,
GroupId,
isGroupBotMember,
+ MessageId,
ProviderInstanceId,
type OrchestrationCommand,
type OrchestrationEvent,
@@ -46,9 +47,25 @@ import {
requireThreadNotArchived,
} from "./commandInvariants.ts";
import { projectEvent } from "./projector.ts";
+import { nextScheduledFor } from "../routines/schedule.ts";
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
+function userInputAnswerText(answers: Record<string, unknown>): string | null {
+ const values = Object.values(answers).flatMap((answer) => {
+ if (typeof answer === "string") return [answer];
+ if (Array.isArray(answer)) {
+ return answer.filter((value): value is string => typeof value === "string");
+ }
+ return [];
+ });
+ const text = values
+ .map((value) => value.trim())
+ .filter(Boolean)
+ .join("\n");
+ return text.length > 0 ? text : null;
+}
+
// Session adoption takes seconds; a user message still unadopted after this
// window is a failed/stale start, not pending work. Mirrors the client's
// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
@@ -717,20 +734,49 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
);
}
const occurredAt = yield* nowIso;
- return {
+ const archivedEvent = {
...(yield* withEventBase({
aggregateKind: "bot",
aggregateId: command.botId,
occurredAt,
commandId: command.commandId,
})),
- type: "bot.archived",
+ type: "bot.archived" as const,
payload: {
botId: command.botId,
archivedAt: occurredAt,
updatedAt: occurredAt,
},
};
+ const pausedEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
+ for (const routine of readModel.routines ?? []) {
+ if (
+ routine.botId !== command.botId ||
+ !routine.enabled ||
+ routine.lifecycle === "deleted"
+ ) {
+ continue;
+ }
+ pausedEvents.push({
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: routine.id,
+ occurredAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.paused",
+ payload: {
+ routine: {
+ ...routine,
+ enabled: false,
+ lifecycle: "paused",
+ nextRunAt: null,
+ updatedAt: occurredAt,
+ },
+ },
+ });
+ }
+ return [...pausedEvents, archivedEvent];
}
case "bot.restore": {
@@ -1405,6 +1451,483 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
+ case "routine.create-approved": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (existing !== undefined) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' already exists.`,
+ });
+ }
+ const routine = {
+ id: command.routineId,
+ botId: command.botId,
+ targetThreadId: command.targetThreadId,
+ job: command.job,
+ procedure: command.procedure,
+ schedule: command.schedule,
+ timezone: command.timezone,
+ skillAssignmentIds: command.skillAssignmentIds,
+ connectorDependencies: command.connectorDependencies,
+ projectId: command.projectId,
+ sandbox: command.sandbox,
+ approvalPolicy: command.approvalPolicy,
+ procedureVersion: 1,
+ approvalVersion: 1,
+ enabled: false as const,
+ lifecycle: "approved" as const,
+ nextRunAt: null,
+ lastRunAt: null,
+ latestResult: null,
+ latestFailure: null,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ deletedAt: null,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.approved",
+ payload: { routine },
+ };
+ }
+
+ case "routine.draft": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (existing?.lifecycle === "deleted") {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' is deleted.`,
+ });
+ }
+ if (
+ existing !== undefined &&
+ command.expectedProcedureVersion !== undefined &&
+ command.expectedProcedureVersion !== existing.procedureVersion
+ ) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' procedure version changed.`,
+ });
+ }
+ const procedureVersion = (existing?.procedureVersion ?? 0) + 1;
+ const routine = {
+ id: command.routineId,
+ botId: command.botId,
+ targetThreadId: command.targetThreadId,
+ job: command.job,
+ procedure: command.procedure,
+ schedule: command.schedule,
+ timezone: command.timezone,
+ skillAssignmentIds: command.skillAssignmentIds,
+ connectorDependencies: command.connectorDependencies,
+ projectId: command.projectId,
+ sandbox: command.sandbox,
+ approvalPolicy: command.approvalPolicy,
+ procedureVersion,
+ approvalVersion: null,
+ enabled: false as const,
+ lifecycle: "draft" as const,
+ nextRunAt: null,
+ lastRunAt: existing?.lastRunAt ?? null,
+ latestResult: existing?.latestResult ?? null,
+ latestFailure: existing?.latestFailure ?? null,
+ createdAt: existing?.createdAt ?? command.createdAt,
+ updatedAt: command.createdAt,
+ deletedAt: null,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.drafted",
+ payload: { routine },
+ };
+ }
+
+ case "routine.approve": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (
+ existing === undefined ||
+ existing.lifecycle === "deleted" ||
+ existing.procedureVersion !== command.procedureVersion
+ ) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' cannot approve procedure version ${command.procedureVersion}.`,
+ });
+ }
+ const routine = {
+ ...existing,
+ approvalVersion: existing.procedureVersion,
+ enabled: false,
+ lifecycle: "approved" as const,
+ updatedAt: command.createdAt,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.approved",
+ payload: { routine },
+ };
+ }
+
+ case "routine.enable": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (
+ existing === undefined ||
+ existing.lifecycle === "deleted" ||
+ existing.approvalVersion !== existing.procedureVersion
+ ) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' requires approval before enable.`,
+ });
+ }
+ const routine = {
+ ...existing,
+ enabled: true,
+ lifecycle: "enabled" as const,
+ nextRunAt: nextScheduledFor(
+ existing.schedule,
+ existing.timezone,
+ Date.parse(command.createdAt),
+ ),
+ latestFailure: null,
+ updatedAt: command.createdAt,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.enabled",
+ payload: { routine },
+ };
+ }
+
+ case "routine.pause": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (existing === undefined || existing.lifecycle === "deleted") {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' does not exist.`,
+ });
+ }
+ const routine = {
+ ...existing,
+ enabled: false,
+ lifecycle: "paused" as const,
+ nextRunAt: null,
+ updatedAt: command.createdAt,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.paused",
+ payload: { routine },
+ };
+ }
+
+ case "routine.run":
+ case "routine.run.scheduled": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (existing === undefined || existing.lifecycle === "deleted") {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' does not exist.`,
+ });
+ }
+ if (command.type === "routine.run.scheduled" && !existing.enabled) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' is not enabled.`,
+ });
+ }
+ if (command.trigger !== "dry-run" && existing.approvalVersion !== existing.procedureVersion) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' procedure approval is stale.`,
+ });
+ }
+ if ((readModel.routineRuns ?? []).some((run) => run.id === command.runId)) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine run '${command.runId}' already exists.`,
+ });
+ }
+ const runBase = {
+ id: command.runId,
+ routineId: command.routineId,
+ procedureVersion: existing.procedureVersion,
+ status: "queued" as const,
+ result: null,
+ failure: null,
+ usageRef: null,
+ threadRef: null,
+ startedAt: null,
+ completedAt: null,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ };
+ const run =
+ command.type === "routine.run.scheduled"
+ ? {
+ ...runBase,
+ trigger: command.trigger,
+ scheduledFor: command.scheduledFor,
+ }
+ : { ...runBase, trigger: command.trigger, scheduledFor: null };
+ const routine = {
+ ...existing,
+ lifecycle: "running" as const,
+ lastRunAt: command.createdAt,
+ updatedAt: command.createdAt,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.running",
+ payload: { routine, run },
+ };
+ }
+
+ case "routine.run.start":
+ case "routine.run.block":
+ case "routine.run.fail":
+ case "routine.run.complete":
+ case "routine.run.cancel": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ const existingRun = (readModel.routineRuns ?? []).find((run) => run.id === command.runId);
+ if (existing === undefined || existing.lifecycle === "deleted" || existingRun === undefined) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine run '${command.runId}' does not exist.`,
+ });
+ }
+ const occurredAt =
+ command.type === "routine.run.start" ? command.startedAt : command.createdAt;
+ const run =
+ command.type === "routine.run.start"
+ ? {
+ ...existingRun,
+ status: "running" as const,
+ threadRef: command.threadRef,
+ startedAt: command.startedAt,
+ updatedAt: command.startedAt,
+ }
+ : command.type === "routine.run.block"
+ ? {
+ ...existingRun,
+ status: "blocked" as const,
+ failure: command.failure,
+ completedAt: command.createdAt,
+ updatedAt: command.createdAt,
+ }
+ : command.type === "routine.run.fail"
+ ? {
+ ...existingRun,
+ status: "failed" as const,
+ failure: command.failure,
+ usageRef: command.usageRef,
+ completedAt: command.createdAt,
+ updatedAt: command.createdAt,
+ }
+ : command.type === "routine.run.complete"
+ ? {
+ ...existingRun,
+ status: "completed" as const,
+ result: command.result,
+ usageRef: command.usageRef,
+ completedAt: command.createdAt,
+ updatedAt: command.createdAt,
+ }
+ : {
+ ...existingRun,
+ status: "canceled" as const,
+ completedAt: command.createdAt,
+ updatedAt: command.createdAt,
+ };
+ const terminal = command.type !== "routine.run.start";
+ const blockedOrFailed =
+ command.type === "routine.run.block" || command.type === "routine.run.fail";
+ const routine = {
+ ...existing,
+ enabled: blockedOrFailed ? false : existing.enabled,
+ lifecycle:
+ command.type === "routine.run.start"
+ ? ("running" as const)
+ : command.type === "routine.run.block"
+ ? ("blocked" as const)
+ : command.type === "routine.run.fail"
+ ? ("failed" as const)
+ : command.type === "routine.run.complete" && existing.enabled
+ ? ("enabled" as const)
+ : command.type === "routine.run.complete"
+ ? ("completed" as const)
+ : existing.enabled
+ ? ("enabled" as const)
+ : ("paused" as const),
+ nextRunAt:
+ command.type === "routine.run.complete"
+ ? command.nextRunAt
+ : blockedOrFailed
+ ? null
+ : existing.nextRunAt,
+ lastRunAt: terminal ? occurredAt : existing.lastRunAt,
+ latestResult:
+ command.type === "routine.run.complete" ? command.result : existing.latestResult,
+ latestFailure:
+ command.type === "routine.run.block" || command.type === "routine.run.fail"
+ ? command.failure
+ : existing.latestFailure,
+ updatedAt: occurredAt,
+ };
+ const type =
+ command.type === "routine.run.start"
+ ? ("routine.running" as const)
+ : command.type === "routine.run.block"
+ ? ("routine.blocked" as const)
+ : command.type === "routine.run.fail"
+ ? ("routine.failed" as const)
+ : command.type === "routine.run.complete"
+ ? ("routine.completed" as const)
+ : ("routine.run-canceled" as const);
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt,
+ commandId: command.commandId,
+ })),
+ type,
+ payload: { routine, run },
+ };
+ }
+
+ case "routine.delete": {
+ const existing = (readModel.routines ?? []).find(
+ (routine) => routine.id === command.routineId,
+ );
+ if (existing === undefined) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Routine '${command.routineId}' does not exist.`,
+ });
+ }
+ const routine = {
+ ...existing,
+ enabled: false,
+ lifecycle: "deleted" as const,
+ nextRunAt: null,
+ updatedAt: command.createdAt,
+ deletedAt: command.createdAt,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "routine",
+ aggregateId: command.routineId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "routine.deleted",
+ payload: { routine },
+ };
+ }
+
+ case "routine.skill.assign": {
+ if (
+ (readModel.skillAssignments ?? []).some(
+ (assignment) => assignment.id === command.assignmentId,
+ )
+ ) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Skill assignment '${command.assignmentId}' already exists.`,
+ });
+ }
+ const assignment = {
+ id: command.assignmentId,
+ botId: command.botId,
+ skillId: command.skillId,
+ name: command.name,
+ description: command.description,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ };
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "skill-assignment",
+ aggregateId: command.assignmentId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "skill-assignment.assigned",
+ payload: { assignment },
+ };
+ }
+
+ case "routine.skill.unassign": {
+ const assignment = (readModel.skillAssignments ?? []).find(
+ (entry) => entry.id === command.assignmentId && entry.botId === command.botId,
+ );
+ if (assignment === undefined) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Skill assignment '${command.assignmentId}' does not exist.`,
+ });
+ }
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "skill-assignment",
+ aggregateId: command.assignmentId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "skill-assignment.unassigned",
+ payload: {
+ assignmentId: command.assignmentId,
+ botId: command.botId,
+ removedAt: command.createdAt,
+ },
+ };
+ }
+
case "thread.create": {
yield* requireProject({
readModel,
@@ -2191,6 +2714,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
interactionMode: targetThread.interactionMode,
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
respondingBotId,
+ ...(command.timezone !== undefined ? { timezone: command.timezone } : {}),
createdAt: command.createdAt,
},
};
@@ -2289,12 +2813,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}
case "thread.user-input.respond": {
- yield* requireThread({
+ const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
- return {
+ const responseRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
@@ -2312,6 +2836,33 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
createdAt: command.createdAt,
},
};
+ const answerText = userInputAnswerText(command.answers);
+ if (answerText === null) return responseRequestedEvent;
+
+ const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
+ ...(yield* withEventBase({
+ aggregateKind: "thread",
+ aggregateId: command.threadId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "thread.message-sent",
+ payload: {
+ threadId: command.threadId,
+ messageId: MessageId.make(`user-input:${command.threadId}:${command.requestId}`),
+ role: "user",
+ text: answerText,
+ turnId: thread.session?.activeTurnId ?? null,
+ streaming: false,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ },
+ };
+
+ return [
+ userMessageEvent,
+ { ...responseRequestedEvent, causationEventId: userMessageEvent.eventId },
+ ];
}
case "thread.checkpoint.revert": {
diff --git a/apps/server/src/orchestration/decider.userInput.test.ts b/apps/server/src/orchestration/decider.userInput.test.ts
new file mode 100644
index 000000000..3416e05d7
--- /dev/null
+++ b/apps/server/src/orchestration/decider.userInput.test.ts
@@ -0,0 +1,103 @@
+import {
+ ApprovalRequestId,
+ CommandId,
+ MessageId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+ TurnId,
+ type OrchestrationReadModel,
+ type OrchestrationThread,
+} from "@t3tools/contracts";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+
+import { decideOrchestrationCommand } from "./decider.ts";
+import { createEmptyReadModel } from "./projector.ts";
+
+const NOW = "2026-09-01T03:40:00.000Z";
+const THREAD_ID = ThreadId.make("thread-user-input");
+const REQUEST_ID = ApprovalRequestId.make("request-color");
+
+function makeThread(): OrchestrationThread {
+ return {
+ id: THREAD_ID,
+ projectId: ProjectId.make("project-1"),
+ botId: null,
+ groupId: null,
+ respondingBotId: null,
+ title: "Question thread",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: NOW,
+ updatedAt: NOW,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ deletedAt: null,
+ messages: [],
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: {
+ threadId: THREAD_ID,
+ status: "running",
+ providerName: "codex",
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ runtimeMode: "full-access",
+ activeTurnId: TurnId.make("turn-1"),
+ lastError: null,
+ updatedAt: NOW,
+ },
+ };
+}
+
+function makeReadModel(): OrchestrationReadModel {
+ return {
+ ...createEmptyReadModel(NOW),
+ threads: [makeThread()],
+ };
+}
+
+it.layer(NodeServices.layer)("user input response decider", (it) => {
+ it.effect("appends the selected answer before resuming the provider", () =>
+ Effect.gen(function* () {
+ const decided = yield* decideOrchestrationCommand({
+ command: {
+ type: "thread.user-input.respond",
+ commandId: CommandId.make("command-answer-color"),
+ threadId: THREAD_ID,
+ requestId: REQUEST_ID,
+ answers: { color: "Red" },
+ createdAt: NOW,
+ },
+ readModel: makeReadModel(),
+ });
+ const events = Array.isArray(decided) ? decided : [decided];
+
+ expect(events.map((event) => event.type)).toEqual([
+ "thread.message-sent",
+ "thread.user-input-response-requested",
+ ]);
+ expect(events[0]).toMatchObject({
+ type: "thread.message-sent",
+ payload: {
+ messageId: MessageId.make(`user-input:${THREAD_ID}:${REQUEST_ID}`),
+ role: "user",
+ text: "Red",
+ turnId: TurnId.make("turn-1"),
+ },
+ });
+ expect(events[1]).toMatchObject({
+ type: "thread.user-input-response-requested",
+ causationEventId: events[0]?.eventId,
+ payload: { answers: { color: "Red" } },
+ });
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index 6586683d4..098315506 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -13,6 +13,18 @@ import {
OrchestrationMessage,
OrchestrationSession,
OrchestrationThread,
+ RoutineApprovedPayload,
+ RoutineBlockedPayload,
+ RoutineCompletedPayload,
+ RoutineDeletedPayload,
+ RoutineDraftedPayload,
+ RoutineEnabledPayload,
+ RoutineFailedPayload,
+ RoutinePausedPayload,
+ RoutineRunCanceledPayload,
+ RoutineRunningPayload,
+ RoutineSkillAssignedPayload,
+ RoutineSkillUnassignedPayload,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
@@ -235,6 +247,9 @@ export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
groups: [],
delegations: [],
mcpServers: [],
+ routines: [],
+ routineRuns: [],
+ skillAssignments: [],
threads: [],
updatedAt: nowIso,
};
@@ -606,6 +621,100 @@ export function projectEvent(
})),
);
+ case "routine.drafted":
+ case "routine.approved":
+ case "routine.enabled":
+ case "routine.paused":
+ case "routine.deleted": {
+ const schema =
+ event.type === "routine.drafted"
+ ? RoutineDraftedPayload
+ : event.type === "routine.approved"
+ ? RoutineApprovedPayload
+ : event.type === "routine.enabled"
+ ? RoutineEnabledPayload
+ : event.type === "routine.paused"
+ ? RoutinePausedPayload
+ : RoutineDeletedPayload;
+ return decodeForEvent(schema, event.payload, event.type, "payload").pipe(
+ Effect.map((payload) => {
+ const routines = nextBase.routines ?? [];
+ return {
+ ...nextBase,
+ routines: routines.some((routine) => routine.id === payload.routine.id)
+ ? routines.map((routine) =>
+ routine.id === payload.routine.id ? payload.routine : routine,
+ )
+ : [...routines, payload.routine],
+ };
+ }),
+ );
+ }
+
+ case "routine.running":
+ case "routine.blocked":
+ case "routine.failed":
+ case "routine.completed":
+ case "routine.run-canceled": {
+ const schema =
+ event.type === "routine.running"
+ ? RoutineRunningPayload
+ : event.type === "routine.blocked"
+ ? RoutineBlockedPayload
+ : event.type === "routine.failed"
+ ? RoutineFailedPayload
+ : event.type === "routine.completed"
+ ? RoutineCompletedPayload
+ : RoutineRunCanceledPayload;
+ return decodeForEvent(schema, event.payload, event.type, "payload").pipe(
+ Effect.map((payload) => {
+ const routines = nextBase.routines ?? [];
+ const runs = nextBase.routineRuns ?? [];
+ return {
+ ...nextBase,
+ routines: routines.some((routine) => routine.id === payload.routine.id)
+ ? routines.map((routine) =>
+ routine.id === payload.routine.id ? payload.routine : routine,
+ )
+ : [...routines, payload.routine],
+ routineRuns: runs.some((run) => run.id === payload.run.id)
+ ? runs.map((run) => (run.id === payload.run.id ? payload.run : run))
+ : [...runs, payload.run],
+ };
+ }),
+ );
+ }
+
+ case "skill-assignment.assigned":
+ return decodeForEvent(RoutineSkillAssignedPayload, event.payload, event.type, "payload").pipe(
+ Effect.map((payload) => {
+ const assignments = nextBase.skillAssignments ?? [];
+ return {
+ ...nextBase,
+ skillAssignments: assignments.some((entry) => entry.id === payload.assignment.id)
+ ? assignments.map((entry) =>
+ entry.id === payload.assignment.id ? payload.assignment : entry,
+ )
+ : [...assignments, payload.assignment],
+ };
+ }),
+ );
+
+ case "skill-assignment.unassigned":
+ return decodeForEvent(
+ RoutineSkillUnassignedPayload,
+ event.payload,
+ event.type,
+ "payload",
+ ).pipe(
+ Effect.map((payload) => ({
+ ...nextBase,
+ skillAssignments: (nextBase.skillAssignments ?? []).filter(
+ (entry) => entry.id !== payload.assignmentId,
+ ),
+ })),
+ );
+
case "group.deleted":
return decodeForEvent(GroupDeletedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts
index 46ed11f98..230007b80 100644
--- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts
+++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts
@@ -13,6 +13,9 @@ import {
OrchestrationEventMetadata,
OrchestrationEventType,
ProjectId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
ThreadId,
} from "@t3tools/contracts";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -39,7 +42,17 @@ const EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMeta
const AppendEventRequestSchema = Schema.Struct({
eventId: EventId,
aggregateKind: OrchestrationAggregateKind,
- streamId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),
+ streamId: Schema.Union([
+ ProjectId,
+ BotId,
+ DelegationId,
+ GroupId,
+ McpServerId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
+ ThreadId,
+ ]),
type: OrchestrationEventType,
causationEventId: Schema.NullOr(EventId),
correlationId: Schema.NullOr(CommandId),
@@ -55,7 +68,17 @@ const OrchestrationEventPersistedRowSchema = Schema.Struct({
eventId: EventId,
type: OrchestrationEventType,
aggregateKind: OrchestrationAggregateKind,
- aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),
+ aggregateId: Schema.Union([
+ ProjectId,
+ BotId,
+ DelegationId,
+ GroupId,
+ McpServerId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
+ ThreadId,
+ ]),
occurredAt: IsoDateTime,
commandId: Schema.NullOr(CommandId),
causationEventId: Schema.NullOr(EventId),
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index f4172ccbb..125393627 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -74,6 +74,8 @@ import Migration0058 from "./Migrations/058_ProjectionDelegations.ts";
import Migration0059 from "./Migrations/059_ProjectionThreadSessionMcpServers.ts";
import Migration0060 from "./Migrations/060_ProjectionMessageReactions.ts";
import Migration0061 from "./Migrations/061_ExternalChannels.ts";
+import Migration0062 from "./Migrations/062_Routines.ts";
+import Migration0063 from "./Migrations/063_RoutineTargetThreadRepair.ts";
/**
* Migration loader with all migrations defined inline.
@@ -147,6 +149,8 @@ export const migrationEntries = [
[59, "ProjectionThreadSessionMcpServers", Migration0059],
[60, "ProjectionMessageReactions", Migration0060],
[61, "ExternalChannels", Migration0061],
+ [62, "Routines", Migration0062],
+ [63, "RoutineTargetThreadRepair", Migration0063],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/062_Routines.test.ts b/apps/server/src/persistence/Migrations/062_Routines.test.ts
new file mode 100644
index 000000000..46e79c34b
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/062_Routines.test.ts
@@ -0,0 +1,106 @@
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+import { RoutineRepository } from "../../routines/Repository.ts";
+import { RoutineRepositoryLive } from "../../routines/RepositoryLive.ts";
+import { runMigrations } from "../Migrations.ts";
+import * as NodeSqliteClient from "../NodeSqliteClient.ts";
+
+it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()))("062_Routines", (it) => {
+ it.effect("persists routine projections and rejects duplicate scheduled slots", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations({ toMigrationInclusive: 62 });
+
+ yield* sql`
+ INSERT INTO routine_run_claims (
+ run_id, routine_id, trigger, scheduled_for, status, claimed_at, updated_at
+ ) VALUES (
+ 'run-1', 'routine-1', 'scheduled', '2026-08-31T12:00:00.000Z',
+ 'claimed', '2026-08-31T12:00:00.000Z', '2026-08-31T12:00:00.000Z'
+ )
+ `;
+ yield* sql`
+ INSERT INTO routine_run_claims (
+ run_id, routine_id, trigger, scheduled_for, status, claimed_at, updated_at
+ ) VALUES (
+ 'run-2', 'routine-1', 'missed', '2026-08-31T12:00:00.000Z',
+ 'claimed', '2026-08-31T12:01:00.000Z', '2026-08-31T12:01:00.000Z'
+ ) ON CONFLICT (routine_id, scheduled_for) DO NOTHING
+ `;
+
+ const rows = yield* sql<{ readonly runId: string }>`
+ SELECT run_id AS "runId" FROM routine_run_claims
+ `;
+ assert.deepEqual(rows, [{ runId: "run-1" }]);
+
+ yield* sql`
+ INSERT INTO routine_run_claims (
+ run_id, routine_id, trigger, scheduled_for, status, claimed_at, updated_at
+ ) VALUES
+ ('manual-1', 'routine-1', 'manual', NULL, 'claimed',
+ '2026-08-31T13:00:00.000Z', '2026-08-31T13:00:00.000Z'),
+ ('manual-2', 'routine-1', 'dry-run', NULL, 'claimed',
+ '2026-08-31T13:01:00.000Z', '2026-08-31T13:01:00.000Z')
+ `;
+ const manualRows = yield* sql<{ readonly runId: string }>`
+ SELECT run_id AS "runId" FROM routine_run_claims
+ WHERE scheduled_for IS NULL ORDER BY run_id
+ `;
+ assert.deepEqual(manualRows, [{ runId: "manual-1" }, { runId: "manual-2" }]);
+ }),
+ );
+
+ it.effect("loads at most five history entries for each routine", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations({ toMigrationInclusive: 62 });
+
+ yield* sql`
+ WITH RECURSIVE runs(number) AS (
+ SELECT 1
+ UNION ALL
+ SELECT number + 1 FROM runs WHERE number < 7
+ )
+ INSERT INTO projection_routine_runs (
+ run_id, routine_id, procedure_version, trigger, status, created_at, updated_at
+ )
+ SELECT
+ 'history-a-' || number, 'routine-history-a', 1, 'manual', 'completed',
+ printf('2026-08-31T12:%02d:00.000Z', number),
+ printf('2026-08-31T12:%02d:00.000Z', number)
+ FROM runs
+ `;
+ yield* sql`
+ INSERT INTO projection_routine_runs (
+ run_id, routine_id, procedure_version, trigger, status, created_at, updated_at
+ ) VALUES
+ ('history-b-1', 'routine-history-b', 1, 'manual', 'completed',
+ '2026-08-31T13:01:00.000Z', '2026-08-31T13:01:00.000Z'),
+ ('history-b-2', 'routine-history-b', 1, 'manual', 'completed',
+ '2026-08-31T13:02:00.000Z', '2026-08-31T13:02:00.000Z'),
+ ('history-b-3', 'routine-history-b', 1, 'manual', 'completed',
+ '2026-08-31T13:03:00.000Z', '2026-08-31T13:03:00.000Z')
+ `;
+
+ const repository = yield* RoutineRepository;
+ const runs = yield* repository.listAllRuns;
+ yield* repository.listRecoverable;
+ assert.deepEqual(
+ runs.map((run) => run.id),
+ [
+ "history-a-3",
+ "history-a-4",
+ "history-a-5",
+ "history-a-6",
+ "history-a-7",
+ "history-b-1",
+ "history-b-2",
+ "history-b-3",
+ ],
+ );
+ }).pipe(Effect.provide(RoutineRepositoryLive)),
+ );
+});
diff --git a/apps/server/src/persistence/Migrations/062_Routines.ts b/apps/server/src/persistence/Migrations/062_Routines.ts
new file mode 100644
index 000000000..62151f189
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/062_Routines.ts
@@ -0,0 +1,101 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS projection_routines (
+ routine_id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL,
+ target_thread_id TEXT NOT NULL,
+ project_id TEXT NOT NULL,
+ job TEXT NOT NULL,
+ procedure TEXT NOT NULL,
+ procedure_version INTEGER NOT NULL,
+ approval_version INTEGER,
+ schedule_json TEXT NOT NULL,
+ timezone TEXT NOT NULL,
+ skill_assignment_ids_json TEXT NOT NULL DEFAULT '[]',
+ connector_dependencies_json TEXT NOT NULL DEFAULT '[]',
+ sandbox TEXT NOT NULL,
+ approval_policy TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 0,
+ lifecycle TEXT NOT NULL CHECK (
+ lifecycle IN (
+ 'draft', 'approved', 'enabled', 'running', 'paused', 'blocked', 'failed',
+ 'completed', 'deleted'
+ )
+ ),
+ next_run_at TEXT,
+ last_run_at TEXT,
+ latest_result_json TEXT,
+ latest_failure_json TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ deleted_at TEXT
+ )
+ `;
+
+ yield* sql`
+ CREATE INDEX IF NOT EXISTS idx_projection_routines_due
+ ON projection_routines(enabled, next_run_at)
+ `;
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS projection_routine_runs (
+ run_id TEXT PRIMARY KEY,
+ routine_id TEXT NOT NULL,
+ procedure_version INTEGER NOT NULL,
+ trigger TEXT NOT NULL CHECK (trigger IN ('dry-run', 'manual', 'scheduled', 'missed')),
+ scheduled_for TEXT,
+ status TEXT NOT NULL CHECK (
+ status IN (
+ 'queued', 'running', 'waiting-for-approval', 'completed', 'failed', 'canceled', 'blocked'
+ )
+ ),
+ thread_ref TEXT,
+ result_json TEXT,
+ failure_json TEXT,
+ usage_ref TEXT,
+ started_at TEXT,
+ completed_at TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE (routine_id, scheduled_for)
+ )
+ `;
+
+ yield* sql`
+ CREATE INDEX IF NOT EXISTS idx_projection_routine_runs_history
+ ON projection_routine_runs(routine_id, scheduled_for DESC)
+ `;
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS routine_run_claims (
+ run_id TEXT PRIMARY KEY,
+ routine_id TEXT NOT NULL,
+ trigger TEXT NOT NULL CHECK (trigger IN ('dry-run', 'manual', 'scheduled', 'missed')),
+ scheduled_for TEXT,
+ status TEXT NOT NULL CHECK (status IN ('claimed', 'dispatched', 'completed', 'failed', 'blocked')),
+ thread_id TEXT,
+ failure TEXT,
+ claimed_at TEXT NOT NULL,
+ completed_at TEXT,
+ updated_at TEXT NOT NULL,
+ UNIQUE (routine_id, scheduled_for)
+ )
+ `;
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS projection_routine_skill_assignments (
+ assignment_id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL,
+ skill_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ )
+ `;
+});
diff --git a/apps/server/src/persistence/Migrations/063_RoutineTargetThreadRepair.test.ts b/apps/server/src/persistence/Migrations/063_RoutineTargetThreadRepair.test.ts
new file mode 100644
index 000000000..ca9eb2ed1
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/063_RoutineTargetThreadRepair.test.ts
@@ -0,0 +1,50 @@
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+import { runMigrations } from "../Migrations.ts";
+import * as NodeSqliteClient from "../NodeSqliteClient.ts";
+
+it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()))("063_RoutineTargetThreadRepair", (it) => {
+ it.effect("repairs databases that already ran the first routine schema", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations({ toMigrationInclusive: 60 });
+ yield* sql`
+ CREATE TABLE projection_routines (
+ routine_id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, project_id TEXT NOT NULL,
+ job TEXT NOT NULL, procedure TEXT NOT NULL, procedure_version INTEGER NOT NULL,
+ approval_version INTEGER, schedule_json TEXT NOT NULL, timezone TEXT NOT NULL,
+ skill_assignment_ids_json TEXT NOT NULL DEFAULT '[]',
+ connector_dependencies_json TEXT NOT NULL DEFAULT '[]', sandbox TEXT NOT NULL,
+ approval_policy TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 0,
+ lifecycle TEXT NOT NULL, next_run_at TEXT, last_run_at TEXT,
+ latest_result_json TEXT, latest_failure_json TEXT, created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL, deleted_at TEXT
+ )
+ `;
+ yield* sql`
+ CREATE TABLE routine_run_claims (
+ run_id TEXT PRIMARY KEY, routine_id TEXT NOT NULL, trigger TEXT NOT NULL,
+ scheduled_for TEXT, status TEXT NOT NULL CHECK (status IN ('claimed', 'dispatched', 'blocked')),
+ thread_id TEXT, failure TEXT, claimed_at TEXT NOT NULL, completed_at TEXT,
+ updated_at TEXT NOT NULL, UNIQUE (routine_id, scheduled_for)
+ )
+ `;
+ yield* runMigrations({ toMigrationInclusive: 63 });
+
+ const columns = yield* sql<{ readonly name: string }>`PRAGMA table_info(projection_routines)`;
+ assert.isTrue(columns.some((column) => column.name === "target_thread_id"));
+ yield* sql`
+ INSERT INTO routine_run_claims (
+ run_id, routine_id, trigger, status, claimed_at, completed_at, updated_at
+ ) VALUES (
+ 'run-1', 'routine-1', 'manual', 'completed',
+ '2026-08-31T12:00:00.000Z', '2026-08-31T12:01:00.000Z',
+ '2026-08-31T12:01:00.000Z'
+ )
+ `;
+ }),
+ );
+});
diff --git a/apps/server/src/persistence/Migrations/063_RoutineTargetThreadRepair.ts b/apps/server/src/persistence/Migrations/063_RoutineTargetThreadRepair.ts
new file mode 100644
index 000000000..6ce1f43f2
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/063_RoutineTargetThreadRepair.ts
@@ -0,0 +1,50 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const columns = yield* sql<{ readonly name: string }>`PRAGMA table_info(projection_routines)`;
+
+ if (!columns.some((column) => column.name === "target_thread_id")) {
+ yield* sql`ALTER TABLE projection_routines ADD COLUMN target_thread_id TEXT NOT NULL DEFAULT ''`;
+ yield* sql`
+ UPDATE projection_routines AS routine
+ SET target_thread_id = COALESCE((
+ SELECT thread_id
+ FROM projection_threads AS thread
+ WHERE thread.project_id = routine.project_id
+ AND (thread.bot_id = routine.bot_id OR thread.responding_bot_id = routine.bot_id)
+ AND thread.archived_at IS NULL
+ ORDER BY thread.updated_at DESC
+ LIMIT 1
+ ), '')
+ `;
+ }
+
+ const claimTables = yield* sql<{ readonly sql: string }>`
+ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'routine_run_claims'
+ `;
+ if (!claimTables[0]?.sql.includes("'completed'")) {
+ yield* sql`
+ CREATE TABLE routine_run_claims_repaired (
+ run_id TEXT PRIMARY KEY,
+ routine_id TEXT NOT NULL,
+ trigger TEXT NOT NULL CHECK (trigger IN ('dry-run', 'manual', 'scheduled', 'missed')),
+ scheduled_for TEXT,
+ status TEXT NOT NULL CHECK (status IN ('claimed', 'dispatched', 'completed', 'failed', 'blocked')),
+ thread_id TEXT,
+ failure TEXT,
+ claimed_at TEXT NOT NULL,
+ completed_at TEXT,
+ updated_at TEXT NOT NULL,
+ UNIQUE (routine_id, scheduled_for)
+ )
+ `;
+ yield* sql`
+ INSERT INTO routine_run_claims_repaired
+ SELECT * FROM routine_run_claims
+ `;
+ yield* sql`DROP TABLE routine_run_claims`;
+ yield* sql`ALTER TABLE routine_run_claims_repaired RENAME TO routine_run_claims`;
+ }
+});
diff --git a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts
index ce5823ffa..5789b6af9 100644
--- a/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts
+++ b/apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts
@@ -17,6 +17,9 @@ import {
OrchestrationAggregateKind,
OrchestrationCommandReceiptStatus,
ProjectId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
ThreadId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
@@ -29,7 +32,17 @@ import type { OrchestrationCommandReceiptRepositoryError } from "../Errors.ts";
export const OrchestrationCommandReceipt = Schema.Struct({
commandId: CommandId,
aggregateKind: OrchestrationAggregateKind,
- aggregateId: Schema.Union([ProjectId, BotId, GroupId, McpServerId, ThreadId, DelegationId]),
+ aggregateId: Schema.Union([
+ ProjectId,
+ BotId,
+ DelegationId,
+ GroupId,
+ McpServerId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
+ ThreadId,
+ ]),
acceptedAt: IsoDateTime,
resultSequence: NonNegativeInt,
status: OrchestrationCommandReceiptStatus,
diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.ts
index 150d376c3..7b80826bd 100644
--- a/apps/server/src/portability.ts
+++ b/apps/server/src/portability.ts
@@ -1314,6 +1314,23 @@ function itemForCommand(
return `delegation:${command.delegation.delegationId}`;
case "delegation.cancel":
return `delegation:${command.delegationId}`;
+ case "routine.create-approved":
+ case "routine.draft":
+ case "routine.approve":
+ case "routine.enable":
+ case "routine.pause":
+ case "routine.run":
+ case "routine.run.scheduled":
+ case "routine.run.start":
+ case "routine.run.block":
+ case "routine.run.fail":
+ case "routine.run.complete":
+ case "routine.run.cancel":
+ case "routine.delete":
+ return `routine:${command.routineId}`;
+ case "routine.skill.assign":
+ case "routine.skill.unassign":
+ return `skill-assignment:${command.assignmentId}`;
default:
return `thread:${command.threadId}`;
}
diff --git a/apps/server/src/provider/AkeruAgentInstructions.ts b/apps/server/src/provider/AkeruAgentInstructions.ts
index 85016951b..18520ce69 100644
--- a/apps/server/src/provider/AkeruAgentInstructions.ts
+++ b/apps/server/src/provider/AkeruAgentInstructions.ts
@@ -10,6 +10,10 @@ export const AKERU_AGENT_INSTRUCTIONS = [
"Use workspace tools only when the task requires file or command work.",
"When asked about available tools, describe only tools present in the current turn.",
"Do not claim that a tool ran unless its result is present in this turn.",
+ "Use akeru_create_routine when the user asks for recurring or scheduled work.",
+ "Use akeru_list_routines before answering whether a routine exists or what state it is in, including enabled, disabled, paused, blocked, or failed.",
+ "When the user asks to delete routines, call akeru_list_routines, then call akeru_delete_routines with the selected IDs. The delete tool asks for confirmation, so do not ask for separate confirmation.",
+ "Routine output goes to the current chat unless the user names an enabled plugin such as Slack. Use the current device timezone unless the user names another timezone.",
].join("\n");
export const AKERU_BOT_TURN_INSTRUCTIONS = [
diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.ts
index d89d62f28..13cc5c721 100644
--- a/apps/server/src/provider/AkeruMastraHarness.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts
@@ -9,6 +9,7 @@ import { RequestContext } from "@mastra/core/request-context";
import { Memory } from "@mastra/memory";
import { ObservationalMemory } from "@mastra/memory/processors";
import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
AKERU_TOOL_CATALOG,
ProviderDriverKind,
@@ -19,6 +20,8 @@ import { assert, describe, expect, it, vi } from "vite-plus/test";
import { AKERU_AGENT_INSTRUCTIONS, AKERU_BOT_INSTRUCTIONS } from "./AkeruAgentInstructions.ts";
import {
AKERU_RECENT_MESSAGE_LIMIT,
+ AKERU_DELETE_ROUTINES_TOOL_NAME,
+ AKERU_LIST_ROUTINES_TOOL_NAME,
AkeruPassiveObservationalMemoryProcessor,
akeruActionNeedsApproval,
createAkeruObserveHooks,
@@ -29,6 +32,8 @@ import {
resolveAkeruInstructions,
resolveAkeruMastraModel,
resolveAkeruTools,
+ routineToolInputSchema,
+ routineToolNeedsGlobalApproval,
} from "./AkeruMastraHarness.ts";
import { productFeedbackToolInputSchema } from "./AkeruMastraHarness.ts";
import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
@@ -383,6 +388,7 @@ describe("AkeruMastraHarness", () => {
assert.include(AKERU_AGENT_INSTRUCTIONS, "general-purpose assistant");
assert.include(AKERU_AGENT_INSTRUCTIONS, "enabled plugin tools");
assert.include(AKERU_AGENT_INSTRUCTIONS, "Prefer preview_* tools over browser_* tools");
+ assert.include(AKERU_AGENT_INSTRUCTIONS, "akeru_list_routines");
assert.include(AKERU_AGENT_INSTRUCTIONS, "Do not assume");
assert.notInclude(AKERU_AGENT_INSTRUCTIONS, "coding agent");
});
@@ -405,9 +411,13 @@ describe("AkeruMastraHarness", () => {
resourceId: "thread-1",
session: { modelId: "openai/gpt-5.6-sol" },
});
+ const approvalInputs: unknown[] = [];
const runtime = {
toolsForThread: () => AKERU_TOOL_CATALOG.filter((tool) => tool.id === "Shell"),
- requiresApproval: async () => true,
+ requiresApproval: async (_threadId: string, _toolId: string, input: unknown) => {
+ approvalInputs.push(input);
+ return true;
+ },
execute: async () => undefined,
} as unknown as AkeruToolRuntime;
const pluginTool = { id: "plugin", execute: async () => undefined, requireApproval: false };
@@ -434,6 +444,9 @@ describe("AkeruMastraHarness", () => {
]);
assert.notProperty(tools, "Read");
assert.notProperty(tools, "execute_command");
+ const shell = tools.Shell as unknown as {
+ readonly needsApprovalFn: (input: unknown) => Promise<boolean>;
+ };
const restart = tools.RestartMcpServers as unknown as {
readonly needsApprovalFn: (input: unknown) => Promise<boolean>;
};
@@ -445,6 +458,10 @@ describe("AkeruMastraHarness", () => {
assert.isTrue(await search.needsApprovalFn({ command: "git push origin main" }));
assert.isTrue(await search.needsApprovalFn({ path: ".env" }));
assert.isFalse(await search.needsApprovalFn({ operation: "read" }));
+ assert.isTrue(
+ await shell.needsApprovalFn({ command: 'printf "hi\\n"', cwd: null, background: null }),
+ );
+ assert.deepEqual(approvalInputs, [{ command: 'printf "hi\\n"' }]);
assert.deepEqual(approvalPolicies, [true, true, true, true, false]);
assert.equal(criticalAkeruAction("RestartMcpServers"), "production");
});
@@ -524,4 +541,204 @@ describe("AkeruMastraHarness", () => {
assert.instanceOf(blockedError, Error);
assert.equal(blockedError.message, "Hook rejected");
});
+
+ it("creates an approved routine for the current chat after tool approval", async () => {
+ assert.isFalse(routineToolNeedsGlobalApproval(AKERU_CREATE_ROUTINE_TOOL_NAME));
+ assert.isFalse(routineToolNeedsGlobalApproval(AKERU_LIST_ROUTINES_TOOL_NAME));
+ assert.isTrue(routineToolNeedsGlobalApproval("execute_command"));
+ assert.isTrue(
+ routineToolInputSchema.safeParse({
+ name: "Morning brief",
+ instructions: "Prepare the morning brief.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ }).success,
+ );
+ assert.isTrue(
+ routineToolInputSchema.safeParse({
+ name: "Morning brief",
+ instructions: "Prepare the morning brief.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ connectorNames: null,
+ }).success,
+ );
+ assert.isFalse(
+ routineToolInputSchema.safeParse({
+ name: "Morning brief",
+ instructions: "Prepare the morning brief.",
+ schedule: { kind: "weekdays", time: {} },
+ }).success,
+ );
+ const calls: unknown[] = [];
+ const requestContext = new RequestContext();
+ requestContext.setRaw("controller", { resourceId: "thread-1" });
+ const tools = await resolveAkeruTools(requestContext, {
+ authStorage: new AuthStorage("/tmp/akeru-unused-auth.json"),
+ getThreadTools: () => ({}),
+ toolRuntime: { toolsForThread: () => [] } as unknown as AkeruToolRuntime,
+ createRoutine: async (threadId, input) => {
+ calls.push({ threadId, input });
+ return { status: "approved" };
+ },
+ });
+ const tool = tools[AKERU_CREATE_ROUTINE_TOOL_NAME] as {
+ requireApproval?: boolean;
+ execute?: (input: unknown, context: unknown) => Promise<unknown>;
+ };
+
+ assert.isFalse(tool.requireApproval);
+ assert.deepEqual(calls, []);
+ assert.deepEqual(
+ await tool.execute?.(
+ {
+ name: "Morning brief",
+ instructions: "Prepare the morning brief.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ skillNames: null,
+ connectorNames: null,
+ },
+ {},
+ ),
+ { status: "approved" },
+ );
+ assert.deepEqual(calls, [
+ {
+ threadId: "thread-1",
+ input: {
+ name: "Morning brief",
+ instructions: "Prepare the morning brief.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ },
+ },
+ ]);
+ });
+
+ it("lets the model inspect this bot's routine states without approval", async () => {
+ const calls: string[] = [];
+ const requestContext = new RequestContext();
+ requestContext.setRaw("controller", { resourceId: "thread-1" });
+ const result = {
+ routines: [
+ { id: "routine-1", name: "Morning brief", enabled: true, lifecycle: "enabled" as const },
+ {
+ id: "routine-2",
+ name: "Weekly review",
+ enabled: false,
+ lifecycle: "approved" as const,
+ },
+ {
+ id: "routine-3",
+ name: "Inbox check",
+ enabled: false,
+ lifecycle: "paused" as const,
+ },
+ ],
+ };
+ const tools = await resolveAkeruTools(requestContext, {
+ authStorage: new AuthStorage("/tmp/akeru-unused-auth.json"),
+ getThreadTools: () => ({}),
+ toolRuntime: { toolsForThread: () => [] } as unknown as AkeruToolRuntime,
+ listRoutines: async (threadId) => {
+ calls.push(threadId);
+ return result;
+ },
+ });
+ const tool = tools[AKERU_LIST_ROUTINES_TOOL_NAME] as {
+ requireApproval?: boolean;
+ execute?: (input: unknown, context: unknown) => Promise<unknown>;
+ };
+
+ assert.deepEqual(calls, []);
+ assert.isFalse(tool.requireApproval);
+ assert.deepEqual(await tool.execute?.({}, {}), result);
+ assert.deepEqual(calls, ["thread-1"]);
+ });
+
+ it("asks once before deleting one or more routines", async () => {
+ const deleted: Array<{ threadId: string; routineIds: ReadonlyArray<string> }> = [];
+ const suspended: unknown[] = [];
+ const requestContext = new RequestContext();
+ requestContext.setRaw("controller", { resourceId: "thread-1" });
+ const tools = await resolveAkeruTools(requestContext, {
+ authStorage: new AuthStorage("/tmp/akeru-unused-auth.json"),
+ getThreadTools: () => ({}),
+ toolRuntime: { toolsForThread: () => [] } as unknown as AkeruToolRuntime,
+ listRoutines: async () => ({
+ routines: [
+ { id: "routine-1", name: "Morning brief", enabled: true, lifecycle: "enabled" },
+ { id: "routine-2", name: "Weekly review", enabled: false, lifecycle: "paused" },
+ ],
+ }),
+ deleteRoutines: async (threadId, routineIds) => {
+ deleted.push({ threadId, routineIds });
+ return { status: "deleted", deletedRoutineIds: [...routineIds] };
+ },
+ });
+ const tool = tools[AKERU_DELETE_ROUTINES_TOOL_NAME] as {
+ requireApproval?: boolean;
+ execute?: (input: unknown, context: unknown) => Promise<unknown>;
+ };
+ const input = { routineIds: ["routine-1", "routine-2"] };
+
+ assert.isFalse(tool.requireApproval);
+ assert.deepEqual(deleted, []);
+ await tool.execute?.(input, {
+ agent: { suspend: async (payload: unknown) => void suspended.push(payload) },
+ });
+ assert.deepEqual(deleted, []);
+ assert.deepEqual(suspended, [
+ {
+ question:
+ 'Are you sure you want to delete these routines: "Morning brief", "Weekly review"?',
+ options: [
+ {
+ label: "Delete routines",
+ description: "Stop these schedules and hide them from the routines list.",
+ },
+ { label: "Cancel", description: "Keep every routine." },
+ ],
+ selectionMode: "single_select",
+ },
+ ]);
+
+ assert.deepEqual(await tool.execute?.(input, { agent: { resumeData: "Cancel" } }), {
+ status: "cancelled",
+ deletedRoutineIds: [],
+ });
+ assert.deepEqual(deleted, []);
+ assert.deepEqual(await tool.execute?.(input, { agent: { resumeData: "Delete routines" } }), {
+ status: "deleted",
+ deletedRoutineIds: ["routine-1", "routine-2"],
+ });
+ assert.deepEqual(deleted, [{ threadId: "thread-1", routineIds: ["routine-1", "routine-2"] }]);
+ });
+
+ it("does not ask or delete when any requested routine is unavailable", async () => {
+ let suspended = false;
+ let deleted = false;
+ const requestContext = new RequestContext();
+ requestContext.setRaw("controller", { resourceId: "thread-1" });
+ const tools = await resolveAkeruTools(requestContext, {
+ authStorage: new AuthStorage("/tmp/akeru-unused-auth.json"),
+ getThreadTools: () => ({}),
+ toolRuntime: { toolsForThread: () => [] } as unknown as AkeruToolRuntime,
+ listRoutines: async () => ({ routines: [] }),
+ deleteRoutines: async () => {
+ deleted = true;
+ return { status: "deleted", deletedRoutineIds: [] };
+ },
+ });
+ const tool = tools[AKERU_DELETE_ROUTINES_TOOL_NAME] as {
+ execute?: (input: unknown, context: unknown) => Promise<unknown>;
+ };
+
+ assert.deepEqual(
+ await tool.execute?.(
+ { routineIds: ["missing-routine"] },
+ { agent: { suspend: async () => void (suspended = true) } },
+ ),
+ { status: "not-found", deletedRoutineIds: [] },
+ );
+ assert.isFalse(suspended);
+ assert.isFalse(deleted);
+ });
});
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index 39851ee09..3b4e73222 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -26,15 +26,19 @@ import {
} from "@mastra/memory/processors";
import {
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
+ AkeruCreateRoutineInput,
ProductFeedbackToolDraft,
classifyAkeruExternalCommand,
classifyAkeruSensitivePath,
type AkeruConversationMemorySnapshot,
type ProviderDriverKind,
type ProductFeedbackToolDraft as ProductFeedbackToolDraftValue,
+ type AkeruCreateRoutineInput as AkeruCreateRoutineInputValue,
} from "@t3tools/contracts";
import * as Exit from "effect/Exit";
import * as Schema from "effect/Schema";
+import { z } from "zod";
import { AKERU_AGENT_INSTRUCTIONS, AKERU_BOT_INSTRUCTIONS } from "./AkeruAgentInstructions.ts";
import { akeruKimiProvider, type AkeruKimiAccess } from "./AkeruKimiProvider.ts";
@@ -83,6 +87,54 @@ const productFeedbackTool = createTool({
execute: async () => ({ status: "draft-opened" as const }),
});
+const routineTime = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
+export const AKERU_LIST_ROUTINES_TOOL_NAME = "akeru_list_routines";
+export const AKERU_DELETE_ROUTINES_TOOL_NAME = "akeru_delete_routines";
+export const routineToolInputSchema = z.object({
+ name: z.string().trim().min(1),
+ instructions: z.string().trim().min(1),
+ schedule: z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("daily"), time: routineTime }),
+ z.object({ kind: z.literal("weekdays"), time: routineTime }),
+ z.object({
+ kind: z.literal("weekly"),
+ weekdays: z
+ .array(
+ z.enum(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]),
+ )
+ .min(1),
+ time: routineTime,
+ }),
+ ]),
+ skillNames: z.array(z.string().trim().min(1)).nullish(),
+ connectorNames: z.array(z.string().trim().min(1)).nullish(),
+});
+const routineListOutputSchema = z.object({
+ routines: z.array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ enabled: z.boolean(),
+ lifecycle: z.enum([
+ "draft",
+ "approved",
+ "enabled",
+ "running",
+ "paused",
+ "blocked",
+ "failed",
+ "completed",
+ ]),
+ }),
+ ),
+});
+export type AkeruRoutineListResult = z.infer<typeof routineListOutputSchema>;
+const routineDeleteResultSchema = z.object({
+ status: z.enum(["deleted", "cancelled", "not-found"]),
+ deletedRoutineIds: z.array(z.string()),
+});
+export type AkeruRoutineDeleteResult = z.infer<typeof routineDeleteResultSchema>;
+
export interface AkeruMastraState {
readonly projectPath?: string;
readonly yolo?: boolean;
@@ -116,6 +168,15 @@ export interface AkeruMastraHarnessOptions {
protectedAction: boolean,
) => Promise<void>;
readonly toolRuntime: AkeruToolRuntime;
+ readonly createRoutine?: (
+ threadId: string,
+ input: AkeruCreateRoutineInputValue,
+ ) => Promise<unknown>;
+ readonly listRoutines?: (threadId: string) => Promise<AkeruRoutineListResult>;
+ readonly deleteRoutines?: (
+ threadId: string,
+ routineIds: ReadonlyArray<string>,
+ ) => Promise<AkeruRoutineDeleteResult>;
}
export interface AkeruMastraHarness {
@@ -141,7 +202,14 @@ export interface AkeruBackgroundObservationInput {
type AkeruMastraToolOptions = Pick<
AkeruMastraHarnessOptions,
- "authStorage" | "getKimiAccess" | "getThreadTools" | "syncThreadToolApproval" | "toolRuntime"
+ | "authStorage"
+ | "getKimiAccess"
+ | "getThreadTools"
+ | "syncThreadToolApproval"
+ | "toolRuntime"
+ | "createRoutine"
+ | "listRoutines"
+ | "deleteRoutines"
>;
export function createAkeruObserveHooks(
@@ -349,10 +417,108 @@ export async function resolveAkeruTools(
): Promise<ToolsInput> {
const threadId = controllerResourceId(requestContext);
if (!threadId) return {};
+ const routineTool = options.createRoutine
+ ? createTool({
+ id: AKERU_CREATE_ROUTINE_TOOL_NAME,
+ description:
+ "Create a disabled routine for recurring work in this chat. Call this tool as soon as the routine details are complete. The app previews the tool arguments and asks the user before execution, so do not ask for separate confirmation. Use the current chat and device timezone by default. Only name plugins or skills the user explicitly requests.",
+ inputSchema: routineToolInputSchema,
+ requireApproval: false,
+ execute: async ({ skillNames, connectorNames, ...input }) =>
+ options.createRoutine!(
+ threadId,
+ await Schema.decodeUnknownPromise(AkeruCreateRoutineInput)(
+ {
+ ...input,
+ ...(skillNames ? { skillNames } : {}),
+ ...(connectorNames ? { connectorNames } : {}),
+ },
+ {
+ onExcessProperty: "error",
+ },
+ ),
+ ),
+ })
+ : undefined;
+ const listRoutinesTool = options.listRoutines
+ ? createTool({
+ id: AKERU_LIST_ROUTINES_TOOL_NAME,
+ description:
+ "List this bot's routines and show whether each schedule is enabled or disabled, plus its exact lifecycle. Use this before answering questions about routine state.",
+ inputSchema: z.object({}),
+ outputSchema: routineListOutputSchema,
+ strict: true,
+ requireApproval: false,
+ execute: async () => options.listRoutines!(threadId),
+ })
+ : undefined;
+ const deleteRoutinesTool =
+ options.listRoutines && options.deleteRoutines
+ ? createTool({
+ id: AKERU_DELETE_ROUTINES_TOOL_NAME,
+ description:
+ "Delete one or more routines owned by this bot. Pass routine IDs from akeru_list_routines. This tool asks the user for confirmation before deleting anything, so do not ask for separate confirmation.",
+ inputSchema: z.object({
+ routineIds: z.array(z.string().trim().min(1)).min(1),
+ }),
+ outputSchema: routineDeleteResultSchema,
+ suspendSchema: z.object({
+ question: z.string(),
+ options: z.array(
+ z.object({
+ label: z.string(),
+ description: z.string(),
+ }),
+ ),
+ selectionMode: z.literal("single_select"),
+ }),
+ resumeSchema: z.string(),
+ strict: true,
+ requireApproval: false,
+ execute: async ({ routineIds }, context) => {
+ const uniqueIds = [...new Set(routineIds)];
+ const available = await options.listRoutines!(threadId);
+ const requested = available.routines.filter((routine) =>
+ uniqueIds.includes(routine.id),
+ );
+ if (requested.length !== uniqueIds.length) {
+ return { status: "not-found" as const, deletedRoutineIds: [] };
+ }
+ const answer = context?.agent?.resumeData;
+ if (answer === undefined) {
+ const suspend = context?.agent?.suspend;
+ if (!suspend) return { status: "cancelled" as const, deletedRoutineIds: [] };
+ const names = requested.map((routine) => `"${routine.name}"`).join(", ");
+ await suspend({
+ question:
+ requested.length === 1
+ ? `Are you sure you want to delete ${names}?`
+ : `Are you sure you want to delete these routines: ${names}?`,
+ options: [
+ {
+ label: "Delete routines",
+ description: "Stop these schedules and hide them from the routines list.",
+ },
+ { label: "Cancel", description: "Keep every routine." },
+ ],
+ selectionMode: "single_select",
+ });
+ return;
+ }
+ if (answer !== "Delete routines") {
+ return { status: "cancelled" as const, deletedRoutineIds: [] };
+ }
+ return options.deleteRoutines!(threadId, uniqueIds);
+ },
+ })
+ : undefined;
return {
...approvalAwareTools(threadId, options.getThreadTools(threadId), options),
...createAkeruMastraTools(threadId, options.toolRuntime),
[AKERU_PRODUCT_FEEDBACK_TOOL_NAME]: productFeedbackTool,
+ ...(routineTool ? { [AKERU_CREATE_ROUTINE_TOOL_NAME]: routineTool } : {}),
+ ...(listRoutinesTool ? { [AKERU_LIST_ROUTINES_TOOL_NAME]: listRoutinesTool } : {}),
+ ...(deleteRoutinesTool ? { [AKERU_DELETE_ROUTINES_TOOL_NAME]: deleteRoutinesTool } : {}),
};
}
@@ -557,6 +723,14 @@ export function akeruToolCategory(toolName: string): AkeruToolCategory {
return "other";
}
+export function routineToolNeedsGlobalApproval(toolName: string): boolean {
+ return (
+ toolName !== AKERU_CREATE_ROUTINE_TOOL_NAME &&
+ toolName !== AKERU_LIST_ROUTINES_TOOL_NAME &&
+ toolName !== AKERU_DELETE_ROUTINES_TOOL_NAME
+ );
+}
+
export async function createAkeruMastraHarness(
options: AkeruMastraHarnessOptions,
): Promise<AkeruMastraHarness> {
@@ -607,6 +781,21 @@ export async function createAkeruMastraHarness(
toolCategoryResolver: akeruToolCategory,
intervalHandlers: [],
});
+ const controllerWithRunOptions = controller as unknown as {
+ buildSharedRunOptions: (session: unknown) => {
+ readonly requireToolApproval?: boolean | ((input: { readonly toolName: string }) => boolean);
+ readonly [key: string]: unknown;
+ };
+ };
+ const buildSharedRunOptions = controllerWithRunOptions.buildSharedRunOptions.bind(controller);
+ controllerWithRunOptions.buildSharedRunOptions = (session) => {
+ const runOptions = buildSharedRunOptions(session);
+ if (runOptions.requireToolApproval !== true) return runOptions;
+ return {
+ ...runOptions,
+ requireToolApproval: ({ toolName }) => routineToolNeedsGlobalApproval(toolName),
+ };
+ };
const observeAfterTurn = (input: AkeruBackgroundObservationInput) => {
if (closing) return Promise.reject(new Error("Akeru observational memory is closing."));
diff --git a/apps/server/src/provider/AkeruMastraTools.ts b/apps/server/src/provider/AkeruMastraTools.ts
index 57e3dbf08..22d3af984 100644
--- a/apps/server/src/provider/AkeruMastraTools.ts
+++ b/apps/server/src/provider/AkeruMastraTools.ts
@@ -17,12 +17,18 @@ function inputSchema(toolId: AkeruRuntimeToolId) {
: AkeruToolInputSchemas[toolId];
}
+function omitNullValues(input: unknown): unknown {
+ if (!input || typeof input !== "object" || Array.isArray(input)) return input;
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== null));
+}
+
export function createAkeruMastraTools(threadId: string, runtime: AkeruToolRuntime): ToolsInput {
return Object.fromEntries(
runtime.toolsForThread(threadId).map((definition) => {
const schema = inputSchema(definition.id);
const standardSchema = Schema.toStandardJSONSchemaV1(schema);
- const approval = (input: unknown) => runtime.requiresApproval(threadId, definition.id, input);
+ const approval = (input: unknown) =>
+ runtime.requiresApproval(threadId, definition.id, omitNullValues(input));
const tool = createTool({
id: definition.id,
description: definition.description,
@@ -40,7 +46,7 @@ export function createAkeruMastraTools(threadId: string, runtime: AkeruToolRunti
threadId,
toolId: definition.id,
toolCallId,
- input,
+ input: omitNullValues(input),
approvalMode: "require-grant",
});
},
diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.ts
index 1463037d0..9cf1af76b 100644
--- a/apps/server/src/provider/AkeruToolRuntime.ts
+++ b/apps/server/src/provider/AkeruToolRuntime.ts
@@ -61,6 +61,7 @@ export interface AkeruToolSession {
readonly billedBotId?: BotId;
readonly runtimeMode: RuntimeMode;
readonly workspaceType: AkeruToolWorkspaceType;
+ readonly timezone?: string;
readonly workspace?: Workspace;
readonly userComputerWorkspace?: Workspace;
readonly memoryHandlers?: Record<AkeruMemoryToolId, AkeruMemoryToolHandler>;
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index f4b18770d..0bb30a9e3 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -7,6 +7,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import type { AgentControllerEvent, MastraDBMessage, Session } from "@mastra/core/agent-controller";
import { LocalFilesystem, LocalSandbox, Workspace } from "@mastra/core/workspace";
import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
AkeruMemoryTenantId,
AkeruMemoryUserId,
@@ -274,6 +275,7 @@ function makeMastraHarness() {
emit,
finishSend: () => resolveSend?.(),
rejectSend: (index: number, cause: unknown) => rejectSends[index]?.(cause),
+ failSend: (cause: unknown) => rejectSends.at(-1)?.(cause),
};
}
@@ -1327,6 +1329,57 @@ describe("AgentControllerLive", () => {
);
});
+ it.effect("recreates a Mastra session after sendMessage fails", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* resolveCodex(controller);
+ const startInput = {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ cwd: process.cwd(),
+ modelSelection: codexSelection,
+ runtimeMode: "full-access" as const,
+ };
+ yield* controller.startSession(codexThreadId, startInput);
+
+ const failedTurn = yield* controller.streamEvents.pipe(
+ Stream.filter(
+ (event) => event.type === "turn.completed" && event.payload.state === "failed",
+ ),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "First turn." });
+ yield* Effect.yieldNow;
+ mastra.failSend(new Error("Mastra session is poisoned"));
+ yield* Fiber.join(failedTurn);
+ yield* Effect.yieldNow;
+
+ assert.deepEqual(yield* controller.listSessions(), []);
+ expect(mastra.session.abort).toHaveBeenCalledOnce();
+ expect(mastra.deleteSession).toHaveBeenCalledWith({
+ resourceId: String(codexThreadId),
+ });
+
+ yield* controller.startSession(codexThreadId, startInput);
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Second turn." });
+
+ expect(mastra.createSession).toHaveBeenCalledTimes(2);
+ expect(mastra.sendMessage).toHaveBeenNthCalledWith(1, { content: "First turn." });
+ expect(mastra.sendMessage).toHaveBeenNthCalledWith(2, { content: "Second turn." });
+ expect(bridge.startSession).not.toHaveBeenCalled();
+ expect(bridge.sendTurn).not.toHaveBeenCalled();
+ mastra.finishSend();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
it.effect("keeps product feedback approval-gated in full-access mode", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
@@ -1350,6 +1403,10 @@ describe("AgentControllerLive", () => {
toolName: AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
policy: "ask",
});
+ expect(mastra.session.permissions.setForTool).not.toHaveBeenCalledWith({
+ toolName: AKERU_CREATE_ROUTINE_TOOL_NAME,
+ policy: expect.anything(),
+ });
expect(mastra.session.permissions.setForTool).toHaveBeenCalledWith({
toolName: "RestartMcpServers",
policy: "ask",
@@ -1764,7 +1821,7 @@ describe("AgentControllerLive", () => {
yield* controller.respondToUserInput({
threadId: codexThreadId,
requestId: ApprovalRequestId.make("tool-input-1"),
- answers: { answer: "Continue" },
+ answers: { "tool-input-1": "Continue" },
});
mastra.emit({ type: "agent_end", reason: "complete" } as AgentControllerEvent);
@@ -1772,8 +1829,92 @@ describe("AgentControllerLive", () => {
assert.isUndefined(completed?.activeTurnId);
expect(mastra.session.respondToToolSuspension).toHaveBeenCalledWith({
toolCallId: "tool-input-1",
- resumeData: { answer: "Continue" },
+ resumeData: "Continue",
+ });
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("fails a cancelled Mastra suspension and accepts the next turn", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ const events: ProviderRuntimeEvent[] = [];
+ const collector = yield* controller.streamEvents.pipe(
+ Stream.runForEach((event) => Effect.sync(() => events.push(event))),
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ cwd: process.cwd(),
+ modelSelection: codexSelection,
+ runtimeMode: "approval-required",
});
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Ask for input." });
+ mastra.emit({
+ type: "tool_suspended",
+ toolCallId: "tool-input-cancelled",
+ toolName: "ask_user",
+ args: {},
+ suspendPayload: {},
+ } as AgentControllerEvent);
+ mastra.emit({ type: "agent_end", reason: "suspended" } as AgentControllerEvent);
+ mastra.finishSend();
+ yield* Effect.yieldNow;
+
+ vi.mocked(mastra.session.respondToToolSuspension).mockImplementationOnce(async () => {
+ mastra.emit({
+ type: "tool_suspension_cancelled",
+ toolCallId: "tool-input-cancelled",
+ toolName: "ask_user",
+ reason: "sendStreamResume() could not find a suspended run",
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "error",
+ error: new Error("AGENT_SEND_STREAM_RESUME_NO_SUSPENDED_THREAD_RUN"),
+ } as AgentControllerEvent);
+ mastra.emit({ type: "agent_end", reason: "error" } as AgentControllerEvent);
+ });
+ const responseExit = yield* controller
+ .respondToUserInput({
+ threadId: codexThreadId,
+ requestId: ApprovalRequestId.make("tool-input-cancelled"),
+ answers: { "tool-input-cancelled": "Continue" },
+ })
+ .pipe(Effect.exit);
+ assert.isTrue(Exit.isFailure(responseExit));
+ yield* Effect.yieldNow;
+
+ const failedTurns = events.filter(
+ (event) => event.type === "turn.completed" && event.payload.state === "failed",
+ );
+ expect(failedTurns).toHaveLength(1);
+ expect(failedTurns[0]).toMatchObject({
+ payload: {
+ errorMessage: "This response could not resume. Send your reply again.",
+ },
+ });
+ expect(
+ events.filter(
+ (event) =>
+ event.type === "user-input.resolved" &&
+ String(event.requestId) === "tool-input-cancelled",
+ ),
+ ).toHaveLength(0);
+ expect(mastra.deleteSession).not.toHaveBeenCalled();
+
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Try again." });
+ expect(mastra.sendMessage).toHaveBeenNthCalledWith(2, { content: "Try again." });
+ expect(mastra.createSession).toHaveBeenCalledTimes(1);
+ mastra.finishSend();
+ yield* Fiber.interrupt(collector);
}),
bridge.service,
mastra.factory,
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index 38610507e..e8662763e 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -24,11 +24,13 @@ import {
ProviderInstanceId,
RuntimeItemId,
RuntimeRequestId,
+ RoutineId,
TurnId,
AKERU_TOOL_CATALOG,
DEFAULT_BOT_SANDBOX_BROWSER_SHARING,
type BotId,
type McpServer,
+ type AkeruCreateRoutineInput,
type ModelSelection,
type ProviderApprovalDecision,
type ProviderRuntimeEvent,
@@ -41,6 +43,7 @@ import {
type AkeruMemoryThreadAccess,
type OrchestrationCommand,
type OrchestrationReadModel,
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
@@ -124,6 +127,7 @@ import {
type AgentControllerShape,
} from "../Services/AgentController.ts";
import { LegacyProviderBridge } from "../Services/LegacyProviderBridge.ts";
+import { RoutineDraftDispatcher } from "../../routines/RoutineDraftDispatcher.ts";
const DEFAULT_MODE_ID = "build";
const PLAN_MODE_ID = "plan";
@@ -216,8 +220,18 @@ export function createAkeruMastraAuthStorage(secretsDir: string): AuthStorage {
return new AuthStorage(NodePath.join(secretsDir, "subscription-auth.json"));
}
+const MISSING_SUSPENDED_RUN = "AGENT_SEND_STREAM_RESUME_NO_SUSPENDED_THREAD_RUN";
+const RESUME_FAILED_MESSAGE = "This response could not resume. Send your reply again.";
+
+function isMissingSuspendedRun(detail: string): boolean {
+ return (
+ detail.includes(MISSING_SUSPENDED_RUN) || detail.includes("could not find a suspended run")
+ );
+}
+
function failureDetail(cause: unknown): string {
- return cause instanceof Error ? cause.message : String(cause);
+ const detail = cause instanceof Error ? cause.message : String(cause);
+ return isMissingSuspendedRun(detail) ? RESUME_FAILED_MESSAGE : detail;
}
function sessionFailureDetail(active: Pick<ActiveSession, "mcpServerIds">, cause: unknown): string {
@@ -438,6 +452,8 @@ const make = (options?: AgentControllerLiveOptions) =>
const mcpSessionRegistry = yield* Effect.serviceOption(McpSessionRegistry.McpSessionRegistry);
const runtimeContext = yield* Effect.context<never>();
const runPromise = Effect.runPromiseWith(runtimeContext);
+ const routineDraftDispatcher = yield* Effect.serviceOption(RoutineDraftDispatcher);
+ const routineDispatcher = Option.getOrUndefined(routineDraftDispatcher);
const mutationLock = yield* Semaphore.make(1);
const runtimeEvents = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const orchestrationEngine = yield* Effect.serviceOption(OrchestrationEngineService);
@@ -502,6 +518,16 @@ const make = (options?: AgentControllerLiveOptions) =>
childWaiters.delete(String(threadId));
waiter.resolve(outcome);
};
+ const pendingRoutineRequests = new Map<
+ string,
+ {
+ readonly threadId: string;
+ readonly input: AkeruCreateRoutineInput;
+ readonly timezone: string;
+ readonly resolve: (result: unknown) => void;
+ readonly reject: (cause: unknown) => void;
+ }
+ >();
const runMastra = <A>(operation: string, run: () => Promise<A>) =>
Effect.tryPromise({
@@ -662,6 +688,64 @@ const make = (options?: AgentControllerLiveOptions) =>
});
},
getThreadTools: (threadId) => sessionResources.getConnectorTools(threadId),
+ ...(routineDispatcher
+ ? {
+ listRoutines: (threadId: string) =>
+ runPromise(
+ routineDispatcher
+ .listForThread(ThreadIdBrand(threadId))
+ .pipe(Effect.map((routines) => ({ routines: [...routines] }))),
+ ),
+ deleteRoutines: (threadId: string, routineIds: ReadonlyArray<string>) =>
+ runPromise(
+ routineDispatcher
+ .deleteForThread(
+ ThreadIdBrand(threadId),
+ routineIds.map((routineId) => RoutineId.make(routineId)),
+ )
+ .pipe(
+ Effect.map((result) => ({
+ status: result.status,
+ deletedRoutineIds: [...result.routineIds],
+ })),
+ ),
+ ),
+ createRoutine: (threadId: string, input: AkeruCreateRoutineInput) => {
+ const active = sessions.get(threadId);
+ const timezone = active?.toolSession.timezone;
+ if (!timezone) {
+ return Promise.reject(new Error("Send a message before creating a routine."));
+ }
+ const requestId = `routine-${NodeCrypto.randomUUID()}`;
+ return new Promise((resolve, reject) => {
+ pendingRoutineRequests.set(requestId, {
+ threadId,
+ input,
+ timezone,
+ resolve,
+ reject,
+ });
+ if (active.activeTurn) active.activeTurn.waiting = true;
+ publishSessionState(ThreadIdBrand(threadId), active, "waiting");
+ publish({
+ ...baseEvent(ThreadIdBrand(threadId), active, active.activeTurn?.turnId),
+ requestId: RuntimeRequestId.make(requestId),
+ type: "request.opened",
+ payload: {
+ requestType: "dynamic_tool_call",
+ detail: "Review routine",
+ toolName: AKERU_CREATE_ROUTINE_TOOL_NAME,
+ args: { ...input, timezone },
+ options: [
+ { decision: "accept", label: "Create routine" },
+ { decision: "decline", label: "Cancel" },
+ ],
+ },
+ });
+ });
+ },
+ }
+ : {}),
toolRuntime,
startMemoryCall: async ({ threadId, category }) => {
const context = memoryUsageByThread.get(threadId);
@@ -940,7 +1024,7 @@ const make = (options?: AgentControllerLiveOptions) =>
finishTurn(threadId, active, "completed");
}
})
- .catch((cause: unknown) => {
+ .catch(async (cause: unknown) => {
if (active.activeTurn?.turnId !== turnId) return;
const detail = sessionFailureDetail(active, cause);
publish({
@@ -949,6 +1033,16 @@ const make = (options?: AgentControllerLiveOptions) =>
payload: { message: detail, class: "provider_error" },
});
finishTurn(threadId, active, "failed", detail);
+ await runPromise(
+ stopSessionWithResources({ threadId }, false).pipe(
+ Effect.catchCause((resetCause) =>
+ Effect.logWarning("provider session reset failed", {
+ threadId,
+ cause: resetCause,
+ }),
+ ),
+ ),
+ );
});
};
@@ -991,6 +1085,11 @@ const make = (options?: AgentControllerLiveOptions) =>
});
});
}
+ for (const [requestId, request] of pendingRoutineRequests) {
+ if (request.threadId !== String(threadId)) continue;
+ pendingRoutineRequests.delete(requestId);
+ request.reject(new Error("The routine review ended before it received a response."));
+ }
active.activeTurn = null;
const nextTurn = active.pendingTurns.shift();
if (nextTurn) {
@@ -1194,7 +1293,9 @@ const make = (options?: AgentControllerLiveOptions) =>
? "Allow Computer Use?"
: event.toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME
? "Review product feedback"
- : approvalDetail(event.toolName, action, oneUseApproval),
+ : event.toolName === AKERU_CREATE_ROUTINE_TOOL_NAME
+ ? "Review routine"
+ : approvalDetail(event.toolName, action, oneUseApproval),
toolName: isCodexComputerUseTool(event.toolName) ? "Computer Use" : event.toolName,
...(action ? { action } : {}),
args: isCodexComputerUseTool(event.toolName) ? undefined : event.args,
@@ -1208,21 +1309,26 @@ const make = (options?: AgentControllerLiveOptions) =>
{ decision: "accept", label: "Add to feedback draft" },
{ decision: "decline", label: "Cancel" },
]
- : AKERU_TOOL_CATALOG.some((tool) => tool.id === event.toolName) ||
- isMemoryToolId(event.toolName) ||
- oneUseApproval
+ : event.toolName === AKERU_CREATE_ROUTINE_TOOL_NAME
? [
- { decision: "decline", label: "Decline" },
- {
- decision: "accept",
- label: oneUseApproval ? "Approve" : "Allow",
- },
+ { decision: "accept", label: "Create routine" },
+ { decision: "decline", label: "Cancel" },
]
- : [
- { decision: "accept", label: "Allow" },
- { decision: "acceptForSession", label: "Allow for session" },
- { decision: "decline", label: "Decline" },
- ],
+ : AKERU_TOOL_CATALOG.some((tool) => tool.id === event.toolName) ||
+ isMemoryToolId(event.toolName) ||
+ oneUseApproval
+ ? [
+ { decision: "decline", label: "Decline" },
+ {
+ decision: "accept",
+ label: oneUseApproval ? "Approve" : "Allow",
+ },
+ ]
+ : [
+ { decision: "accept", label: "Allow" },
+ { decision: "acceptForSession", label: "Allow for session" },
+ { decision: "decline", label: "Decline" },
+ ],
},
});
return;
@@ -1233,6 +1339,31 @@ const make = (options?: AgentControllerLiveOptions) =>
active.toolNames.set(event.toolCallId, event.toolName);
turn.waiting = true;
publishSessionState(threadId, active, "waiting");
+ const suspendPayload =
+ event.suspendPayload && typeof event.suspendPayload === "object"
+ ? (event.suspendPayload as Record<string, unknown>)
+ : {};
+ const question =
+ typeof suspendPayload.question === "string" && suspendPayload.question.trim()
+ ? suspendPayload.question.trim()
+ : `Input required for ${event.toolName}`;
+ const options = Array.isArray(suspendPayload.options)
+ ? suspendPayload.options.flatMap((option) => {
+ if (!option || typeof option !== "object") return [];
+ const value = option as Record<string, unknown>;
+ if (typeof value.label !== "string" || !value.label.trim()) return [];
+ const label = value.label.trim();
+ return [
+ {
+ label,
+ description:
+ typeof value.description === "string" && value.description.trim()
+ ? value.description.trim()
+ : label,
+ },
+ ];
+ })
+ : [];
publish({
...baseEvent(threadId, active, turn.turnId),
requestId: RuntimeRequestId.make(event.toolCallId),
@@ -1241,10 +1372,10 @@ const make = (options?: AgentControllerLiveOptions) =>
questions: [
{
id: event.toolCallId,
- header: event.toolName,
- question: `Input required for ${event.toolName}`,
- options: [],
- multiSelect: false,
+ header: "Question",
+ question,
+ options,
+ multiSelect: suspendPayload.selectionMode === "multi_select",
},
],
},
@@ -1798,6 +1929,10 @@ const make = (options?: AgentControllerLiveOptions) =>
: providerInput,
);
}
+ if (input.timezone !== undefined) {
+ active.toolSession = { ...active.toolSession, timezone: input.timezone };
+ toolRuntime.registerSession(key, active.toolSession);
+ }
const attachmentFiles = yield* Effect.forEach(input.attachments ?? [], (attachment) => {
const path = resolveAttachmentPath({
attachmentsDir: config.attachmentsDir,
@@ -1874,12 +2009,59 @@ const make = (options?: AgentControllerLiveOptions) =>
if (
usesMastraCode(resolvedByThread.get(key)?.provider ?? ProviderDriverKind.make("codex"))
) {
- return;
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToRequest",
+ detail: `Stale pending approval request: ${input.requestId}. The agent session restarted. Send the request again.`,
+ });
}
return yield* legacyProviderBridge.respondToRequest(input);
}
- if (!active.activeTurn) return;
+ if (!active.activeTurn) {
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToRequest",
+ detail: `Stale pending approval request: ${input.requestId}. The agent turn has ended. Send the request again.`,
+ });
+ }
const toolCallId = String(input.requestId);
+ const routineRequest = pendingRoutineRequests.get(toolCallId);
+ if (routineRequest) {
+ pendingRoutineRequests.delete(toolCallId);
+ if (active.activeTurn) active.activeTurn.waiting = false;
+ publish({
+ ...baseEvent(input.threadId, active, active.activeTurn?.turnId),
+ requestId: RuntimeRequestId.make(toolCallId),
+ type: "request.resolved",
+ payload: { requestType: "dynamic_tool_call" as const, decision: input.decision },
+ });
+ publishSessionState(input.threadId, active, "running");
+ if (input.decision === "decline" || input.decision === "cancel") {
+ routineRequest.resolve({ status: "cancelled" });
+ return;
+ }
+ const result = yield* routineDispatcher!
+ .createApprovedForThread(
+ ThreadIdBrand(routineRequest.threadId),
+ routineRequest.timezone,
+ routineRequest.input,
+ )
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new AgentControllerRuntimeError({
+ operation: "respondToRequest.routine",
+ detail: cause.message,
+ cause,
+ }),
+ ),
+ Effect.tapError((cause) =>
+ Effect.sync(() => {
+ routineRequest.reject(cause);
+ }),
+ ),
+ );
+ routineRequest.resolve(result);
+ return;
+ }
const toolRequest = active.approvalRequests.get(toolCallId);
const pendingApproval = active.pendingApprovals.get(toolCallId);
if (!toolRequest || !pendingApproval) return;
@@ -1946,15 +2128,40 @@ const make = (options?: AgentControllerLiveOptions) =>
if (
usesMastraCode(resolvedByThread.get(key)?.provider ?? ProviderDriverKind.make("codex"))
) {
- return;
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToUserInput",
+ detail: `Unknown pending user-input request: ${input.requestId}. The agent session restarted. Send the request again.`,
+ });
}
return yield* legacyProviderBridge.respondToUserInput(input);
}
const toolCallId = String(input.requestId);
+ const answer = input.answers[toolCallId];
+ if (answer === undefined) {
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToToolSuspension",
+ detail: `No answer was supplied for pending user-input request '${toolCallId}'.`,
+ });
+ }
if (active.activeTurn) active.activeTurn.waiting = false;
+ let resumeFailure: string | undefined;
+ const unsubscribe = active.session.subscribe((event) => {
+ if (event.type === "tool_suspension_cancelled" && event.toolCallId === toolCallId) {
+ resumeFailure = event.reason;
+ } else if (event.type === "error") {
+ resumeFailure ??= event.error.message;
+ }
+ });
yield* runMastra("respondToToolSuspension", () =>
- active.session.respondToToolSuspension({ toolCallId, resumeData: input.answers }),
- );
+ active.session.respondToToolSuspension({ toolCallId, resumeData: answer }),
+ ).pipe(Effect.ensuring(Effect.sync(unsubscribe)));
+ if (resumeFailure !== undefined) {
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToToolSuspension",
+ detail: `Unknown pending user-input request: ${toolCallId}. ${resumeFailure}`,
+ cause: new Error(resumeFailure),
+ });
+ }
publish({
...baseEvent(input.threadId, active, active.activeTurn?.turnId),
requestId: RuntimeRequestId.make(toolCallId),
diff --git a/apps/server/src/routines/Repository.ts b/apps/server/src/routines/Repository.ts
new file mode 100644
index 000000000..7c6afe9d1
--- /dev/null
+++ b/apps/server/src/routines/Repository.ts
@@ -0,0 +1,75 @@
+import * as Context from "effect/Context";
+import type * as Effect from "effect/Effect";
+
+import type { PersistenceSqlError } from "../persistence/Errors.ts";
+import type { RoutineSkillAssignment } from "@t3tools/contracts";
+import type { Routine, RoutineId, RoutineRun, RoutineRunId, RoutineRunTrigger } from "./types.ts";
+
+interface RoutineClaimBase {
+ readonly runId: RoutineRunId;
+ readonly routineId: RoutineId;
+ readonly claimedAt: string;
+ readonly status?: "claimed" | "dispatched";
+ readonly threadRef?: string | null;
+ readonly terminalState?: "completed" | "error" | "interrupted" | null;
+ readonly terminalAt?: string | null;
+ readonly sessionState?:
+ | "ready"
+ | "starting"
+ | "running"
+ | "error"
+ | "interrupted"
+ | "stopped"
+ | null;
+ readonly sessionUpdatedAt?: string | null;
+}
+
+export type RoutineClaim = RoutineClaimBase &
+ (
+ | {
+ readonly trigger: Extract<RoutineRunTrigger, "dry-run" | "manual">;
+ readonly scheduledFor: null;
+ }
+ | {
+ readonly trigger: Extract<RoutineRunTrigger, "scheduled" | "missed">;
+ readonly scheduledFor: string;
+ }
+ );
+
+export interface RoutineRepositoryShape {
+ readonly listAll: Effect.Effect<ReadonlyArray<Routine>, PersistenceSqlError>;
+ readonly listEnabled: Effect.Effect<ReadonlyArray<Routine>, PersistenceSqlError>;
+ readonly getById: (routineId: RoutineId) => Effect.Effect<Routine | null, PersistenceSqlError>;
+ readonly listRuns: (
+ routineId: RoutineId,
+ ) => Effect.Effect<ReadonlyArray<RoutineRun>, PersistenceSqlError>;
+ readonly listAllRuns: Effect.Effect<ReadonlyArray<RoutineRun>, PersistenceSqlError>;
+ readonly getActiveRunByThreadRef: (
+ threadRef: string,
+ turnId?: string | null,
+ ) => Effect.Effect<RoutineRun | null, PersistenceSqlError>;
+ readonly listSkillAssignments: Effect.Effect<
+ ReadonlyArray<RoutineSkillAssignment>,
+ PersistenceSqlError
+ >;
+ readonly claim: (claim: RoutineClaim) => Effect.Effect<boolean, PersistenceSqlError>;
+ readonly markDispatched: (
+ runId: RoutineRunId,
+ threadId: string,
+ ) => Effect.Effect<void, PersistenceSqlError>;
+ readonly markBlocked: (
+ runId: RoutineRunId,
+ failure: string,
+ completedAt: string,
+ ) => Effect.Effect<void, PersistenceSqlError>;
+ readonly markSettled: (
+ runId: RoutineRunId,
+ status: "completed" | "failed",
+ completedAt: string,
+ ) => Effect.Effect<void, PersistenceSqlError>;
+ readonly listRecoverable: Effect.Effect<ReadonlyArray<RoutineClaim>, PersistenceSqlError>;
+}
+
+export class RoutineRepository extends Context.Service<RoutineRepository, RoutineRepositoryShape>()(
+ "akeru-bot/routines/Repository/RoutineRepository",
+) {}
diff --git a/apps/server/src/routines/RepositoryLive.ts b/apps/server/src/routines/RepositoryLive.ts
new file mode 100644
index 000000000..98492f79a
--- /dev/null
+++ b/apps/server/src/routines/RepositoryLive.ts
@@ -0,0 +1,336 @@
+import { BotId, McpServerId, ProjectId, ThreadId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+import { toPersistenceSqlError } from "../persistence/Errors.ts";
+import { RoutineRepository, type RoutineClaim, type RoutineRepositoryShape } from "./Repository.ts";
+import type { Routine, RoutineRun } from "./types.ts";
+
+const RoutineRow = Schema.Struct({
+ id: Schema.String,
+ botId: BotId,
+ targetThreadId: ThreadId,
+ projectId: ProjectId,
+ job: Schema.String,
+ procedure: Schema.String,
+ procedureVersion: Schema.Number,
+ approvalVersion: Schema.NullOr(Schema.Number),
+ schedule: Schema.fromJsonString(
+ Schema.Union([
+ Schema.Struct({ kind: Schema.Literals(["daily", "weekdays"]), time: Schema.String }),
+ Schema.Struct({
+ kind: Schema.Literal("weekly"),
+ weekdays: Schema.Array(
+ Schema.Literals([
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+ "sunday",
+ ]),
+ ),
+ time: Schema.String,
+ }),
+ ]),
+ ),
+ timezone: Schema.String,
+ skillAssignmentIds: Schema.fromJsonString(Schema.Array(Schema.String)),
+ connectorDependencies: Schema.fromJsonString(Schema.Array(McpServerId)),
+ sandbox: Schema.String,
+ approvalPolicy: Schema.String,
+ enabled: Schema.Number,
+ lifecycle: Schema.Literals([
+ "draft",
+ "approved",
+ "enabled",
+ "running",
+ "paused",
+ "blocked",
+ "failed",
+ "completed",
+ "deleted",
+ ]),
+ nextRunAt: Schema.NullOr(Schema.String),
+ lastRunAt: Schema.NullOr(Schema.String),
+ latestResult: Schema.NullOr(Schema.fromJsonString(Schema.Struct({ summary: Schema.String }))),
+ latestFailure: Schema.NullOr(
+ Schema.fromJsonString(Schema.Struct({ kind: Schema.String, message: Schema.String })),
+ ),
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+ deletedAt: Schema.NullOr(Schema.String),
+});
+
+const RoutineRunRow = Schema.Struct({
+ id: Schema.String,
+ routineId: Schema.String,
+ procedureVersion: Schema.Number,
+ trigger: Schema.Literals(["dry-run", "manual", "scheduled", "missed"]),
+ scheduledFor: Schema.NullOr(Schema.String),
+ status: Schema.Literals([
+ "queued",
+ "running",
+ "waiting-for-approval",
+ "completed",
+ "failed",
+ "canceled",
+ "blocked",
+ ]),
+ threadRef: Schema.NullOr(ThreadId),
+ result: Schema.NullOr(Schema.fromJsonString(Schema.Struct({ summary: Schema.String }))),
+ failure: Schema.NullOr(
+ Schema.fromJsonString(Schema.Struct({ kind: Schema.String, message: Schema.String })),
+ ),
+ usageRef: Schema.NullOr(Schema.String),
+ startedAt: Schema.NullOr(Schema.String),
+ completedAt: Schema.NullOr(Schema.String),
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+});
+
+const SkillAssignmentRow = Schema.Struct({
+ id: Schema.String,
+ botId: BotId,
+ skillId: Schema.String,
+ name: Schema.String,
+ description: Schema.NullOr(Schema.String),
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+});
+
+const decodeRoutine = Schema.decodeUnknownSync(RoutineRow);
+const decodeRun = Schema.decodeUnknownSync(RoutineRunRow);
+const decodeSkillAssignment = Schema.decodeUnknownSync(SkillAssignmentRow);
+
+const make = Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ const readRoutines = (parameter?: string) =>
+ parameter === undefined
+ ? sql<Record<string, unknown>>`
+ SELECT routine_id AS id, bot_id AS "botId", target_thread_id AS "targetThreadId",
+ project_id AS "projectId", job,
+ procedure, procedure_version AS "procedureVersion",
+ approval_version AS "approvalVersion", schedule_json AS schedule, timezone,
+ skill_assignment_ids_json AS "skillAssignmentIds",
+ connector_dependencies_json AS "connectorDependencies", sandbox,
+ approval_policy AS "approvalPolicy", enabled, lifecycle,
+ next_run_at AS "nextRunAt", last_run_at AS "lastRunAt",
+ latest_result_json AS "latestResult", latest_failure_json AS "latestFailure",
+ created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt"
+ FROM projection_routines ORDER BY created_at, routine_id
+ `
+ : sql<Record<string, unknown>>`
+ SELECT routine_id AS id, bot_id AS "botId", target_thread_id AS "targetThreadId",
+ project_id AS "projectId", job,
+ procedure, procedure_version AS "procedureVersion",
+ approval_version AS "approvalVersion", schedule_json AS schedule, timezone,
+ skill_assignment_ids_json AS "skillAssignmentIds",
+ connector_dependencies_json AS "connectorDependencies", sandbox,
+ approval_policy AS "approvalPolicy", enabled, lifecycle,
+ next_run_at AS "nextRunAt", last_run_at AS "lastRunAt",
+ latest_result_json AS "latestResult", latest_failure_json AS "latestFailure",
+ created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt"
+ FROM projection_routines WHERE routine_id = ${parameter}
+ `;
+
+ const listAll: RoutineRepositoryShape["listAll"] = readRoutines().pipe(
+ Effect.map((rows) =>
+ rows.map((row) => {
+ const decoded = decodeRoutine(row);
+ return { ...decoded, enabled: decoded.enabled === 1 } as Routine;
+ }),
+ ),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.listAll")),
+ );
+
+ const listEnabled: RoutineRepositoryShape["listEnabled"] = listAll.pipe(
+ Effect.map((routines) => routines.filter((routine) => routine.enabled)),
+ );
+
+ const getById: RoutineRepositoryShape["getById"] = (routineId) =>
+ readRoutines(routineId).pipe(
+ Effect.map((rows) => {
+ if (rows[0] === undefined) return null;
+ const decoded = decodeRoutine(rows[0]);
+ return { ...decoded, enabled: decoded.enabled === 1 } as Routine;
+ }),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.getById")),
+ );
+
+ const listRuns: RoutineRepositoryShape["listRuns"] = (routineId) =>
+ sql<Record<string, unknown>>`
+ SELECT run_id AS id, routine_id AS "routineId", procedure_version AS "procedureVersion",
+ trigger, scheduled_for AS "scheduledFor", status, thread_ref AS "threadRef",
+ result_json AS result, failure_json AS failure, usage_ref AS "usageRef",
+ started_at AS "startedAt", completed_at AS "completedAt", created_at AS "createdAt",
+ updated_at AS "updatedAt"
+ FROM projection_routine_runs
+ WHERE routine_id = ${routineId}
+ ORDER BY scheduled_for DESC, run_id DESC
+ `.pipe(
+ Effect.map((rows) => rows.map((row) => decodeRun(row) as RoutineRun)),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.listRuns")),
+ );
+
+ const listAllRuns: RoutineRepositoryShape["listAllRuns"] = sql<Record<string, unknown>>`
+ SELECT run_id AS id, routine_id AS "routineId", procedure_version AS "procedureVersion",
+ trigger, scheduled_for AS "scheduledFor", status, thread_ref AS "threadRef",
+ result_json AS result, failure_json AS failure, usage_ref AS "usageRef",
+ started_at AS "startedAt", completed_at AS "completedAt", created_at AS "createdAt",
+ updated_at AS "updatedAt"
+ FROM projection_routine_runs
+ WHERE run_id IN (
+ SELECT run_id FROM (
+ SELECT run_id,
+ ROW_NUMBER() OVER (
+ PARTITION BY routine_id ORDER BY created_at DESC, run_id DESC
+ ) AS history_rank
+ FROM projection_routine_runs
+ ) WHERE history_rank <= 5
+ )
+ ORDER BY created_at, run_id
+ `.pipe(
+ Effect.map((rows) => rows.map((row) => decodeRun(row) as RoutineRun)),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.listAllRuns")),
+ );
+
+ const getActiveRunByThreadRef: RoutineRepositoryShape["getActiveRunByThreadRef"] = (
+ threadRef,
+ turnId = null,
+ ) =>
+ sql<Record<string, unknown>>`
+ SELECT run_id AS id, routine_id AS "routineId", procedure_version AS "procedureVersion",
+ trigger, scheduled_for AS "scheduledFor", status, thread_ref AS "threadRef",
+ result_json AS result, failure_json AS failure, usage_ref AS "usageRef",
+ started_at AS "startedAt", completed_at AS "completedAt", created_at AS "createdAt",
+ updated_at AS "updatedAt"
+ FROM projection_routine_runs
+ WHERE thread_ref = ${threadRef}
+ AND status IN ('queued', 'running', 'waiting-for-approval')
+ AND EXISTS (
+ SELECT 1 FROM projection_turns AS turn
+ WHERE turn.thread_id = ${threadRef}
+ AND turn.pending_message_id = 'routine:' || projection_routine_runs.run_id || ':message'
+ AND (${turnId} IS NULL OR turn.turn_id = ${turnId})
+ AND turn.state IN ('completed', 'error', 'interrupted')
+ )
+ ORDER BY updated_at DESC LIMIT 1
+ `.pipe(
+ Effect.map((rows) => (rows[0] === undefined ? null : (decodeRun(rows[0]) as RoutineRun))),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.getActiveRunByThreadRef")),
+ );
+
+ const listSkillAssignments: RoutineRepositoryShape["listSkillAssignments"] = sql<
+ Record<string, unknown>
+ >`
+ SELECT assignment_id AS id, bot_id AS "botId", skill_id AS "skillId", name,
+ description, created_at AS "createdAt", updated_at AS "updatedAt"
+ FROM projection_routine_skill_assignments
+ ORDER BY created_at, assignment_id
+ `.pipe(
+ Effect.map((rows) => rows.map((row) => decodeSkillAssignment(row)) as never),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.listSkillAssignments")),
+ );
+
+ const claim: RoutineRepositoryShape["claim"] = (input) =>
+ sql<{ readonly runId: string }>`
+ INSERT INTO routine_run_claims (
+ run_id, routine_id, trigger, scheduled_for, status, claimed_at, updated_at
+ ) VALUES (
+ ${input.runId}, ${input.routineId}, ${input.trigger}, ${input.scheduledFor},
+ 'claimed', ${input.claimedAt}, ${input.claimedAt}
+ )
+ ON CONFLICT DO NOTHING
+ RETURNING run_id AS "runId"
+ `.pipe(
+ Effect.map((rows) => rows.length === 1),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.claim")),
+ );
+
+ const markDispatched: RoutineRepositoryShape["markDispatched"] = (runId, threadId) =>
+ sql`
+ UPDATE routine_run_claims
+ SET status = 'dispatched', thread_id = ${threadId}, updated_at = CURRENT_TIMESTAMP
+ WHERE run_id = ${runId}
+ `.pipe(
+ Effect.asVoid,
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.markDispatched")),
+ );
+
+ const markBlocked: RoutineRepositoryShape["markBlocked"] = (runId, failure, completedAt) =>
+ sql`
+ UPDATE routine_run_claims
+ SET status = 'blocked', failure = ${failure}, completed_at = ${completedAt},
+ updated_at = ${completedAt}
+ WHERE run_id = ${runId}
+ `.pipe(Effect.asVoid, Effect.mapError(toPersistenceSqlError("RoutineRepository.markBlocked")));
+
+ const markSettled: RoutineRepositoryShape["markSettled"] = (runId, status, completedAt) =>
+ sql`
+ UPDATE routine_run_claims
+ SET status = ${status}, completed_at = ${completedAt}, updated_at = ${completedAt}
+ WHERE run_id = ${runId}
+ `.pipe(Effect.asVoid, Effect.mapError(toPersistenceSqlError("RoutineRepository.markSettled")));
+
+ const listRecoverable: RoutineRepositoryShape["listRecoverable"] = sql<{
+ readonly runId: string;
+ readonly routineId: string;
+ readonly trigger: "dry-run" | "manual" | "scheduled" | "missed";
+ readonly scheduledFor: string | null;
+ readonly claimedAt: string;
+ readonly status: "claimed" | "dispatched";
+ readonly threadRef: string | null;
+ readonly terminalState: "completed" | "error" | "interrupted" | null;
+ readonly terminalAt: string | null;
+ readonly sessionState:
+ | "ready"
+ | "starting"
+ | "running"
+ | "error"
+ | "interrupted"
+ | "stopped"
+ | null;
+ readonly sessionUpdatedAt: string | null;
+ }>`
+ SELECT run_id AS "runId", routine_id AS "routineId", trigger,
+ scheduled_for AS "scheduledFor", claimed_at AS "claimedAt", claims.status,
+ claims.thread_id AS "threadRef", turns.state AS "terminalState",
+ turns.completed_at AS "terminalAt", sessions.status AS "sessionState",
+ sessions.updated_at AS "sessionUpdatedAt"
+ FROM routine_run_claims AS claims
+ LEFT JOIN projection_turns AS turns ON turns.row_id = (
+ SELECT MAX(candidate.row_id) FROM projection_turns AS candidate
+ WHERE candidate.thread_id = claims.thread_id
+ AND candidate.pending_message_id = 'routine:' || claims.run_id || ':message'
+ AND candidate.state IN ('completed', 'error', 'interrupted')
+ )
+ LEFT JOIN projection_thread_sessions AS sessions ON sessions.thread_id = claims.thread_id
+ WHERE claims.status IN ('claimed', 'dispatched')
+ ORDER BY claimed_at, run_id
+ `.pipe(
+ Effect.map((rows) => rows as ReadonlyArray<RoutineClaim>),
+ Effect.mapError(toPersistenceSqlError("RoutineRepository.listRecoverable")),
+ );
+
+ return {
+ listAll,
+ listEnabled,
+ getById,
+ listRuns,
+ listAllRuns,
+ getActiveRunByThreadRef,
+ listSkillAssignments,
+ claim,
+ markDispatched,
+ markBlocked,
+ markSettled,
+ listRecoverable,
+ } satisfies RoutineRepositoryShape;
+});
+
+export const RoutineRepositoryLive = Layer.effect(RoutineRepository, make);
diff --git a/apps/server/src/routines/RoutineDraftDispatcher.test.ts b/apps/server/src/routines/RoutineDraftDispatcher.test.ts
new file mode 100644
index 000000000..4f010e1b9
--- /dev/null
+++ b/apps/server/src/routines/RoutineDraftDispatcher.test.ts
@@ -0,0 +1,255 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import {
+ BotId,
+ IsoDateTime,
+ type OrchestrationBot,
+ type OrchestrationCommand,
+ type OrchestrationShellSnapshot,
+ type OrchestrationThread,
+ PositiveInt,
+ ProjectId,
+ ProviderInstanceId,
+ RoutineId,
+ RoutineTimeZone,
+ ThreadId,
+ type Routine,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Stream from "effect/Stream";
+import { describe, expect, it } from "vite-plus/test";
+
+import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
+import {
+ ProjectionSnapshotQuery,
+ type ProjectionSnapshotQueryShape,
+} from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import {
+ RoutineDraftDispatcher,
+ RoutineDraftDispatcherLive,
+ routineStatusesForBot,
+} from "./RoutineDraftDispatcher.ts";
+
+const botId = BotId.make("bot-1");
+const otherBotId = BotId.make("bot-2");
+const now = IsoDateTime.make("2026-09-01T09:00:00.000Z");
+
+function bot(id: BotId): OrchestrationBot {
+ return {
+ id,
+ name: id,
+ title: "Agent",
+ label: null,
+ description: null,
+ disabledMcpServerIds: [],
+ avatar: { kind: "dither", seed: id },
+ engine: null,
+ sandbox: "local",
+ runtimeMode: "full-access",
+ usageCap: null,
+ voiceEnabled: false,
+ groupId: null,
+ archivedAt: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+}
+
+function routine(id: string, overrides: Partial<Routine> = {}): Routine {
+ return {
+ id: RoutineId.make(id),
+ botId,
+ targetThreadId: ThreadId.make("thread-1"),
+ job: `Routine ${id}`,
+ procedure: "Reply in this chat.",
+ schedule: { kind: "daily", time: "09:00" },
+ timezone: RoutineTimeZone.make("America/New_York"),
+ skillAssignmentIds: [],
+ connectorDependencies: [],
+ projectId: ProjectId.make("project-1"),
+ sandbox: "local",
+ approvalPolicy: "approval-required",
+ procedureVersion: PositiveInt.make(1),
+ approvalVersion: PositiveInt.make(1),
+ enabled: false,
+ lifecycle: "approved",
+ nextRunAt: null,
+ lastRunAt: null,
+ latestResult: null,
+ latestFailure: null,
+ createdAt: now,
+ updatedAt: now,
+ deletedAt: null,
+ ...overrides,
+ };
+}
+
+describe("routineStatusesForBot", () => {
+ it("returns only active routines owned by the current bot", () => {
+ expect(
+ routineStatusesForBot(
+ [
+ routine("enabled", { enabled: true, lifecycle: "enabled" }),
+ routine("disabled"),
+ routine("blocked", { lifecycle: "blocked" }),
+ routine("other-bot", { botId: otherBotId, enabled: true, lifecycle: "enabled" }),
+ routine("deleted", {
+ lifecycle: "deleted",
+ deletedAt: IsoDateTime.make("2026-09-01T10:00:00.000Z"),
+ }),
+ ],
+ botId,
+ ),
+ ).toEqual([
+ { id: "enabled", name: "Routine enabled", enabled: true, lifecycle: "enabled" },
+ { id: "disabled", name: "Routine disabled", enabled: false, lifecycle: "approved" },
+ { id: "blocked", name: "Routine blocked", enabled: false, lifecycle: "blocked" },
+ ]);
+ });
+});
+
+function deleteHarness(input: {
+ readonly routines: ReadonlyArray<Routine>;
+ readonly respondingBotId?: BotId | null;
+}) {
+ const commands: Array<OrchestrationCommand> = [];
+ const thread: OrchestrationThread = {
+ id: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-1"),
+ botId,
+ groupId: null,
+ respondingBotId: input.respondingBotId ?? null,
+ title: "Routine thread",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5.6-sol",
+ },
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ deletedAt: null,
+ messages: [],
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: null,
+ };
+ const snapshot: OrchestrationShellSnapshot = {
+ snapshotSequence: 1,
+ projects: [],
+ bots: [bot(botId), bot(otherBotId)],
+ groups: [],
+ delegations: [],
+ routines: input.routines,
+ threads: [],
+ updatedAt: now,
+ };
+ const query: ProjectionSnapshotQueryShape = {
+ getCommandReadModel: () => Effect.die("unused"),
+ getSnapshot: () => Effect.die("unused"),
+ getThreadDetailById: () => Effect.succeed(Option.some(thread)),
+ getShellSnapshot: () => Effect.succeed(snapshot),
+ getArchivedShellSnapshot: () => Effect.die("unused"),
+ searchThreads: () => Effect.succeed({ matches: [] }),
+ getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
+ getCounts: () => Effect.die("unused"),
+ getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
+ getOriginalProjectIdByWorkspaceRoot: () => Effect.succeed(Option.none()),
+ getProjectShellById: () => Effect.succeed(Option.none()),
+ getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
+ getThreadCheckpointContext: () => Effect.succeed(Option.none()),
+ getFullThreadDiffContext: () => Effect.succeed(Option.none()),
+ getThreadShellById: () => Effect.succeed(Option.none()),
+ getThreadDetailSnapshot: () => Effect.die("unused"),
+ };
+ const layer = RoutineDraftDispatcherLive.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.succeed(ProjectionSnapshotQuery, query),
+ Layer.succeed(OrchestrationEngineService, {
+ dispatch: (command) =>
+ Effect.sync(() => {
+ commands.push(command);
+ return { sequence: commands.length };
+ }),
+ readEvents: () => Stream.empty,
+ streamDomainEvents: Stream.empty,
+ latestSequence: Effect.succeed(0),
+ }),
+ ),
+ ),
+ Layer.provideMerge(NodeServices.layer),
+ );
+ return { commands, layer };
+}
+
+describe("RoutineDraftDispatcher.deleteForThread", () => {
+ it("validates the full batch before dispatching scoped delete commands", async () => {
+ const test = deleteHarness({
+ routines: [routine("owned"), routine("other", { botId: otherBotId })],
+ });
+
+ await Effect.runPromise(
+ Effect.gen(function* () {
+ const dispatcher = yield* RoutineDraftDispatcher;
+ const error = yield* dispatcher
+ .deleteForThread(ThreadId.make("thread-1"), [
+ RoutineId.make("owned"),
+ RoutineId.make("other"),
+ ])
+ .pipe(Effect.flip);
+
+ expect(error.message).toBe("One or more routines are unavailable.");
+ expect(test.commands).toEqual([]);
+ }).pipe(Effect.provide(test.layer)),
+ );
+ });
+
+ it("deletes each unique routine owned by the responding bot", async () => {
+ const test = deleteHarness({
+ respondingBotId: otherBotId,
+ routines: [
+ routine("primary"),
+ routine("first", { botId: otherBotId }),
+ routine("second", { botId: otherBotId }),
+ ],
+ });
+
+ await Effect.runPromise(
+ Effect.gen(function* () {
+ const dispatcher = yield* RoutineDraftDispatcher;
+ const result = yield* dispatcher.deleteForThread(ThreadId.make("thread-1"), [
+ RoutineId.make("first"),
+ RoutineId.make("second"),
+ RoutineId.make("first"),
+ ]);
+
+ expect(result).toEqual({
+ routineIds: ["first", "second"],
+ sequences: [1, 2],
+ status: "deleted",
+ });
+ expect(test.commands).toHaveLength(2);
+ expect(test.commands.map(({ type }) => type)).toEqual(["routine.delete", "routine.delete"]);
+ expect(
+ test.commands.map((command) => command.type === "routine.delete" && command.routineId),
+ ).toEqual(["first", "second"]);
+ expect(
+ test.commands.every(
+ (command) =>
+ command.type === "routine.delete" &&
+ command.commandId.startsWith("agent:routine.delete:"),
+ ),
+ ).toBe(true);
+ }).pipe(Effect.provide(test.layer)),
+ );
+ });
+});
diff --git a/apps/server/src/routines/RoutineDraftDispatcher.ts b/apps/server/src/routines/RoutineDraftDispatcher.ts
new file mode 100644
index 000000000..01d50bc9a
--- /dev/null
+++ b/apps/server/src/routines/RoutineDraftDispatcher.ts
@@ -0,0 +1,244 @@
+import {
+ BotId,
+ CommandId,
+ type Routine,
+ RoutineId,
+ RoutineTimeZone,
+ ThreadId,
+ type AkeruCreateRoutineInput,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+
+import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
+import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+
+export interface RoutineApprovedResult {
+ readonly routineId: RoutineId;
+ readonly sequence: number;
+ readonly status: "approved";
+}
+
+export interface RoutinesDeletedResult {
+ readonly routineIds: ReadonlyArray<RoutineId>;
+ readonly sequences: ReadonlyArray<number>;
+ readonly status: "deleted";
+}
+
+export type AkeruRoutineStatus = Pick<Routine, "id" | "enabled"> & {
+ readonly name: string;
+ readonly lifecycle: Exclude<Routine["lifecycle"], "deleted">;
+};
+
+export function routineStatusesForBot(
+ routines: ReadonlyArray<Routine>,
+ botId: BotId,
+): ReadonlyArray<AkeruRoutineStatus> {
+ return routines.flatMap((routine) =>
+ routine.botId === botId && routine.lifecycle !== "deleted" && routine.deletedAt === null
+ ? [
+ {
+ id: routine.id,
+ name: routine.job,
+ enabled: routine.enabled,
+ lifecycle: routine.lifecycle,
+ },
+ ]
+ : [],
+ );
+}
+
+export class RoutineDraftError extends Schema.TaggedErrorClass<RoutineDraftError>()(
+ "RoutineDraftError",
+ { message: Schema.String },
+) {}
+
+export interface RoutineDraftDispatcherShape {
+ readonly createApprovedForThread: (
+ threadId: ThreadId,
+ timezone: string,
+ input: AkeruCreateRoutineInput,
+ ) => Effect.Effect<RoutineApprovedResult, RoutineDraftError>;
+ readonly listForThread: (
+ threadId: ThreadId,
+ ) => Effect.Effect<ReadonlyArray<AkeruRoutineStatus>, RoutineDraftError>;
+ readonly deleteForThread: (
+ threadId: ThreadId,
+ routineIds: ReadonlyArray<RoutineId>,
+ ) => Effect.Effect<RoutinesDeletedResult, RoutineDraftError>;
+}
+
+export class RoutineDraftDispatcher extends Context.Service<
+ RoutineDraftDispatcher,
+ RoutineDraftDispatcherShape
+>()("akeru-bot/routines/RoutineDraftDispatcher") {}
+
+const make = Effect.gen(function* () {
+ const engine = yield* OrchestrationEngineService;
+ const snapshots = yield* ProjectionSnapshotQuery;
+ const crypto = yield* Crypto.Crypto;
+ const decodeTimezone = Schema.decodeUnknownEffect(RoutineTimeZone);
+ const fail = (message: string) => new RoutineDraftError({ message });
+
+ const createApprovedForThread: RoutineDraftDispatcherShape["createApprovedForThread"] = (
+ threadId,
+ timezone,
+ input,
+ ) =>
+ Effect.gen(function* () {
+ const thread = Option.getOrUndefined(yield* snapshots.getThreadDetailById(threadId));
+ if (!thread || thread.archivedAt !== null) {
+ return yield* fail("The current chat is unavailable.");
+ }
+ const botId = thread.respondingBotId ?? thread.botId;
+ if (botId === null || botId === undefined) {
+ return yield* fail("Routines can only be created from a bot chat.");
+ }
+ const decodedTimezone = yield* decodeTimezone(timezone).pipe(
+ Effect.mapError(() => fail("The current device timezone is invalid.")),
+ );
+ const snapshot = yield* snapshots.getShellSnapshot();
+ const bot = snapshot.bots.find(
+ (candidate) => candidate.id === botId && candidate.archivedAt === null,
+ );
+ if (!bot) return yield* fail("The current bot is unavailable.");
+
+ const requestedSkills = new Set((input.skillNames ?? []).map((name) => name.toLowerCase()));
+ const skillAssignmentIds = (snapshot.skillAssignments ?? [])
+ .filter(
+ (assignment) =>
+ assignment.botId === botId && requestedSkills.has(assignment.name.toLowerCase()),
+ )
+ .map((assignment) => assignment.id);
+ if (skillAssignmentIds.length !== requestedSkills.size) {
+ return yield* fail("Assign the requested skills to this bot first.");
+ }
+
+ const requestedConnectors = new Set(
+ (input.connectorNames ?? []).map((name) => name.toLowerCase()),
+ );
+ const connectorDependencies = (snapshot.mcpServers ?? [])
+ .filter((server) => server.enabled && requestedConnectors.has(server.name.toLowerCase()))
+ .map((server) => server.id);
+ if (connectorDependencies.length !== requestedConnectors.size) {
+ return yield* fail("Connect the requested plugin first.");
+ }
+
+ const uuid = yield* crypto.randomUUIDv4;
+ const now = DateTime.formatIso(yield* DateTime.now);
+ const routineId = RoutineId.make(uuid);
+ const result = yield* engine.dispatch({
+ type: "routine.create-approved",
+ commandId: CommandId.make(`agent:routine.create-approved:${uuid}`),
+ routineId,
+ botId,
+ targetThreadId: threadId,
+ job: input.name,
+ procedure: input.instructions,
+ schedule: input.schedule,
+ timezone: decodedTimezone,
+ skillAssignmentIds,
+ connectorDependencies,
+ projectId: thread.projectId,
+ sandbox: "local",
+ approvalPolicy: thread.runtimeMode,
+ createdAt: now,
+ });
+ return { routineId, sequence: result.sequence, status: "approved" as const };
+ }).pipe(
+ Effect.mapError((cause) =>
+ Schema.is(RoutineDraftError)(cause)
+ ? cause
+ : fail(cause instanceof Error ? cause.message : String(cause)),
+ ),
+ );
+
+ const listForThread: RoutineDraftDispatcherShape["listForThread"] = (threadId) =>
+ Effect.gen(function* () {
+ const thread = Option.getOrUndefined(yield* snapshots.getThreadDetailById(threadId));
+ if (!thread || thread.archivedAt !== null) {
+ return yield* fail("The current chat is unavailable.");
+ }
+ const botId = thread.respondingBotId ?? thread.botId;
+ if (botId === null || botId === undefined) {
+ return yield* fail("Routines can only be inspected from a bot chat.");
+ }
+ const snapshot = yield* snapshots.getShellSnapshot();
+ const bot = snapshot.bots.find(
+ (candidate) => candidate.id === botId && candidate.archivedAt === null,
+ );
+ if (!bot) return yield* fail("The current bot is unavailable.");
+ return routineStatusesForBot(snapshot.routines ?? [], botId);
+ }).pipe(
+ Effect.mapError((cause) =>
+ Schema.is(RoutineDraftError)(cause)
+ ? cause
+ : fail(cause instanceof Error ? cause.message : String(cause)),
+ ),
+ );
+
+ const deleteForThread: RoutineDraftDispatcherShape["deleteForThread"] = (threadId, routineIds) =>
+ Effect.gen(function* () {
+ const thread = Option.getOrUndefined(yield* snapshots.getThreadDetailById(threadId));
+ if (!thread || thread.archivedAt !== null) {
+ return yield* fail("The current chat is unavailable.");
+ }
+ const botId = thread.respondingBotId ?? thread.botId;
+ if (botId === null || botId === undefined) {
+ return yield* fail("Routines can only be deleted from a bot chat.");
+ }
+ const snapshot = yield* snapshots.getShellSnapshot();
+ const bot = snapshot.bots.find(
+ (candidate) => candidate.id === botId && candidate.archivedAt === null,
+ );
+ if (!bot) return yield* fail("The current bot is unavailable.");
+
+ const uniqueRoutineIds = [...new Set(routineIds)];
+ if (uniqueRoutineIds.length === 0) {
+ return yield* fail("Select at least one routine to delete.");
+ }
+ const availableRoutineIds = new Set(
+ routineStatusesForBot(snapshot.routines ?? [], botId).map((routine) => routine.id),
+ );
+ if (uniqueRoutineIds.some((routineId) => !availableRoutineIds.has(routineId))) {
+ return yield* fail("One or more routines are unavailable.");
+ }
+
+ const createdAt = DateTime.formatIso(yield* DateTime.now);
+ const results = yield* Effect.forEach(uniqueRoutineIds, (routineId) =>
+ Effect.gen(function* () {
+ const uuid = yield* crypto.randomUUIDv4;
+ return yield* engine.dispatch({
+ type: "routine.delete",
+ commandId: CommandId.make(`agent:routine.delete:${uuid}`),
+ routineId,
+ createdAt,
+ });
+ }),
+ );
+ return {
+ routineIds: uniqueRoutineIds,
+ sequences: results.map((result) => result.sequence),
+ status: "deleted" as const,
+ };
+ }).pipe(
+ Effect.mapError((cause) =>
+ Schema.is(RoutineDraftError)(cause)
+ ? cause
+ : fail(cause instanceof Error ? cause.message : String(cause)),
+ ),
+ );
+
+ return {
+ createApprovedForThread,
+ listForThread,
+ deleteForThread,
+ } satisfies RoutineDraftDispatcherShape;
+});
+
+export const RoutineDraftDispatcherLive = Layer.effect(RoutineDraftDispatcher, make);
diff --git a/apps/server/src/routines/Runtime.ts b/apps/server/src/routines/Runtime.ts
new file mode 100644
index 000000000..20d0bacbc
--- /dev/null
+++ b/apps/server/src/routines/Runtime.ts
@@ -0,0 +1,22 @@
+import * as Context from "effect/Context";
+import type * as Effect from "effect/Effect";
+import type * as Scope from "effect/Scope";
+
+import type { PersistenceSqlError } from "../persistence/Errors.ts";
+import type { RoutineId, RoutineRun, RoutineRunId, RoutineRunTrigger } from "./types.ts";
+
+export interface RoutineRuntimeShape {
+ readonly runDue: Effect.Effect<void, never>;
+ readonly canRunNow: (routineId: RoutineId) => Effect.Effect<boolean, PersistenceSqlError>;
+ readonly runNow: (
+ routineId: RoutineId,
+ runId: RoutineRunId,
+ trigger: Extract<RoutineRunTrigger, "dry-run" | "manual">,
+ ) => Effect.Effect<RoutineRun | null, PersistenceSqlError>;
+ readonly recover: Effect.Effect<void, never>;
+ readonly start: Effect.Effect<void, never, Scope.Scope>;
+}
+
+export class RoutineRuntime extends Context.Service<RoutineRuntime, RoutineRuntimeShape>()(
+ "akeru-bot/routines/Runtime/RoutineRuntime",
+) {}
diff --git a/apps/server/src/routines/RuntimeAdapterLive.ts b/apps/server/src/routines/RuntimeAdapterLive.ts
new file mode 100644
index 000000000..ed8ed1c61
--- /dev/null
+++ b/apps/server/src/routines/RuntimeAdapterLive.ts
@@ -0,0 +1,305 @@
+import { CommandId, MessageId, ThreadId, type OrchestrationCommand } from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+
+import { BotInboxService, type BotInboxItem } from "../bot-inbox/service.ts";
+import { ServerConfig } from "../config.ts";
+import { isSubscriptionProviderId, SubscriptionAuthService } from "../subscription-auth/service.ts";
+import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
+import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import { ProjectionBotRepository } from "../persistence/Services/ProjectionBots.ts";
+import { ProjectionMcpServerRepository } from "../persistence/Services/ProjectionMcpServers.ts";
+import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
+import {
+ RoutineRuntimeAdapter,
+ type RoutineDependencyFailure,
+ type RoutineRuntimeAdapterShape,
+} from "./types.ts";
+
+export const findBlockingDependencyIncident = (
+ incidents: ReadonlyArray<BotInboxItem>,
+ botId: BotInboxItem["botId"],
+ connectorDependencies: ReadonlyArray<string>,
+) =>
+ incidents.find((incident) => {
+ if (
+ incident.botId !== botId ||
+ incident.status !== "open" ||
+ (incident.kind !== "oauth-expired" &&
+ incident.kind !== "connector-failure" &&
+ incident.kind !== "browser-dead")
+ ) {
+ return false;
+ }
+ const [, dependencyId] = incident.incidentKey.split(":");
+ if (!dependencyId) return false;
+ return connectorDependencies.some(
+ (id) => id === dependencyId || `mcp-${id}` === dependencyId || id === `mcp-${dependencyId}`,
+ );
+ });
+
+const make = Effect.gen(function* () {
+ const engine = yield* OrchestrationEngineService;
+ const bots = yield* ProjectionBotRepository;
+ const mcpServers = yield* ProjectionMcpServerRepository;
+ const snapshots = yield* ProjectionSnapshotQuery;
+ const providers = yield* ProviderRegistry;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const config = yield* ServerConfig;
+ const inbox = BotInboxService.forSecretsDir(config.secretsDir);
+ const subscriptionAuth = SubscriptionAuthService.forSecretsDir(config.secretsDir);
+
+ const dispatch = (command: OrchestrationCommand) => engine.dispatch(command);
+
+ const isTargetBusy: RoutineRuntimeAdapterShape["isTargetBusy"] = (routine) =>
+ snapshots.getThreadShellById(routine.targetThreadId).pipe(
+ Effect.map(
+ Option.match({
+ onNone: () => false,
+ onSome: (thread) =>
+ thread.latestTurn?.state === "running" ||
+ thread.session?.status === "starting" ||
+ thread.session?.status === "running",
+ }),
+ ),
+ Effect.orDie,
+ );
+
+ const checkDependencies: RoutineRuntimeAdapterShape["checkDependencies"] = (routine) =>
+ Effect.gen(function* () {
+ const bot = yield* bots.getById({ botId: routine.botId });
+ if (Option.isNone(bot) || bot.value.archivedAt !== null) {
+ return {
+ kind: "bot",
+ reason: "The assigned bot is archived or missing.",
+ nextAction: "Restore the bot, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ const target = yield* snapshots.getThreadShellById(routine.targetThreadId);
+ if (
+ Option.isNone(target) ||
+ target.value.archivedAt !== null ||
+ target.value.projectId !== routine.projectId ||
+ target.value.botId !== routine.botId
+ ) {
+ return {
+ kind: "workspace",
+ reason: "The routine chat is unavailable.",
+ nextAction: "Restore the bot chat, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ inbox.reload();
+ const dependencyIncident = findBlockingDependencyIncident(
+ inbox.list(),
+ routine.botId,
+ routine.connectorDependencies,
+ );
+ if (dependencyIncident !== undefined) {
+ return {
+ kind: dependencyIncident.kind === "browser-dead" ? "browser" : "connector",
+ reason: dependencyIncident.lastFailure,
+ nextAction: dependencyIncident.nextAction,
+ } satisfies RoutineDependencyFailure;
+ }
+
+ const project = yield* snapshots.getProjectShellById(routine.projectId);
+ if (Option.isNone(project) || !(yield* fileSystem.exists(project.value.workspaceRoot))) {
+ return {
+ kind: "workspace",
+ reason: "The routine workspace is unavailable.",
+ nextAction: "Restore the project workspace, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ const readModel = yield* snapshots.getCommandReadModel();
+ const missingSkill = routine.skillAssignmentIds.find(
+ (id) =>
+ !(readModel.skillAssignments ?? []).some(
+ (assignment) => assignment.id === id && assignment.botId === routine.botId,
+ ),
+ );
+ if (missingSkill !== undefined) {
+ return {
+ kind: "bot",
+ reason: `Assigned skill '${missingSkill}' is unavailable.`,
+ nextAction: "Assign the skill again, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ const configuredMcpServers = yield* mcpServers.listAll();
+ const unavailableConnector = routine.connectorDependencies.find(
+ (id) => !configuredMcpServers.some((server) => server.id === id && server.enabled),
+ );
+ if (unavailableConnector !== undefined) {
+ return {
+ kind: "connector",
+ reason: `Required connector '${unavailableConnector}' is unavailable.`,
+ nextAction: "Enable or reconnect the connector, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ const unhealthySubscription = routine.connectorDependencies.find((id) => {
+ if (!isSubscriptionProviderId(id)) return false;
+ const status = subscriptionAuth.statuses().find((entry) => entry.provider === id);
+ return (
+ status !== undefined &&
+ ["expired", "revoked", "failed", "failed-first-request"].includes(status.health)
+ );
+ });
+ if (unhealthySubscription !== undefined) {
+ return {
+ kind: "connector",
+ reason: `Required connector '${unhealthySubscription}' needs attention.`,
+ nextAction: "Reconnect the connector, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ const providerInstanceId = target.value.modelSelection.instanceId;
+ const providerSnapshots = yield* providers.getProviders;
+ if (!providerSnapshots.some((provider) => provider.instanceId === providerInstanceId)) {
+ return {
+ kind: "provider",
+ reason: `Provider '${providerInstanceId}' is unavailable.`,
+ nextAction: "Reconnect the provider, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ if (routine.sandbox !== "local") {
+ return {
+ kind: "execution",
+ reason: `Sandbox '${routine.sandbox}' is unavailable.`,
+ nextAction: "Restore the sandbox provider, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ }
+
+ inbox.resolve(`routine:${routine.id}`);
+ return null;
+ }).pipe(Effect.orDie);
+
+ const recordQueued: RoutineRuntimeAdapterShape["recordQueued"] = (run) =>
+ run.trigger === "scheduled" || run.trigger === "missed"
+ ? dispatch({
+ type: "routine.run.scheduled",
+ commandId: CommandId.make(`server:routine.run:${run.routineId}:${run.scheduledFor}`),
+ routineId: run.routineId,
+ runId: run.id,
+ trigger: run.trigger,
+ scheduledFor: run.scheduledFor,
+ createdAt: run.createdAt,
+ }).pipe(Effect.asVoid, Effect.orDie)
+ : Effect.void;
+
+ const recordBlocked: RoutineRuntimeAdapterShape["recordBlocked"] = (run, failure) =>
+ DateTime.now.pipe(
+ Effect.flatMap((now) =>
+ dispatch({
+ type: "routine.run.block",
+ commandId: CommandId.make(`server:routine.block:${run.id}`),
+ routineId: run.routineId,
+ runId: run.id,
+ failure: { kind: failure.kind, message: failure.reason },
+ createdAt: DateTime.formatIso(now),
+ }),
+ ),
+ Effect.asVoid,
+ Effect.orDie,
+ );
+
+ const recordCompleted: RoutineRuntimeAdapterShape["recordCompleted"] = (
+ run,
+ nextRunAt,
+ summary,
+ completedAt,
+ ) =>
+ dispatch({
+ type: "routine.run.complete",
+ commandId: CommandId.make(`server:routine.complete:${run.id}`),
+ routineId: run.routineId,
+ runId: run.id,
+ result: { summary },
+ usageRef: null,
+ nextRunAt,
+ createdAt: completedAt,
+ }).pipe(Effect.asVoid, Effect.orDie);
+
+ const recordFailed: RoutineRuntimeAdapterShape["recordFailed"] = (run, failure, completedAt) =>
+ dispatch({
+ type: "routine.run.fail",
+ commandId: CommandId.make(`server:routine.fail:${run.id}`),
+ routineId: run.routineId,
+ runId: run.id,
+ failure: { kind: failure.kind, message: failure.reason },
+ usageRef: null,
+ createdAt: completedAt,
+ }).pipe(Effect.asVoid, Effect.orDie);
+
+ const openFailureIncident: RoutineRuntimeAdapterShape["openFailureIncident"] = (
+ routine,
+ failure,
+ ) =>
+ Effect.gen(function* () {
+ const bot = yield* bots.getById({ botId: routine.botId });
+ inbox.ensureOpen({
+ incidentKey: `routine:${routine.id}`,
+ kind: "routine-failure",
+ botId: routine.botId,
+ botName: Option.isSome(bot) ? bot.value.name : "Bot",
+ taskOrRoutine: routine.job,
+ lastFailure: failure.reason,
+ nextAction: failure.nextAction,
+ });
+ }).pipe(Effect.orDie);
+
+ const resolveFailureIncident: RoutineRuntimeAdapterShape["resolveFailureIncident"] = (
+ routineId,
+ ) => Effect.sync(() => void inbox.resolve(`routine:${routineId}`));
+
+ const dispatchTurn: RoutineRuntimeAdapterShape["dispatchTurn"] = (routine, run) =>
+ Effect.gen(function* () {
+ const threadRef = routine.targetThreadId;
+ const createdAt = DateTime.formatIso(yield* DateTime.now);
+ yield* dispatch({
+ type: "routine.run.start",
+ commandId: CommandId.make(`server:routine.start:${run.id}`),
+ routineId: routine.id,
+ runId: run.id,
+ threadRef,
+ startedAt: createdAt,
+ });
+ yield* dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make(`server:routine.turn:${run.id}`),
+ threadId: threadRef,
+ message: {
+ messageId: MessageId.make(`routine:${run.id}:message`),
+ role: "user",
+ text: `Execute this routine now. Do not create or change a schedule.\n\n${routine.procedure}`,
+ attachments: [],
+ },
+ titleSeed: routine.job,
+ runtimeMode: routine.approvalPolicy,
+ interactionMode: "default",
+ createdAt,
+ });
+ return { threadRef };
+ }).pipe(Effect.orDie);
+
+ return {
+ checkDependencies,
+ isTargetBusy,
+ recordQueued,
+ recordBlocked,
+ recordCompleted,
+ recordFailed,
+ openFailureIncident,
+ resolveFailureIncident,
+ dispatchTurn,
+ } satisfies RoutineRuntimeAdapterShape;
+});
+
+export const RoutineRuntimeAdapterLive = Layer.effect(RoutineRuntimeAdapter, make);
diff --git a/apps/server/src/routines/RuntimeLive.test.ts b/apps/server/src/routines/RuntimeLive.test.ts
new file mode 100644
index 000000000..f1281a295
--- /dev/null
+++ b/apps/server/src/routines/RuntimeLive.test.ts
@@ -0,0 +1,399 @@
+import {
+ BotId,
+ EventId,
+ type OrchestrationEvent,
+ ProjectId,
+ RoutineId,
+ RoutineRunId,
+ ThreadId,
+} from "@t3tools/contracts";
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Stream from "effect/Stream";
+import * as TestClock from "effect/testing/TestClock";
+
+import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
+import { RoutineRepository, type RoutineClaim, type RoutineRepositoryShape } from "./Repository.ts";
+import { RoutineRuntime } from "./Runtime.ts";
+import { findBlockingDependencyIncident } from "./RuntimeAdapterLive.ts";
+import { RoutineRuntimeLive } from "./RuntimeLive.ts";
+import {
+ RoutineRuntimeAdapter,
+ type Routine,
+ type RoutineDependencyFailure,
+ type RoutineRun,
+ type RoutineRuntimeAdapterShape,
+} from "./types.ts";
+
+const routine = (overrides: Partial<Routine> = {}): Routine => ({
+ id: RoutineId.make("routine-1"),
+ botId: BotId.make("bot-1"),
+ targetThreadId: ThreadId.make("thread-1"),
+ projectId: ProjectId.make("project-1"),
+ job: "Morning research",
+ procedure: "Prepare the morning research brief.",
+ procedureVersion: 2,
+ approvalVersion: 2,
+ schedule: { kind: "daily", time: "09:00" },
+ timezone: "America/New_York",
+ skillAssignmentIds: [],
+ connectorDependencies: [],
+ sandbox: "local",
+ approvalPolicy: "approval-required",
+ enabled: true,
+ lifecycle: "enabled",
+ nextRunAt: "2026-08-28T13:00:00.000Z",
+ lastRunAt: null,
+ latestResult: null,
+ latestFailure: null,
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ deletedAt: null,
+ ...overrides,
+});
+
+const harness = (
+ value: Routine,
+ recoverable: ReadonlyArray<RoutineClaim> = [],
+ dependencyFailure: RoutineDependencyFailure | null = null,
+ targetBusy = false,
+ domainEvents: Stream.Stream<OrchestrationEvent> = Stream.empty,
+ projectedStatus: RoutineRun["status"] | null = null,
+) => {
+ const claims = new Map<string, RoutineClaim>();
+ const events: string[] = [];
+ const repository = RoutineRepository.of({
+ listAll: Effect.succeed([value]),
+ listEnabled: Effect.succeed([value]),
+ getById: () => Effect.succeed(value),
+ listRuns: () =>
+ Effect.succeed(
+ recoverable.map((claim) => ({
+ id: claim.runId,
+ routineId: claim.routineId,
+ procedureVersion: value.procedureVersion,
+ trigger:
+ claim.trigger === "manual" || claim.trigger === "dry-run" ? "manual" : claim.trigger,
+ scheduledFor:
+ claim.trigger === "manual" || claim.trigger === "dry-run" ? null : claim.scheduledFor,
+ status: projectedStatus ?? ("running" as const),
+ result: null,
+ failure: null,
+ usageRef: null,
+ threadRef: ThreadId.make("thread-1"),
+ startedAt: claim.claimedAt,
+ completedAt: null,
+ createdAt: claim.claimedAt,
+ updatedAt: claim.claimedAt,
+ })) as never,
+ ),
+ listAllRuns: Effect.succeed([]),
+ getActiveRunByThreadRef: () => Effect.succeed(null),
+ listSkillAssignments: Effect.succeed([]),
+ claim: (claim) =>
+ Effect.sync(() => {
+ const key =
+ claim.scheduledFor === null ? claim.runId : `${claim.routineId}:${claim.scheduledFor}`;
+ if (claims.has(key)) return false;
+ claims.set(key, claim);
+ events.push(`claimed:${claim.trigger}:${claim.scheduledFor}`);
+ return true;
+ }),
+ markDispatched: () => Effect.sync(() => events.push("dispatched")),
+ markBlocked: () => Effect.sync(() => events.push("claim-blocked")),
+ markSettled: () => Effect.sync(() => events.push("claim-settled")),
+ listRecoverable: Effect.succeed(recoverable),
+ } satisfies RoutineRepositoryShape);
+ const adapter = RoutineRuntimeAdapter.of({
+ isTargetBusy: () => Effect.succeed(targetBusy),
+ checkDependencies: () => Effect.succeed(dependencyFailure),
+ recordQueued: () => Effect.sync(() => events.push("queued")),
+ recordBlocked: () => Effect.sync(() => events.push("run-blocked")),
+ recordCompleted: () => Effect.sync(() => events.push("completed")),
+ recordFailed: () => Effect.void,
+ openFailureIncident: () => Effect.sync(() => events.push("incident")),
+ resolveFailureIncident: (routineId) =>
+ Effect.sync(() => events.push(`incident-resolved:${routineId}`)),
+ dispatchTurn: () =>
+ Effect.sync(() => {
+ events.push("turn");
+ return { threadRef: ThreadId.make("thread-1") };
+ }),
+ } satisfies RoutineRuntimeAdapterShape);
+ const layer = RoutineRuntimeLive.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.succeed(RoutineRepository, repository),
+ Layer.succeed(RoutineRuntimeAdapter, adapter),
+ Layer.succeed(OrchestrationEngineService, {
+ dispatch: () => Effect.die("unused"),
+ readEvents: () => Stream.empty,
+ streamDomainEvents: domainEvents,
+ latestSequence: Effect.succeed(0),
+ }),
+ ),
+ ),
+ );
+ return { events, layer };
+};
+
+it.effect("resolves a routine incident when the routine is deleted", () => {
+ const value = routine();
+ const deleted = {
+ sequence: 1,
+ eventId: EventId.make("event-routine-deleted"),
+ aggregateKind: "routine",
+ aggregateId: value.id,
+ occurredAt: "2026-08-01T00:00:00.000Z",
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "routine.deleted",
+ payload: {
+ routine: {
+ ...value,
+ enabled: false,
+ lifecycle: "deleted",
+ nextRunAt: null,
+ deletedAt: "2026-08-01T00:00:00.000Z",
+ },
+ },
+ } satisfies Extract<OrchestrationEvent, { type: "routine.deleted" }>;
+ const test = harness(value, [], null, false, Stream.make(deleted));
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-08-01T00:00:00.000Z"));
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.start;
+ yield* Effect.yieldNow;
+ assert(test.events.includes(`incident-resolved:${value.id}`));
+ }),
+ ).pipe(Effect.provide(test.layer));
+});
+
+it.effect("resolves stale incidents for routines deleted before restart", () => {
+ const value = routine({ enabled: false, lifecycle: "deleted", nextRunAt: null });
+ const test = harness(value);
+
+ return Effect.gen(function* () {
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.recover;
+ assert.deepEqual(test.events, [`incident-resolved:${value.id}`]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it("finds open connector and browser incidents for the routine bot", () => {
+ const item = {
+ id: "incident-1",
+ incidentKey: "connector:gmail:bot-1",
+ kind: "oauth-expired" as const,
+ status: "open" as const,
+ botId: BotId.make("bot-1"),
+ botName: "Inbox bot",
+ taskOrRoutine: "Gmail access",
+ lastFailure: "OAuth expired.",
+ nextAction: "Reconnect Gmail.",
+ firstSeenAt: "2026-08-31T12:00:00.000Z",
+ lastSeenAt: "2026-08-31T12:00:00.000Z",
+ occurrenceCount: 1,
+ };
+
+ assert.strictEqual(findBlockingDependencyIncident([item], BotId.make("bot-1"), ["gmail"]), item);
+ assert.strictEqual(
+ findBlockingDependencyIncident([item], BotId.make("bot-1"), ["slack"]),
+ undefined,
+ );
+ assert.strictEqual(
+ findBlockingDependencyIncident([item], BotId.make("bot-2"), ["gmail"]),
+ undefined,
+ );
+ assert.strictEqual(
+ findBlockingDependencyIncident([{ ...item, status: "resolved" }], BotId.make("bot-1"), [
+ "gmail",
+ ]),
+ undefined,
+ );
+});
+
+it.effect("coalesces missed slots and claims each slot once", () => {
+ const test = harness(routine());
+ return Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-08-31T20:00:00.000Z"));
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.runDue;
+ yield* runtime.runDue;
+ assert.deepEqual(test.events, [
+ "claimed:missed:2026-08-31T13:00:00.000Z",
+ "queued",
+ "turn",
+ "dispatched",
+ ]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("defers a due run while its target chat is busy", () => {
+ const test = harness(routine(), [], null, true);
+ return Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-08-31T20:00:00.000Z"));
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.runDue;
+ assert.deepEqual(test.events, []);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("settles a dispatched run from durable terminal state after restart", () => {
+ const value = routine();
+ const test = harness(value, [
+ {
+ runId: RoutineRunId.make("run-1"),
+ routineId: value.id,
+ trigger: "scheduled",
+ scheduledFor: "2026-08-31T13:00:00.000Z",
+ claimedAt: "2026-08-31T13:00:00.000Z",
+ status: "dispatched",
+ threadRef: "thread-1",
+ terminalState: "completed",
+ terminalAt: "2026-08-31T13:05:00.000Z",
+ },
+ ]);
+ return Effect.gen(function* () {
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.recover;
+ assert.deepEqual(test.events, ["completed", "claim-settled"]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("leaves an in-flight dispatched run attached after restart", () => {
+ const value = routine();
+ const test = harness(value, [
+ {
+ runId: RoutineRunId.make("run-in-flight"),
+ routineId: value.id,
+ trigger: "manual",
+ scheduledFor: null,
+ claimedAt: "2026-08-31T13:00:00.000Z",
+ status: "dispatched",
+ threadRef: "thread-1",
+ terminalState: null,
+ terminalAt: null,
+ },
+ ]);
+ return Effect.gen(function* () {
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.recover;
+ assert.deepEqual(test.events, []);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("blocks a dispatched run whose session stopped before a turn", () => {
+ const value = routine();
+ const test = harness(value, [
+ {
+ runId: RoutineRunId.make("run-stopped"),
+ routineId: value.id,
+ trigger: "manual",
+ scheduledFor: null,
+ claimedAt: "2026-08-31T13:00:00.000Z",
+ status: "dispatched",
+ threadRef: "thread-1",
+ terminalState: null,
+ terminalAt: null,
+ sessionState: "stopped",
+ sessionUpdatedAt: "2026-08-31T13:01:00.000Z",
+ },
+ ]);
+ return Effect.gen(function* () {
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.recover;
+ assert.deepEqual(test.events, ["incident", "claim-blocked"]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("does not restart a claim whose projected run is already blocked", () => {
+ const value = routine({ enabled: false, lifecycle: "blocked", nextRunAt: null });
+ const test = harness(
+ value,
+ [
+ {
+ runId: RoutineRunId.make("run-blocked-before-claim-update"),
+ routineId: value.id,
+ trigger: "scheduled",
+ scheduledFor: "2026-08-31T13:00:00.000Z",
+ claimedAt: "2026-08-31T13:00:00.000Z",
+ status: "claimed",
+ threadRef: null,
+ terminalState: null,
+ terminalAt: null,
+ },
+ ],
+ null,
+ false,
+ Stream.empty,
+ "blocked",
+ );
+ return Effect.gen(function* () {
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.recover;
+ assert.deepEqual(test.events, ["claim-blocked"]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("validates dry runs without dispatching a provider turn", () => {
+ const test = harness(routine());
+ return Effect.gen(function* () {
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.runNow(RoutineId.make("routine-1"), RoutineRunId.make("manual-1"), "manual");
+ yield* runtime.runNow(RoutineId.make("routine-1"), RoutineRunId.make("dry-1"), "dry-run");
+ assert.deepEqual(test.events, [
+ "claimed:manual:null",
+ "queued",
+ "turn",
+ "dispatched",
+ "claimed:dry-run:null",
+ "queued",
+ "completed",
+ "claim-settled",
+ ]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("blocks an unapproved routine and opens one incident", () => {
+ const test = harness(routine({ approvalVersion: 1 }));
+ return Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-08-31T20:00:00.000Z"));
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.runDue;
+ yield* runtime.runDue;
+ assert.deepEqual(test.events, [
+ "claimed:missed:2026-08-31T13:00:00.000Z",
+ "queued",
+ "run-blocked",
+ "incident",
+ "claim-blocked",
+ ]);
+ }).pipe(Effect.provide(test.layer));
+});
+
+it.effect("blocks a broken connector without retrying the same slot", () => {
+ const test = harness(routine(), [], {
+ kind: "connector",
+ reason: "Required connector 'gmail' is unavailable.",
+ nextAction: "Reconnect the connector, then resume the routine.",
+ });
+ return Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-08-31T20:00:00.000Z"));
+ const runtime = yield* RoutineRuntime;
+ yield* runtime.runDue;
+ yield* runtime.runDue;
+ assert.deepEqual(test.events, [
+ "claimed:missed:2026-08-31T13:00:00.000Z",
+ "queued",
+ "run-blocked",
+ "incident",
+ "claim-blocked",
+ ]);
+ }).pipe(Effect.provide(test.layer));
+});
diff --git a/apps/server/src/routines/RuntimeLive.ts b/apps/server/src/routines/RuntimeLive.ts
new file mode 100644
index 000000000..8e70d5846
--- /dev/null
+++ b/apps/server/src/routines/RuntimeLive.ts
@@ -0,0 +1,332 @@
+import { RoutineRunId, type OrchestrationEvent } from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schedule from "effect/Schedule";
+import * as Stream from "effect/Stream";
+
+import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
+import { RoutineRepository, type RoutineClaim } from "./Repository.ts";
+import { RoutineRuntime, type RoutineRuntimeShape } from "./Runtime.ts";
+import { latestScheduledFor, nextScheduledFor } from "./schedule.ts";
+import {
+ RoutineRuntimeAdapter,
+ type Routine,
+ type RoutineDependencyFailure,
+ type RoutineRun,
+ type RoutineRunTrigger,
+} from "./types.ts";
+
+const approvalFailure: RoutineDependencyFailure = {
+ kind: "approval",
+ reason: "The approved procedure version is not current.",
+ nextAction: "Review and approve the current procedure, then resume the routine.",
+};
+
+const makeRun = (routine: Routine, claim: RoutineClaim): RoutineRun => {
+ const base = {
+ id: claim.runId,
+ routineId: claim.routineId,
+ procedureVersion: routine.procedureVersion,
+ status: "queued" as const,
+ threadRef: null,
+ result: null,
+ failure: null,
+ usageRef: null,
+ startedAt: null,
+ completedAt: null,
+ createdAt: claim.claimedAt,
+ updatedAt: claim.claimedAt,
+ };
+ if (claim.scheduledFor === null) {
+ return { ...base, trigger: claim.trigger, scheduledFor: null };
+ }
+ return { ...base, trigger: claim.trigger, scheduledFor: claim.scheduledFor };
+};
+
+const makeRunId = (routineId: string, scheduledFor: string) =>
+ RoutineRunId.make(`routine:${routineId}:${scheduledFor}`);
+
+const make = Effect.gen(function* () {
+ const repository = yield* RoutineRepository;
+ const adapter = yield* RoutineRuntimeAdapter;
+ const engine = yield* Effect.serviceOption(OrchestrationEngineService);
+
+ const block = Effect.fn("RoutineRuntime.block")(function* (
+ routine: Routine,
+ run: RoutineRun,
+ failure: RoutineDependencyFailure,
+ ) {
+ const completedAt = DateTime.formatIso(yield* DateTime.now);
+ yield* adapter.recordBlocked(run, failure);
+ yield* adapter.openFailureIncident(routine, failure);
+ yield* repository.markBlocked(run.id, failure.reason, completedAt);
+ });
+
+ const execute = Effect.fn("RoutineRuntime.execute")(function* (
+ routine: Routine,
+ claim: RoutineClaim,
+ ) {
+ const run = makeRun(routine, claim);
+ yield* adapter.recordQueued(run);
+
+ const failure =
+ claim.trigger !== "dry-run" && routine.approvalVersion !== routine.procedureVersion
+ ? approvalFailure
+ : yield* adapter.checkDependencies(routine);
+ if (failure !== null) {
+ yield* block(routine, run, failure);
+ return run;
+ }
+
+ if (claim.trigger === "dry-run") {
+ const completedAt = DateTime.formatIso(yield* DateTime.now);
+ yield* adapter.recordCompleted(run, routine.nextRunAt, "Dry run passed.", completedAt);
+ yield* repository.markSettled(run.id, "completed", completedAt);
+ return { ...run, status: "completed" as const, completedAt, summary: "Dry run passed." };
+ }
+
+ const dispatched = yield* adapter.dispatchTurn(routine, run);
+ yield* repository.markDispatched(run.id, dispatched.threadRef);
+ return { ...run, status: "running" as const, ...dispatched };
+ });
+
+ const claimAndExecute = Effect.fn("RoutineRuntime.claimAndExecute")(function* (
+ routine: Routine,
+ trigger: Extract<RoutineRunTrigger, "scheduled" | "missed">,
+ scheduledFor: string,
+ claimedAt: string,
+ ) {
+ if (yield* adapter.isTargetBusy(routine)) return null;
+ const claim = {
+ runId: makeRunId(routine.id, scheduledFor),
+ routineId: routine.id,
+ trigger,
+ scheduledFor,
+ claimedAt,
+ } satisfies RoutineClaim;
+ if (!(yield* repository.claim(claim))) return null;
+ return yield* execute(routine, claim);
+ });
+
+ const runDue = Effect.gen(function* () {
+ const nowEpochMillis = yield* Clock.currentTimeMillis;
+ const now = DateTime.formatIso(yield* DateTime.now);
+ const routines = yield* repository.listEnabled;
+ for (const routine of routines) {
+ if (routine.nextRunAt === null || Date.parse(routine.nextRunAt) > nowEpochMillis) continue;
+ const scheduledFor = latestScheduledFor(routine.schedule, routine.timezone, nowEpochMillis);
+ const trigger = scheduledFor === routine.nextRunAt ? "scheduled" : "missed";
+ yield* claimAndExecute(routine, trigger, scheduledFor, now);
+ }
+ }).pipe(
+ Effect.catchCause((cause) => Effect.logError("routine scheduler tick failed", { cause })),
+ );
+
+ const canRunNow: RoutineRuntimeShape["canRunNow"] = (routineId) =>
+ Effect.gen(function* () {
+ const routine = yield* repository.getById(routineId);
+ return (
+ routine !== null &&
+ routine.lifecycle !== "deleted" &&
+ !(yield* adapter.isTargetBusy(routine))
+ );
+ });
+
+ const runNow: RoutineRuntimeShape["runNow"] = (routineId, runId, trigger) =>
+ Effect.gen(function* () {
+ const routine = yield* repository.getById(routineId);
+ if (routine === null || routine.lifecycle === "deleted") return null;
+ const now = DateTime.formatIso(yield* DateTime.now);
+ const claim = {
+ runId,
+ routineId,
+ trigger,
+ scheduledFor: null,
+ claimedAt: now,
+ } satisfies RoutineClaim;
+ if (!(yield* repository.claim(claim))) return null;
+ return yield* execute(routine, claim);
+ });
+
+ const settleRunForEvent = Effect.fn("RoutineRuntime.settleRunForEvent")(function* (
+ event: OrchestrationEvent,
+ ) {
+ if (event.type === "routine.deleted") {
+ yield* adapter.resolveFailureIncident(event.payload.routine.id);
+ return;
+ }
+ if (event.type !== "thread.turn-diff-completed" && event.type !== "thread.session-set") return;
+ if (
+ event.type === "thread.session-set" &&
+ event.payload.session.status !== "ready" &&
+ event.payload.session.status !== "error" &&
+ event.payload.session.status !== "interrupted" &&
+ event.payload.session.status !== "stopped"
+ )
+ return;
+ const threadRef = event.payload.threadId;
+ const run = yield* repository.getActiveRunByThreadRef(
+ threadRef,
+ event.type === "thread.turn-diff-completed" ? event.payload.turnId : null,
+ );
+ if (run === null) return;
+ const routine = yield* repository.getById(run.routineId);
+ if (routine === null || routine.lifecycle === "deleted") return;
+ const completedAt =
+ event.type === "thread.turn-diff-completed"
+ ? event.payload.completedAt
+ : event.payload.session.updatedAt;
+ if (
+ (event.type === "thread.turn-diff-completed" && event.payload.status === "ready") ||
+ (event.type === "thread.session-set" && event.payload.session.status === "ready")
+ ) {
+ const nextRunAt = routine.enabled
+ ? nextScheduledFor(routine.schedule, routine.timezone, Date.parse(completedAt))
+ : null;
+ yield* adapter.recordCompleted(run, nextRunAt, "Routine completed.", completedAt);
+ yield* repository.markSettled(run.id, "completed", completedAt);
+ return;
+ }
+ const failure = {
+ kind: "execution",
+ reason:
+ event.type === "thread.turn-diff-completed"
+ ? `Routine checkpoint ended with status '${event.payload.status}'.`
+ : (event.payload.session.lastError ??
+ `Routine session ended with status '${event.payload.session.status}'.`),
+ nextAction: "Review the routine thread, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ yield* adapter.recordFailed(run, failure, completedAt);
+ yield* adapter.openFailureIncident(routine, failure);
+ yield* repository.markBlocked(run.id, failure.reason, completedAt);
+ });
+
+ const recover = Effect.gen(function* () {
+ for (const routine of yield* repository.listAll) {
+ if (routine.lifecycle === "deleted") yield* adapter.resolveFailureIncident(routine.id);
+ }
+ for (const claim of yield* repository.listRecoverable) {
+ const routine = yield* repository.getById(claim.routineId);
+ if (routine === null || routine.lifecycle === "deleted") {
+ yield* repository.markBlocked(
+ claim.runId,
+ "The routine no longer exists.",
+ DateTime.formatIso(yield* DateTime.now),
+ );
+ continue;
+ }
+ const projectedRun = (yield* repository.listRuns(claim.routineId)).find(
+ (candidate) => candidate.id === claim.runId,
+ );
+ if (projectedRun?.status === "completed") {
+ yield* repository.markSettled(
+ claim.runId,
+ "completed",
+ projectedRun.completedAt ?? projectedRun.updatedAt,
+ );
+ continue;
+ }
+ if (projectedRun?.status === "blocked") {
+ yield* repository.markBlocked(
+ claim.runId,
+ projectedRun.failure?.message ?? "The routine run was blocked.",
+ projectedRun.completedAt ?? projectedRun.updatedAt,
+ );
+ continue;
+ }
+ if (projectedRun?.status === "failed" || projectedRun?.status === "canceled") {
+ yield* repository.markSettled(
+ claim.runId,
+ "failed",
+ projectedRun.completedAt ?? projectedRun.updatedAt,
+ );
+ continue;
+ }
+ if (
+ claim.status === "dispatched" &&
+ claim.terminalState !== null &&
+ claim.terminalState !== undefined
+ ) {
+ const run = (yield* repository.listRuns(claim.routineId)).find(
+ (candidate) => candidate.id === claim.runId,
+ );
+ if (run !== undefined) {
+ const completedAt = claim.terminalAt ?? DateTime.formatIso(yield* DateTime.now);
+ if (claim.terminalState === "completed") {
+ const nextRunAt = routine.enabled
+ ? nextScheduledFor(routine.schedule, routine.timezone, Date.parse(completedAt))
+ : null;
+ yield* adapter.recordCompleted(run, nextRunAt, "Routine completed.", completedAt);
+ yield* repository.markSettled(run.id, "completed", completedAt);
+ } else {
+ const failure = {
+ kind: "execution",
+ reason: `Routine thread ended with state '${claim.terminalState}'.`,
+ nextAction: "Review the routine thread, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ yield* adapter.recordFailed(run, failure, completedAt);
+ yield* adapter.openFailureIncident(routine, failure);
+ yield* repository.markBlocked(run.id, failure.reason, completedAt);
+ }
+ continue;
+ }
+ }
+ if (
+ claim.status === "dispatched" &&
+ claim.sessionState !== undefined &&
+ claim.sessionState !== null &&
+ claim.sessionState !== "ready" &&
+ claim.sessionState !== "starting" &&
+ claim.sessionState !== "running"
+ ) {
+ const completedAt = claim.sessionUpdatedAt ?? DateTime.formatIso(yield* DateTime.now);
+ const run = (yield* repository.listRuns(claim.routineId)).find(
+ (candidate) => candidate.id === claim.runId,
+ );
+ if (run !== undefined) {
+ const failure = {
+ kind: "execution",
+ reason: `Routine session ended with state '${claim.sessionState}'.`,
+ nextAction: "Review the routine thread, then resume the routine.",
+ } satisfies RoutineDependencyFailure;
+ yield* adapter.recordFailed(run, failure, completedAt);
+ yield* adapter.openFailureIncident(routine, failure);
+ yield* repository.markBlocked(run.id, failure.reason, completedAt);
+ }
+ continue;
+ }
+ if (claim.status === "dispatched") continue;
+ yield* execute(routine, claim);
+ }
+ }).pipe(
+ Effect.catchCause((cause) => Effect.logError("routine scheduler recovery failed", { cause })),
+ );
+
+ const start = Effect.gen(function* () {
+ if (Option.isSome(engine)) {
+ yield* Effect.forkScoped(
+ engine.value.streamDomainEvents.pipe(
+ Stream.runForEach((event) =>
+ settleRunForEvent(event).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logError("routine run settlement failed", { cause }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+ yield* recover;
+ yield* runDue;
+ yield* Effect.forkScoped(
+ recover.pipe(Effect.andThen(runDue), Effect.repeat(Schedule.spaced("1 minute"))),
+ );
+ });
+
+ return { runDue, canRunNow, runNow, recover, start } satisfies RoutineRuntimeShape;
+});
+
+export const RoutineRuntimeLive = Layer.effect(RoutineRuntime, make);
diff --git a/apps/server/src/routines/layer.ts b/apps/server/src/routines/layer.ts
new file mode 100644
index 000000000..cdbd076d2
--- /dev/null
+++ b/apps/server/src/routines/layer.ts
@@ -0,0 +1,9 @@
+import * as Layer from "effect/Layer";
+
+import { RoutineRepositoryLive } from "./RepositoryLive.ts";
+import { RoutineRuntimeLive } from "./RuntimeLive.ts";
+import { RoutineRuntimeAdapterLive } from "./RuntimeAdapterLive.ts";
+
+export const RoutineLayerLive = RoutineRuntimeLive.pipe(
+ Layer.provide(Layer.mergeAll(RoutineRepositoryLive, RoutineRuntimeAdapterLive)),
+);
diff --git a/apps/server/src/routines/schedule.test.ts b/apps/server/src/routines/schedule.test.ts
new file mode 100644
index 000000000..934996a63
--- /dev/null
+++ b/apps/server/src/routines/schedule.test.ts
@@ -0,0 +1,25 @@
+import { assert, it } from "@effect/vitest";
+
+import { latestScheduledFor, nextScheduledFor } from "./schedule.ts";
+
+it("keeps daily wall time across daylight saving changes", () => {
+ assert.equal(
+ nextScheduledFor(
+ { kind: "daily", time: "09:00" },
+ "America/New_York",
+ Date.parse("2026-03-07T15:00:00.000Z"),
+ ),
+ "2026-03-08T13:00:00.000Z",
+ );
+});
+
+it("finds the latest weekday slot for missed-run coalescing", () => {
+ assert.equal(
+ latestScheduledFor(
+ { kind: "weekdays", time: "09:00" },
+ "America/New_York",
+ Date.parse("2026-08-31T20:00:00.000Z"),
+ ),
+ "2026-08-31T13:00:00.000Z",
+ );
+});
diff --git a/apps/server/src/routines/schedule.ts b/apps/server/src/routines/schedule.ts
new file mode 100644
index 000000000..c99d06a66
--- /dev/null
+++ b/apps/server/src/routines/schedule.ts
@@ -0,0 +1,100 @@
+import * as DateTime from "effect/DateTime";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+
+import type { RoutineSchedule, RoutineWeekday } from "./types.ts";
+
+export class RoutineScheduleError extends Schema.TaggedErrorClass<RoutineScheduleError>()(
+ "RoutineScheduleError",
+ { detail: Schema.String },
+) {}
+
+const parseTime = (time: string): readonly [hour: number, minute: number] => {
+ const match = /^(?:[01]\d|2[0-3]):[0-5]\d$/.exec(time);
+ if (match === null) throw new RoutineScheduleError({ detail: `Invalid routine time: ${time}` });
+ return [Number(time.slice(0, 2)), Number(time.slice(3, 5))];
+};
+
+const matchesDay = (schedule: RoutineSchedule, weekDay: number) => {
+ switch (schedule.kind) {
+ case "daily":
+ return true;
+ case "weekdays":
+ return weekDay >= 1 && weekDay <= 5;
+ case "weekly":
+ return schedule.weekdays.includes(weekdays[weekDay]!);
+ }
+};
+
+const weekdays: ReadonlyArray<RoutineWeekday> = [
+ "sunday",
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+];
+
+const candidateForDay = (
+ day: DateTime.Zoned,
+ schedule: RoutineSchedule,
+ timezone: string,
+): DateTime.Zoned => {
+ const [hour, minute] = parseTime(schedule.time);
+ const parts = DateTime.toParts(day);
+ const candidate = DateTime.makeZoned(
+ {
+ year: parts.year,
+ month: parts.month,
+ day: parts.day,
+ hour,
+ minute,
+ },
+ { timeZone: timezone, adjustForTimeZone: true },
+ );
+ if (Option.isNone(candidate)) {
+ throw new RoutineScheduleError({ detail: `Invalid routine timezone: ${timezone}` });
+ }
+ return candidate.value;
+};
+
+export const latestScheduledFor = (
+ schedule: RoutineSchedule,
+ timezone: string,
+ nowEpochMillis: number,
+): string => {
+ const now = DateTime.makeZoned(nowEpochMillis, { timeZone: timezone });
+ if (Option.isNone(now)) {
+ throw new RoutineScheduleError({ detail: `Invalid routine timezone: ${timezone}` });
+ }
+
+ for (let daysBack = 0; daysBack <= 7; daysBack += 1) {
+ const day = DateTime.subtract(now.value, { days: daysBack });
+ if (!matchesDay(schedule, DateTime.toParts(day).weekDay)) continue;
+ const candidate = candidateForDay(day, schedule, timezone);
+ if (DateTime.toEpochMillis(candidate) <= nowEpochMillis) return DateTime.formatIso(candidate);
+ }
+
+ throw new RoutineScheduleError({ detail: "Routine schedule has no matching day." });
+};
+
+export const nextScheduledFor = (
+ schedule: RoutineSchedule,
+ timezone: string,
+ afterEpochMillis: number,
+): string => {
+ const after = DateTime.makeZoned(afterEpochMillis, { timeZone: timezone });
+ if (Option.isNone(after)) {
+ throw new RoutineScheduleError({ detail: `Invalid routine timezone: ${timezone}` });
+ }
+
+ for (let daysAhead = 0; daysAhead <= 7; daysAhead += 1) {
+ const day = DateTime.add(after.value, { days: daysAhead });
+ if (!matchesDay(schedule, DateTime.toParts(day).weekDay)) continue;
+ const candidate = candidateForDay(day, schedule, timezone);
+ if (DateTime.toEpochMillis(candidate) > afterEpochMillis) return DateTime.formatIso(candidate);
+ }
+
+ throw new RoutineScheduleError({ detail: "Routine schedule has no matching day." });
+};
diff --git a/apps/server/src/routines/types.ts b/apps/server/src/routines/types.ts
new file mode 100644
index 000000000..3fb01b9b6
--- /dev/null
+++ b/apps/server/src/routines/types.ts
@@ -0,0 +1,68 @@
+import type {
+ Routine,
+ RoutineId,
+ RoutineFailureKind,
+ RoutineRun,
+ RoutineRunId,
+ RoutineRunTrigger,
+ RoutineSchedule,
+ RoutineWeekday,
+ ThreadId,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import type * as Effect from "effect/Effect";
+
+export type {
+ Routine,
+ RoutineId,
+ RoutineRun,
+ RoutineRunId,
+ RoutineRunTrigger,
+ RoutineSchedule,
+ RoutineWeekday,
+};
+
+export interface RoutineDependencyFailure {
+ readonly kind: RoutineFailureKind;
+ readonly reason: string;
+ readonly nextAction: string;
+}
+
+export interface RoutineDispatchResult {
+ readonly threadRef: ThreadId;
+}
+
+export interface RoutineRuntimeAdapterShape {
+ readonly isTargetBusy: (routine: Routine) => Effect.Effect<boolean>;
+ readonly checkDependencies: (routine: Routine) => Effect.Effect<RoutineDependencyFailure | null>;
+ readonly recordQueued: (run: RoutineRun) => Effect.Effect<void>;
+ readonly recordBlocked: (
+ run: RoutineRun,
+ failure: RoutineDependencyFailure,
+ ) => Effect.Effect<void>;
+ readonly recordCompleted: (
+ run: RoutineRun,
+ nextRunAt: string | null,
+ summary: string,
+ completedAt: string,
+ ) => Effect.Effect<void>;
+ readonly recordFailed: (
+ run: RoutineRun,
+ failure: RoutineDependencyFailure,
+ completedAt: string,
+ ) => Effect.Effect<void>;
+ readonly openFailureIncident: (
+ routine: Routine,
+ failure: RoutineDependencyFailure,
+ ) => Effect.Effect<void, never>;
+ readonly resolveFailureIncident: (routineId: RoutineId) => Effect.Effect<void, never>;
+ readonly dispatchTurn: (
+ routine: Routine,
+ run: RoutineRun,
+ ) => Effect.Effect<RoutineDispatchResult>;
+}
+
+export class RoutineRuntimeAdapter extends Context.Service<
+ RoutineRuntimeAdapter,
+ RoutineRuntimeAdapterShape
+>()("akeru-bot/routines/types/RoutineRuntimeAdapter") {}
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 06c6f98d0..9d2238798 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -29,6 +29,8 @@ import {
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
+ RoutineId,
+ RoutineRunId,
ResolvedKeybindingRule,
ThreadId,
TurnId,
@@ -156,6 +158,8 @@ import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import { BotUsageLedger, type BotUsageLedgerShape } from "./usage/BotUsageLedger.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
+import { RoutineRepository, type RoutineRepositoryShape } from "./routines/Repository.ts";
+import { RoutineRuntime, type RoutineRuntimeShape } from "./routines/Runtime.ts";
import * as Data from "effect/Data";
import { makeOrchestrationIntegrationHarness } from "../integration/OrchestrationEngineHarness.integration.ts";
@@ -431,6 +435,14 @@ const buildAppUnderTest = (options?: {
>;
terminalManager?: Partial<TerminalManager.TerminalManager["Service"]>;
orchestrationEngine?: Partial<OrchestrationEngine.OrchestrationEngineService["Service"]>;
+ routineRepository?: Partial<RoutineRepositoryShape>;
+ routineRuntime?: Partial<RoutineRuntimeShape>;
+ analyticsService?: Partial<AnalyticsService.AnalyticsService["Service"]> & {
+ readonly record?: (
+ event: string,
+ properties?: Readonly<Record<string, unknown>>,
+ ) => Effect.Effect<void>;
+ };
projectionSnapshotQuery?: Partial<ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]>;
projectionBots?: Partial<ProjectionBots.ProjectionBotRepositoryShape>;
botUsageLedger?: Partial<BotUsageLedgerShape>;
@@ -804,13 +816,44 @@ const buildAppUnderTest = (options?: {
),
),
Layer.provide(
- Layer.mock(OrchestrationEngine.OrchestrationEngineService)({
- readEvents: () => Stream.empty,
- dispatch: () => Effect.succeed({ sequence: 0 }),
- streamDomainEvents: Stream.empty,
- latestSequence: Effect.succeed(0),
- ...options?.layers?.orchestrationEngine,
- }),
+ Layer.mergeAll(
+ Layer.mock(OrchestrationEngine.OrchestrationEngineService)({
+ readEvents: () => Stream.empty,
+ dispatch: () => Effect.succeed({ sequence: 0 }),
+ streamDomainEvents: Stream.empty,
+ latestSequence: Effect.succeed(0),
+ ...options?.layers?.orchestrationEngine,
+ }),
+ Layer.succeed(
+ RoutineRepository,
+ RoutineRepository.of({
+ listAll: Effect.succeed([]),
+ listEnabled: Effect.succeed([]),
+ getById: () => Effect.succeed(null),
+ listRuns: () => Effect.succeed([]),
+ listAllRuns: Effect.succeed([]),
+ getActiveRunByThreadRef: () => Effect.succeed(null),
+ listSkillAssignments: Effect.succeed([]),
+ claim: () => Effect.succeed(false),
+ markDispatched: () => Effect.void,
+ markBlocked: () => Effect.void,
+ listRecoverable: Effect.succeed([]),
+ ...options?.layers?.routineRepository,
+ markSettled: options?.layers?.routineRepository?.markSettled ?? (() => Effect.void),
+ } satisfies RoutineRepositoryShape),
+ ),
+ Layer.succeed(
+ RoutineRuntime,
+ RoutineRuntime.of({
+ runDue: Effect.void,
+ canRunNow: () => Effect.succeed(true),
+ runNow: () => Effect.succeed(null),
+ recover: Effect.void,
+ start: Effect.void,
+ ...options?.layers?.routineRuntime,
+ } satisfies RoutineRuntimeShape),
+ ),
+ ),
),
Layer.provide(
Layer.mergeAll(
@@ -906,6 +949,7 @@ const buildAppUnderTest = (options?: {
Layer.provide(
Layer.mock(AnalyticsService.AnalyticsService)({
flush: Effect.void,
+ ...options?.layers?.analyticsService,
}),
),
Layer.provide(
@@ -3690,6 +3734,141 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("records thread analytics only after a client command succeeds", () =>
+ Effect.gen(function* () {
+ const effects: string[] = [];
+ const analyticsProperties: Array<Readonly<Record<string, unknown>> | undefined> = [];
+ const failedCommandId = CommandId.make("cmd-thread-create-failed");
+
+ yield* buildAppUnderTest({
+ layers: {
+ analyticsService: {
+ record: (event, properties) =>
+ Effect.sync(() => {
+ effects.push(`analytics:${event}`);
+ analyticsProperties.push(properties);
+ }),
+ },
+ orchestrationEngine: {
+ dispatch: (command) =>
+ Effect.sync(() => effects.push(`dispatch:${command.commandId}`)).pipe(
+ Effect.flatMap(() =>
+ command.commandId === failedCommandId
+ ? Effect.fail(
+ new OrchestrationListenerCallbackError({
+ listener: "domain-event",
+ detail: "thread creation failed",
+ }),
+ )
+ : Effect.succeed({ sequence: 1 }),
+ ),
+ ),
+ },
+ },
+ });
+
+ const createThreadCommand = (commandId: CommandId, threadId: ThreadId) =>
+ ({
+ type: "thread.create",
+ commandId,
+ threadId,
+ projectId: defaultProjectId,
+ title: "Analytics test",
+ modelSelection: defaultModelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ }) as const;
+
+ const wsUrl = yield* getWsServerUrl(
+ "/ws?clientSurface=mobile&clientAppVersion=1.2.3&clientOs=iOS&clientOsMajorVersion=18&clientDeviceModel=iPhone+15+Pro",
+ );
+ yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) =>
+ Effect.gen(function* () {
+ const failed = yield* client[ORCHESTRATION_WS_METHODS.dispatchCommand](
+ createThreadCommand(failedCommandId, ThreadId.make("thread-create-failed")),
+ ).pipe(Effect.result);
+
+ assert.equal(failed._tag, "Failure");
+ assert.deepEqual(effects, [
+ "analytics:client.connected",
+ "dispatch:cmd-thread-create-failed",
+ ]);
+
+ const succeeded = yield* client[ORCHESTRATION_WS_METHODS.dispatchCommand](
+ createThreadCommand(
+ CommandId.make("cmd-thread-create-succeeded"),
+ ThreadId.make("thread-create-succeeded"),
+ ),
+ );
+
+ assert.equal(succeeded.sequence, 1);
+ }),
+ ),
+ );
+
+ assert.deepEqual(effects, [
+ "analytics:client.connected",
+ "dispatch:cmd-thread-create-failed",
+ "dispatch:cmd-thread-create-succeeded",
+ "analytics:client.thread.started",
+ ]);
+ assert.deepEqual(analyticsProperties, [
+ {
+ surface: "mobile",
+ appVersion: "1.2.3",
+ os: "iOS",
+ osMajorVersion: 18,
+ deviceModel: "iPhone 15 Pro",
+ },
+ { surface: "mobile", appVersion: "1.2.3" },
+ ]);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("reports a manual routine run that does not start", () =>
+ Effect.gen(function* () {
+ let dispatchCount = 0;
+ yield* buildAppUnderTest({
+ layers: {
+ orchestrationEngine: {
+ dispatch: () =>
+ Effect.sync(() => {
+ dispatchCount += 1;
+ return { sequence: 7 };
+ }),
+ },
+ routineRuntime: {
+ canRunNow: () => Effect.succeed(false),
+ runNow: () => Effect.die("busy routine must not run"),
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const result = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) =>
+ client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
+ type: "routine.run",
+ commandId: CommandId.make("cmd-routine-run-collision"),
+ routineId: RoutineId.make("routine-1"),
+ runId: RoutineRunId.make("run-1"),
+ trigger: "manual",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ }).pipe(Effect.result),
+ ),
+ );
+
+ assert.equal(result._tag, "Failure");
+ if (result._tag === "Failure") {
+ assert.include(result.failure.message, "did not start");
+ }
+ assert.equal(dispatchCount, 0);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
it.effect("routes websocket rpc projects.writeFile errors", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index cc5f86732..592214721 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -109,6 +109,8 @@ import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
import * as NetService from "@t3tools/shared/Net";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
import { ServerActivation } from "./serverActivation.ts";
+import { RoutineLayerLive } from "./routines/layer.ts";
+import { RoutineDraftDispatcherLive } from "./routines/RoutineDraftDispatcher.ts";
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
@@ -273,6 +275,7 @@ const RuntimeMemoryRepositoriesWithPersistenceLive = RuntimeMemoryRepositoriesLi
const ProviderLayerLive = AgentControllerLive.pipe(
Layer.provide(LegacyProviderLayerLive),
Layer.provide(RuntimeMemoryRepositoriesWithPersistenceLive),
+ Layer.provide(RoutineDraftDispatcherLive.pipe(Layer.provide(OrchestrationLayerLive))),
);
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
@@ -412,7 +415,12 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(ServerSecretStore.layer),
);
-const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
+const RuntimeCoreWithRoutinesLive = Layer.merge(
+ RuntimeCoreDependenciesLive,
+ RoutineLayerLive.pipe(Layer.provide(RuntimeCoreDependenciesLive)),
+);
+
+const RuntimeDependenciesLive = RuntimeCoreWithRoutinesLive.pipe(
// Misc.
Layer.provideMerge(BackgroundLayerLive),
Layer.provideMerge(ResourceDiagnosticsLayerLive),
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index e64847d54..3c196b79f 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -47,6 +47,7 @@ import {
isWildcardHost,
issueHeadlessServeAccessInfo,
} from "./startupAccess.ts";
+import { RoutineRuntime } from "./routines/Runtime.ts";
export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
"ServerRuntimeStartupError",
@@ -430,6 +431,10 @@ export const make = (options?: StartupOptions) =>
yield* forkParked(
ChannelRuntime.stopArchivedBotChannels(orchestrationEngine.streamDomainEvents),
).pipe(Scope.provide(reactorScope));
+ const routineRuntime = yield* Effect.serviceOption(RoutineRuntime);
+ if (Option.isSome(routineRuntime)) {
+ yield* routineRuntime.value.start.pipe(Scope.provide(reactorScope));
+ }
}),
);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 292725343..add0522c5 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -57,6 +57,7 @@ import {
ProjectSearchEntriesError,
ProjectWriteFileError,
ProviderUploadFeedbackError,
+ RoutineReadError,
type ServerSelfUpdateError,
type ServerSelfUpdateProgressEvent,
type ServerProvider,
@@ -126,6 +127,8 @@ import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as ServerSettings from "./serverSettings.ts";
+import { RoutineRepository } from "./routines/Repository.ts";
+import { RoutineRuntime } from "./routines/Runtime.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -492,6 +495,8 @@ const makeWsRpcLayer = (
const projectionGroups = yield* ProjectionGroups.ProjectionGroupRepository;
const entityMemoryRepository = yield* Effect.serviceOption(EntityMemoryRepository);
const memoryCandidates = yield* Effect.serviceOption(MemoryCandidateRepository);
+ const routineRepository = yield* RoutineRepository;
+ const routineRuntime = yield* RoutineRuntime;
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
// Every command dispatched on this connection carries the connecting
// client's origin, including server-generated bootstrap sub-commands:
@@ -922,6 +927,47 @@ const makeWsRpcLayer = (
delegation: event.payload.delegation,
}),
);
+ case "routine.drafted":
+ case "routine.approved":
+ case "routine.enabled":
+ case "routine.running":
+ case "routine.paused":
+ case "routine.blocked":
+ case "routine.failed":
+ case "routine.completed":
+ case "routine.run-canceled":
+ return Effect.succeed(
+ Option.some({
+ kind: "routine-upserted" as const,
+ sequence: event.sequence,
+ routine: event.payload.routine,
+ ...("run" in event.payload ? { run: event.payload.run } : {}),
+ }),
+ );
+ case "routine.deleted":
+ return Effect.succeed(
+ Option.some({
+ kind: "routine-removed" as const,
+ sequence: event.sequence,
+ routineId: event.payload.routine.id,
+ }),
+ );
+ case "skill-assignment.assigned":
+ return Effect.succeed(
+ Option.some({
+ kind: "skill-assignment-upserted" as const,
+ sequence: event.sequence,
+ assignment: event.payload.assignment,
+ }),
+ );
+ case "skill-assignment.unassigned":
+ return Effect.succeed(
+ Option.some({
+ kind: "skill-assignment-removed" as const,
+ sequence: event.sequence,
+ assignmentId: event.payload.assignmentId,
+ }),
+ );
case "thread.deleted":
case "thread.archived":
return Effect.succeed(
@@ -1429,7 +1475,7 @@ const makeWsRpcLayer = (
const dispatchNormalizedCommand = (
normalizedCommand: OrchestrationCommand,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
- const dispatchEffect =
+ const baseDispatchEffect =
normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
? dispatchBootstrapTurnStart(normalizedCommand)
: dispatchFromClient(normalizedCommand).pipe(
@@ -1438,6 +1484,48 @@ const makeWsRpcLayer = (
),
);
+ const dispatchEffect =
+ normalizedCommand.type === "routine.run"
+ ? routineRuntime.canRunNow(normalizedCommand.routineId).pipe(
+ Effect.flatMap((canRun) =>
+ canRun
+ ? baseDispatchEffect
+ : Effect.fail(
+ new OrchestrationDispatchCommandError({
+ message: `Routine run '${normalizedCommand.runId}' did not start.`,
+ }),
+ ),
+ ),
+ Effect.flatMap((result) =>
+ routineRuntime
+ .runNow(
+ normalizedCommand.routineId,
+ normalizedCommand.runId,
+ normalizedCommand.trigger,
+ )
+ .pipe(
+ Effect.catchCause((cause) =>
+ Effect.fail(
+ toDispatchCommandError(
+ Cause.squash(cause),
+ "Failed to start the routine run.",
+ ),
+ ),
+ ),
+ Effect.flatMap((run) =>
+ run === null
+ ? Effect.fail(
+ new OrchestrationDispatchCommandError({
+ message: `Routine run '${normalizedCommand.runId}' did not start.`,
+ }),
+ )
+ : Effect.succeed(result),
+ ),
+ ),
+ ),
+ )
+ : baseDispatchEffect;
+
return startup
.enqueueCommand(dispatchEffect)
.pipe(
@@ -2260,6 +2348,21 @@ const makeWsRpcLayer = (
}).pipe(Effect.mapError((cause) => portabilityError("apply", cause))),
{ "rpc.aggregate": "portability" },
),
+ [WS_METHODS.routinesListRuns]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.routinesListRuns,
+ routineRepository.listRuns(input.routineId).pipe(
+ Effect.map((runs) => ({ runs })),
+ Effect.mapError(
+ (cause) =>
+ new RoutineReadError({
+ routineId: input.routineId,
+ message: cause.message,
+ }),
+ ),
+ ),
+ { "rpc.aggregate": "routines" },
+ ),
[WS_METHODS.subscriptionAuthList]: (_input) =>
observeRpcEffect(WS_METHODS.subscriptionAuthList, getAccessHealthSnapshot(), {
"rpc.aggregate": "server",
diff --git a/apps/web/src/components/chat/ChatComposer.controls.test.tsx b/apps/web/src/components/chat/ChatComposer.controls.test.tsx
index 7cb624c29..dc8792c78 100644
--- a/apps/web/src/components/chat/ChatComposer.controls.test.tsx
+++ b/apps/web/src/components/chat/ChatComposer.controls.test.tsx
@@ -138,7 +138,9 @@ describe("ChatComposer launch-control removal", () => {
);
expect(markup).toContain("rm -rf node_modules");
- expect(markup).toContain("Approve");
+ expect(markup).toContain("Allow once");
+ expect(markup).toContain("Always allow");
+ expect(markup).toContain("Never");
expectNoLaunchControls(markup);
});
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 7951dcd3a..b9d01757f 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -2754,7 +2754,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<div
className="chat-composer-top-drawer"
data-chat-composer-top-drawer="true"
- data-variant={activePendingApproval ? "warning" : "info"}
+ data-variant={activePendingApproval ? undefined : "info"}
>
{!isComposerCollapsedMobile && activePendingApproval ? (
<div className="flex min-w-0 flex-wrap items-center gap-1 px-3 py-1.5 sm:px-4">
@@ -2765,6 +2765,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<div className="flex min-w-0 flex-wrap items-center gap-0.5">
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
+ requestKind={activePendingApproval.requestKind}
+ toolName={activePendingApproval.toolName}
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
options={activePendingApproval.options}
onRespondToApproval={respondToApproval}
@@ -2795,6 +2797,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<div className="flex flex-wrap items-center justify-end gap-1 px-3 pt-2 pb-3 sm:px-4">
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
+ requestKind={activePendingApproval.requestKind}
+ toolName={activePendingApproval.toolName}
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
options={activePendingApproval.options}
onRespondToApproval={respondToApproval}
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
index 16141270f..ed1768a1a 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
@@ -1,4 +1,4 @@
-import { ApprovalRequestId } from "@t3tools/contracts";
+import { AKERU_CREATE_ROUTINE_TOOL_NAME, ApprovalRequestId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
@@ -55,4 +55,59 @@ describe("ComposerPendingApprovalActions", () => {
expect(markup).toContain('class="max-w-40 truncate"');
expect(markup).toContain(label);
});
+
+ it("uses the three clear command permission choices", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalActions
+ requestId={ApprovalRequestId.make("approval-shell")}
+ requestKind="command"
+ isResponding={false}
+ options={[
+ { decision: "decline", label: "Decline" },
+ { decision: "accept", label: "Allow" },
+ ]}
+ onRespondToApproval={async () => undefined}
+ />,
+ );
+
+ expect(markup).toContain("Always allow");
+ expect(markup).toContain("Allow once");
+ expect(markup).toContain("Never");
+ expect(markup).not.toContain(">Decline<");
+ });
+
+ it("uses one create or cancel choice for a routine", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalActions
+ requestId={ApprovalRequestId.make("approval-routine")}
+ requestKind="command"
+ toolName={AKERU_CREATE_ROUTINE_TOOL_NAME}
+ isResponding={false}
+ options={[
+ { decision: "accept", label: "Create routine" },
+ { decision: "decline", label: "Cancel" },
+ ]}
+ onRespondToApproval={async () => undefined}
+ />,
+ );
+
+ expect(markup).toContain("Create routine");
+ expect(markup).toContain(">Cancel<");
+ expect(markup).not.toContain("Always allow");
+ expect(markup).not.toContain("Allow once");
+ expect(markup).not.toContain(">Never<");
+
+ const fallbackMarkup = renderToStaticMarkup(
+ <ComposerPendingApprovalActions
+ requestId={ApprovalRequestId.make("approval-routine-fallback")}
+ requestKind="command"
+ toolName={AKERU_CREATE_ROUTINE_TOOL_NAME}
+ isResponding={false}
+ onRespondToApproval={async () => undefined}
+ />,
+ );
+ expect(fallbackMarkup).toContain("Create routine");
+ expect(fallbackMarkup).toContain(">Cancel<");
+ expect(fallbackMarkup).not.toContain("Always allow");
+ });
});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
index 7482f665b..19f31d3d4 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
@@ -1,13 +1,17 @@
import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
type ApprovalRequestId,
type ProviderApprovalDecision,
type ProviderApprovalOption,
+ type ProviderRequestKind,
} from "@t3tools/contracts";
import { memo } from "react";
import { Button } from "../ui/button";
interface ComposerPendingApprovalActionsProps {
requestId: ApprovalRequestId;
+ requestKind?: ProviderRequestKind | undefined;
+ toolName?: string | undefined;
isResponding: boolean;
options?: ReadonlyArray<ProviderApprovalOption> | undefined;
onRespondToApproval: (
@@ -23,22 +27,57 @@ const DEFAULT_APPROVAL_OPTIONS = [
{ decision: "acceptForSession", label: "Always allow this session" },
{ decision: "accept", label: "Approve" },
] satisfies ReadonlyArray<ProviderApprovalOption>;
+const ROUTINE_APPROVAL_OPTIONS = [
+ { decision: "accept", label: "Create routine" },
+ { decision: "decline", label: "Cancel" },
+] satisfies ReadonlyArray<ProviderApprovalOption>;
+
+function commandApprovalOptions(
+ options: ReadonlyArray<ProviderApprovalOption>,
+): ReadonlyArray<ProviderApprovalOption> {
+ const always =
+ options.find((option) => option.decision === "acceptAlways") ??
+ options.find((option) => option.decision === "acceptForSession") ??
+ ({ decision: "acceptForSession", label: "Always allow" } as const);
+ const once =
+ options.find((option) => option.decision === "accept") ??
+ ({ decision: "accept", label: "Allow once" } as const);
+ const never =
+ options.find((option) => option.decision === "decline") ??
+ options.find((option) => option.decision === "cancel") ??
+ ({ decision: "decline", label: "Never" } as const);
+
+ return [
+ { ...always, label: "Always allow" },
+ { ...once, label: "Allow once" },
+ { ...never, label: "Never" },
+ ];
+}
export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({
requestId,
+ requestKind,
+ toolName,
isResponding,
options = DEFAULT_APPROVAL_OPTIONS,
onRespondToApproval,
}: ComposerPendingApprovalActionsProps) {
+ const visibleOptions =
+ toolName === AKERU_CREATE_ROUTINE_TOOL_NAME
+ ? ROUTINE_APPROVAL_OPTIONS
+ : requestKind === "command"
+ ? commandApprovalOptions(options)
+ : options;
+
return (
<>
- {options.map((option) => (
+ {visibleOptions.map((option) => (
<Button
key={option.decision}
size="micro"
variant="ghost-muted"
className={`${APPROVAL_ACTION_CLASS_NAME}${
- option.decision === "decline"
+ option.decision === "decline" && requestKind !== "command"
? " text-destructive-foreground [:hover,[data-pressed]]:text-destructive-foreground"
: option.decision === "accept"
? " text-foreground"
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
index a7ef6bc7d..18c7eeda9 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
@@ -1,4 +1,4 @@
-import { ApprovalRequestId } from "@t3tools/contracts";
+import { AKERU_CREATE_ROUTINE_TOOL_NAME, ApprovalRequestId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
@@ -24,14 +24,16 @@ describe("ComposerPendingApprovalPanel", () => {
expect(markup).toContain('role="group"');
expect(markup).toContain('tabindex="0"');
expect(markup).toContain(detail);
- expect(markup).toContain("max-h-20");
+ expect(markup).toContain("max-h-40");
expect(markup).toContain("overflow-auto");
- expect(markup).toContain("whitespace-pre");
+ expect(markup).toContain("whitespace-pre-wrap");
expect(markup).toContain("[scrollbar-width:thin]");
expect(markup).toContain("[&amp;::-webkit-scrollbar]:h-1.5");
- expect(markup).not.toContain("truncate");
+ expect(markup).toContain("truncate");
expect(markup).not.toContain("line-clamp");
expect(markup).toContain("min-w-0");
+ expect(markup).toContain("Expand");
+ expect(markup).toContain("Collapse");
expect(markup).not.toContain("Command approval requested");
});
@@ -92,4 +94,53 @@ describe("ComposerPendingApprovalPanel", () => {
expect(markup).toContain('data-approval-detail="complete"');
expect(markup).toContain(detail);
});
+
+ it("shows a routine preview instead of a generic command approval", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalPanel
+ approval={{
+ requestId: ApprovalRequestId.make("approval-routine"),
+ requestKind: "command",
+ toolName: AKERU_CREATE_ROUTINE_TOOL_NAME,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ detail: "Review routine",
+ args: {
+ name: "Daily brief",
+ instructions: "Summarize the work in this chat.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ },
+ }}
+ pendingCount={1}
+ />,
+ );
+
+ expect(markup).toContain("Review routine");
+ expect(markup).toContain("Daily brief");
+ expect(markup).toContain("Weekdays at 09:00");
+ expect(markup).toContain("Summarize the work in this chat.");
+ expect(markup).not.toContain("Command approval");
+ expect(markup).not.toContain("Allow akeru_create_routine?");
+ });
+
+ it("shows the exact weekday and timezone in a weekly routine preview", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalPanel
+ approval={{
+ requestId: ApprovalRequestId.make("approval-weekly-routine"),
+ requestKind: "command",
+ toolName: AKERU_CREATE_ROUTINE_TOOL_NAME,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ args: {
+ name: "Friday review",
+ instructions: "Review the week.",
+ schedule: { kind: "weekly", weekdays: ["friday"], time: "14:00" },
+ timezone: "America/New_York",
+ },
+ }}
+ pendingCount={1}
+ />,
+ );
+
+ expect(markup).toContain("Friday at 14:00 (America/New_York)");
+ });
});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
index 61a872c9a..42aab016b 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
@@ -1,5 +1,8 @@
import { memo } from "react";
-import { AKERU_PRODUCT_FEEDBACK_TOOL_NAME } from "@t3tools/contracts";
+import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+} from "@t3tools/contracts";
import { type PendingApproval } from "../../session-logic";
import { cn } from "~/lib/utils";
@@ -15,49 +18,138 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
className,
}: ComposerPendingApprovalPanelProps) {
const isProductFeedback = approval.toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME;
- const fallbackLabel = isProductFeedback
- ? "Product feedback approval"
- : approval.requestKind === "mcp-elicitation"
- ? "App access approval"
- : approval.requestKind === "command"
- ? "Command approval"
- : approval.requestKind === "file-read"
- ? "File read approval"
- : "File change approval";
- const detailAriaLabel = isProductFeedback
- ? "Product feedback draft"
- : approval.requestKind === "mcp-elicitation"
- ? "App access request"
- : approval.requestKind === "command"
- ? "Command"
- : approval.requestKind === "file-read"
- ? "File to read"
- : "File change";
+ const isRoutine = approval.toolName === AKERU_CREATE_ROUTINE_TOOL_NAME;
+ const routineArgs =
+ isRoutine && approval.args && typeof approval.args === "object"
+ ? (approval.args as Record<string, unknown>)
+ : null;
+ const routineName = typeof routineArgs?.name === "string" ? routineArgs.name : "New routine";
+ const routineInstructions =
+ typeof routineArgs?.instructions === "string" ? routineArgs.instructions : null;
+ const routineSchedule =
+ routineArgs?.schedule && typeof routineArgs.schedule === "object"
+ ? (routineArgs.schedule as Record<string, unknown>)
+ : null;
+ const scheduleTime = typeof routineSchedule?.time === "string" ? routineSchedule.time : null;
+ const scheduleTimezone = typeof routineArgs?.timezone === "string" ? routineArgs.timezone : null;
+ const weeklyDays = Array.isArray(routineSchedule?.weekdays)
+ ? routineSchedule.weekdays.filter((day): day is string => typeof day === "string")
+ : [];
+ const scheduleKind =
+ routineSchedule?.kind === "weekdays"
+ ? "Weekdays"
+ : routineSchedule?.kind === "weekly"
+ ? weeklyDays.length > 0
+ ? weeklyDays.map((day) => `${day.slice(0, 1).toUpperCase()}${day.slice(1)}`).join(", ")
+ : "Weekly"
+ : "Daily";
+ const fallbackLabel = isRoutine
+ ? "Routine approval"
+ : isProductFeedback
+ ? "Product feedback approval"
+ : approval.requestKind === "mcp-elicitation"
+ ? "App access approval"
+ : approval.requestKind === "command"
+ ? "Command approval"
+ : approval.requestKind === "file-read"
+ ? "File read approval"
+ : "File change approval";
+ const detailAriaLabel = isRoutine
+ ? "Routine details"
+ : isProductFeedback
+ ? "Product feedback draft"
+ : approval.requestKind === "mcp-elicitation"
+ ? "App access request"
+ : approval.requestKind === "command"
+ ? "Command"
+ : approval.requestKind === "file-read"
+ ? "File to read"
+ : "File change";
+ const command =
+ approval.requestKind === "command" &&
+ approval.args &&
+ typeof approval.args === "object" &&
+ "command" in approval.args &&
+ typeof approval.args.command === "string"
+ ? approval.args.command
+ : null;
+ const detail = command ?? approval.detail ?? fallbackLabel;
+
+ if (isRoutine) {
+ return (
+ <div
+ aria-label={fallbackLabel}
+ className={cn("flex min-w-0 flex-1 flex-col gap-2", className)}
+ role="group"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="text-xs font-medium text-foreground">Review routine</span>
+ {pendingCount > 1 ? (
+ <span className="ml-auto text-[10px] text-muted-foreground tabular-nums">
+ 1/{pendingCount}
+ </span>
+ ) : null}
+ </div>
+ <div aria-label={detailAriaLabel} className="rounded-lg bg-foreground/[0.04] px-3 py-2.5">
+ <div className="flex min-w-0 items-center justify-between gap-3">
+ <span className="truncate text-sm font-medium text-foreground">{routineName}</span>
+ {scheduleTime ? (
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {scheduleKind} at {scheduleTime}
+ {scheduleTimezone ? ` (${scheduleTimezone})` : ""}
+ </span>
+ ) : null}
+ </div>
+ {routineInstructions ? (
+ <p className="mt-1.5 line-clamp-3 text-xs leading-5 text-muted-foreground">
+ {routineInstructions}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+ }
return (
<div
aria-label={fallbackLabel}
- className={cn("flex min-w-0 flex-1 items-center gap-2", className)}
+ className={cn("flex min-w-0 flex-1 flex-col gap-1.5", className)}
role="group"
>
- {approval.appName ? (
- <span className="max-w-32 shrink truncate text-[11px] font-medium text-foreground">
- {approval.appName}
- </span>
- ) : null}
- <code
- aria-label={detailAriaLabel}
- className="block max-h-20 min-w-0 flex-1 overflow-auto whitespace-pre font-mono text-[11px] text-foreground/85 [scrollbar-width:thin] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70 [&::-webkit-scrollbar]:h-1.5"
- data-approval-detail="complete"
- tabIndex={0}
- >
- {approval.detail || fallbackLabel}
- </code>
- {pendingCount > 1 ? (
- <span className="shrink-0 text-[10px] font-medium text-muted-foreground tabular-nums">
- 1/{pendingCount}
- </span>
- ) : null}
+ <div className="flex w-full min-w-0 items-center gap-2">
+ <span className="text-xs font-medium text-foreground">{fallbackLabel}</span>
+ {approval.appName ? (
+ <span className="max-w-32 shrink truncate text-[11px] text-muted-foreground">
+ {approval.appName}
+ </span>
+ ) : null}
+ {pendingCount > 1 ? (
+ <span className="ml-auto shrink-0 text-[10px] font-medium text-muted-foreground tabular-nums">
+ 1/{pendingCount}
+ </span>
+ ) : null}
+ </div>
+ <details className="group w-full min-w-0">
+ <summary className="flex cursor-pointer list-none items-center gap-2 rounded-md bg-foreground/[0.04] px-2.5 py-2 marker:content-none">
+ <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-foreground/85">
+ {detail.split("\n", 1)[0]}
+ </code>
+ <span className="shrink-0 text-[10px] text-muted-foreground group-open:hidden">
+ Expand
+ </span>
+ <span className="hidden shrink-0 text-[10px] text-muted-foreground group-open:inline">
+ Collapse
+ </span>
+ </summary>
+ <code
+ aria-label={detailAriaLabel}
+ className="mt-1.5 block max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-foreground/[0.04] px-2.5 py-2 font-mono text-[11px] text-foreground/85 [scrollbar-width:thin] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70 [&::-webkit-scrollbar]:h-1.5"
+ data-approval-detail="complete"
+ tabIndex={0}
+ >
+ {detail}
+ </code>
+ </details>
</div>
);
});
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
index 817182190..71c679f0a 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
@@ -30,7 +30,6 @@ function renderPanel() {
answers={{}}
questionIndex={0}
onToggleOption={() => {}}
- onAdvance={() => {}}
/>,
);
}
@@ -58,4 +57,23 @@ describe("ComposerPendingUserInputPanel", () => {
expect(markup).toContain("Incremental");
expect(markup).toContain("Big bang");
});
+
+ it("shows a submit action after a multi-select answer is selected", () => {
+ const multiSelectPrompt: PendingUserInput = {
+ ...prompt,
+ questions: [{ ...prompt.questions[0]!, multiSelect: true }],
+ };
+ const markup = renderToStaticMarkup(
+ <ComposerPendingUserInputPanel
+ pendingUserInputs={[multiSelectPrompt]}
+ respondingRequestIds={[]}
+ answers={{ "question-1": { selectedOptionLabels: ["Incremental"] } }}
+ questionIndex={0}
+ onToggleOption={() => {}}
+ onAdvance={() => {}}
+ />,
+ );
+
+ expect(markup).toContain(">Submit</button>");
+ });
});
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
index c121110bb..b68e82eb4 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
@@ -7,6 +7,7 @@ import {
} from "../../pendingUserInput";
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
+import { Button } from "../ui/button";
import { cn } from "~/lib/utils";
interface PendingUserInputPanelProps {
@@ -15,7 +16,8 @@ interface PendingUserInputPanelProps {
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
onToggleOption: (questionId: string, optionLabel: string) => void;
- onAdvance: () => void;
+ onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
+ onAdvance?: () => void;
}
export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
@@ -24,6 +26,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
answers,
questionIndex,
onToggleOption,
+ onSelectSingleOption,
onAdvance,
}: PendingUserInputPanelProps) {
if (pendingUserInputs.length === 0) return null;
@@ -38,7 +41,8 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
answers={answers}
questionIndex={questionIndex}
onToggleOption={onToggleOption}
- onAdvance={onAdvance}
+ {...(onSelectSingleOption ? { onSelectSingleOption } : {})}
+ {...(onAdvance ? { onAdvance } : {})}
/>
);
});
@@ -49,6 +53,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
answers,
questionIndex,
onToggleOption,
+ onSelectSingleOption,
onAdvance,
}: {
prompt: PendingUserInput;
@@ -56,12 +61,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
answers: Record<string, PendingUserInputDraftAnswer>;
questionIndex: number;
onToggleOption: (questionId: string, optionLabel: string) => void;
- onAdvance: () => void;
+ onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
+ onAdvance?: () => void;
}) {
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
const autoAdvanceTimerRef = useRef<number | null>(null);
- const onAdvanceRef = useRef(onAdvance);
const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
questionId: string;
optionLabel: string;
@@ -75,9 +80,14 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
- useEffect(() => {
- onAdvanceRef.current = onAdvance;
- }, [onAdvance]);
+ useEffect(
+ () => () => {
+ if (autoAdvanceTimerRef.current !== null) {
+ window.clearTimeout(autoAdvanceTimerRef.current);
+ }
+ },
+ [],
+ );
useEffect(() => {
if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
@@ -100,15 +110,6 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
progress.selectedOptionLabels,
]);
- // Clear auto-advance timer on unmount
- useEffect(() => {
- return () => {
- if (autoAdvanceTimerRef.current !== null) {
- window.clearTimeout(autoAdvanceTimerRef.current);
- }
- };
- }, []);
-
const handleOptionSelection = useCallback(
(questionId: string, optionLabel: string) => {
if (activeQuestion?.multiSelect) {
@@ -116,16 +117,22 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
return;
}
setOptimisticSingleSelect({ questionId, optionLabel });
+ if (onSelectSingleOption) {
+ onSelectSingleOption(questionId, optionLabel);
+ return;
+ }
onToggleOption(questionId, optionLabel);
- if (autoAdvanceTimerRef.current !== null) {
- window.clearTimeout(autoAdvanceTimerRef.current);
+ if (onAdvance) {
+ if (autoAdvanceTimerRef.current !== null) {
+ window.clearTimeout(autoAdvanceTimerRef.current);
+ }
+ autoAdvanceTimerRef.current = window.setTimeout(() => {
+ autoAdvanceTimerRef.current = null;
+ onAdvance();
+ }, 200);
}
- autoAdvanceTimerRef.current = window.setTimeout(() => {
- autoAdvanceTimerRef.current = null;
- onAdvanceRef.current();
- }, 200);
},
- [activeQuestion, onToggleOption],
+ [activeQuestion, onAdvance, onSelectSingleOption, onToggleOption],
);
// Keyboard shortcut: number keys 1-9 select corresponding options when focus is
@@ -276,6 +283,17 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
);
})}
</div>
+ {activeQuestion.multiSelect && onAdvance ? (
+ <div className="mt-2 flex justify-end">
+ <Button
+ size="xs"
+ disabled={isResponding || progress.selectedOptionLabels.length === 0}
+ onClick={onAdvance}
+ >
+ {questionIndex < prompt.questions.length - 1 ? "Continue" : "Submit"}
+ </Button>
+ </div>
+ ) : null}
</div>
</CollapsiblePanel>
</Collapsible>
diff --git a/apps/web/src/components/roster/BotDetailsPanel.test.tsx b/apps/web/src/components/roster/BotDetailsPanel.test.tsx
index 62387389a..4130c3deb 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.test.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.test.tsx
@@ -62,10 +62,11 @@ describe("BotDetailsPanel", () => {
expect(markup).toContain(">Manage</span>");
expect(markup).toContain('aria-label="Collapse Akeru bot sidebar"');
expect(markup).toContain('aria-label="Open Akeru bot sidebar"');
- expect(markup).not.toContain("Routines");
+ expect(markup).toContain("Routines");
+ expect(markup).toContain("Routines are not available for this environment.");
expect(markup).not.toContain("mock data");
expect(markup).not.toContain("border-b border-border");
- expect(markup).not.toContain("border-t border-border");
+ expect(markup).toContain("border-t border-border");
});
it("sets, clears, and rejects invalid hard stops", () => {
diff --git a/apps/web/src/components/roster/BotDetailsPanel.tsx b/apps/web/src/components/roster/BotDetailsPanel.tsx
index 1e45059e3..7ca4e6361 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.tsx
@@ -54,6 +54,7 @@ import {
type BotSandboxChoice,
} from "./botSandbox";
import { BotToolsSheet, buildBotToolItems } from "./BotToolsSheet";
+import { RoutinePanel, type RoutinePanelProps } from "./RoutinePanel";
import type { Bot } from "./types";
import type { ScopedThreadRef } from "@t3tools/contracts";
@@ -122,11 +123,13 @@ function BotProfileEditor({
onSave,
threadRef,
active,
+ routinePanel,
}: {
readonly bot: Bot;
readonly onSave?: (input: BotProfileUpdate) => Promise<boolean>;
readonly threadRef: ScopedThreadRef | null;
readonly active: boolean;
+ readonly routinePanel?: Omit<RoutinePanelProps, "botName">;
}) {
const providers = useAtomValue(primaryServerProvidersAtom);
const environmentId = usePrimaryEnvironmentId();
@@ -439,6 +442,8 @@ function BotProfileEditor({
</Button>
</div>
+ <RoutinePanel botName={bot.name} {...(routinePanel ?? { status: "unavailable" as const })} />
+
<AvatarPickerDialog bot={bot} open={avatarOpen} onOpenChange={setAvatarOpen} />
<BotToolsSheet
open={toolsOpen}
@@ -459,10 +464,12 @@ export function BotDetailsPanel({
bot,
onSaveBot,
threadRef = null,
+ routinePanel,
}: {
readonly bot: Bot;
readonly onSaveBot?: (input: BotProfileUpdate) => Promise<boolean>;
readonly threadRef?: ScopedThreadRef | null;
+ readonly routinePanel?: Omit<RoutinePanelProps, "botName">;
}) {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const [panelState, dispatchPanel] = useReducer(reduceBotDetailsPanelState, {
@@ -517,6 +524,7 @@ export function BotDetailsPanel({
threadRef={threadRef}
active={active}
{...(onSaveBot ? { onSave: onSaveBot } : {})}
+ {...(routinePanel ? { routinePanel } : {})}
/>
</>
) : null}
diff --git a/apps/web/src/components/roster/BotInboxAlertStack.test.tsx b/apps/web/src/components/roster/BotInboxAlertStack.test.tsx
index 3b145adfe..ae4610c96 100644
--- a/apps/web/src/components/roster/BotInboxAlertStack.test.tsx
+++ b/apps/web/src/components/roster/BotInboxAlertStack.test.tsx
@@ -52,4 +52,32 @@ describe("bot inbox alerts", () => {
expect(markup).toContain("Next: Reconnect Claude in Settings.");
expect(markup).toContain("View details");
});
+
+ it("leaves approval requests to the inline approval card", () => {
+ const markup = renderToStaticMarkup(
+ <BotInboxAlertStack
+ items={[
+ incident({
+ kind: "approval-request",
+ lastFailure: "Allow Shell?",
+ nextAction: "Open the thread and approve or decline the request.",
+ }),
+ ]}
+ onOpenDetails={() => {}}
+ />,
+ );
+
+ expect(markup).toBe("");
+ });
+
+ it("leaves routine failures in the inbox instead of blocking chat", () => {
+ const markup = renderToStaticMarkup(
+ <BotInboxAlertStack
+ items={[incident({ kind: "routine-failure" })]}
+ onOpenDetails={() => {}}
+ />,
+ );
+
+ expect(markup).toBe("");
+ });
});
diff --git a/apps/web/src/components/roster/BotInboxAlertStack.tsx b/apps/web/src/components/roster/BotInboxAlertStack.tsx
index 50daba0f1..969cfa71b 100644
--- a/apps/web/src/components/roster/BotInboxAlertStack.tsx
+++ b/apps/web/src/components/roster/BotInboxAlertStack.tsx
@@ -11,12 +11,15 @@ export function BotInboxAlertStack({
readonly items: ReadonlyArray<BotInboxItem>;
readonly onOpenDetails: () => void;
}) {
- if (items.length === 0) return null;
+ const visibleItems = items.filter(
+ (item) => item.kind !== "approval-request" && item.kind !== "routine-failure",
+ );
+ if (visibleItems.length === 0) return null;
return (
<ComposerBannerStack
className="relative z-0 mx-4 sm:mx-6"
- items={items.map((item) => ({
+ items={visibleItems.map((item) => ({
id: item.id,
variant: "error",
icon: <CircleAlertIcon />,
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index cf0b2a217..3480d26ee 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -35,7 +35,7 @@ import { BotInboxAlertStack } from "./BotInboxAlertStack";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
import { DelegationCard } from "./DelegationCard";
-import { visibleBotChatMessages } from "./botConversationPresentation";
+import { isBotConversationWorking, visibleBotChatMessages } from "./botConversationPresentation";
import { resolveStickyBotEngine } from "./botEngineSelection";
import { BotPromptComposer } from "./BotPromptComposer";
import { BotMessageAttachments } from "./BotMessageAttachments";
@@ -177,8 +177,12 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
}, [bot, navigate]);
if (!bot || bot.archivedAt !== null) return null;
- const working = runtime.sending || presence === "working";
- const messages = visibleBotChatMessages(runtime.messages);
+ const working = isBotConversationWorking({
+ sending: runtime.sending,
+ respondingToUserInput: runtime.respondingRequestIds.length > 0,
+ presence,
+ });
+ const messages = visibleBotChatMessages(runtime.messages, working);
const pendingApproval = approvalState.pendingApproval;
const inboxItems = selectOpenBotInboxItems(inboxQuery.data?.inbox ?? [], new Set([bot.id]));
const delegations = runtime.linkedThreadRef
diff --git a/apps/web/src/components/roster/RoutinePanel.test.tsx b/apps/web/src/components/roster/RoutinePanel.test.tsx
new file mode 100644
index 000000000..4a004080e
--- /dev/null
+++ b/apps/web/src/components/roster/RoutinePanel.test.tsx
@@ -0,0 +1,191 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ boundedRunHistory,
+ RoutinePanel,
+ routineScheduleLabel,
+ type RoutineAdapterItem,
+ type RoutineAdapterRun,
+} from "./RoutinePanel";
+import { toRoutineSchedule } from "./routineAdapter";
+
+const run: RoutineAdapterRun = {
+ id: "run-1",
+ status: "failed",
+ startedAt: "2026-08-31T12:00:00.000Z",
+ finishedAt: "2026-08-31T12:01:00.000Z",
+ summary: null,
+ error: "Connector timed out",
+ usage: "1,240 tokens",
+};
+
+const routine: RoutineAdapterItem = {
+ id: "routine-1",
+ name: "Morning brief",
+ prompt: "Summarize the inbox and prepare the daily brief.",
+ projectId: "project-1",
+ sandbox: "local",
+ schedule: {
+ frequency: "weekdays",
+ time: "09:00",
+ timezone: "America/New_York",
+ weekday: null,
+ },
+ approval: "approval-required",
+ skills: ["research"],
+ connectors: ["Gmail"],
+ procedureApproved: true,
+ enabled: true,
+ paused: false,
+ nextRunAt: "2026-09-01T13:00:00.000Z",
+ lastRunAt: "2026-08-31T12:00:00.000Z",
+ latestRun: run,
+ runHistory: [run],
+};
+
+describe("RoutinePanel", () => {
+ it("formats each supported schedule", () => {
+ expect(routineScheduleLabel(routine.schedule)).toBe("Weekdays at 09:00 (America/New_York)");
+ expect(
+ routineScheduleLabel({
+ frequency: "daily",
+ time: "08:30",
+ timezone: "UTC",
+ weekday: null,
+ }),
+ ).toBe("Daily at 08:30 (UTC)");
+ expect(
+ routineScheduleLabel({
+ frequency: "weekly",
+ time: "14:00",
+ timezone: "Europe/London",
+ weekday: 5,
+ }),
+ ).toBe("Friday at 14:00 (Europe/London)");
+ });
+
+ it("maps the selected weekly day to the routine contract", () => {
+ expect(
+ toRoutineSchedule({
+ name: "Friday review",
+ prompt: "Review the week.",
+ projectId: "project-1",
+ sandbox: "local",
+ schedule: {
+ frequency: "weekly",
+ time: "14:00",
+ timezone: "Europe/London",
+ weekday: 5,
+ },
+ approval: "approval-required",
+ skills: [],
+ connectors: [],
+ }),
+ ).toEqual({ kind: "weekly", weekdays: ["friday"], time: "14:00" });
+ });
+
+ it("limits rendered run history data", () => {
+ const history = Array.from({ length: 7 }, (_, index) => ({
+ ...run,
+ id: `run-${index}`,
+ }));
+ expect(boundedRunHistory(history).map((item) => item.id)).toEqual([
+ "run-0",
+ "run-1",
+ "run-2",
+ "run-3",
+ "run-4",
+ ]);
+ });
+
+ it("renders routine controls and the latest failure", () => {
+ const markup = renderToStaticMarkup(
+ <RoutinePanel
+ botName="Akeru"
+ status="ready"
+ routines={[routine]}
+ onDryRun={() => undefined}
+ onRunNow={() => undefined}
+ onSetPaused={() => undefined}
+ />,
+ );
+
+ expect(markup).toContain(">Routines</h3>");
+ expect(markup).not.toContain("New routine");
+ expect(markup).toContain(">Morning brief</h4>");
+ expect(markup).toContain("Weekdays at 09:00 (America/New_York)");
+ expect(markup).toContain("Connector timed out");
+ expect(markup).not.toContain("Usage reference: 1,240 tokens");
+ expect(markup).toContain("Next Sep 1");
+ expect(markup).toContain(">Dry run</button>");
+ expect(markup).toContain(">Run now</button>");
+ expect(markup).toContain(">Pause</button>");
+ expect(markup).toContain(">Edit</button>");
+ });
+
+ it("renders loading, empty, error, and unavailable states", () => {
+ expect(renderToStaticMarkup(<RoutinePanel botName="Akeru" status="loading" />)).toContain(
+ 'aria-label="Loading routines"',
+ );
+ expect(
+ renderToStaticMarkup(<RoutinePanel botName="Akeru" status="ready" routines={[]} />),
+ ).toContain("Ask Akeru to create one.");
+ expect(
+ renderToStaticMarkup(<RoutinePanel botName="Akeru" status="error" error="Request failed" />),
+ ).toContain("Request failed");
+ expect(renderToStaticMarkup(<RoutinePanel botName="Akeru" status="unavailable" />)).toContain(
+ "Routines are not available for this environment.",
+ );
+ });
+
+ it("shows approval and reverse-state actions", () => {
+ const needsApproval: RoutineAdapterItem = {
+ ...routine,
+ procedureApproved: false,
+ latestRun: { ...run, status: "waiting-for-approval", error: null },
+ };
+ const disabled = { ...routine, id: "disabled", enabled: false };
+ const paused = { ...routine, id: "paused", enabled: false, paused: true };
+ const markup = renderToStaticMarkup(
+ <RoutinePanel
+ botName="Akeru"
+ status="ready"
+ routines={[needsApproval, disabled, paused]}
+ onApproveProcedure={() => undefined}
+ onSetEnabled={() => undefined}
+ onSetPaused={() => undefined}
+ />,
+ );
+
+ expect(markup).toContain(">Approve procedure</button>");
+ expect(markup).toContain(">Enable</button>");
+ expect(markup).toContain(">Resume</button>");
+ expect(markup).toContain(">Delete</button>");
+
+ const needsApprovalMarkup = renderToStaticMarkup(
+ <RoutinePanel
+ botName="Akeru"
+ status="ready"
+ routines={[{ ...needsApproval, enabled: false }]}
+ onApproveProcedure={() => undefined}
+ onSetEnabled={() => undefined}
+ onSetPaused={() => undefined}
+ />,
+ );
+ expect(needsApprovalMarkup).not.toContain(">Enable</button>");
+ expect(needsApprovalMarkup).not.toContain(">Pause</button>");
+
+ const pausedMarkup = renderToStaticMarkup(
+ <RoutinePanel
+ botName="Akeru"
+ status="ready"
+ routines={[paused]}
+ onSetEnabled={() => undefined}
+ onSetPaused={() => undefined}
+ />,
+ );
+ expect(pausedMarkup).toContain(">Resume</button>");
+ expect(pausedMarkup).not.toContain(">Enable</button>");
+ });
+});
diff --git a/apps/web/src/components/roster/RoutinePanel.tsx b/apps/web/src/components/roster/RoutinePanel.tsx
new file mode 100644
index 000000000..80f919ea4
--- /dev/null
+++ b/apps/web/src/components/roster/RoutinePanel.tsx
@@ -0,0 +1,523 @@
+import { useState } from "react";
+
+import { Button } from "../ui/button";
+import { Badge } from "../ui/badge";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogPopup,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
+import {
+ Dialog,
+ DialogClose,
+ DialogFooter,
+ DialogHeader,
+ DialogPanel,
+ DialogPopup,
+ DialogTitle,
+} from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Textarea } from "../ui/textarea";
+
+export type RoutineAdapterFrequency = "daily" | "weekdays" | "weekly";
+export type RoutineAdapterApproval =
+ | "approval-required"
+ | "auto-accept-edits"
+ | "auto"
+ | "full-access";
+export type RoutineAdapterSandbox = "local" | "e2b" | "daytona" | "vercel-sandbox" | "upstash-box";
+export type RoutineAdapterRunStatus =
+ | "queued"
+ | "waiting-for-approval"
+ | "running"
+ | "blocked"
+ | "failed"
+ | "completed"
+ | "canceled";
+
+export interface RoutineAdapterProject {
+ readonly id: string;
+ readonly name: string;
+}
+
+export interface RoutineAdapterSchedule {
+ readonly frequency: RoutineAdapterFrequency;
+ readonly time: string;
+ readonly timezone: string;
+ readonly weekday: number | null;
+}
+
+export interface RoutineAdapterRun {
+ readonly id: string;
+ readonly status: RoutineAdapterRunStatus;
+ readonly startedAt: string;
+ readonly finishedAt: string | null;
+ readonly summary: string | null;
+ readonly error: string | null;
+ readonly usage: string | null;
+}
+
+export interface RoutineAdapterItem {
+ readonly id: string;
+ readonly name: string;
+ readonly prompt: string;
+ readonly projectId: string;
+ readonly sandbox: RoutineAdapterSandbox;
+ readonly schedule: RoutineAdapterSchedule;
+ readonly approval: RoutineAdapterApproval;
+ readonly skills: readonly string[];
+ readonly connectors: readonly string[];
+ readonly procedureApproved: boolean;
+ readonly enabled: boolean;
+ readonly paused: boolean;
+ readonly nextRunAt: string | null;
+ readonly lastRunAt: string | null;
+ readonly latestRun: RoutineAdapterRun | null;
+ readonly runHistory: readonly RoutineAdapterRun[];
+}
+
+export interface RoutineAdapterDraft {
+ readonly name: string;
+ readonly prompt: string;
+ readonly projectId: string;
+ readonly sandbox: RoutineAdapterSandbox;
+ readonly schedule: RoutineAdapterSchedule;
+ readonly approval: RoutineAdapterApproval;
+ readonly skills: readonly string[];
+ readonly connectors: readonly string[];
+}
+
+export interface RoutinePanelProps {
+ readonly botName: string;
+ readonly status: "loading" | "ready" | "error" | "unavailable";
+ readonly error?: string | null;
+ readonly routines?: readonly RoutineAdapterItem[];
+ readonly projectOptions?: readonly RoutineAdapterProject[];
+ readonly skillOptions?: readonly string[];
+ readonly connectorOptions?: readonly string[];
+ readonly busyRoutineId?: string | null;
+ readonly onCreate?: (draft: RoutineAdapterDraft) => void | Promise<void>;
+ readonly onUpdate?: (routineId: string, draft: RoutineAdapterDraft) => void | Promise<void>;
+ readonly onDryRun?: (routineId: string) => void;
+ readonly onApproveProcedure?: (routineId: string) => void;
+ readonly onRunNow?: (routineId: string) => void;
+ readonly onSetEnabled?: (routineId: string, enabled: boolean) => void;
+ readonly onSetPaused?: (routineId: string, paused: boolean) => void;
+ readonly onDelete?: (routineId: string) => void;
+}
+
+const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
+
+export function routineScheduleLabel(schedule: RoutineAdapterSchedule) {
+ const frequency =
+ schedule.frequency === "daily"
+ ? "Daily"
+ : schedule.frequency === "weekdays"
+ ? "Weekdays"
+ : WEEKDAYS[schedule.weekday ?? 1];
+ return `${frequency} at ${schedule.time} (${schedule.timezone})`;
+}
+
+export function boundedRunHistory(history: readonly RoutineAdapterRun[]) {
+ return history.slice(0, 5);
+}
+
+function shortDate(value: string | null) {
+ if (!value) return "Not scheduled";
+ return new Date(value).toLocaleString(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ });
+}
+
+function runLabel(run: RoutineAdapterRun) {
+ if (run.error) return run.error;
+ if (run.summary) return run.summary;
+ return run.status === "completed" ? "Completed" : run.status.replaceAll("-", " ");
+}
+
+function editDraft(routine: RoutineAdapterItem): RoutineAdapterDraft {
+ return {
+ name: routine.name,
+ prompt: routine.prompt,
+ projectId: routine.projectId,
+ sandbox: routine.sandbox,
+ schedule: routine.schedule,
+ approval: routine.approval,
+ skills: routine.skills,
+ connectors: routine.connectors,
+ };
+}
+
+function csv(value: string) {
+ return value
+ .split(",")
+ .map((item) => item.trim())
+ .filter(Boolean);
+}
+
+function RoutineEditor({
+ routine,
+ projectOptions,
+ onClose,
+ onUpdate,
+}: {
+ readonly routine: RoutineAdapterItem;
+ readonly projectOptions: readonly RoutineAdapterProject[];
+ readonly onClose: () => void;
+ readonly onUpdate?: RoutinePanelProps["onUpdate"];
+}) {
+ const [draft, setDraft] = useState(() => editDraft(routine));
+ const [saving, setSaving] = useState(false);
+ const save = async () => {
+ if (!onUpdate) return;
+ setSaving(true);
+ try {
+ await onUpdate(routine.id, draft);
+ onClose();
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogPopup className="max-h-[min(42rem,90dvh)] max-w-lg flex-col overflow-hidden">
+ <DialogHeader className="border-b px-6 py-5">
+ <DialogTitle>Edit routine</DialogTitle>
+ </DialogHeader>
+ <DialogPanel className="space-y-4 px-6 py-5">
+ <label className="block space-y-1.5 text-sm">
+ <span>Name</span>
+ <Input
+ value={draft.name}
+ onChange={(event) => setDraft({ ...draft, name: event.target.value })}
+ />
+ </label>
+ <label className="block space-y-1.5 text-sm">
+ <span>Instructions</span>
+ <Textarea
+ value={draft.prompt}
+ onChange={(event) => setDraft({ ...draft, prompt: event.target.value })}
+ />
+ </label>
+ <div className="grid grid-cols-2 gap-3">
+ <label className="space-y-1.5 text-sm">
+ <span>Schedule</span>
+ <select
+ className="h-8 w-full rounded-md border border-input bg-background px-2 text-sm"
+ value={draft.schedule.frequency}
+ onChange={(event) =>
+ setDraft({
+ ...draft,
+ schedule: {
+ ...draft.schedule,
+ frequency: event.target.value as RoutineAdapterFrequency,
+ weekday:
+ event.target.value === "weekly" ? (draft.schedule.weekday ?? 1) : null,
+ },
+ })
+ }
+ >
+ <option value="daily">Daily</option>
+ <option value="weekdays">Weekdays</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ </label>
+ <label className="space-y-1.5 text-sm">
+ <span>Time</span>
+ <Input
+ type="time"
+ value={draft.schedule.time}
+ onChange={(event) =>
+ setDraft({ ...draft, schedule: { ...draft.schedule, time: event.target.value } })
+ }
+ />
+ </label>
+ </div>
+ {draft.schedule.frequency === "weekly" ? (
+ <label className="block space-y-1.5 text-sm">
+ <span>Day</span>
+ <select
+ className="h-8 w-full rounded-md border border-input bg-background px-2 text-sm"
+ value={draft.schedule.weekday ?? 1}
+ onChange={(event) =>
+ setDraft({
+ ...draft,
+ schedule: { ...draft.schedule, weekday: Number(event.target.value) },
+ })
+ }
+ >
+ {WEEKDAYS.map((day, index) => (
+ <option key={day} value={index}>
+ {day}
+ </option>
+ ))}
+ </select>
+ </label>
+ ) : null}
+ <label className="block space-y-1.5 text-sm">
+ <span>Timezone</span>
+ <Input
+ value={draft.schedule.timezone}
+ onChange={(event) =>
+ setDraft({
+ ...draft,
+ schedule: { ...draft.schedule, timezone: event.target.value },
+ })
+ }
+ />
+ </label>
+ {projectOptions.length > 0 ? (
+ <label className="block space-y-1.5 text-sm">
+ <span>Project</span>
+ <select
+ className="h-8 w-full rounded-md border border-input bg-background px-2 text-sm"
+ value={draft.projectId}
+ onChange={(event) => setDraft({ ...draft, projectId: event.target.value })}
+ >
+ {projectOptions.map((project) => (
+ <option key={project.id} value={project.id}>
+ {project.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ ) : null}
+ <label className="block space-y-1.5 text-sm">
+ <span>Skills</span>
+ <Input
+ value={draft.skills.join(", ")}
+ onChange={(event) => setDraft({ ...draft, skills: csv(event.target.value) })}
+ />
+ </label>
+ <label className="block space-y-1.5 text-sm">
+ <span>Connectors</span>
+ <Input
+ value={draft.connectors.join(", ")}
+ onChange={(event) => setDraft({ ...draft, connectors: csv(event.target.value) })}
+ />
+ </label>
+ </DialogPanel>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
+ <Button
+ disabled={saving || !draft.name.trim() || !draft.prompt.trim()}
+ onClick={() => void save()}
+ >
+ {saving ? "Saving" : "Save changes"}
+ </Button>
+ </DialogFooter>
+ </DialogPopup>
+ </Dialog>
+ );
+}
+
+function RoutineCard({
+ routine,
+ busy,
+ onEdit,
+ onDeleteRequest,
+ ...actions
+}: {
+ readonly routine: RoutineAdapterItem;
+ readonly busy: boolean;
+ readonly onEdit: () => void;
+ readonly onDeleteRequest: () => void;
+} & Pick<
+ RoutinePanelProps,
+ "onApproveProcedure" | "onDryRun" | "onRunNow" | "onSetEnabled" | "onSetPaused"
+>) {
+ const status = routine.paused ? "Paused" : routine.enabled ? "Active" : "Draft";
+ const latest = routine.latestRun;
+ return (
+ <article className="rounded-lg border border-border/80 px-3 py-2.5">
+ <div className="flex items-center gap-2">
+ <h4 className="min-w-0 flex-1 truncate text-sm font-medium">{routine.name}</h4>
+ <Badge
+ size="sm"
+ variant={routine.paused ? "warning" : routine.enabled ? "success" : "secondary"}
+ >
+ {status}
+ </Badge>
+ </div>
+ <p className="mt-1 truncate text-xs text-muted-foreground">
+ {routineScheduleLabel(routine.schedule)}
+ </p>
+ <div className="mt-2 flex items-center gap-2 text-xs">
+ <span className="shrink-0 text-muted-foreground">Next {shortDate(routine.nextRunAt)}</span>
+ {latest ? (
+ <span
+ className={
+ latest.error
+ ? "min-w-0 truncate text-destructive"
+ : "min-w-0 truncate text-muted-foreground"
+ }
+ >
+ {runLabel(latest)}
+ </span>
+ ) : null}
+ </div>
+ {!routine.procedureApproved ? (
+ <Button
+ className="mt-2"
+ size="micro"
+ disabled={busy || !actions.onApproveProcedure}
+ onClick={() => actions.onApproveProcedure?.(routine.id)}
+ >
+ Approve procedure
+ </Button>
+ ) : null}
+ <div className="mt-2 flex flex-wrap gap-1">
+ <Button
+ size="micro"
+ variant="outline"
+ disabled={busy || !actions.onDryRun}
+ onClick={() => actions.onDryRun?.(routine.id)}
+ >
+ Dry run
+ </Button>
+ <Button
+ size="micro"
+ variant="outline"
+ disabled={busy || !routine.procedureApproved || !actions.onRunNow}
+ onClick={() => actions.onRunNow?.(routine.id)}
+ >
+ Run now
+ </Button>
+ {routine.paused ? (
+ <Button
+ size="micro"
+ variant="outline"
+ disabled={busy || !actions.onSetPaused}
+ onClick={() => actions.onSetPaused?.(routine.id, false)}
+ >
+ Resume
+ </Button>
+ ) : !routine.enabled && routine.procedureApproved ? (
+ <Button
+ size="micro"
+ variant="outline"
+ disabled={busy || !actions.onSetEnabled}
+ onClick={() => actions.onSetEnabled?.(routine.id, true)}
+ >
+ Enable
+ </Button>
+ ) : routine.enabled ? (
+ <Button
+ size="micro"
+ variant="outline"
+ disabled={busy || !actions.onSetPaused}
+ onClick={() => actions.onSetPaused?.(routine.id, true)}
+ >
+ Pause
+ </Button>
+ ) : null}
+ <Button size="micro" variant="ghost" disabled={busy} onClick={onEdit}>
+ Edit
+ </Button>
+ <Button size="micro" variant="ghost-muted" disabled={busy} onClick={onDeleteRequest}>
+ Delete
+ </Button>
+ </div>
+ </article>
+ );
+}
+
+export function RoutinePanel({
+ botName,
+ status,
+ error,
+ routines = [],
+ projectOptions = [],
+ busyRoutineId = null,
+ onUpdate,
+ onDelete,
+ ...actions
+}: RoutinePanelProps) {
+ const [editorRoutine, setEditorRoutine] = useState<RoutineAdapterItem | null>(null);
+ const [deleteRoutine, setDeleteRoutine] = useState<RoutineAdapterItem | null>(null);
+
+ return (
+ <section className="border-t border-border px-3 py-3">
+ <h3 className="text-sm font-medium">Routines</h3>
+ {status === "loading" ? (
+ <div
+ className="flex min-h-20 items-center justify-center text-xs text-muted-foreground"
+ aria-label="Loading routines"
+ >
+ Loading
+ </div>
+ ) : status === "error" ? (
+ <p className="mt-2 text-xs text-destructive">{error || "Could not load routines."}</p>
+ ) : status === "unavailable" ? (
+ <p className="mt-2 text-xs text-muted-foreground">
+ Routines are not available for this environment.
+ </p>
+ ) : routines.length === 0 ? (
+ <div className="py-5 text-center">
+ <p className="text-sm font-medium">No routines</p>
+ <p className="mt-1 text-xs text-muted-foreground">Ask {botName} to create one.</p>
+ </div>
+ ) : (
+ <div className="mt-2 space-y-2">
+ {routines.map((routine) => (
+ <RoutineCard
+ key={routine.id}
+ routine={routine}
+ busy={busyRoutineId === routine.id}
+ onEdit={() => setEditorRoutine(routine)}
+ onDeleteRequest={() => setDeleteRoutine(routine)}
+ {...(actions.onApproveProcedure
+ ? { onApproveProcedure: actions.onApproveProcedure }
+ : {})}
+ {...(actions.onDryRun ? { onDryRun: actions.onDryRun } : {})}
+ {...(actions.onRunNow ? { onRunNow: actions.onRunNow } : {})}
+ {...(actions.onSetEnabled ? { onSetEnabled: actions.onSetEnabled } : {})}
+ {...(actions.onSetPaused ? { onSetPaused: actions.onSetPaused } : {})}
+ />
+ ))}
+ </div>
+ )}
+ {editorRoutine ? (
+ <RoutineEditor
+ routine={editorRoutine}
+ projectOptions={projectOptions}
+ onUpdate={onUpdate}
+ onClose={() => setEditorRoutine(null)}
+ />
+ ) : null}
+ <AlertDialog
+ open={deleteRoutine !== null}
+ onOpenChange={(open) => !open && setDeleteRoutine(null)}
+ >
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete routine "{deleteRoutine?.name}"?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This removes the schedule and its run history.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
+ <AlertDialogClose
+ render={<Button variant="destructive" />}
+ onClick={() => {
+ if (deleteRoutine) onDelete?.(deleteRoutine.id);
+ setDeleteRoutine(null);
+ }}
+ >
+ Delete
+ </AlertDialogClose>
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
+ </section>
+ );
+}
diff --git a/apps/web/src/components/roster/botConversationPresentation.test.ts b/apps/web/src/components/roster/botConversationPresentation.test.ts
index f9b2c7886..1a4e475a1 100644
--- a/apps/web/src/components/roster/botConversationPresentation.test.ts
+++ b/apps/web/src/components/roster/botConversationPresentation.test.ts
@@ -5,6 +5,7 @@ import {
channelOriginLabel,
channelOriginForAssistantMessage,
channelProviderLabel,
+ isBotConversationWorking,
visibleBotChatMessages,
} from "./botConversationPresentation";
@@ -54,6 +55,23 @@ describe("bot conversation presentation", () => {
expect(channelOriginForAssistantMessage(messages, 0)).toBeNull();
});
+ it("shows working as soon as a question response starts", () => {
+ expect(
+ isBotConversationWorking({
+ sending: false,
+ respondingToUserInput: true,
+ presence: "needs-you",
+ }),
+ ).toBe(true);
+ expect(
+ isBotConversationWorking({
+ sending: false,
+ respondingToUserInput: false,
+ presence: "needs-you",
+ }),
+ ).toBe(false);
+ });
+
it("keeps user messages and settled answers only", () => {
const messages = [
message("user", "user", false),
@@ -65,21 +83,17 @@ describe("bot conversation presentation", () => {
expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual(["user", "answer"]);
});
- it("shows each settled assistant note from one turn", () => {
+ it("shows only the last settled assistant record from one turn", () => {
const messages = [
message("user", "user", false),
message("intermediate", "assistant", false, "turn-1"),
message("final", "assistant", false, "turn-1"),
];
- expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual([
- "user",
- "intermediate",
- "final",
- ]);
+ expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual(["user", "final"]);
});
- it("shows completed status beats while the turn remains active", () => {
+ it("hides assistant records from the active turn behind the working status", () => {
const messages = [
message("first-user", "user", false),
message("first-answer", "assistant", false, "turn-1"),
@@ -87,11 +101,19 @@ describe("bot conversation presentation", () => {
message("active-intermediate", "assistant", false, "turn-2"),
];
- expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual([
+ expect(visibleBotChatMessages(messages, true).map((entry) => entry.id)).toEqual([
"first-user",
"first-answer",
"active-user",
- "active-intermediate",
]);
});
+
+ it("hides internal routine trigger messages", () => {
+ const messages = [
+ message("routine:run-1:message", "user", false),
+ message("answer", "assistant", false, "turn-1"),
+ ];
+
+ expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual(["answer"]);
+ });
});
diff --git a/apps/web/src/components/roster/botConversationPresentation.ts b/apps/web/src/components/roster/botConversationPresentation.ts
index 2dbd23d70..3e4350390 100644
--- a/apps/web/src/components/roster/botConversationPresentation.ts
+++ b/apps/web/src/components/roster/botConversationPresentation.ts
@@ -1,4 +1,5 @@
import type { ChannelMessageOrigin, OrchestrationMessage } from "@t3tools/contracts";
+import type { RosterPresence } from "./roster.logic";
export function channelProviderLabel(
provider: ChannelMessageOrigin["provider"] | "whatsapp",
@@ -27,14 +28,47 @@ export function channelOriginForAssistantMessage(
return null;
}
+export function isBotConversationWorking(input: {
+ sending: boolean;
+ respondingToUserInput: boolean;
+ presence: RosterPresence;
+}): boolean {
+ return input.sending || input.respondingToUserInput || input.presence === "working";
+}
+
/**
- * Bot chat shows user messages and every completed assistant note. A turn can
- * answer before tools, add status beats during work, and finish with a result.
+ * Bot chat shows each user message and one final assistant answer per turn.
+ * Provider progress and intermediate assistant records stay behind the working
+ * status so one provider turn cannot appear as several bot replies.
*/
export function visibleBotChatMessages(
messages: ReadonlyArray<OrchestrationMessage>,
+ working = false,
): ReadonlyArray<OrchestrationMessage> {
- return messages.filter(
- (message) => message.role === "user" || (message.role === "assistant" && !message.streaming),
- );
+ const latestAssistantIndexByResponse = new Map<string, number>();
+ let precedingUserId = "before-first-user";
+ let lastUserIndex = -1;
+
+ messages.forEach((message, index) => {
+ if (message.role === "user" && String(message.id).startsWith("routine:")) return;
+ if (message.role === "user") {
+ precedingUserId = message.id;
+ lastUserIndex = index;
+ return;
+ }
+ if (message.role !== "assistant" || message.streaming) return;
+ latestAssistantIndexByResponse.set(message.turnId ?? precedingUserId, index);
+ });
+
+ precedingUserId = "before-first-user";
+ return messages.filter((message, index) => {
+ if (message.role === "user" && String(message.id).startsWith("routine:")) return false;
+ if (message.role === "user") {
+ precedingUserId = message.id;
+ return true;
+ }
+ if (message.role !== "assistant" || message.streaming) return false;
+ if (working && index > lastUserIndex) return false;
+ return latestAssistantIndexByResponse.get(message.turnId ?? precedingUserId) === index;
+ });
}
diff --git a/apps/web/src/components/roster/routineAdapter.ts b/apps/web/src/components/roster/routineAdapter.ts
new file mode 100644
index 000000000..86d2b4678
--- /dev/null
+++ b/apps/web/src/components/roster/routineAdapter.ts
@@ -0,0 +1,103 @@
+import type {
+ McpServer,
+ Routine,
+ RoutineRun,
+ RoutineSchedule,
+ RoutineSkillAssignment,
+} from "@t3tools/contracts";
+
+import type {
+ RoutineAdapterDraft,
+ RoutineAdapterItem,
+ RoutineAdapterRun,
+ RoutineAdapterSchedule,
+} from "./RoutinePanel";
+
+const WEEKDAYS = [
+ "sunday",
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+] as const;
+
+export function toRoutineSchedule(draft: RoutineAdapterDraft): RoutineSchedule {
+ if (draft.schedule.frequency !== "weekly") {
+ return { kind: draft.schedule.frequency, time: draft.schedule.time };
+ }
+ return {
+ kind: "weekly",
+ weekdays: [WEEKDAYS[draft.schedule.weekday ?? 1]!],
+ time: draft.schedule.time,
+ };
+}
+
+function toAdapterSchedule(routine: Routine): RoutineAdapterSchedule {
+ return {
+ frequency: routine.schedule.kind,
+ time: routine.schedule.time,
+ timezone: routine.timezone,
+ weekday:
+ routine.schedule.kind === "weekly"
+ ? WEEKDAYS.indexOf(routine.schedule.weekdays[0] ?? "monday")
+ : null,
+ };
+}
+
+function toAdapterRun(run: RoutineRun): RoutineAdapterRun {
+ return {
+ id: run.id,
+ status: run.status,
+ startedAt: run.startedAt ?? run.createdAt,
+ finishedAt: run.completedAt,
+ summary: run.result?.summary ?? null,
+ error: run.failure?.message ?? null,
+ usage: run.usageRef,
+ };
+}
+
+export function toRoutinePanelItem(
+ routine: Routine,
+ runs: readonly RoutineRun[],
+ assignments: readonly RoutineSkillAssignment[],
+ mcpServers: readonly McpServer[],
+): RoutineAdapterItem {
+ const history = runs
+ .filter((run) => run.routineId === routine.id)
+ .toSorted((left, right) => right.createdAt.localeCompare(left.createdAt))
+ .map(toAdapterRun);
+ const assignmentNames = new Map(
+ assignments.map((assignment) => [assignment.id, assignment.name]),
+ );
+ const connectorNames = new Map(mcpServers.map((server) => [server.id, server.name]));
+
+ return {
+ id: routine.id,
+ name: routine.job,
+ prompt: routine.procedure,
+ projectId: routine.projectId,
+ sandbox: routine.sandbox,
+ schedule: toAdapterSchedule(routine),
+ approval: routine.approvalPolicy,
+ skills: routine.skillAssignmentIds.flatMap((id) => {
+ const name = assignmentNames.get(id);
+ return name ? [name] : [];
+ }),
+ connectors: routine.connectorDependencies.flatMap((id) => {
+ const name = connectorNames.get(id);
+ return name ? [name] : [];
+ }),
+ procedureApproved: routine.approvalVersion === routine.procedureVersion,
+ enabled: routine.enabled,
+ paused:
+ routine.lifecycle === "paused" ||
+ routine.lifecycle === "blocked" ||
+ routine.lifecycle === "failed",
+ nextRunAt: routine.nextRunAt,
+ lastRunAt: routine.lastRunAt,
+ latestRun: history[0] ?? null,
+ runHistory: history,
+ };
+}
diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.ts
index 1e217e54e..2bfdf6242 100644
--- a/apps/web/src/components/roster/useBotThreadRuntime.ts
+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts
@@ -3,12 +3,14 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
BotId,
+ type ApprovalRequestId,
EnvironmentId,
ThreadId,
type ModelSelection,
+ type ProviderApprovalDecision,
type ScopedThreadRef,
} from "@t3tools/contracts";
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { usePrimarySettings } from "../../hooks/useSettings";
import { DEFAULT_INTERACTION_MODE } from "../../types";
@@ -17,6 +19,7 @@ import { resolveAppModelSelectionState } from "../../modelSelection";
import {
useAllEnvironmentShellsBootstrapped,
useProjects,
+ useThreadActivities,
useThreadMessages,
useThreadShell,
useThreadShells,
@@ -26,6 +29,13 @@ import { usePrimaryEnvironmentId } from "../../state/environments";
import { primaryServerProvidersAtom } from "../../state/server";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
+import { derivePendingApprovals, derivePendingUserInputs } from "../../session-logic";
+import {
+ applyPendingUserInputSingleSelect,
+ buildPendingUserInputAnswers,
+ type PendingUserInputDraftAnswer,
+ togglePendingUserInputOptionSelection,
+} from "../../pendingUserInput";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import { resolveBotRuntimeMode } from "./botSandbox";
import {
@@ -107,6 +117,9 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
retainedThreadRef.current.threadRef = linkedThreadRef;
}
const messages = useThreadMessages(linkedThreadRef);
+ const activities = useThreadActivities(linkedThreadRef);
+ const pendingApprovals = useMemo(() => derivePendingApprovals(activities), [activities]);
+ const pendingUserInputs = useMemo(() => derivePendingUserInputs(activities), [activities]);
const defaultProject = useMemo(
() =>
bootstrapped && primaryEnvironmentId
@@ -132,6 +145,12 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
reportFailure: false,
});
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
+ const respondToApprovalCommand = useAtomCommand(threadEnvironment.respondToApproval, {
+ reportFailure: false,
+ });
+ const respondToUserInputCommand = useAtomCommand(threadEnvironment.respondToUserInput, {
+ reportFailure: false,
+ });
const appendVoiceTranscript = useAtomCommand(threadEnvironment.appendVoiceTranscript, {
reportFailure: false,
});
@@ -141,7 +160,43 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
const sendQueueRef = useRef(createBotTurnSubmissionQueue());
const queuedSendCountRef = useRef(0);
const [sending, setSending] = useState(false);
+ const [respondingToApproval, setRespondingToApproval] = useState(false);
+ const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
+ const respondingRequestIdsRef = useRef(new Set<ApprovalRequestId>());
+ const singleSelectInFlightRef = useRef<string | null>(null);
+ const [pendingUserInputAnswers, setPendingUserInputAnswers] = useState<
+ Record<string, PendingUserInputDraftAnswer>
+ >({});
+ const [pendingUserInputQuestionIndex, setPendingUserInputQuestionIndex] = useState(0);
const [error, setError] = useState<string | null>(null);
+ const submitPendingUserInput = useCallback(
+ async (
+ requestId: ApprovalRequestId,
+ answers: Record<string, string | string[]>,
+ ): Promise<boolean> => {
+ if (!linkedThreadRef || respondingRequestIdsRef.current.has(requestId)) return false;
+ respondingRequestIdsRef.current.add(requestId);
+ setRespondingRequestIds((current) =>
+ current.includes(requestId) ? current : [...current, requestId],
+ );
+ const result = await respondToUserInputCommand({
+ environmentId: linkedThreadRef.environmentId,
+ input: {
+ threadId: linkedThreadRef.threadId,
+ requestId,
+ answers,
+ },
+ });
+ if (result._tag === "Failure") {
+ respondingRequestIdsRef.current.delete(requestId);
+ setRespondingRequestIds((current) => current.filter((id) => id !== requestId));
+ setError(errorMessage(result));
+ return false;
+ }
+ return true;
+ },
+ [linkedThreadRef, respondToUserInputCommand],
+ );
const ensureTranscriptThread = useCallback(
async (title = `Call with ${bot?.name ?? "bot"}`): Promise<ScopedThreadRef | null> => {
@@ -192,7 +247,25 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
);
const send = useCallback(
- (prompt: string, files: readonly File[]): Promise<boolean> => {
+ async (prompt: string, files: readonly File[]): Promise<boolean> => {
+ const pendingUserInput = pendingUserInputs[0];
+ if (pendingUserInput && linkedThreadRef && files.length === 0) {
+ if (respondingRequestIds.includes(pendingUserInput.requestId)) return false;
+ const question = pendingUserInput.questions[pendingUserInputQuestionIndex];
+ if (!question || !prompt.trim()) return false;
+ const nextAnswers = {
+ ...pendingUserInputAnswers,
+ [question.id]: { customAnswer: prompt.trim() },
+ };
+ setPendingUserInputAnswers(nextAnswers);
+ if (pendingUserInputQuestionIndex < pendingUserInput.questions.length - 1) {
+ setPendingUserInputQuestionIndex((index) => index + 1);
+ return true;
+ }
+ const answers = buildPendingUserInputAnswers(pendingUserInput.questions, nextAnswers);
+ if (!answers) return false;
+ return submitPendingUserInput(pendingUserInput.requestId, answers);
+ }
if (!botReady) {
setError("The bot is still connecting.");
return Promise.resolve(false);
@@ -306,6 +379,13 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
rememberedThread?.runtimeMode,
settings.localExecutionMode,
setRuntimeMode,
+ linkedThreadRef,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ pendingUserInputs,
+ respondToUserInputCommand,
+ respondingRequestIds,
+ submitPendingUserInput,
startTurn,
],
);
@@ -330,6 +410,97 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
[appendVoiceTranscript, botId, ensureTranscriptThread],
);
+ const respondToApproval = useCallback(
+ async (
+ requestId: (typeof pendingApprovals)[number]["requestId"],
+ decision: ProviderApprovalDecision,
+ ) => {
+ if (!linkedThreadRef || respondingToApproval) return;
+ setRespondingToApproval(true);
+ const result = await respondToApprovalCommand({
+ environmentId: linkedThreadRef.environmentId,
+ input: { threadId: linkedThreadRef.threadId, requestId, decision },
+ });
+ setRespondingToApproval(false);
+ if (result._tag === "Failure") setError(errorMessage(result));
+ },
+ [linkedThreadRef, pendingApprovals, respondToApprovalCommand, respondingToApproval],
+ );
+
+ useEffect(() => {
+ setPendingUserInputAnswers({});
+ setPendingUserInputQuestionIndex(0);
+ singleSelectInFlightRef.current = null;
+ const pendingIds = new Set(pendingUserInputs.map((pending) => pending.requestId));
+ for (const requestId of respondingRequestIdsRef.current) {
+ if (!pendingIds.has(requestId)) respondingRequestIdsRef.current.delete(requestId);
+ }
+ setRespondingRequestIds((current) => current.filter((requestId) => pendingIds.has(requestId)));
+ }, [pendingUserInputs[0]?.requestId]);
+
+ const selectPendingUserInputOption = useCallback(
+ (questionId: string, optionLabel: string) => {
+ const pending = pendingUserInputs[0];
+ const question = pending?.questions.find((entry) => entry.id === questionId);
+ if (!pending || !question) return;
+ if (!question.multiSelect) {
+ const selectionKey = `${pending.requestId}:${questionId}`;
+ if (singleSelectInFlightRef.current === selectionKey) return;
+ const selection = applyPendingUserInputSingleSelect(
+ pending.questions,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ questionId,
+ optionLabel,
+ );
+ if (!selection) return;
+ singleSelectInFlightRef.current = selectionKey;
+ setPendingUserInputAnswers(selection.draftAnswers);
+ if (!selection.answers) {
+ setPendingUserInputQuestionIndex(selection.questionIndex);
+ return;
+ }
+ void submitPendingUserInput(pending.requestId, selection.answers).then((submitted) => {
+ if (!submitted) singleSelectInFlightRef.current = null;
+ });
+ return;
+ }
+ setPendingUserInputAnswers((current) => ({
+ ...current,
+ [questionId]: togglePendingUserInputOptionSelection(
+ question,
+ current[questionId],
+ optionLabel,
+ ),
+ }));
+ },
+ [
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ pendingUserInputs,
+ submitPendingUserInput,
+ ],
+ );
+
+ const advancePendingUserInput = useCallback(async () => {
+ const pending = pendingUserInputs[0];
+ if (!pending || !linkedThreadRef || respondingRequestIds.includes(pending.requestId)) return;
+ if (pendingUserInputQuestionIndex < pending.questions.length - 1) {
+ setPendingUserInputQuestionIndex((index) => index + 1);
+ return;
+ }
+ const answers = buildPendingUserInputAnswers(pending.questions, pendingUserInputAnswers);
+ if (!answers) return;
+ await submitPendingUserInput(pending.requestId, answers);
+ }, [
+ linkedThreadRef,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ pendingUserInputs,
+ respondingRequestIds,
+ submitPendingUserInput,
+ ]);
+
return {
appendTranscript,
bootstrapped,
@@ -339,6 +510,15 @@ export function useBotThreadRuntime(botId: string, effectiveModelSelection: Mode
linkedThreadRef,
latestTurn: rememberedThread?.latestTurn ?? null,
messages,
+ pendingApprovals,
+ pendingUserInputs,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ respondingRequestIds,
+ selectPendingUserInputOption,
+ advancePendingUserInput,
+ respondToApproval,
+ respondingToApproval,
send,
sending,
};
diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.ts
index 3d1cb336e..ff12bd69e 100644
--- a/apps/web/src/pendingUserInput.test.ts
+++ b/apps/web/src/pendingUserInput.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
+ applyPendingUserInputSingleSelect,
buildPendingUserInputAnswers,
countAnsweredPendingUserInputQuestions,
derivePendingUserInputProgress,
@@ -104,6 +105,39 @@ describe("togglePendingUserInputOptionSelection", () => {
});
});
+describe("applyPendingUserInputSingleSelect", () => {
+ it("builds the final answer from the clicked option without waiting for state", () => {
+ expect(
+ applyPendingUserInputSingleSelect(
+ [singleSelectQuestion],
+ {},
+ 0,
+ "scope",
+ "Orchestration-first",
+ ),
+ ).toEqual({
+ draftAnswers: {
+ scope: { customAnswer: "", selectedOptionLabels: ["Orchestration-first"] },
+ },
+ questionIndex: 0,
+ answers: { scope: "Orchestration-first" },
+ });
+ });
+
+ it("advances a multi-question prompt without submitting it early", () => {
+ const second = { ...singleSelectQuestion, id: "second" };
+ expect(
+ applyPendingUserInputSingleSelect(
+ [singleSelectQuestion, second],
+ {},
+ 0,
+ "scope",
+ "Orchestration-first",
+ ),
+ ).toMatchObject({ questionIndex: 1, answers: null });
+ });
+});
+
describe("buildPendingUserInputAnswers", () => {
it("returns a canonical answer map for complete prompts", () => {
expect(
diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.ts
index d3a7a1293..8baf25575 100644
--- a/apps/web/src/pendingUserInput.ts
+++ b/apps/web/src/pendingUserInput.ts
@@ -102,6 +102,43 @@ export function togglePendingUserInputOptionSelection(
};
}
+export interface PendingUserInputSingleSelectResult {
+ draftAnswers: Record<string, PendingUserInputDraftAnswer>;
+ questionIndex: number;
+ answers: Record<string, string | string[]> | null;
+}
+
+export function applyPendingUserInputSingleSelect(
+ questions: ReadonlyArray<UserInputQuestion>,
+ draftAnswers: Record<string, PendingUserInputDraftAnswer>,
+ questionIndex: number,
+ questionId: string,
+ optionLabel: string,
+): PendingUserInputSingleSelectResult | null {
+ const question = questions[questionIndex];
+ if (!question || question.id !== questionId || question.multiSelect) return null;
+ if (!question.options.some((option) => option.label === optionLabel)) return null;
+
+ const nextDraftAnswers = {
+ ...draftAnswers,
+ [questionId]: togglePendingUserInputOptionSelection(
+ question,
+ draftAnswers[questionId],
+ optionLabel,
+ ),
+ };
+ const nextQuestionIndex = Math.min(questionIndex + 1, Math.max(questions.length - 1, 0));
+
+ return {
+ draftAnswers: nextDraftAnswers,
+ questionIndex: nextQuestionIndex,
+ answers:
+ questionIndex === questions.length - 1
+ ? buildPendingUserInputAnswers(questions, nextDraftAnswers)
+ : null,
+ };
+}
+
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
diff --git a/apps/web/src/routes/_chat.bots.$botId.tsx b/apps/web/src/routes/_chat.bots.$botId.tsx
index 4ecdeb544..6bcecd660 100644
--- a/apps/web/src/routes/_chat.bots.$botId.tsx
+++ b/apps/web/src/routes/_chat.bots.$botId.tsx
@@ -1,23 +1,150 @@
-import { BotId } from "@t3tools/contracts";
+import { useAtomValue } from "@effect/atom-react";
+import {
+ BotId,
+ EnvironmentId,
+ McpServerId,
+ ProjectId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
+ SkillId,
+} from "@t3tools/contracts";
import { createFileRoute } from "@tanstack/react-router";
+import { useMemo, useState } from "react";
import { BotThreadLanding } from "../components/roster/BotThreadLanding";
import { BotDetailsPanel } from "../components/roster/BotDetailsPanel";
import { useBotThreadRef } from "../components/roster/useBotThreadRef";
+import type { RoutineAdapterDraft } from "../components/roster/RoutinePanel";
+import { toRoutinePanelItem, toRoutineSchedule } from "../components/roster/routineAdapter";
import { useRosterStore } from "../components/roster/rosterStore";
import { toastManager } from "../components/ui/toast";
+import { randomUUID } from "../lib/utils";
import { botEnvironment } from "../state/bots";
import { usePrimaryEnvironmentId } from "../state/environments";
+import { routineEnvironment } from "../state/routines";
+import { primaryServerProvidersAtom } from "../state/server";
+import { environmentSnapshotAtom } from "../state/shell";
import { useAtomCommand } from "../state/use-atom-command";
+const NO_ENVIRONMENT = "" as EnvironmentId;
+
function BotThreadRouteView() {
const { botId } = Route.useParams();
const environmentId = usePrimaryEnvironmentId();
const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });
+ const draftRoutine = useAtomCommand(routineEnvironment.draft, { reportFailure: false });
+ const approveRoutine = useAtomCommand(routineEnvironment.approve, { reportFailure: false });
+ const enableRoutine = useAtomCommand(routineEnvironment.enable, { reportFailure: false });
+ const pauseRoutine = useAtomCommand(routineEnvironment.pause, { reportFailure: false });
+ const runRoutine = useAtomCommand(routineEnvironment.run, { reportFailure: false });
+ const deleteRoutine = useAtomCommand(routineEnvironment.delete, { reportFailure: false });
+ const assignSkill = useAtomCommand(routineEnvironment.assignSkill, { reportFailure: false });
+ const snapshot = useAtomValue(environmentSnapshotAtom(environmentId ?? NO_ENVIRONMENT));
+ const providers = useAtomValue(primaryServerProvidersAtom);
+ const [busyRoutineId, setBusyRoutineId] = useState<string | null>(null);
const bot = useRosterStore((state) =>
state.bots.find((candidate) => candidate.id === botId && candidate.archivedAt === null),
);
const threadRef = useBotThreadRef(botId);
+ const botAssignments = useMemo(
+ () => (snapshot?.skillAssignments ?? []).filter((assignment) => assignment.botId === botId),
+ [botId, snapshot?.skillAssignments],
+ );
+ const providerSkills = useMemo(
+ () =>
+ providers
+ .filter((provider) => provider.instanceId === bot?.engine?.provider)
+ .flatMap((provider) => provider.skills)
+ .filter((skill) => skill.enabled),
+ [bot?.engine?.provider, providers],
+ );
+ const skillOptions = useMemo(
+ () =>
+ [
+ ...new Set([
+ ...botAssignments.map((assignment) => assignment.name),
+ ...providerSkills.map((skill) => skill.name),
+ ]),
+ ].sort(),
+ [botAssignments, providerSkills],
+ );
+ const routines = useMemo(
+ () =>
+ (snapshot?.routines ?? [])
+ .filter((routine) => routine.botId === botId && routine.lifecycle !== "deleted")
+ .map((routine) =>
+ toRoutinePanelItem(
+ routine,
+ snapshot?.routineRuns ?? [],
+ snapshot?.skillAssignments ?? [],
+ snapshot?.mcpServers ?? [],
+ ),
+ ),
+ [botId, snapshot],
+ );
+
+ const requireSuccess = (result: { readonly _tag: string }, message: string) => {
+ if (result._tag === "Success") return;
+ toastManager.add({ type: "error", title: message });
+ throw new Error(message);
+ };
+
+ const withBusy = async (routineId: string, action: () => Promise<void>) => {
+ setBusyRoutineId(routineId);
+ try {
+ await action();
+ } finally {
+ setBusyRoutineId(null);
+ }
+ };
+ const startBusy = (routineId: string, action: () => Promise<void>) => {
+ void withBusy(routineId, action).catch(() => undefined);
+ };
+
+ const skillAssignmentIds = async (draft: RoutineAdapterDraft) => {
+ if (!environmentId || !bot) throw new Error("The routine environment is unavailable.");
+ const ids: SkillAssignmentId[] = [];
+ for (const name of draft.skills) {
+ const existing = botAssignments.find((assignment) => assignment.name === name);
+ if (existing) {
+ ids.push(existing.id);
+ continue;
+ }
+ const assignmentId = SkillAssignmentId.make(randomUUID());
+ const metadata = providerSkills.find((skill) => skill.name === name);
+ const result = await assignSkill({
+ environmentId,
+ input: {
+ assignmentId,
+ botId: BotId.make(bot.id),
+ skillId: SkillId.make(name),
+ name,
+ description: metadata?.description ?? metadata?.shortDescription ?? null,
+ createdAt: new Date().toISOString(),
+ },
+ });
+ requireSuccess(result, `Could not assign ${name}`);
+ ids.push(assignmentId);
+ }
+ return ids;
+ };
+
+ const routineDefinition = async (draft: RoutineAdapterDraft) => ({
+ botId: BotId.make(botId),
+ job: draft.name,
+ procedure: draft.prompt,
+ schedule: toRoutineSchedule(draft),
+ timezone: draft.schedule.timezone,
+ skillAssignmentIds: await skillAssignmentIds(draft),
+ connectorDependencies: draft.connectors.flatMap((name) => {
+ const server = snapshot?.mcpServers?.find((candidate) => candidate.name === name);
+ return server ? [McpServerId.make(server.id)] : [];
+ }),
+ projectId: ProjectId.make(draft.projectId),
+ sandbox: draft.sandbox,
+ approvalPolicy: draft.approval,
+ });
return (
<>
@@ -27,6 +154,145 @@ function BotThreadRouteView() {
key={bot.id}
bot={bot}
threadRef={threadRef}
+ routinePanel={{
+ status:
+ snapshot === null
+ ? "loading"
+ : snapshot.routines === undefined
+ ? "unavailable"
+ : "ready",
+ routines,
+ skillOptions,
+ connectorOptions: (snapshot?.mcpServers ?? []).map((server) => server.name),
+ projectOptions: (snapshot?.projects ?? []).map((project) => ({
+ id: project.id,
+ name: project.title,
+ })),
+ busyRoutineId,
+ onUpdate: async (routineId, draft) => {
+ if (!environmentId) throw new Error("The routine environment is unavailable.");
+ const current = snapshot?.routines?.find((routine) => routine.id === routineId);
+ if (!current) throw new Error("The routine no longer exists.");
+ await withBusy(routineId, async () => {
+ const result = await draftRoutine({
+ environmentId,
+ input: {
+ routineId: RoutineId.make(routineId),
+ targetThreadId: current.targetThreadId,
+ ...(await routineDefinition(draft)),
+ expectedProcedureVersion: current.procedureVersion,
+ createdAt: new Date().toISOString(),
+ },
+ });
+ requireSuccess(result, "Could not save routine");
+ toastManager.add({ type: "success", title: "Routine draft saved" });
+ });
+ },
+ onApproveProcedure: (routineId) => {
+ const current = snapshot?.routines?.find((routine) => routine.id === routineId);
+ if (!environmentId || !current) return;
+ startBusy(routineId, async () => {
+ const result = await approveRoutine({
+ environmentId,
+ input: {
+ routineId: current.id,
+ procedureVersion: current.procedureVersion,
+ createdAt: new Date().toISOString(),
+ },
+ });
+ requireSuccess(result, "Could not approve procedure");
+ });
+ },
+ onDryRun: (routineId) => {
+ if (!environmentId) return;
+ startBusy(routineId, async () => {
+ const result = await runRoutine({
+ environmentId,
+ input: {
+ routineId: RoutineId.make(routineId),
+ runId: RoutineRunId.make(randomUUID()),
+ trigger: "dry-run",
+ createdAt: new Date().toISOString(),
+ },
+ });
+ requireSuccess(result, "Could not start dry run");
+ });
+ },
+ onRunNow: (routineId) => {
+ if (!environmentId) return;
+ startBusy(routineId, async () => {
+ const result = await runRoutine({
+ environmentId,
+ input: {
+ routineId: RoutineId.make(routineId),
+ runId: RoutineRunId.make(randomUUID()),
+ trigger: "manual",
+ createdAt: new Date().toISOString(),
+ },
+ });
+ requireSuccess(result, "Could not start routine");
+ });
+ },
+ onSetEnabled: (routineId, enabled) => {
+ if (!environmentId) return;
+ startBusy(routineId, async () => {
+ const createdAt = new Date().toISOString();
+ const result = enabled
+ ? await enableRoutine({
+ environmentId,
+ input: { routineId: RoutineId.make(routineId), createdAt },
+ })
+ : await pauseRoutine({
+ environmentId,
+ input: {
+ routineId: RoutineId.make(routineId),
+ reason: "Paused by the user.",
+ createdAt,
+ },
+ });
+ requireSuccess(
+ result,
+ enabled ? "Could not enable routine" : "Could not pause routine",
+ );
+ });
+ },
+ onSetPaused: (routineId, paused) => {
+ if (!environmentId) return;
+ startBusy(routineId, async () => {
+ const createdAt = new Date().toISOString();
+ const result = paused
+ ? await pauseRoutine({
+ environmentId,
+ input: {
+ routineId: RoutineId.make(routineId),
+ reason: "Paused by the user.",
+ createdAt,
+ },
+ })
+ : await enableRoutine({
+ environmentId,
+ input: { routineId: RoutineId.make(routineId), createdAt },
+ });
+ requireSuccess(
+ result,
+ paused ? "Could not pause routine" : "Could not resume routine",
+ );
+ });
+ },
+ onDelete: (routineId) => {
+ if (!environmentId) return;
+ startBusy(routineId, async () => {
+ const result = await deleteRoutine({
+ environmentId,
+ input: {
+ routineId: RoutineId.make(routineId),
+ createdAt: new Date().toISOString(),
+ },
+ });
+ requireSuccess(result, "Could not delete routine");
+ });
+ },
+ }}
onSaveBot={async ({
name,
label,
diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts
index f6c23e123..a807f6326 100644
--- a/apps/web/src/session-logic.test.ts
+++ b/apps/web/src/session-logic.test.ts
@@ -71,6 +71,28 @@ function makeActivity(overrides: {
}
describe("derivePendingApprovals", () => {
+ it("carries command arguments from the matching tool activity", () => {
+ const args = { command: 'printf "hi\\n"', cwd: null };
+ const approvals = derivePendingApprovals([
+ makeActivity({
+ kind: "tool.started",
+ payload: { toolCallId: "shell-1", data: { args } },
+ }),
+ makeActivity({
+ kind: "approval.requested",
+ tone: "approval",
+ payload: {
+ requestId: "shell-1",
+ requestType: "dynamic_tool_call",
+ toolName: "Shell",
+ detail: "Allow Shell?",
+ },
+ }),
+ ]);
+
+ expect(approvals[0]).toMatchObject({ requestId: "shell-1", args });
+ });
+
it("keeps feedback tool arguments for the editable draft", () => {
const args = { feedback: "The button is unresponsive." };
const approvals = derivePendingApprovals([
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 53753f509..8a897cb4a 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -422,6 +422,7 @@ export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
+ const toolArgsByCallId = new Map<string, unknown>();
const ordered = [...activities].toSorted(compareActivitiesByOrder);
for (const activity of ordered) {
@@ -429,6 +430,17 @@ export function derivePendingApprovals(
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
+ const toolCallId =
+ payload && typeof payload.toolCallId === "string" ? payload.toolCallId : null;
+ const data =
+ payload?.data && typeof payload.data === "object"
+ ? (payload.data as Record<string, unknown>)
+ : null;
+ if (activity.kind === "tool.started" && toolCallId && data) {
+ const toolArgs =
+ data.args ?? (typeof data.command === "string" ? { command: data.command } : undefined);
+ if (toolArgs !== undefined) toolArgsByCallId.set(toolCallId, toolArgs);
+ }
const requestId =
payload && typeof payload.requestId === "string"
? ApprovalRequestId.make(payload.requestId)
@@ -442,7 +454,7 @@ export function derivePendingApprovals(
const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
const appName = payload && typeof payload.appName === "string" ? payload.appName : undefined;
const toolName = payload && typeof payload.toolName === "string" ? payload.toolName : undefined;
- const args = payload?.args;
+ const args = payload?.args ?? (requestId ? toolArgsByCallId.get(requestId) : undefined);
const options = Array.isArray(payload?.options)
? payload.options.filter(isProviderApprovalOption)
: undefined;
diff --git a/apps/web/src/state/routines.ts b/apps/web/src/state/routines.ts
new file mode 100644
index 000000000..15e61bb4c
--- /dev/null
+++ b/apps/web/src/state/routines.ts
@@ -0,0 +1,5 @@
+import { createRoutineEnvironmentAtoms } from "@t3tools/client-runtime/state/routines";
+
+import { connectionAtomRuntime } from "../connection/runtime";
+
+export const routineEnvironment = createRoutineEnvironmentAtoms(connectionAtomRuntime);
diff --git a/docs/internals/data-portability.md b/docs/internals/data-portability.md
index f7eecbf50..c91b2224a 100644
--- a/docs/internals/data-portability.md
+++ b/docs/internals/data-portability.md
@@ -2,9 +2,9 @@
The `akeru.archive` format mirrors data that Akeru owns and can restore without credentials or local paths.
-`packages/contracts/src/orchestration.ts` defines the durable read model. It contains projects, bots, groups, MCP servers, and threads. Thread records carry messages, proposed plans, approval activities, avatars, lifecycle state, and workspace or sandbox references. The portability layer restores approval activities as inert `approval.history` rows so an import cannot reopen a provider request.
+`packages/contracts/src/orchestration.ts` defines the durable read model. It contains projects, bots, groups, MCP servers, routines, routine runs, skill assignments, and threads. Thread records carry messages, proposed plans, approval activities, avatars, lifecycle state, and workspace or sandbox references. The portability layer restores approval activities as inert `approval.history` rows so an import cannot reopen a provider request.
-The same read model has no jobs or routines collection. Durable memory has a separate SQLite repository and a version 2 memory archive with preview and apply support. The main portability archive does not include these separate domains. `ServerProvider.skills` in `packages/contracts/src/server.ts` reports discovered provider skills, but Akeru has no persisted skill-assignment model.
+The main archive does not export or restore routines, routine runs, or skill assignments yet. Durable memory has a separate SQLite repository and a version 2 memory archive with preview and apply support.
`packages/contracts/src/usage.ts` defines a read result, not an Akeru repository. `apps/server/src/usage/UsageService.ts` scans provider-owned Claude and Codex transcript files. It has no write or import operation, so the main portability archive does not include usage history.
diff --git a/docs/user/bots.md b/docs/user/bots.md
index f60b7ddfd..ddd8dd5e5 100644
--- a/docs/user/bots.md
+++ b/docs/user/bots.md
@@ -19,6 +19,14 @@ Settings controls whether bots share their workspace and browser. **Separate** i
Local bots ask before file changes and shell commands by default. Select **Settings > General > Local execution > Full access** to skip those local prompts. Actions that send, pay, delete, change production, or use secrets still ask. Bots that run in a cloud sandbox do not show the local computer prompt.
+## Run a routine
+
+Open **Routines** in a bot's panel. Add a job, procedure, schedule, timezone, required skills, and connectors. Run a dry run and approve the procedure before you enable its schedule.
+
+The panel shows the next and last run, latest result or failure, and the five latest attempts. You can run, pause, resume, edit, or delete the routine. A procedure change requires approval again.
+
+If a required connector, provider, bot, or workspace is unavailable, Akeru pauses the routine and adds one item to the bot inbox. Fix the dependency, then resume the routine. Restoring an archived bot does not resume its routines.
+
Use the panel button to collapse or reopen the editor. The default shortcut is **Mod+Alt+B**, and you can change `Right Panel: Toggle` in the keybinding settings. On a narrow screen, the same button opens a sheet.
When a request needs tools, the bot first replies in plain language. During longer work, it adds short status notes after meaningful progress. When work resumes automatically, it continues without a repeated opening note.
diff --git a/docs/user/plugins.md b/docs/user/plugins.md
index 33899fb12..929db040b 100644
--- a/docs/user/plugins.md
+++ b/docs/user/plugins.md
@@ -2,7 +2,7 @@
Open **Plugins** from the sidebar or command palette. Use **All**, **Featured**, **Installed**, or one of the eight categories. Search checks the plugin name, title, description, category, tags, capabilities, and publisher name.
-Select a plugin to review its publisher, authentication, hosted or local execution, transport, platform support, permissions, approval classes, setup, documentation, source, and active dependent bots. Routines are unavailable until routines ship. Health shows **Not checked** until Akeru completes a real request. An enabled plugin does not imply a healthy connection.
+Select a plugin to review its publisher, authentication, hosted or local execution, transport, platform support, permissions, approval classes, setup, documentation, source, and active dependent bots. A routine can require an enabled connector. Health shows **Not checked** until Akeru completes a real request. An enabled plugin does not imply a healthy connection.
The available action matches the current state:
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index c5cb9c7a3..20a20dc31 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -115,6 +115,10 @@
"types": "./src/state/review.ts",
"default": "./src/state/review.ts"
},
+ "./state/routines": {
+ "types": "./src/state/routines.ts",
+ "default": "./src/state/routines.ts"
+ },
"./state/runtime": {
"types": "./src/state/runtime.ts",
"default": "./src/state/runtime.ts"
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index a65167460..de34d51d8 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -37,6 +37,7 @@ import {
sendChannelMessage,
settleThread,
setGroupBoss,
+ startThreadTurn,
stopThreadSession,
unassignGroupMember,
unsettleThread,
@@ -268,6 +269,33 @@ describe("environment commands", () => {
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
+ it.effect("stamps turn starts with the client timezone", () =>
+ Effect.gen(function* () {
+ const dispatched: ClientOrchestrationCommand[] = [];
+ const supervisor = yield* makeSupervisor(dispatched);
+
+ yield* startThreadTurn({
+ commandId: CommandId.make("start-turn"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: MessageId.make("message-1"),
+ role: "user",
+ text: "Create a morning routine.",
+ attachments: [],
+ },
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ createdAt: "2026-06-06T00:01:00.000Z",
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
+
+ expect(dispatched).toHaveLength(1);
+ expect(dispatched[0]).toMatchObject({
+ type: "thread.turn.start",
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
+ });
+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
+ );
+
it.effect("does not add timestamps to commands without createdAt", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index 419be0d1f..5c38c3be9 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -56,6 +56,14 @@ export type UpdateMcpServerInput = CommandInput<"mcp-server.update">;
export type DeleteMcpServerInput = CommandInput<"mcp-server.delete">;
export type EnableMcpServerInput = CommandInput<"mcp-server.enable">;
export type DisableMcpServerInput = CommandInput<"mcp-server.disable">;
+export type DraftRoutineInput = CommandInput<"routine.draft">;
+export type ApproveRoutineInput = CommandInput<"routine.approve">;
+export type EnableRoutineInput = CommandInput<"routine.enable">;
+export type PauseRoutineInput = CommandInput<"routine.pause">;
+export type RunRoutineInput = CommandInput<"routine.run">;
+export type DeleteRoutineInput = CommandInput<"routine.delete">;
+export type AssignRoutineSkillInput = CommandInput<"routine.skill.assign">;
+export type UnassignRoutineSkillInput = CommandInput<"routine.skill.unassign">;
export type CreateThreadInput = CommandInput<"thread.create">;
export type DeleteThreadInput = CommandInput<"thread.delete">;
export type ArchiveThreadInput = CommandInput<"thread.archive">;
@@ -411,6 +419,102 @@ export const disableMcpServer: (input: DisableMcpServerInput) => CommandEffect =
});
});
+export const draftRoutine: (input: DraftRoutineInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.draftRoutine",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.draft",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const approveRoutine: (input: ApproveRoutineInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.approveRoutine",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.approve",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const enableRoutine: (input: EnableRoutineInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.enableRoutine",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.enable",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const pauseRoutine: (input: PauseRoutineInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.pauseRoutine",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.pause",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const runRoutine: (input: RunRoutineInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.runRoutine",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.run",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const deleteRoutine: (input: DeleteRoutineInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.deleteRoutine",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.delete",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const assignRoutineSkill: (input: AssignRoutineSkillInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.assignRoutineSkill",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.skill.assign",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
+export const unassignRoutineSkill: (input: UnassignRoutineSkillInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.unassignRoutineSkill",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "routine.skill.unassign",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
+
export const createThread: (input: CreateThreadInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.createThread",
)(function* (input) {
@@ -562,6 +666,7 @@ export const startThreadTurn: (input: StartThreadTurnInput) => CommandEffect = E
const metadata = yield* timestampedCommandMetadata(input);
return yield* dispatch({
...input,
+ timezone: input.timezone ?? (Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"),
type: "thread.turn.start",
commandId: metadata.commandId,
createdAt: metadata.createdAt,
diff --git a/packages/client-runtime/src/state/routines.ts b/packages/client-runtime/src/state/routines.ts
new file mode 100644
index 000000000..c649e87d5
--- /dev/null
+++ b/packages/client-runtime/src/state/routines.ts
@@ -0,0 +1,69 @@
+import * as Crypto from "effect/Crypto";
+import { Atom } from "effect/unstable/reactivity";
+
+import type { EnvironmentRegistry } from "../connection/registry.ts";
+import {
+ type ApproveRoutineInput,
+ type AssignRoutineSkillInput,
+ type DeleteRoutineInput,
+ type DraftRoutineInput,
+ type EnableRoutineInput,
+ type PauseRoutineInput,
+ type RunRoutineInput,
+ type UnassignRoutineSkillInput,
+ approveRoutine,
+ assignRoutineSkill,
+ deleteRoutine,
+ draftRoutine,
+ enableRoutine,
+ pauseRoutine,
+ runRoutine,
+ unassignRoutineSkill,
+} from "../operations/commands.ts";
+import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";
+
+export type {
+ ApproveRoutineInput,
+ AssignRoutineSkillInput,
+ DeleteRoutineInput,
+ DraftRoutineInput,
+ EnableRoutineInput,
+ PauseRoutineInput,
+ RunRoutineInput,
+ UnassignRoutineSkillInput,
+} from "../operations/commands.ts";
+
+export function createRoutineEnvironmentAtoms<R, E>(
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,
+) {
+ const scheduler = createAtomCommandScheduler();
+ const concurrency = {
+ mode: "serial" as const,
+ key: ({ environmentId, input }: { environmentId: string; input: { routineId: string } }) =>
+ JSON.stringify([environmentId, "routine", input.routineId]),
+ };
+
+ const command = <Input extends { routineId: string }>(
+ label: string,
+ execute: (input: Input) => ReturnType<typeof draftRoutine>,
+ ) => createEnvironmentCommand(runtime, { label, execute, scheduler, concurrency });
+
+ return {
+ draft: command("environment-data:commands:routine:draft", draftRoutine),
+ approve: command("environment-data:commands:routine:approve", approveRoutine),
+ enable: command("environment-data:commands:routine:enable", enableRoutine),
+ pause: command("environment-data:commands:routine:pause", pauseRoutine),
+ run: command("environment-data:commands:routine:run", runRoutine),
+ delete: command("environment-data:commands:routine:delete", deleteRoutine),
+ assignSkill: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:routine:skill:assign",
+ execute: (input: AssignRoutineSkillInput) => assignRoutineSkill(input),
+ scheduler,
+ }),
+ unassignSkill: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:routine:skill:unassign",
+ execute: (input: UnassignRoutineSkillInput) => unassignRoutineSkill(input),
+ scheduler,
+ }),
+ };
+}
diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts
index 80c9068ba..53ee5787f 100644
--- a/packages/client-runtime/src/state/shellReducer.test.ts
+++ b/packages/client-runtime/src/state/shellReducer.test.ts
@@ -7,6 +7,10 @@ import {
McpServerId,
ProjectId,
ProviderInstanceId,
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
+ SkillId,
ThreadId,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
@@ -132,6 +136,59 @@ const stubThread = {
session: null,
} as const;
+const stubAssignment = {
+ id: SkillAssignmentId.make("assignment-1"),
+ botId: stubBot.id,
+ skillId: SkillId.make("research"),
+ name: "Research",
+ description: null,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+};
+
+const stubRoutine = {
+ id: RoutineId.make("routine-1"),
+ botId: stubBot.id,
+ targetThreadId: stubThread.id,
+ job: "Morning brief",
+ procedure: "Prepare the morning brief.",
+ schedule: { kind: "daily" as const, time: "09:00" },
+ timezone: "UTC",
+ skillAssignmentIds: [stubAssignment.id],
+ connectorDependencies: [stubMcpServer.id],
+ projectId: stubProject.id,
+ sandbox: "local" as const,
+ approvalPolicy: "approval-required" as const,
+ procedureVersion: 1,
+ approvalVersion: 1,
+ enabled: true,
+ lifecycle: "enabled" as const,
+ nextRunAt: "2026-04-02T09:00:00.000Z",
+ lastRunAt: null,
+ latestResult: null,
+ latestFailure: null,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ deletedAt: null,
+};
+
+const stubRoutineRun = {
+ id: RoutineRunId.make("run-1"),
+ routineId: stubRoutine.id,
+ procedureVersion: 1,
+ trigger: "scheduled" as const,
+ scheduledFor: "2026-04-02T09:00:00.000Z",
+ status: "completed" as const,
+ result: { summary: "Prepared the brief." },
+ failure: null,
+ usageRef: null,
+ threadRef: null,
+ startedAt: "2026-04-02T09:00:00.000Z",
+ completedAt: "2026-04-02T09:01:00.000Z",
+ createdAt: "2026-04-02T09:00:00.000Z",
+ updatedAt: "2026-04-02T09:01:00.000Z",
+};
+
describe("applyShellStreamEvent", () => {
it("ignores stale project upserts without mutating the snapshot", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
@@ -243,6 +300,37 @@ describe("applyShellStreamEvent", () => {
});
});
+ describe("routine events", () => {
+ it("updates routines, run history, and skill assignments", () => {
+ const assigned = applyShellStreamEvent(baseSnapshot, {
+ kind: "skill-assignment-upserted",
+ sequence: 1,
+ assignment: stubAssignment,
+ });
+ const updated = applyShellStreamEvent(assigned, {
+ kind: "routine-upserted",
+ sequence: 2,
+ routine: stubRoutine,
+ run: stubRoutineRun,
+ });
+
+ expect(updated.skillAssignments).toEqual([stubAssignment]);
+ expect(updated.routines).toEqual([stubRoutine]);
+ expect(updated.routineRuns).toEqual([stubRoutineRun]);
+ expect(updated.snapshotSequence).toBe(2);
+ });
+
+ it("removes a routine with its run history", () => {
+ const next = applyShellStreamEvent(
+ { ...baseSnapshot, routines: [stubRoutine], routineRuns: [stubRoutineRun] },
+ { kind: "routine-removed", sequence: 3, routineId: stubRoutine.id },
+ );
+
+ expect(next.routines).toEqual([]);
+ expect(next.routineRuns).toEqual([]);
+ });
+ });
+
describe("bot-upserted", () => {
it("adds and updates a bot", () => {
const added = applyShellStreamEvent(baseSnapshot, {
diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts
index 5dfa1ad8d..7f3872f86 100644
--- a/packages/client-runtime/src/state/shellReducer.ts
+++ b/packages/client-runtime/src/state/shellReducer.ts
@@ -76,6 +76,61 @@ export function applyShellStreamEvent(
: Arr.append(snapshot.delegations, event.delegation);
return { ...snapshot, delegations, snapshotSequence: event.sequence };
}
+ case "routine-upserted": {
+ const routines = snapshot.routines ?? [];
+ const nextRoutines = routines.some((routine) => routine.id === event.routine.id)
+ ? Arr.map(routines, (routine) =>
+ routine.id === event.routine.id ? event.routine : routine,
+ )
+ : Arr.append(routines, event.routine);
+ const runs = snapshot.routineRuns ?? [];
+ const eventRun = event.run;
+ const nextRuns = eventRun
+ ? runs.some((run) => run.id === eventRun.id)
+ ? Arr.map(runs, (run) => (run.id === eventRun.id ? eventRun : run))
+ : Arr.append(runs, eventRun)
+ : runs;
+ return {
+ ...snapshot,
+ routines: nextRoutines,
+ routineRuns: nextRuns,
+ snapshotSequence: event.sequence,
+ };
+ }
+ case "routine-removed":
+ return {
+ ...snapshot,
+ routines: Arr.filter(snapshot.routines ?? [], (routine) => routine.id !== event.routineId),
+ routineRuns: Arr.filter(
+ snapshot.routineRuns ?? [],
+ (run) => run.routineId !== event.routineId,
+ ),
+ snapshotSequence: event.sequence,
+ };
+ case "skill-assignment-upserted": {
+ const assignments = snapshot.skillAssignments ?? [];
+ const nextAssignments = assignments.some(
+ (assignment) => assignment.id === event.assignment.id,
+ )
+ ? Arr.map(assignments, (assignment) =>
+ assignment.id === event.assignment.id ? event.assignment : assignment,
+ )
+ : Arr.append(assignments, event.assignment);
+ return {
+ ...snapshot,
+ skillAssignments: nextAssignments,
+ snapshotSequence: event.sequence,
+ };
+ }
+ case "skill-assignment-removed":
+ return {
+ ...snapshot,
+ skillAssignments: Arr.filter(
+ snapshot.skillAssignments ?? [],
+ (assignment) => assignment.id !== event.assignmentId,
+ ),
+ snapshotSequence: event.sequence,
+ };
case "thread-upserted": {
const threads = snapshot.threads.some((t) => t.id === event.thread.id)
? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t))
diff --git a/packages/contracts/src/akeruUsage.ts b/packages/contracts/src/akeruUsage.ts
index bf3d54ab3..7f8552fd2 100644
--- a/packages/contracts/src/akeruUsage.ts
+++ b/packages/contracts/src/akeruUsage.ts
@@ -1,6 +1,7 @@
import * as Schema from "effect/Schema";
import {
+ AkeruUsageReservationId,
BotId,
IsoDateTime,
NonNegativeInt,
@@ -11,11 +12,6 @@ import {
import { ProviderDriverKind } from "./providerInstance.ts";
import { BotEngine, BotUsageCap } from "./orchestration.ts";
-export const AkeruUsageReservationId = TrimmedNonEmptyString.pipe(
- Schema.brand("AkeruUsageReservationId"),
-);
-export type AkeruUsageReservationId = typeof AkeruUsageReservationId.Type;
-
export const AkeruUsageCategory = Schema.Literals([
"turn",
"tool",
diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts
index f4f99a340..3f527755e 100644
--- a/packages/contracts/src/baseSchemas.ts
+++ b/packages/contracts/src/baseSchemas.ts
@@ -100,3 +100,5 @@ export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
export type ApprovalRequestId = typeof ApprovalRequestId.Type;
export const CheckpointRef = makeEntityId("CheckpointRef");
export type CheckpointRef = typeof CheckpointRef.Type;
+export const AkeruUsageReservationId = makeEntityId("AkeruUsageReservationId");
+export type AkeruUsageReservationId = typeof AkeruUsageReservationId.Type;
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index 912f55d99..1c403f1ca 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -6,6 +6,7 @@ export * from "./productFeedback.ts";
export * from "./akeruMemory.ts";
export * from "./akeruUsage.ts";
export * from "./analytics.ts";
+export * from "./routines.ts";
export * from "./auth.ts";
export * from "./environment.ts";
export * from "./environmentHttp.ts";
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index af62b7fe9..c0a01a358 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -29,6 +29,28 @@ import {
import { ProviderInstanceId } from "./providerInstance.ts";
import { McpServer, McpServerId, McpServerUrl } from "./mcpServer.ts";
import { AkeruDelegationRecord, DelegationId } from "./akeruDelegation.ts";
+import {
+ ClientRoutineCommand,
+ InternalRoutineCommand,
+ Routine,
+ RoutineApprovedPayload,
+ RoutineBlockedPayload,
+ RoutineCompletedPayload,
+ RoutineDeletedPayload,
+ RoutineDraftedPayload,
+ RoutineEnabledPayload,
+ RoutineFailedPayload,
+ RoutineId,
+ RoutinePausedPayload,
+ RoutineRun,
+ RoutineRunCanceledPayload,
+ RoutineRunId,
+ RoutineRunningPayload,
+ RoutineSkillAssignedPayload,
+ RoutineSkillAssignment,
+ RoutineSkillUnassignedPayload,
+ SkillAssignmentId,
+} from "./routines.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
@@ -635,6 +657,9 @@ export const OrchestrationReadModel = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
mcpServers: Schema.optional(Schema.Array(McpServer)),
+ routines: Schema.optional(Schema.Array(Routine)),
+ routineRuns: Schema.optional(Schema.Array(RoutineRun)),
+ skillAssignments: Schema.optional(Schema.Array(RoutineSkillAssignment)),
threads: Schema.Array(OrchestrationThread),
updatedAt: IsoDateTime,
});
@@ -726,6 +751,9 @@ export const OrchestrationShellSnapshot = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
mcpServers: Schema.optional(Schema.Array(McpServer)),
+ routines: Schema.optional(Schema.Array(Routine)),
+ routineRuns: Schema.optional(Schema.Array(RoutineRun)),
+ skillAssignments: Schema.optional(Schema.Array(RoutineSkillAssignment)),
threads: Schema.Array(OrchestrationThreadShell),
updatedAt: IsoDateTime,
});
@@ -772,6 +800,27 @@ export const OrchestrationShellStreamEvent = Schema.Union([
sequence: NonNegativeInt,
delegation: Schema.suspend(() => AkeruDelegationRecord),
}),
+ Schema.Struct({
+ kind: Schema.Literal("routine-upserted"),
+ sequence: NonNegativeInt,
+ routine: Routine,
+ run: Schema.optional(RoutineRun),
+ }),
+ Schema.Struct({
+ kind: Schema.Literal("routine-removed"),
+ sequence: NonNegativeInt,
+ routineId: RoutineId,
+ }),
+ Schema.Struct({
+ kind: Schema.Literal("skill-assignment-upserted"),
+ sequence: NonNegativeInt,
+ assignment: RoutineSkillAssignment,
+ }),
+ Schema.Struct({
+ kind: Schema.Literal("skill-assignment-removed"),
+ sequence: NonNegativeInt,
+ assignmentId: SkillAssignmentId,
+ }),
Schema.Struct({
kind: Schema.Literal("thread-upserted"),
sequence: NonNegativeInt,
@@ -1438,6 +1487,7 @@ export const ThreadTurnStartCommand = Schema.Struct({
senderPersonId: Schema.optional(AuthSessionId),
senderDisplayName: Schema.optional(TrimmedNonEmptyString),
senderCanManageGroups: Schema.optional(Schema.Boolean),
+ timezone: Schema.optional(TrimmedNonEmptyString),
createdAt: IsoDateTime,
});
@@ -1458,6 +1508,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({
bootstrap: Schema.optional(ThreadTurnStartBootstrap),
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
respondingBotId: Schema.optional(BotId),
+ timezone: Schema.optional(TrimmedNonEmptyString),
createdAt: IsoDateTime,
});
@@ -1549,6 +1600,7 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
McpServerDeleteCommand,
McpServerEnableCommand,
McpServerDisableCommand,
+ ClientRoutineCommand,
ThreadCreateCommand,
ThreadDeleteCommand,
ThreadArchiveCommand,
@@ -1604,6 +1656,7 @@ export const ClientOrchestrationCommand = Schema.Union([
McpServerDeleteCommand,
McpServerEnableCommand,
McpServerDisableCommand,
+ ClientRoutineCommand,
ThreadCreateCommand,
ThreadDeleteCommand,
ThreadArchiveCommand,
@@ -1744,6 +1797,7 @@ export const DelegationStateSetCommand = Schema.Struct({
});
const InternalOrchestrationCommand = Schema.Union([
+ InternalRoutineCommand,
ThreadSessionSetCommand,
ThreadMessageAssistantDeltaCommand,
ThreadMessageAssistantCompleteCommand,
@@ -1786,6 +1840,18 @@ export const OrchestrationEventType = Schema.Literals([
"mcp-server.deleted",
"mcp-server.enabled",
"mcp-server.disabled",
+ "routine.drafted",
+ "routine.approved",
+ "routine.enabled",
+ "routine.running",
+ "routine.paused",
+ "routine.blocked",
+ "routine.failed",
+ "routine.completed",
+ "routine.run-canceled",
+ "routine.deleted",
+ "skill-assignment.assigned",
+ "skill-assignment.unassigned",
"thread.created",
"thread.ownership-updated",
"thread.deleted",
@@ -1824,6 +1890,9 @@ export const OrchestrationAggregateKind = Schema.Literals([
"bot",
"group",
"mcp-server",
+ "routine",
+ "routine-run",
+ "skill-assignment",
"thread",
"delegation",
]);
@@ -2144,6 +2213,7 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
),
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
respondingBotId: Schema.optional(Schema.NullOr(BotId)),
+ timezone: Schema.optional(TrimmedNonEmptyString),
createdAt: IsoDateTime,
});
@@ -2246,8 +2316,11 @@ const EventBaseFields = {
BotId,
GroupId,
McpServerId,
- ThreadId,
Schema.suspend(() => DelegationId),
+ RoutineId,
+ RoutineRunId,
+ SkillAssignmentId,
+ ThreadId,
]),
occurredAt: IsoDateTime,
commandId: Schema.NullOr(CommandId),
@@ -2357,6 +2430,66 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("mcp-server.disabled"),
payload: McpServerDisabledPayload,
}),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.drafted"),
+ payload: RoutineDraftedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.approved"),
+ payload: RoutineApprovedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.enabled"),
+ payload: RoutineEnabledPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.running"),
+ payload: RoutineRunningPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.paused"),
+ payload: RoutinePausedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.blocked"),
+ payload: RoutineBlockedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.failed"),
+ payload: RoutineFailedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.completed"),
+ payload: RoutineCompletedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.run-canceled"),
+ payload: RoutineRunCanceledPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("routine.deleted"),
+ payload: RoutineDeletedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("skill-assignment.assigned"),
+ payload: RoutineSkillAssignedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("skill-assignment.unassigned"),
+ payload: RoutineSkillUnassignedPayload,
+ }),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.created"),
diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts
index 5a244965f..a571e950e 100644
--- a/packages/contracts/src/provider.ts
+++ b/packages/contracts/src/provider.ts
@@ -86,6 +86,7 @@ export const ProviderSendTurnInput = Schema.Struct({
),
modelSelection: Schema.optional(ModelSelection),
interactionMode: Schema.optional(ProviderInteractionMode),
+ timezone: Schema.optional(TrimmedNonEmptyString),
});
export type ProviderSendTurnInput = typeof ProviderSendTurnInput.Type;
diff --git a/packages/contracts/src/routines.test.ts b/packages/contracts/src/routines.test.ts
new file mode 100644
index 000000000..6ab4db521
--- /dev/null
+++ b/packages/contracts/src/routines.test.ts
@@ -0,0 +1,120 @@
+import * as Schema from "effect/Schema";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ ClientRoutineCommand,
+ InternalRoutineCommand,
+ Routine,
+ RoutineDraftedPayload,
+ RoutineRun,
+ RoutineSchedule,
+} from "./routines.ts";
+
+const now = "2026-08-31T09:00:00.000Z";
+
+const definition = {
+ botId: "bot-inbox",
+ targetThreadId: "thread-inbox",
+ job: "Morning inbox",
+ procedure: "Check new mail and prepare a summary.",
+ schedule: { kind: "weekdays", time: "09:00" },
+ timezone: "America/New_York",
+ skillAssignmentIds: ["skill-assignment-email"],
+ connectorDependencies: ["builtin-gmail"],
+ projectId: "project-inbox",
+ sandbox: "local",
+ approvalPolicy: "approval-required",
+} as const;
+
+const routine = {
+ id: "routine-inbox",
+ ...definition,
+ procedureVersion: 2,
+ approvalVersion: 2,
+ enabled: true,
+ lifecycle: "enabled",
+ nextRunAt: "2026-09-01T13:00:00.000Z",
+ lastRunAt: null,
+ latestResult: null,
+ latestFailure: null,
+ createdAt: now,
+ updatedAt: now,
+ deletedAt: null,
+} as const;
+
+describe("routine contracts", () => {
+ it("decodes a provider-neutral routine and durable run", () => {
+ expect(Schema.decodeUnknownSync(Routine)(routine)).toMatchObject({
+ id: "routine-inbox",
+ schedule: { kind: "weekdays", time: "09:00" },
+ approvalVersion: 2,
+ });
+
+ expect(
+ Schema.decodeUnknownSync(RoutineRun)({
+ id: "run-inbox-1",
+ routineId: routine.id,
+ procedureVersion: 2,
+ trigger: "missed",
+ scheduledFor: "2026-09-01T13:00:00.000Z",
+ status: "completed",
+ result: { summary: "Prepared a summary of 4 messages." },
+ failure: null,
+ usageRef: "usage-inbox-1",
+ threadRef: "thread-inbox-1",
+ startedAt: "2026-09-01T13:01:00.000Z",
+ completedAt: "2026-09-01T13:02:00.000Z",
+ createdAt: "2026-09-01T13:01:00.000Z",
+ updatedAt: "2026-09-01T13:02:00.000Z",
+ }),
+ ).toMatchObject({ id: "run-inbox-1", trigger: "missed", status: "completed" });
+ });
+
+ it("rejects invalid local times, timezones, and empty weekly schedules", () => {
+ const decode = Schema.decodeUnknownSync(RoutineSchedule);
+ expect(() => decode({ kind: "daily", time: "24:00" })).toThrow();
+ expect(() => decode({ kind: "weekly", weekdays: [], time: "09:00" })).toThrow();
+ expect(() =>
+ Schema.decodeUnknownSync(Routine)({ ...routine, timezone: "Mars/Olympus" }),
+ ).toThrow();
+ });
+
+ it("requires a material draft to clear approval and disable the schedule", () => {
+ const decode = Schema.decodeUnknownSync(RoutineDraftedPayload);
+ expect(
+ decode({
+ routine: { ...routine, approvalVersion: null, enabled: false, lifecycle: "draft" },
+ }),
+ ).toBeDefined();
+ expect(() => decode({ routine })).toThrow();
+ });
+
+ it("keeps scheduled and recovery triggers out of client run commands", () => {
+ const decode = Schema.decodeUnknownSync(ClientRoutineCommand);
+ const command = {
+ type: "routine.run",
+ commandId: "command-run-1",
+ routineId: routine.id,
+ runId: "run-inbox-1",
+ createdAt: now,
+ };
+ expect(decode({ ...command, trigger: "dry-run" })).toMatchObject({ trigger: "dry-run" });
+ expect(() => decode({ ...command, trigger: "scheduled" })).toThrow();
+ });
+
+ it("keeps atomic approved creation internal", () => {
+ const command = {
+ type: "routine.create-approved",
+ commandId: "command-create-approved-1",
+ routineId: routine.id,
+ ...definition,
+ createdAt: now,
+ };
+
+ expect(Schema.decodeUnknownSync(InternalRoutineCommand)(command)).toMatchObject({
+ type: "routine.create-approved",
+ routineId: routine.id,
+ });
+ expect(() => Schema.decodeUnknownSync(ClientRoutineCommand)(command)).toThrow();
+ });
+});
diff --git a/packages/contracts/src/routines.ts b/packages/contracts/src/routines.ts
new file mode 100644
index 000000000..c7d5caa16
--- /dev/null
+++ b/packages/contracts/src/routines.ts
@@ -0,0 +1,393 @@
+import * as Schema from "effect/Schema";
+
+import {
+ AkeruUsageReservationId,
+ BotId,
+ CommandId,
+ IsoDateTime,
+ PositiveInt,
+ ProjectId,
+ ThreadId,
+ TrimmedNonEmptyString,
+} from "./baseSchemas.ts";
+import { McpServerId } from "./mcpServer.ts";
+
+export const RoutineId = TrimmedNonEmptyString.pipe(Schema.brand("RoutineId"));
+export type RoutineId = typeof RoutineId.Type;
+
+export const RoutineRunId = TrimmedNonEmptyString.pipe(Schema.brand("RoutineRunId"));
+export type RoutineRunId = typeof RoutineRunId.Type;
+
+export const SkillAssignmentId = TrimmedNonEmptyString.pipe(Schema.brand("SkillAssignmentId"));
+export type SkillAssignmentId = typeof SkillAssignmentId.Type;
+
+export const SkillId = TrimmedNonEmptyString.pipe(Schema.brand("SkillId"));
+export type SkillId = typeof SkillId.Type;
+
+export const RoutineWeekday = Schema.Literals([
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+ "sunday",
+]);
+export type RoutineWeekday = typeof RoutineWeekday.Type;
+
+export const RoutineLocalTime = Schema.String.check(
+ Schema.isPattern(/^(?:[01]\d|2[0-3]):[0-5]\d$/),
+);
+export type RoutineLocalTime = typeof RoutineLocalTime.Type;
+
+export const RoutineSchedule = Schema.Union([
+ Schema.Struct({ kind: Schema.Literal("daily"), time: RoutineLocalTime }),
+ Schema.Struct({ kind: Schema.Literal("weekdays"), time: RoutineLocalTime }),
+ Schema.Struct({
+ kind: Schema.Literal("weekly"),
+ weekdays: Schema.Array(RoutineWeekday).check(Schema.isMinLength(1)),
+ time: RoutineLocalTime,
+ }),
+]);
+export type RoutineSchedule = typeof RoutineSchedule.Type;
+
+export const RoutineTimeZone = TrimmedNonEmptyString.check(
+ Schema.makeFilter((value) => {
+ try {
+ new Intl.DateTimeFormat("en", { timeZone: value });
+ return true;
+ } catch {
+ return "timezone must be a valid IANA time zone";
+ }
+ }),
+);
+export type RoutineTimeZone = typeof RoutineTimeZone.Type;
+
+export const RoutineSandbox = Schema.Literals([
+ "local",
+ "e2b",
+ "daytona",
+ "vercel-sandbox",
+ "upstash-box",
+]);
+export type RoutineSandbox = typeof RoutineSandbox.Type;
+
+export const RoutineApprovalPolicy = Schema.Literals([
+ "approval-required",
+ "auto-accept-edits",
+ "auto",
+ "full-access",
+]);
+export type RoutineApprovalPolicy = typeof RoutineApprovalPolicy.Type;
+
+export const RoutineLifecycle = Schema.Literals([
+ "draft",
+ "approved",
+ "enabled",
+ "running",
+ "paused",
+ "blocked",
+ "failed",
+ "completed",
+ "deleted",
+]);
+export type RoutineLifecycle = typeof RoutineLifecycle.Type;
+
+export const RoutineRunTrigger = Schema.Literals(["dry-run", "manual", "scheduled", "missed"]);
+export type RoutineRunTrigger = typeof RoutineRunTrigger.Type;
+
+export const RoutineRunStatus = Schema.Literals([
+ "queued",
+ "waiting-for-approval",
+ "running",
+ "blocked",
+ "failed",
+ "completed",
+ "canceled",
+]);
+export type RoutineRunStatus = typeof RoutineRunStatus.Type;
+
+export const RoutineFailureKind = Schema.Literals([
+ "connector",
+ "browser",
+ "provider",
+ "bot",
+ "workspace",
+ "approval",
+ "execution",
+]);
+export type RoutineFailureKind = typeof RoutineFailureKind.Type;
+
+export const RoutineRunResult = Schema.Struct({ summary: TrimmedNonEmptyString });
+export type RoutineRunResult = typeof RoutineRunResult.Type;
+
+export const RoutineRunFailure = Schema.Struct({
+ kind: RoutineFailureKind,
+ message: TrimmedNonEmptyString,
+});
+export type RoutineRunFailure = typeof RoutineRunFailure.Type;
+
+export const RoutineSkillAssignment = Schema.Struct({
+ id: SkillAssignmentId,
+ botId: BotId,
+ skillId: SkillId,
+ name: TrimmedNonEmptyString,
+ description: Schema.NullOr(TrimmedNonEmptyString),
+ createdAt: IsoDateTime,
+ updatedAt: IsoDateTime,
+});
+export type RoutineSkillAssignment = typeof RoutineSkillAssignment.Type;
+
+export const RoutineDefinition = Schema.Struct({
+ botId: BotId,
+ targetThreadId: ThreadId,
+ job: TrimmedNonEmptyString,
+ procedure: TrimmedNonEmptyString,
+ schedule: RoutineSchedule,
+ timezone: RoutineTimeZone,
+ skillAssignmentIds: Schema.Array(SkillAssignmentId),
+ connectorDependencies: Schema.Array(McpServerId),
+ projectId: ProjectId,
+ sandbox: RoutineSandbox,
+ approvalPolicy: RoutineApprovalPolicy,
+});
+export type RoutineDefinition = typeof RoutineDefinition.Type;
+
+export const AKERU_CREATE_ROUTINE_TOOL_NAME = "akeru_create_routine";
+export const AkeruCreateRoutineInput = Schema.Struct({
+ name: TrimmedNonEmptyString,
+ instructions: TrimmedNonEmptyString,
+ schedule: RoutineSchedule,
+ skillNames: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
+ connectorNames: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
+});
+export type AkeruCreateRoutineInput = typeof AkeruCreateRoutineInput.Type;
+
+export const Routine = Schema.Struct({
+ id: RoutineId,
+ ...RoutineDefinition.fields,
+ procedureVersion: PositiveInt,
+ approvalVersion: Schema.NullOr(PositiveInt),
+ enabled: Schema.Boolean,
+ lifecycle: RoutineLifecycle,
+ nextRunAt: Schema.NullOr(IsoDateTime),
+ lastRunAt: Schema.NullOr(IsoDateTime),
+ latestResult: Schema.NullOr(RoutineRunResult),
+ latestFailure: Schema.NullOr(RoutineRunFailure),
+ createdAt: IsoDateTime,
+ updatedAt: IsoDateTime,
+ deletedAt: Schema.NullOr(IsoDateTime),
+});
+export type Routine = typeof Routine.Type;
+
+const RoutineRunFields = {
+ id: RoutineRunId,
+ routineId: RoutineId,
+ procedureVersion: PositiveInt,
+ status: RoutineRunStatus,
+ result: Schema.NullOr(RoutineRunResult),
+ failure: Schema.NullOr(RoutineRunFailure),
+ usageRef: Schema.NullOr(AkeruUsageReservationId),
+ threadRef: Schema.NullOr(ThreadId),
+ startedAt: Schema.NullOr(IsoDateTime),
+ completedAt: Schema.NullOr(IsoDateTime),
+ createdAt: IsoDateTime,
+ updatedAt: IsoDateTime,
+} as const;
+
+export const RoutineRun = Schema.Union([
+ Schema.Struct({
+ ...RoutineRunFields,
+ trigger: Schema.Literals(["dry-run", "manual"]),
+ scheduledFor: Schema.Null,
+ }),
+ Schema.Struct({
+ ...RoutineRunFields,
+ trigger: Schema.Literals(["scheduled", "missed"]),
+ scheduledFor: IsoDateTime,
+ }),
+]);
+export type RoutineRun = typeof RoutineRun.Type;
+
+export const RoutineListRunsInput = Schema.Struct({ routineId: RoutineId });
+export type RoutineListRunsInput = typeof RoutineListRunsInput.Type;
+
+export const RoutineListRunsResult = Schema.Struct({ runs: Schema.Array(RoutineRun) });
+export type RoutineListRunsResult = typeof RoutineListRunsResult.Type;
+
+export class RoutineReadError extends Schema.TaggedErrorClass<RoutineReadError>()(
+ "RoutineReadError",
+ { routineId: RoutineId, message: TrimmedNonEmptyString },
+) {}
+
+const RoutineCommandFields = {
+ commandId: CommandId,
+ routineId: RoutineId,
+} as const;
+
+export const RoutineDraftCommand = Schema.Struct({
+ type: Schema.Literal("routine.draft"),
+ ...RoutineCommandFields,
+ ...RoutineDefinition.fields,
+ expectedProcedureVersion: Schema.optional(PositiveInt),
+ createdAt: IsoDateTime,
+});
+
+export const RoutineApproveCommand = Schema.Struct({
+ type: Schema.Literal("routine.approve"),
+ ...RoutineCommandFields,
+ procedureVersion: PositiveInt,
+ createdAt: IsoDateTime,
+});
+
+export const RoutineEnableCommand = Schema.Struct({
+ type: Schema.Literal("routine.enable"),
+ ...RoutineCommandFields,
+ createdAt: IsoDateTime,
+});
+
+export const RoutinePauseCommand = Schema.Struct({
+ type: Schema.Literal("routine.pause"),
+ ...RoutineCommandFields,
+ reason: TrimmedNonEmptyString,
+ createdAt: IsoDateTime,
+});
+
+export const RoutineRunCommand = Schema.Struct({
+ type: Schema.Literal("routine.run"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ trigger: Schema.Literals(["dry-run", "manual"]),
+ createdAt: IsoDateTime,
+});
+
+export const RoutineDeleteCommand = Schema.Struct({
+ type: Schema.Literal("routine.delete"),
+ ...RoutineCommandFields,
+ createdAt: IsoDateTime,
+});
+
+export const RoutineSkillAssignCommand = Schema.Struct({
+ type: Schema.Literal("routine.skill.assign"),
+ commandId: CommandId,
+ assignmentId: SkillAssignmentId,
+ botId: BotId,
+ skillId: SkillId,
+ name: TrimmedNonEmptyString,
+ description: Schema.NullOr(TrimmedNonEmptyString),
+ createdAt: IsoDateTime,
+});
+
+export const RoutineSkillUnassignCommand = Schema.Struct({
+ type: Schema.Literal("routine.skill.unassign"),
+ commandId: CommandId,
+ assignmentId: SkillAssignmentId,
+ botId: BotId,
+ createdAt: IsoDateTime,
+});
+
+export const ClientRoutineCommand = Schema.Union([
+ RoutineDraftCommand,
+ RoutineApproveCommand,
+ RoutineEnableCommand,
+ RoutinePauseCommand,
+ RoutineRunCommand,
+ RoutineDeleteCommand,
+ RoutineSkillAssignCommand,
+ RoutineSkillUnassignCommand,
+]);
+export type ClientRoutineCommand = typeof ClientRoutineCommand.Type;
+
+export const RoutineRunScheduledCommand = Schema.Struct({
+ type: Schema.Literal("routine.run.scheduled"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ trigger: Schema.Literals(["scheduled", "missed"]),
+ scheduledFor: IsoDateTime,
+ createdAt: IsoDateTime,
+});
+
+export const RoutineCreateApprovedCommand = Schema.Struct({
+ type: Schema.Literal("routine.create-approved"),
+ ...RoutineCommandFields,
+ ...RoutineDefinition.fields,
+ createdAt: IsoDateTime,
+});
+
+export const RoutineRunStartCommand = Schema.Struct({
+ type: Schema.Literal("routine.run.start"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ threadRef: Schema.NullOr(ThreadId),
+ startedAt: IsoDateTime,
+});
+
+export const RoutineRunBlockCommand = Schema.Struct({
+ type: Schema.Literal("routine.run.block"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ failure: RoutineRunFailure,
+ createdAt: IsoDateTime,
+});
+
+export const RoutineRunFailCommand = Schema.Struct({
+ type: Schema.Literal("routine.run.fail"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ failure: RoutineRunFailure,
+ usageRef: Schema.NullOr(AkeruUsageReservationId),
+ createdAt: IsoDateTime,
+});
+
+export const RoutineRunCompleteCommand = Schema.Struct({
+ type: Schema.Literal("routine.run.complete"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ result: RoutineRunResult,
+ usageRef: Schema.NullOr(AkeruUsageReservationId),
+ nextRunAt: Schema.NullOr(IsoDateTime),
+ createdAt: IsoDateTime,
+});
+
+export const RoutineRunCancelCommand = Schema.Struct({
+ type: Schema.Literal("routine.run.cancel"),
+ ...RoutineCommandFields,
+ runId: RoutineRunId,
+ createdAt: IsoDateTime,
+});
+
+export const InternalRoutineCommand = Schema.Union([
+ RoutineCreateApprovedCommand,
+ RoutineRunScheduledCommand,
+ RoutineRunStartCommand,
+ RoutineRunBlockCommand,
+ RoutineRunFailCommand,
+ RoutineRunCompleteCommand,
+ RoutineRunCancelCommand,
+]);
+export type InternalRoutineCommand = typeof InternalRoutineCommand.Type;
+
+export const RoutineDraftedRecord = Schema.Struct({
+ ...Routine.fields,
+ approvalVersion: Schema.Null,
+ enabled: Schema.Literal(false),
+ lifecycle: Schema.Literal("draft"),
+});
+export type RoutineDraftedRecord = typeof RoutineDraftedRecord.Type;
+
+export const RoutineDraftedPayload = Schema.Struct({ routine: RoutineDraftedRecord });
+export const RoutineApprovedPayload = Schema.Struct({ routine: Routine });
+export const RoutineEnabledPayload = Schema.Struct({ routine: Routine });
+export const RoutinePausedPayload = Schema.Struct({ routine: Routine });
+export const RoutineRunningPayload = Schema.Struct({ routine: Routine, run: RoutineRun });
+export const RoutineBlockedPayload = Schema.Struct({ routine: Routine, run: RoutineRun });
+export const RoutineFailedPayload = Schema.Struct({ routine: Routine, run: RoutineRun });
+export const RoutineCompletedPayload = Schema.Struct({ routine: Routine, run: RoutineRun });
+export const RoutineRunCanceledPayload = Schema.Struct({ routine: Routine, run: RoutineRun });
+export const RoutineDeletedPayload = Schema.Struct({ routine: Routine });
+export const RoutineSkillAssignedPayload = Schema.Struct({ assignment: RoutineSkillAssignment });
+export const RoutineSkillUnassignedPayload = Schema.Struct({
+ assignmentId: SkillAssignmentId,
+ botId: BotId,
+ removedAt: IsoDateTime,
+});
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 9d25d7eef..6e11b9464 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -217,6 +217,7 @@ import {
PortabilityImportPreview,
PortabilityPreviewImportInput,
} from "./portability.ts";
+import { RoutineListRunsInput, RoutineListRunsResult, RoutineReadError } from "./routines.ts";
export const WS_METHODS = {
// Project registry methods
@@ -324,6 +325,7 @@ export const WS_METHODS = {
portabilityExport: "portability.export",
portabilityPreviewImport: "portability.previewImport",
portabilityApplyImport: "portability.applyImport",
+ routinesListRuns: "routines.listRuns",
// Source control methods
sourceControlLookupRepository: "sourceControl.lookupRepository",
@@ -611,6 +613,12 @@ export const WsPortabilityApplyImportRpc = Rpc.make(WS_METHODS.portabilityApplyI
error: Schema.Union([PortabilityArchiveError, EnvironmentAuthorizationError]),
});
+export const WsRoutinesListRunsRpc = Rpc.make(WS_METHODS.routinesListRuns, {
+ payload: RoutineListRunsInput,
+ success: RoutineListRunsResult,
+ error: Schema.Union([RoutineReadError, EnvironmentAuthorizationError]),
+});
+
export const WsSourceControlLookupRepositoryRpc = Rpc.make(
WS_METHODS.sourceControlLookupRepository,
{
@@ -1059,6 +1067,7 @@ export const WsRpcGroup = RpcGroup.make(
WsPortabilityExportRpc,
WsPortabilityPreviewImportRpc,
WsPortabilityApplyImportRpc,
+ WsRoutinesListRunsRpc,
WsSourceControlLookupRepositoryRpc,
WsSourceControlCloneRepositoryRpc,
WsSourceControlPublishRepositoryRpc,