Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): scheduled agents (backend) (#2629)

Eric Hayes4f2025264792
diff --git a/.github/services-config.json b/.github/services-config.json
index dd6258c5e9..68ff1fe655 100644
--- a/.github/services-config.json
+++ b/.github/services-config.json
@@ -1,5 +1,11 @@
{
"services": {
+ "agent-schedule-service": {
+ "source_paths": [
+ "rust/cloud-storage/scheduled_action/**"
+ ],
+ "stack_path": "infra/stacks/agent-schedule-service/**"
+ },
"authentication-service": {
"source_paths": [
"rust/cloud-storage/authentication_service/**",
diff --git a/.github/workflows/deploy-service-generic.yml b/.github/workflows/deploy-service-generic.yml
index 26581135c5..4e23487fed 100644
--- a/.github/workflows/deploy-service-generic.yml
+++ b/.github/workflows/deploy-service-generic.yml
@@ -7,6 +7,7 @@ on:
required: true
description: Select the service to deploy
options:
+ - agent-schedule-service
- authentication-service
- bulk-upload
- connection-gateway
diff --git a/infra/bun.lock b/infra/bun.lock
index ec14ec8e34..e09e876db6 100644
--- a/infra/bun.lock
+++ b/infra/bun.lock
@@ -44,6 +44,10 @@
"name": "vpc",
"version": "0.0.0",
},
+ "stacks/agent-schedule-service": {
+ "name": "agent-schedule-service-stack",
+ "version": "0.0.0",
+ },
"stacks/authentication-service": {
"name": "authentication-service-stack",
"version": "0.0.0",
@@ -528,6 +532,8 @@
"agent-base": ["[email protected]", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="],
+ "agent-schedule-service-stack": ["agent-schedule-service-stack@workspace:stacks/agent-schedule-service"],
+
"aggregate-error": ["[email protected]", "", { "dependencies": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" } }, "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA=="],
"ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
diff --git a/infra/stacks/agent-schedule-service/Pulumi.dev.yaml b/infra/stacks/agent-schedule-service/Pulumi.dev.yaml
new file mode 100644
index 0000000000..eda952ad45
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/Pulumi.dev.yaml
@@ -0,0 +1,13 @@
+config:
+ aws-native:region: us-east-1
+ aws:region: us-east-1
+ agent-schedule-service:macro_db_secret_key: macro-db-dev
+ agent-schedule-service:jwt_secret_key: fusionauth-jwt-secret-dev
+ agent-schedule-service:fusionauth_client_id: fusionauth-client-id-key-dev
+ agent-schedule-service:fusionauth_issuer: fusionauth-dev.macro.com
+ agent-schedule-service:internal_auth_key: document-storage-service-auth-key-dev
+ agent-schedule-service:openai_api_key: openai-key
+ agent-schedule-service:anthropic_api_key: anthropic-api-key-dev
+ agent-schedule-service:xai-api-key: xai-api-key
+ agent-schedule-service:open-router-api-key: open-router-api-key-dev-v2
+ agent-schedule-service:perplexity-api-key: perplexity-api-key
diff --git a/infra/stacks/agent-schedule-service/Pulumi.prod.yaml b/infra/stacks/agent-schedule-service/Pulumi.prod.yaml
new file mode 100644
index 0000000000..3f48e586b0
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/Pulumi.prod.yaml
@@ -0,0 +1,13 @@
+config:
+ aws-native:region: us-east-1
+ aws:region: us-east-1
+ agent-schedule-service:macro_db_secret_key: macro-db-prod
+ agent-schedule-service:jwt_secret_key: fusionauth-jwt-secret-prod
+ agent-schedule-service:fusionauth_client_id: fusionauth-client-id-key-prod
+ agent-schedule-service:fusionauth_issuer: auth.macro.com
+ agent-schedule-service:internal_auth_key: document-storage-service-auth-key-prod
+ agent-schedule-service:openai_api_key: openai-key
+ agent-schedule-service:anthropic_api_key: anthropic-api-key
+ agent-schedule-service:xai-api-key: xai-api-key
+ agent-schedule-service:open-router-api-key: open-router-api-key-prod-v2
+ agent-schedule-service:perplexity-api-key: perplexity-api-key
diff --git a/infra/stacks/agent-schedule-service/Pulumi.yaml b/infra/stacks/agent-schedule-service/Pulumi.yaml
new file mode 100644
index 0000000000..413060c941
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/Pulumi.yaml
@@ -0,0 +1,3 @@
+name: agent-schedule-service
+runtime: nodejs
+description: Macro Agent Schedule Service
diff --git a/infra/stacks/agent-schedule-service/index.ts b/infra/stacks/agent-schedule-service/index.ts
new file mode 100644
index 0000000000..a8b33f5801
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/index.ts
@@ -0,0 +1,314 @@
+import * as aws from '@pulumi/aws';
+import * as pulumi from '@pulumi/pulumi';
+import {
+ config,
+ getMacroApiToken,
+ getMacroNotify,
+ stack,
+} from '../../packages/shared';
+import { get_coparse_api_vpc } from '../../packages/vpc';
+import { AgentScheduleService } from './service';
+
+const tags = {
+ environment: stack,
+ env: stack,
+ tech_lead: 'ehayes',
+ project: 'agent-schedule-service',
+ service: 'agent-schedule-service',
+};
+
+// ── Secrets ──────────────────────────────────────────────────────────────────
+
+const DATABASE_URL = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('macro_db_secret_key'),
+ })
+ .apply((secret) => secret.secretString);
+
+const JWT_SECRET_KEY = config.require('jwt_secret_key');
+const jwtSecretKeyArn = aws.secretsmanager
+ .getSecretVersionOutput({ secretId: JWT_SECRET_KEY })
+ .apply((secret) => secret.arn);
+
+const FUSIONAUTH_CLIENT_ID = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('fusionauth_client_id'),
+ })
+ .apply((secret) => secret.secretString);
+
+const FUSIONAUTH_ISSUER = config.require('fusionauth_issuer');
+
+const OPEN_ROUTER_API_KEY = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('open-router-api-key'),
+ })
+ .apply((secret) => secret.secretString);
+
+const OPENAI_API_KEY = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('openai_api_key'),
+ })
+ .apply((secret) => secret.secretString);
+
+const XAI_API_KEY = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('xai-api-key'),
+ })
+ .apply((secret) => secret.secretString);
+
+const ANTHROPIC_API_KEY = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('anthropic_api_key'),
+ })
+ .apply((secret) => secret.secretString);
+
+const PERPLEXITY_API_KEY = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('perplexity-api-key'),
+ })
+ .apply((secret) => secret.secretString);
+
+// Name of the Secrets Manager entry that holds the internal auth key. The
+// env var passes this NAME; the container fetches the current value at
+// runtime via the secrets manager client. The task role's read permission
+// is granted below via `internalAuthKeyArn` in `secretKeyArns`.
+const INTERNAL_AUTH_KEY_NAME = config.require('internal_auth_key');
+const internalAuthKeyArn = aws.secretsmanager
+ .getSecretVersionOutput({ secretId: INTERNAL_AUTH_KEY_NAME })
+ .apply((secret) => secret.arn);
+
+const MACRO_API_TOKENS = getMacroApiToken();
+const { notificationIngressQueueArn, notificationIngressQueueName } =
+ getMacroNotify();
+
+// ── Stack references ─────────────────────────────────────────────────────────
+
+const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {
+ name: `macro-inc/document-storage/${stack}`,
+});
+
+const cloudStorageServiceStack = new pulumi.StackReference(
+ 'cloud-storage-service',
+ {
+ name: `macro-inc/cloud-storage-service/${stack}`,
+ }
+);
+
+const linksharingStack = new pulumi.StackReference('linksharing-stack', {
+ name: `macro-inc/link-sharing/${stack}`,
+});
+
+const emailServiceStack = new pulumi.StackReference('email-service-stack', {
+ name: `macro-inc/email-service/${stack}`,
+});
+
+const cloudStorageClusterArn = cloudStorageStack
+ .getOutput('cloudStorageClusterArn')
+ .apply((value) => value as string);
+
+const cloudStorageClusterName = cloudStorageStack
+ .getOutput('cloudStorageClusterName')
+ .apply((value) => value as string);
+
+const documentStorageBucketId = cloudStorageStack
+ .getOutput('documentStorageBucketId')
+ .apply((value) => value as string);
+
+const documentStorageBucketArn = cloudStorageStack
+ .getOutput('documentStorageBucketArn')
+ .apply((value) => value as string);
+
+const docxUploadBucketName = cloudStorageServiceStack
+ .getOutput('docxUploadBucketName')
+ .apply((value) => value as string);
+
+const docxUploadBucketArn = cloudStorageServiceStack
+ .getOutput('docxUploadBucketArn')
+ .apply((value) => value as string);
+
+const documentStorageServiceUrl = cloudStorageServiceStack
+ .getOutput('cloudStorageServiceUrl')
+ .apply((value) => value as string);
+
+const cloudfrontDistributionUrl = linksharingStack
+ .getOutput('cloudfrontDistributionUrl')
+ .apply((value) => value as string);
+
+const cloudfrontSignerPublicKeyId = linksharingStack
+ .getOutput('cloudfrontDistributionPublicKeyId')
+ .apply((value) => value as string);
+
+const CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME = `linksharing-private-key-${stack}`;
+const cloudfrontPrivateKeySecretArn = aws.secretsmanager
+ .getSecretOutput({
+ name: CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME,
+ })
+ .apply((secret) => secret.arn);
+
+const emailScheduledQueueArn = emailServiceStack
+ .getOutput('scheduledQueueArn')
+ .apply((value) => value as string);
+
+const emailScheduledQueueName = emailServiceStack
+ .getOutput('scheduledQueueName')
+ .apply((value) => value as string);
+
+// ── Service ──────────────────────────────────────────────────────────────────
+
+const vpc = get_coparse_api_vpc();
+
+const service = new AgentScheduleService(`agent-schedule-service-${stack}`, {
+ vpc,
+ tags,
+ platform: { family: 'linux', architecture: 'amd64' },
+ serviceContainerPort: 8080,
+ healthCheckPath: '/health',
+ isPrivate: false,
+ ecsClusterArn: cloudStorageClusterArn,
+ cloudStorageClusterName,
+ secretKeyArns: [
+ jwtSecretKeyArn,
+ cloudfrontPrivateKeySecretArn,
+ MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
+ internalAuthKeyArn,
+ ],
+ queueArns: [notificationIngressQueueArn, emailScheduledQueueArn],
+ bucketArns: [documentStorageBucketArn, docxUploadBucketArn],
+ containerEnvVars: [
+ // Core
+ {
+ name: 'DATABASE_URL',
+ value: pulumi.interpolate`${DATABASE_URL}`,
+ },
+ {
+ name: 'PORT',
+ value: '8080',
+ },
+ {
+ name: 'ENVIRONMENT',
+ value: stack,
+ },
+ {
+ name: 'RUST_LOG',
+ value: 'scheduled_action=info,ai=info,ai_tools=info,tower_http=info',
+ },
+ // Auth
+ {
+ name: 'JWT_SECRET_KEY',
+ value: pulumi.interpolate`${JWT_SECRET_KEY}`,
+ },
+ {
+ name: 'AUDIENCE',
+ value: pulumi.interpolate`${FUSIONAUTH_CLIENT_ID}`,
+ },
+ {
+ name: 'ISSUER',
+ value: pulumi.interpolate`${FUSIONAUTH_ISSUER}`,
+ },
+ {
+ name: 'MACRO_API_TOKEN_ISSUER',
+ value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,
+ },
+ {
+ name: 'MACRO_API_TOKEN_PUBLIC_KEY',
+ value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,
+ },
+ // Queues
+ {
+ name: 'NOTIFICATION_QUEUE',
+ value: pulumi.interpolate`${notificationIngressQueueName}`,
+ },
+ {
+ name: 'EMAIL_SCHEDULED_QUEUE',
+ value: pulumi.interpolate`${emailScheduledQueueName}`,
+ },
+ // Tool context: internal service URLs
+ {
+ name: 'INTERNAL_API_SECRET_KEY',
+ value: INTERNAL_AUTH_KEY_NAME,
+ },
+ {
+ name: 'CONNECTION_GATEWAY_URL',
+ value: `https://connection-gateway${
+ stack === 'prod' ? '' : `-${stack}`
+ }.macro.com`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_URL',
+ value: pulumi.interpolate`${documentStorageServiceUrl}`,
+ },
+ {
+ name: 'SEARCH_SERVICE_URL',
+ value: pulumi.interpolate`${documentStorageServiceUrl}`,
+ },
+ {
+ name: 'SYNC_SERVICE_URL',
+ value: `https://sync-service-${stack === 'dev' ? 'dev3' : 'prod2'}.macroverse.workers.dev`,
+ },
+ {
+ name: 'LEXICAL_SERVICE_URL',
+ value: `https://lexical-service-${stack}.macroverse.workers.dev`,
+ },
+ {
+ name: 'EMAIL_SERVICE_URL',
+ value: `https://email-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,
+ },
+ {
+ name: 'STATIC_FILE_SERVICE_URL',
+ value: `https://static-file-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`,
+ },
+ // Tool context: storage
+ {
+ name: 'DOCUMENT_STORAGE_BUCKET',
+ value: pulumi.interpolate`${documentStorageBucketId}`,
+ },
+ {
+ name: 'DOCX_DOCUMENT_UPLOAD_BUCKET',
+ value: pulumi.interpolate`${docxUploadBucketName}`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL',
+ value: pulumi.interpolate`${cloudfrontDistributionUrl}`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID',
+ value: pulumi.interpolate`${cloudfrontSignerPublicKeyId}`,
+ },
+ {
+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME',
+ value: CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME,
+ },
+ // AI model API keys
+ {
+ name: 'OPEN_ROUTER_API_KEY',
+ value: pulumi.interpolate`${OPEN_ROUTER_API_KEY}`,
+ },
+ {
+ name: 'OPENAI_API_KEY',
+ value: pulumi.interpolate`${OPENAI_API_KEY}`,
+ },
+ {
+ name: 'ANTHROPIC_API_KEY',
+ value: pulumi.interpolate`${ANTHROPIC_API_KEY}`,
+ },
+ {
+ name: 'XAI_API_KEY',
+ value: pulumi.interpolate`${XAI_API_KEY}`,
+ },
+ {
+ name: 'PERPLEXITY_API_KEY',
+ value: pulumi.interpolate`${PERPLEXITY_API_KEY}`,
+ },
+ // Datadog
+ {
+ name: 'DD_SERVICE',
+ value: 'agent-schedule-service',
+ },
+ {
+ name: 'DD_ENV',
+ value: stack,
+ },
+ ],
+});
+
+export const agentScheduleServiceUrl = pulumi.interpolate`${service.domain}`;
diff --git a/infra/stacks/agent-schedule-service/package.json b/infra/stacks/agent-schedule-service/package.json
new file mode 100644
index 0000000000..ae442d0b0c
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "agent-schedule-service-stack",
+ "version": "0.0.0",
+ "private": true,
+ "license": "MIT"
+}
diff --git a/infra/stacks/agent-schedule-service/service.ts b/infra/stacks/agent-schedule-service/service.ts
new file mode 100644
index 0000000000..5a377a8f0c
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/service.ts
@@ -0,0 +1,459 @@
+import * as aws from '@pulumi/aws';
+import * as awsx from '@pulumi/awsx';
+import * as pulumi from '@pulumi/pulumi';
+import {
+ DATADOG_API_KEY,
+ datadogAgentContainer,
+ fargateLogRouterSidecarContainer,
+ serviceLoadBalancer,
+} from '../../packages/resources';
+import { EcrImage } from '../../packages/service';
+import {
+ BASE_DOMAIN,
+ CLOUD_TRAIL_SNS_TOPIC_ARN,
+ stack,
+} from '../../packages/shared';
+
+const BASE_NAME = 'agent-schedule-service';
+const BASE_PATH = '../../../rust/cloud-storage';
+
+export const SERVICE_DOMAIN_NAME = `agent-schedule${
+ stack === 'prod' ? '' : `-${stack}`
+}.${BASE_DOMAIN}`;
+
+type Args = {
+ vpc: {
+ vpcId: pulumi.Output<string> | string;
+ publicSubnetIds: pulumi.Output<string[]> | string[];
+ privateSubnetIds: pulumi.Output<string[]> | string[];
+ };
+ tags: { [key: string]: string };
+ containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];
+ platform: { family: string; architecture: 'amd64' | 'arm64' };
+ serviceContainerPort: number;
+ healthCheckPath: string;
+ isPrivate?: boolean;
+ ecsClusterArn: pulumi.Output<string> | string;
+ cloudStorageClusterName: pulumi.Output<string> | string;
+ secretKeyArns: (pulumi.Output<string> | string)[];
+ /** SQS queues the service is allowed to send messages to. */
+ queueArns: (pulumi.Output<string> | string)[];
+ /** S3 buckets the service needs access to. */
+ bucketArns: (pulumi.Output<string> | string)[];
+};
+
+export class AgentScheduleService extends pulumi.ComponentResource {
+ public role: aws.iam.Role;
+ public ecr: awsx.ecr.Repository;
+ public serviceAlbSg: aws.ec2.SecurityGroup;
+ public serviceSg: aws.ec2.SecurityGroup;
+ public domain: string;
+ public targetGroup: aws.lb.TargetGroup;
+ public lb: aws.lb.LoadBalancer;
+ public listener: aws.lb.Listener;
+ public service: awsx.ecs.FargateService;
+ public cloudStorageClusterName: pulumi.Output<string> | string;
+ public tags: { [key: string]: string };
+
+ constructor(
+ name: string,
+ args: Args,
+ opts?: pulumi.ComponentResourceOptions
+ ) {
+ super('my:components:AgentScheduleService', name, {}, opts);
+ const {
+ vpc,
+ tags,
+ platform,
+ serviceContainerPort,
+ healthCheckPath,
+ isPrivate,
+ ecsClusterArn,
+ containerEnvVars,
+ cloudStorageClusterName,
+ secretKeyArns,
+ queueArns,
+ bucketArns,
+ } = args;
+
+ this.domain = `https://${SERVICE_DOMAIN_NAME}`;
+ this.cloudStorageClusterName = cloudStorageClusterName;
+ this.tags = tags;
+
+ const secretsManagerPolicy = new aws.iam.Policy(
+ `${BASE_NAME}-secrets-manager-policy`,
+ {
+ name: `${BASE_NAME}-secrets-manager-policy-${stack}`,
+ policy: {
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: [
+ 'secretsmanager:GetSecretValue',
+ 'secretsmanager:DescribeSecret',
+ ],
+ Resource: secretKeyArns,
+ Effect: 'Allow',
+ },
+ ],
+ },
+ tags,
+ },
+ { parent: this }
+ );
+
+ const sqsPolicy = new aws.iam.Policy(
+ `${BASE_NAME}-sqs-policy`,
+ {
+ name: `${BASE_NAME}-sqs-policy-${stack}`,
+ policy: pulumi.output({
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: ['sqs:SendMessage'],
+ Resource: queueArns,
+ Effect: 'Allow',
+ },
+ ],
+ }),
+ tags,
+ },
+ { parent: this }
+ );
+
+ const s3Policy = new aws.iam.Policy(
+ `${BASE_NAME}-s3-policy`,
+ {
+ name: `${BASE_NAME}-s3-policy-${stack}`,
+ policy: pulumi.output({
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Effect: 'Allow',
+ Action: [
+ 's3:ListBucket',
+ 's3:GetObject',
+ 's3:PutObject',
+ 's3:DeleteObject',
+ ],
+ Resource: bucketArns.flatMap((arn) => [
+ arn,
+ pulumi.interpolate`${arn}/*`,
+ ]),
+ },
+ ],
+ }),
+ tags,
+ },
+ { parent: this }
+ );
+
+ this.role = new aws.iam.Role(
+ `${BASE_NAME}-role`,
+ {
+ name: `${BASE_NAME}-role-${stack}`,
+ assumeRolePolicy: {
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: 'sts:AssumeRole',
+ Principal: {
+ Service: 'ecs-tasks.amazonaws.com',
+ },
+ Effect: 'Allow',
+ },
+ ],
+ },
+ managedPolicyArns: [
+ secretsManagerPolicy.arn,
+ sqsPolicy.arn,
+ s3Policy.arn,
+ ],
+ tags,
+ },
+ { parent: this }
+ );
+
+ const image = new EcrImage(
+ `${BASE_NAME}-ecr-image-${stack}`,
+ {
+ repositoryId: `${BASE_NAME}-ecr-${stack}`,
+ repositoryName: `${BASE_NAME}-${stack}`,
+ imageId: `${BASE_NAME}-image-${stack}`,
+ imagePath: BASE_PATH,
+ dockerfile: 'Dockerfile',
+ platform,
+ buildArgs: {
+ SERVICE_NAME: 'service',
+ },
+ tags,
+ },
+ { parent: this }
+ );
+ this.ecr = image.ecr;
+
+ const { serviceAlbSg, serviceSg } = this.initializeSecurityGroups({
+ vpcId: vpc.vpcId,
+ serviceContainerPort,
+ });
+ this.serviceAlbSg = serviceAlbSg;
+ this.serviceSg = serviceSg;
+
+ const { targetGroup, lb, listener } = serviceLoadBalancer(this, {
+ serviceName: BASE_NAME,
+ serviceContainerPort,
+ healthCheckPath,
+ vpc,
+ albSecurityGroupId: serviceAlbSg.id,
+ isPrivate,
+ tags,
+ });
+ this.targetGroup = targetGroup;
+ this.lb = lb;
+ this.listener = listener;
+
+ this.service = new awsx.ecs.FargateService(
+ `${BASE_NAME}`,
+ {
+ tags,
+ cluster: ecsClusterArn,
+ networkConfiguration: {
+ subnets: vpc.privateSubnetIds,
+ securityGroups: [serviceSg.id],
+ },
+ taskDefinitionArgs: {
+ taskRole: {
+ roleArn: this.role.arn,
+ },
+ containers: {
+ log_router: fargateLogRouterSidecarContainer,
+ datadog_agent: datadogAgentContainer,
+ service: {
+ name: BASE_NAME,
+ image: image.image.imageUri,
+ stopTimeout: 10,
+ cpu: 256,
+ memory: 512,
+ environment: [
+ ...containerEnvVars,
+ {
+ name: 'BASE_URL',
+ value: this.domain,
+ },
+ ],
+ logConfiguration: {
+ logDriver: 'awsfirelens',
+ options: {
+ Name: 'datadog',
+ Host: 'http-intake.logs.us5.datadoghq.com',
+ apikey: DATADOG_API_KEY,
+ dd_service: 'agent-schedule-service',
+ dd_source: 'fargate',
+ dd_tags: `project:cloudstorage, env:${stack}`,
+ provider: 'ecs',
+ },
+ },
+ portMappings: [
+ {
+ appProtocol: 'http',
+ name: `${BASE_NAME}-tcp-${stack}`,
+ hostPort: serviceContainerPort,
+ containerPort: serviceContainerPort,
+ targetGroup,
+ },
+ ],
+ },
+ },
+ runtimePlatform: {
+ operatingSystemFamily: platform.family.toUpperCase(),
+ cpuArchitecture:
+ platform.architecture === 'amd64'
+ ? 'X86_64'
+ : platform.architecture.toUpperCase(),
+ },
+ },
+ desiredCount: 1,
+ },
+ { parent: this }
+ );
+
+ this.setupAutoScaling();
+ this.setupServiceAlarms();
+
+ const zone = aws.route53.getZoneOutput({ name: BASE_DOMAIN });
+ new aws.route53.Record(
+ `${BASE_NAME}-domain-record`,
+ {
+ name: SERVICE_DOMAIN_NAME,
+ type: 'A',
+ zoneId: zone.zoneId,
+ aliases: [
+ {
+ evaluateTargetHealth: false,
+ name: this.lb.dnsName,
+ zoneId: this.lb.zoneId,
+ },
+ ],
+ },
+ { parent: this }
+ );
+ }
+
+ private initializeSecurityGroups({
+ vpcId,
+ serviceContainerPort,
+ }: {
+ vpcId: pulumi.Output<string> | string;
+ serviceContainerPort: number;
+ }) {
+ const serviceAlbSg = new aws.ec2.SecurityGroup(
+ `${BASE_NAME}-alb-sg-${stack}`,
+ {
+ name: `${BASE_NAME}-alb-sg-${stack}`,
+ description: `${BASE_NAME} application load balancer security group`,
+ vpcId,
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ const serviceSg = new aws.ec2.SecurityGroup(
+ `${BASE_NAME}-sg-${stack}`,
+ {
+ name: `${BASE_NAME}-sg-${stack}`,
+ vpcId,
+ description: `${BASE_NAME} service security group`,
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.vpc.SecurityGroupIngressRule(
+ `${BASE_NAME}-alb-in`,
+ {
+ securityGroupId: serviceSg.id,
+ description: 'Allow inbound traffic from the service ALB',
+ referencedSecurityGroupId: serviceAlbSg.id,
+ fromPort: serviceContainerPort,
+ toPort: serviceContainerPort,
+ ipProtocol: 'tcp',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.vpc.SecurityGroupEgressRule(
+ `${BASE_NAME}-service-out`,
+ {
+ securityGroupId: serviceSg.id,
+ description: 'Allow all outbound traffic',
+ cidrIpv4: '0.0.0.0/0',
+ ipProtocol: '-1',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.vpc.SecurityGroupIngressRule(
+ `${BASE_NAME}-http`,
+ {
+ securityGroupId: serviceAlbSg.id,
+ description: 'Allow inbound HTTP traffic',
+ cidrIpv4: '0.0.0.0/0',
+ fromPort: 80,
+ toPort: 80,
+ ipProtocol: 'tcp',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.vpc.SecurityGroupIngressRule(
+ `${BASE_NAME}-https`,
+ {
+ securityGroupId: serviceAlbSg.id,
+ description: 'Allow inbound HTTPS traffic',
+ cidrIpv4: '0.0.0.0/0',
+ fromPort: 443,
+ toPort: 443,
+ ipProtocol: 'tcp',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.vpc.SecurityGroupEgressRule(
+ `${BASE_NAME}-alb-out`,
+ {
+ securityGroupId: serviceAlbSg.id,
+ description: 'Allow traffic to the service security group',
+ referencedSecurityGroupId: serviceSg.id,
+ fromPort: serviceContainerPort,
+ toPort: serviceContainerPort,
+ ipProtocol: 'tcp',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ return { serviceAlbSg, serviceSg };
+ }
+
+ private setupAutoScaling() {
+ const target = new aws.appautoscaling.Target(
+ `${BASE_NAME}-service-scalable-target-${stack}`,
+ {
+ maxCapacity: stack === 'prod' ? 3 : 2,
+ minCapacity: 1,
+ resourceId: pulumi.interpolate`service/${this.cloudStorageClusterName}/${this.service.service.name}`,
+ scalableDimension: 'ecs:service:DesiredCount',
+ serviceNamespace: 'ecs',
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
+ new aws.appautoscaling.Policy(
+ `${BASE_NAME}-scaling-policy-cpu-${stack}`,
+ {
+ policyType: 'TargetTrackingScaling',
+ resourceId: target.resourceId,
+ scalableDimension: target.scalableDimension,
+ serviceNamespace: target.serviceNamespace,
+ targetTrackingScalingPolicyConfiguration: {
+ targetValue: 60,
+ predefinedMetricSpecification: {
+ predefinedMetricType: 'ECSServiceAverageCPUUtilization',
+ },
+ scaleInCooldown: 60,
+ scaleOutCooldown: 120,
+ },
+ },
+ { parent: this }
+ );
+ }
+
+ private setupServiceAlarms() {
+ new aws.cloudwatch.MetricAlarm(
+ `${BASE_NAME}-service-cpu-alarm`,
+ {
+ name: `${BASE_NAME}-service-cpu-${stack}`,
+ alarmDescription: `Alarm when ${BASE_NAME} CPU stays elevated`,
+ namespace: 'AWS/ECS',
+ metricName: 'CPUUtilization',
+ statistic: 'Average',
+ period: 300,
+ evaluationPeriods: 2,
+ threshold: 90,
+ comparisonOperator: 'GreaterThanOrEqualToThreshold',
+ dimensions: {
+ ClusterName: pulumi.interpolate`${this.cloudStorageClusterName}`,
+ ServiceName: this.service.service.name,
+ },
+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+ }
+}
diff --git a/infra/stacks/agent-schedule-service/tsconfig.json b/infra/stacks/agent-schedule-service/tsconfig.json
new file mode 100644
index 0000000000..4082f16a5d
--- /dev/null
+++ b/infra/stacks/agent-schedule-service/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "../../tsconfig.json"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 667d2df9da..148ba134ca 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -93,6 +93,8 @@ dependencies = [
"anthropic",
"anyhow",
"async-trait",
+ "aws-sdk-secretsmanager",
+ "aws-sdk-sqs",
"axum",
"call",
"chrono",
@@ -100,6 +102,7 @@ dependencies = [
"connection",
"cool_asserts",
"dateparser",
+ "document_storage_service_client",
"documents",
"email",
"email_service_client",
@@ -107,7 +110,11 @@ dependencies = [
"frecency",
"item_filters",
"lazy_static",
+ "lexical_client",
+ "macro_aws_config",
"macro_db_client",
+ "macro_env",
+ "macro_env_var",
"macro_user_id",
"model",
"model_notifications",
@@ -120,15 +127,20 @@ dependencies = [
"notification",
"properties",
"rand 0.9.3",
+ "readonly_pool",
+ "remote_env_var",
"schemars",
"scribe",
"search_service_client",
+ "secretsmanager_client",
"serde",
"serde_json",
"soup",
"sqlx",
"sqs_client",
+ "static_file_service_client",
"strum",
+ "sync_service_client",
"tokio",
"tracing",
"utoipa",
@@ -1908,6 +1920,17 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "chrono-tz"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
+dependencies = [
+ "chrono",
+ "phf 0.12.1",
+ "serde",
+]
+
[[package]]
name = "cipher"
version = "0.4.4"
@@ -2506,6 +2529,18 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "cron"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "089df96cf6a25253b4b6b6744d86f91150a3d4df546f31a95def47976b8cba97"
+dependencies = [
+ "chrono",
+ "once_cell",
+ "phf 0.11.3",
+ "winnow",
+]
+
[[package]]
name = "crossbeam-deque"
version = "0.8.6"
@@ -5726,7 +5761,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
- "windows-targets 0.48.5",
+ "windows-targets 0.52.6",
]
[[package]]
@@ -6435,20 +6470,9 @@ dependencies = [
"ai_tools",
"ai_toolset",
"anyhow",
- "aws-sdk-sqs",
"axum",
- "call",
"chrono",
- "comms",
- "document_storage_service_client",
- "documents",
- "email",
- "email_service_client",
- "entity_access",
- "frecency",
"futures",
- "lexical_client",
- "macro_aws_config",
"macro_db_migrator",
"macro_entrypoint",
"macro_env",
@@ -6456,17 +6480,9 @@ dependencies = [
"macro_user_id",
"macro_uuid",
"model_user",
- "properties",
- "readonly_pool",
- "scribe",
- "search_service_client",
"serde",
"serde_json",
- "soup",
"sqlx",
- "sqs_client",
- "static_file_service_client",
- "sync_service_client",
"thiserror 2.0.17",
"tokio",
"tracing",
@@ -7950,6 +7966,15 @@ dependencies = [
"phf_shared 0.11.3",
]
+[[package]]
+name = "phf"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
+dependencies = [
+ "phf_shared 0.12.1",
+]
+
[[package]]
name = "phf_codegen"
version = "0.10.0"
@@ -8021,6 +8046,15 @@ dependencies = [
"siphasher 1.0.1",
]
+[[package]]
+name = "phf_shared"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
+dependencies = [
+ "siphasher 1.0.1",
+]
+
[[package]]
name = "pin-project"
version = "1.1.9"
@@ -9316,6 +9350,49 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "scheduled_action"
+version = "0.1.0"
+dependencies = [
+ "ai",
+ "ai_tools",
+ "ai_toolset",
+ "anyhow",
+ "aws-sdk-secretsmanager",
+ "aws-sdk-sqs",
+ "axum",
+ "chat",
+ "chrono",
+ "chrono-tz",
+ "connection_gateway_client",
+ "cron",
+ "futures",
+ "macro_auth",
+ "macro_aws_config",
+ "macro_cors",
+ "macro_db_client",
+ "macro_entrypoint",
+ "macro_env",
+ "macro_env_var",
+ "macro_middleware",
+ "macro_user_id",
+ "macro_uuid",
+ "memory",
+ "model",
+ "model-entity",
+ "model_notifications",
+ "model_user",
+ "notification",
+ "secretsmanager_client",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "utoipa-swagger-ui",
+]
+
[[package]]
name = "schemars"
version = "1.0.4"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 0308c48e0a..8474d99afc 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -2,7 +2,7 @@
resolver = "2"
members = [
- "ai",
+ "ai",
"ai_format",
"ai_tools",
"ai_toolset",
@@ -115,6 +115,7 @@ members = [
"s3_client",
"s3_key",
"scribe",
+ "scheduled_action",
"search_processing_service",
"search_service",
"search_service_client",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index d5b13659be..e12626f78c 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -4,6 +4,9 @@ name = "ai_tools"
publish = false
version = "0.1.0"
+[features]
+test-support = []
+
[dependencies]
ai = { path = "../ai" }
ai_format = { path = "../ai_format" }
@@ -12,6 +15,7 @@ anthropic = { path = "../anthropic" }
anyhow.workspace = true
async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
+aws-sdk-sqs.workspace = true
call = { path = "../call", default-features = false, features = ["ports"] }
chrono.workspace = true
dateparser.workspace = true
@@ -19,6 +23,7 @@ comms = { path = "../comms", features = ["outbound"] }
connection = { path = "../connection", default-features = false, features = [
"ports",
] }
+document_storage_service_client = { path = "../document_storage_service_client" }
documents = { path = "../documents", features = ["ai_tools"] }
email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }
email_service_client = { path = "../email_service_client" }
@@ -26,7 +31,10 @@ entity_access = { path = "../entity_access" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
item_filters = { path = "../item_filters" }
lazy_static.workspace = true
+lexical_client = { path = "../lexical_client" }
+macro_aws_config = { path = "../macro_aws_config" }
macro_db_client = { path = "../macro_db_client" }
+macro_env_var = { path = "../macro_env_var" }
macro_user_id = { path = "../macro_user_id" }
model = { path = "../model" }
model_notifications = { path = "../model_notifications" }
@@ -38,6 +46,7 @@ notification = { path = "../notification" }
models_properties = { path = "../models_properties" }
models_search = { path = "../models_search" }
rand.workspace = true
+readonly_pool = { path = "../readonly_pool" }
schemars.workspace = true
scribe = { path = "../scribe", features = [
"channel",
@@ -53,11 +62,17 @@ properties = { path = "../properties", features = ["ai_tools"] }
soup = { path = "../soup", features = ["ai_tools", "outbound"] }
sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail"] }
sqlx.workspace = true
+static_file_service_client = { path = "../static_file_service_client" }
strum.workspace = true
+sync_service_client = { path = "../sync_service_client" }
tokio.workspace = true
tracing.workspace = true
utoipa.workspace = true
uuid.workspace = true
+remote_env_var = { path = "../remote_env_var" }
+macro_env = { path = "../macro_env" }
+secretsmanager_client = { path = "../secretsmanager_client" }
+aws-sdk-secretsmanager = { workspace = true }
[dev-dependencies]
cool_asserts = "2"
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
similarity index 54%
rename from rust/cloud-storage/memory/src/context.rs
rename to rust/cloud-storage/ai_tools/src/build_context.rs
index d5798e3566..c3b2c1d012 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -1,6 +1,13 @@
-use ai_tools::{
+//! Builds a [`ToolServiceContext`] from environment variables.
+//!
+//! Services that host the AI tools (e.g. `memory`, `scheduled_action`) call
+//! [`build_tool_service_context_from_env`] to wire up the shared context
+//! instead of duplicating the wiring logic.
+
+use crate::tool_context::{
NoOpConnectionService, NoOpNotificationService, NoOpTaskProperties, ToolServiceContext,
};
+use anyhow::Context;
use comms::domain::service::ChannelServiceImpl;
use comms::outbound::postgres::comms_repo::PgCommsRepo;
use comms::outbound::postgres::user_repo::PgUserRepo;
@@ -18,66 +25,130 @@ use entity_access::outbound::PgAccessRepository;
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use lexical_client::LexicalClient;
+use macro_env::Environment;
+use macro_env_var::{env_var, maybe_env_var};
+use readonly_pool::ReadOnlyPool;
use scribe::ScribeClient;
use scribe::document::DocumentClient;
use search_service_client::SearchServiceClient;
+use secretsmanager_client::{SecretManager, SecretsManager};
use soup::domain::service::SoupImpl;
use soup::outbound::pg_soup_repo::PgSoupRepo;
use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
-use crate::config::Config;
+env_var! {
+ struct ToolContextEnvVars {
+ DocumentStorageServiceUrl,
+ SearchServiceUrl,
+ EmailServiceUrl,
+ SyncServiceUrl,
+ SyncServiceAuthKey,
+ StaticFileServiceUrl,
+ DocumentStorageBucket,
+ DocxDocumentUploadBucket,
+ EmailScheduledQueue,
+ DocumentStorageServiceCloudfrontDistributionUrl,
+ DocumentStorageServiceCloudfrontSignerPublicKeyId,
+ DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
+ }
+}
+
+maybe_env_var! {
+ struct ToolContextMaybeEnvVars {
+ InternalApiSecretKey,
+ LexicalServiceUrl,
+ }
+}
-/// Builds a [`ToolServiceContext`] from environment variables and a database pool.
+/// Builds a [`ToolServiceContext`] by reading the required environment
+/// variables and wiring up all the shared services.
///
-/// Required env vars: `INTERNAL_API_SECRET_KEY`, `DOCUMENT_STORAGE_SERVICE_URL`,
-/// `SEARCH_SERVICE_URL`, `EMAIL_SERVICE_URL`, `SYNC_SERVICE_URL`,
-/// `DOCUMENT_COGNITION_SERVICE_URL`, `STATIC_FILE_SERVICE_URL`,
-/// `DOCUMENT_STORAGE_BUCKET`, `DOCX_DOCUMENT_UPLOAD_BUCKET`,
-/// `EMAIL_SCHEDULED_QUEUE`,
+/// In `Develop` and `Production`, secret env vars (`SYNC_SERVICE_AUTH_KEY`
+/// and `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`)
+/// are treated as AWS Secrets Manager secret names and resolved through the
+/// secrets manager. In `Local`, their values are used directly.
+///
+/// Required env vars: `DOCUMENT_STORAGE_SERVICE_URL`, `SEARCH_SERVICE_URL`,
+/// `EMAIL_SERVICE_URL`, `SYNC_SERVICE_URL`, `SYNC_SERVICE_AUTH_KEY`,
+/// `STATIC_FILE_SERVICE_URL`, `DOCUMENT_STORAGE_BUCKET`,
+/// `DOCX_DOCUMENT_UPLOAD_BUCKET`, `EMAIL_SCHEDULED_QUEUE`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`,
-/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`
-#[tracing::instrument(skip(pool, config), err)]
-pub async fn build_tool_service_context(
+/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`.
+///
+/// Optional env vars (with fallbacks for local dev):
+/// - `INTERNAL_API_SECRET_KEY` (defaults to `"local"`)
+/// - `LEXICAL_SERVICE_URL` (defaults to `http://localhost:8096`)
+#[tracing::instrument(skip(pool), err)]
+pub async fn build_tool_service_context_from_env(
pool: sqlx::PgPool,
- config: &Config,
) -> anyhow::Result<ToolServiceContext> {
+ let env = ToolContextEnvVars::new()?;
+ let maybe_env = ToolContextMaybeEnvVars::new();
+ let environment = Environment::new_or_prod();
+
+ let internal_api_secret_key: Arc<str> = maybe_env
+ .internal_api_secret_key
+ .map(|v| v.as_arc())
+ .context("expected INTERNAL_API_SECRET_KEY")?;
+
+ let lexical_service_url: Arc<str> = maybe_env
+ .lexical_service_url
+ .map(|v| v.as_arc())
+ .context("expected LEXICAL_SERVICE_URL")?;
+
let aws_config = macro_aws_config::get_macro_aws_config().await;
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
- .email_scheduled_queue(&config.email_scheduled_queue);
+ .email_scheduled_queue(&env.email_scheduled_queue);
+
+ let secretsmanager_client =
+ SecretsManager::new(aws_sdk_secretsmanager::Client::new(&aws_config));
+
+ let sync_service_auth_key = secretsmanager_client
+ .get_maybe_secret_value(environment, env.sync_service_auth_key.as_ref())
+ .await
+ .context("failed to get sync service auth key from secrets manager")?
+ .as_ref()
+ .to_string();
+
+ let cloudfront_signer_private_key = secretsmanager_client
+ .get_maybe_secret_value(
+ environment,
+ env.document_storage_service_cloudfront_signer_private_key_secret_name
+ .as_ref(),
+ )
+ .await
+ .context("failed to get CloudFront signer private key from secrets manager")?
+ .as_ref()
+ .to_string();
- // Service clients
let dss_client = Arc::new(DocumentStorageServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.document_storage_service_url.clone(),
+ internal_api_secret_key.to_string(),
+ env.document_storage_service_url.to_string(),
));
let search_client = Arc::new(SearchServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.search_service_url.clone(),
+ internal_api_secret_key.to_string(),
+ env.search_service_url.to_string(),
));
let sync_client = Arc::new(SyncServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.sync_service_url.clone(),
+ sync_service_auth_key.clone(),
+ env.sync_service_url.to_string(),
));
let email_client = Arc::new(EmailServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.email_service_url.clone(),
+ internal_api_secret_key.to_string(),
+ env.email_service_url.to_string(),
));
let sfs_client = Arc::new(StaticFileServiceClient::new(
- config.internal_api_secret_key.clone(),
- config.static_file_service_url.clone(),
+ internal_api_secret_key.to_string(),
+ env.static_file_service_url.to_string(),
));
let email_ext_client = Arc::new(EmailServiceClientExternal::new(
- config.email_service_url.clone(),
+ env.email_service_url.to_string(),
));
- let lexical_client = LexicalClient::new(
- config.internal_api_secret_key.clone(),
- config.lexical_service_url.clone(),
- );
+ let lexical_client = LexicalClient::new(sync_service_auth_key, lexical_service_url.to_string());
- // Scribe
let scribe = Arc::new(
ScribeClient::new()
.with_document_client(
@@ -94,7 +165,6 @@ pub async fn build_tool_service_context(
.with_static_file_client(sfs_client),
);
- // Soup service
let frecency_storage = FrecencyPgStorage::new(pool.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
let email_service = EmailServiceImpl::new(
@@ -104,37 +174,35 @@ pub async fn build_tool_service_context(
0,
);
let channels_service = ChannelServiceImpl::new(
- PgCommsRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
+ PgCommsRepo::new(ReadOnlyPool(pool.clone())),
PgUserRepo::new(pool.clone()),
frecency_storage,
);
- let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
+ let email_service_for_tools: Arc<crate::tool_context::ToolEmailService> =
+ Arc::new(email_service.clone());
let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
+ PgSoupRepo::new(ReadOnlyPool(pool.clone())),
frecency_service,
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
call::domain::ports::NoOpCallRecordQueryService,
));
- // Document tool context
let s3_client = macro_aws_config::s3_client().await;
let s3_upload_adapter = S3UploadUrlAdapter::new(
s3_client,
- &config.document_storage_bucket,
- &config.docx_document_upload_bucket,
+ env.document_storage_bucket.to_string(),
+ env.docx_document_upload_bucket.to_string(),
);
let document_repo = PgDocumentRepo::new(pool.clone());
let cloudfront_config = CloudFrontConfig {
- distribution_url: config
+ distribution_url: env
.document_storage_service_cloudfront_distribution_url
- .clone(),
- signer_public_key_id: config
+ .to_string(),
+ signer_public_key_id: env
.document_storage_service_cloudfront_signer_public_key_id
- .clone(),
- signer_private_key: config
- .document_storage_service_cloudfront_signer_private_key_secret_name
- .clone(),
+ .to_string(),
+ signer_private_key: cloudfront_signer_private_key,
presigned_url_expiry_seconds: 3600,
browser_cache_expiry_seconds: 86400,
};
@@ -146,15 +214,15 @@ pub async fn build_tool_service_context(
NoOpTaskProperties,
NoOpConnectionService,
);
- let entity_access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone()));
- let entity_access_service = Arc::new(entity_access_service);
+ let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ )));
let document_tool_context = DocumentToolContext::new(
document_service,
(*entity_access_service).clone(),
lexical_client,
);
- // Properties tool context
let properties_service = properties::PropertiesServiceImpl::new(
properties::PropertiesPgRepo::new(pool.clone()),
Some(properties::PermissionServiceImpl::new(
@@ -166,7 +234,6 @@ pub async fn build_tool_service_context(
let properties_tool_context =
properties::inbound::toolset::PropertiesToolContext::new(properties_service);
- // Email tool context
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
Arc::new(EmailServiceImpl::new(
EmailPgRepo::new(pool.clone()),
@@ -189,5 +256,6 @@ pub async fn build_tool_service_context(
document_tool_context,
properties_tool_context,
email_tool_context,
+ schedule_tool_context: crate::NoOpScheduleContext,
})
}
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 7c82c76af2..76a839fe93 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -2,6 +2,7 @@
use ai_toolset::AsyncToolSet;
use ai_toolset::schema::{ToolSchemaGenerator, ToolSchemas};
+mod build_context;
pub mod code_execution;
pub mod prompts;
pub mod read;
@@ -22,6 +23,7 @@ use soup::inbound::toolset::{ListEntities, SoupToolContext};
use std::sync::Arc;
use web_fetch::anthropic_web_fetch_tool;
+pub use build_context::build_tool_service_context_from_env;
pub use search::search_toolset;
pub use tool_context::*;
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 73486276a2..46e6b04925 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -1,31 +1,16 @@
use axum::extract::FromRef;
-use comms::{
- domain::service::ChannelServiceImpl,
- outbound::postgres::{comms_repo::PgCommsRepo, user_repo::PgUserRepo},
-};
use connection::domain::ports::ConnectionService;
-use documents::{
- domain::ports::TaskPropertiesPort,
- inbound::toolset::DocumentToolContext,
- outbound::{pg_document_repo::PgDocumentRepo, s3_upload_url::S3UploadUrlAdapter},
-};
+use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToolContext};
use email::{
- domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},
- inbound::toolset::EmailToolContext,
- outbound::EmailPgRepo,
+ domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,
};
-use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
-use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_user_id::user_id::MacroUserIdStr;
use properties::inbound::toolset::PropertiesToolContext;
use scribe::{
ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
email::EmailClient, static_file::StaticFileClient,
};
-use soup::{
- domain::service::SoupImpl, inbound::toolset::SoupToolContext,
- outbound::pg_soup_repo::PgSoupRepo,
-};
+use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};
use std::sync::Arc;
pub use ai_toolset::RequestContext;
@@ -34,7 +19,9 @@ pub type ToolScribe =
ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
/// Type alias for the frecency service implementation
-pub type ToolFrecencyService = FrecencyQueryServiceImpl<FrecencyPgStorage>;
+pub type ToolFrecencyService = frecency::domain::services::FrecencyQueryServiceImpl<
+ frecency::outbound::postgres::FrecencyPgStorage,
+>;
/// Type alias for the email service implementation
pub type ToolEmailService =
@@ -44,7 +31,11 @@ pub type ToolEmailService =
pub type ToolUserEmailService = EmailServiceImpl<EmailPgRepo, ToolFrecencyService, sqs_client::SQS>;
/// Type alias for the comms/channels service implementation
-pub type ToolCommsService = ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;
+pub type ToolCommsService = comms::domain::service::ChannelServiceImpl<
+ comms::outbound::postgres::comms_repo::PgCommsRepo,
+ comms::outbound::postgres::user_repo::PgUserRepo,
+ frecency::outbound::postgres::FrecencyPgStorage,
+>;
/// No-op task properties service (not needed for AI tools)
#[derive(Clone)]
@@ -99,14 +90,16 @@ impl ConnectionService for NoOpConnectionService {
/// Type alias for the document service implementation used by AI tools
pub type ToolDocumentService = documents::domain::service::DocumentServiceImpl<
- PgDocumentRepo,
- S3UploadUrlAdapter,
+ documents::outbound::pg_document_repo::PgDocumentRepo,
+ documents::outbound::s3_upload_url::S3UploadUrlAdapter,
NoOpTaskProperties,
NoOpConnectionService,
>;
/// Type alias for the entity access service implementation
-pub type ToolEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+pub type ToolEntityAccessService = entity_access::domain::service::EntityAccessServiceImpl<
+ entity_access::outbound::PgAccessRepository,
+>;
/// Type alias for the document tool context
pub type ToolDocumentToolContext =
@@ -114,9 +107,9 @@ pub type ToolDocumentToolContext =
/// Type alias for the soup service implementation
pub type ToolSoupService = SoupImpl<
- PgSoupRepo,
+ soup::outbound::pg_soup_repo::PgSoupRepo,
ToolFrecencyService,
- ReadonlyEmailPreviewAdapter<ToolEmailService>,
+ email::domain::ports::ReadonlyEmailPreviewAdapter<ToolEmailService>,
ToolCommsService,
call::domain::ports::NoOpCallRecordQueryService,
>;
@@ -153,6 +146,14 @@ pub type ToolPropertiesToolContext = PropertiesToolContext<ToolPropertiesService
/// Type alias for the email tool context
pub type ToolEmailToolContext = EmailToolContext<ToolUserEmailService>;
+#[derive(Clone, Default)]
+pub struct NoOpScheduleContext;
+
+#[cfg(any(test, feature = "test-support"))]
+pub fn no_op_schedule_context() -> NoOpScheduleContext {
+ NoOpScheduleContext
+}
+
/// The full service context containing all API clients.
/// Individual tools should extract only the clients they need via `FromRef`.
#[derive(Clone, FromRef)]
@@ -165,6 +166,7 @@ pub struct ToolServiceContext {
pub document_tool_context: ToolDocumentToolContext,
pub properties_tool_context: ToolPropertiesToolContext,
pub email_tool_context: ToolEmailToolContext,
+ pub schedule_tool_context: NoOpScheduleContext,
}
impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 4045d59815..5da1f0a6ce 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -138,5 +138,6 @@ url = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
+ai_tools = { path = "../ai_tools", features = ["test-support"] }
macro_auth = { path = "../macro_auth", features = ["testing"] }
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index d8c8424ce9..cad71853e9 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -290,6 +290,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
document_tool_context: document_tool_context.clone(),
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
+ schedule_tool_context: ai_tools::no_op_schedule_context(),
};
let all_tools = ai_tools::all_tools();
let all_tools_toolset = all_tools.toolset.clone();
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index c7b3f7ec3d..e38a96d293 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -25,11 +25,10 @@ use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsQueue;
+use readonly_pool::ReadOnlyPool;
use scribe::{ScribeClient, document::DocumentClient};
use search_service_client::SearchServiceClient;
use secretsmanager_client::SecretManager;
-use soup::domain::service::SoupImpl;
-use soup::outbound::pg_soup_repo::PgSoupRepo;
use sqlx::postgres::PgPoolOptions;
use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
@@ -121,7 +120,6 @@ async fn main() -> anyhow::Result<()> {
);
tracing::info!("initialized search service client");
-
let jwt_args =
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await
@@ -144,31 +142,6 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized static file service client");
- // Build soup service
- let frecency_storage = FrecencyPgStorage::new(db.clone());
- let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
- let email_service = EmailServiceImpl::new(
- EmailPgRepo::new(db.clone()),
- frecency_service.clone(),
- email::domain::ports::NoOpEnqueuer,
- 0,
- );
- let channels_service = ChannelServiceImpl::new(
- PgCommsRepo::new(readonly_pool::ReadOnlyPool(db.clone())),
- PgUserRepo::new(db.clone()),
- frecency_storage,
- );
- let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
- let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(readonly_pool::ReadOnlyPool(db.clone())),
- frecency_service,
- ReadonlyEmailPreviewAdapter(email_service),
- channels_service,
- call::domain::ports::NoOpCallRecordQueryService,
- ));
-
- tracing::info!("initialized soup service");
-
// Initialize Redis client for stream service
let redis_client = Arc::new(
redis::Client::open(config.redis_host.as_ref())
@@ -203,8 +176,34 @@ async fn main() -> anyhow::Result<()> {
});
tracing::info!("initialized notification ingress service");
+ let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ db.clone(),
+ )));
+
+ let frecency_storage = FrecencyPgStorage::new(db.clone());
+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
+ let email_service = EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ frecency_service.clone(),
+ email::domain::ports::NoOpEnqueuer,
+ 0,
+ );
+ let channels_service = ChannelServiceImpl::new(
+ PgCommsRepo::new(ReadOnlyPool(db.clone())),
+ PgUserRepo::new(db.clone()),
+ frecency_storage,
+ );
+ let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
+ let soup_service = Arc::new(soup::domain::service::SoupImpl::new(
+ soup::outbound::pg_soup_repo::PgSoupRepo::new(ReadOnlyPool(db.clone())),
+ frecency_service,
+ ReadonlyEmailPreviewAdapter(email_service),
+ channels_service,
+ call::domain::ports::NoOpCallRecordQueryService,
+ ));
+
+ tracing::info!("initialized soup service");
- // Build document tool context for AI tools
let s3_client = macro_aws_config::s3_client().await;
let s3_upload_adapter = S3UploadUrlAdapter::new(
s3_client,
@@ -235,9 +234,6 @@ async fn main() -> anyhow::Result<()> {
NoOpTaskProperties,
NoOpConnectionService,
);
- let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
- db.clone(),
- )));
let lexical_client_for_tools = (*lexical_client).clone();
let document_tool_context = DocumentToolContext::new(
document_service,
@@ -268,7 +264,6 @@ async fn main() -> anyhow::Result<()> {
);
let search_service_client = Arc::new(search_service_client);
- // Build properties tool context for AI tools
let properties_service = properties::PropertiesServiceImpl::new(
properties::PropertiesPgRepo::new(db.clone()),
Some(properties::PermissionServiceImpl::new(
@@ -282,7 +277,6 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized properties tool context");
- // Build email tool context for AI tools
let email_tool_context = email::inbound::toolset::EmailToolContext::new(
Arc::new(EmailServiceImpl::new(
EmailPgRepo::new(db.clone()),
@@ -298,7 +292,6 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized email tool context");
- // Build shared tool context and toolset
let tool_service_context = ai_tools::ToolServiceContext {
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
@@ -308,6 +301,7 @@ async fn main() -> anyhow::Result<()> {
document_tool_context: document_tool_context.clone(),
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
+ schedule_tool_context: ai_tools::NoOpScheduleContext,
};
let all_tools = ai_tools::all_tools();
let all_tools_toolset = all_tools.toolset.clone();
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260416135258_scheduled_agent.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260416135258_scheduled_agent.down.sql
new file mode 100644
index 0000000000..d05662b6cd
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260416135258_scheduled_agent.down.sql
@@ -0,0 +1,5 @@
+
+DROP INDEX IF EXISTS action_execution_record_action_id_idx;
+DROP TABLE IF EXISTS action_execution_record;
+DROP INDEX IF EXISTS scheduled_action_owner_idx;
+DROP TABLE IF EXISTS scheduled_action;
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260416135258_scheduled_agent.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260416135258_scheduled_agent.up.sql
new file mode 100644
index 0000000000..80b42cfc03
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260416135258_scheduled_agent.up.sql
@@ -0,0 +1,34 @@
+-- Add migration script here
+CREATE TABLE IF NOT EXISTS scheduled_action
+(
+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
+ owner TEXT NOT NULL REFERENCES "User" (id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ schedule TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ timezone TEXT NOT NULL,
+ task JSONB NOT NULL,
+ claimed TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ next_run_at TIMESTAMPTZ NOT NULL,
+ enabled BOOLEAN NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS scheduled_action_owner_idx
+ ON scheduled_action (owner);
+
+CREATE TABLE IF NOT EXISTS action_execution_record
+(
+ id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
+ action_id UUID NOT NULL REFERENCES scheduled_action (id) ON DELETE CASCADE,
+ resource_id TEXT,
+ start_time TIMESTAMPTZ NOT NULL,
+ end_time TIMESTAMPTZ NOT NULL,
+ is_success BOOLEAN NOT NULL,
+ result JSONB NOT NULL DEFAULT '{}',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS action_execution_record_action_id_idx
+ ON action_execution_record (action_id, start_time DESC);
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index ae137d9bd0..5816c12034 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -1,7 +1,8 @@
use std::sync::Arc;
use ai_tools::{
- NoOpConnectionService, NoOpNotificationService, NoOpTaskProperties, ToolServiceContext,
+ NoOpConnectionService, NoOpNotificationService, NoOpScheduleContext, NoOpTaskProperties,
+ ToolServiceContext,
};
use anyhow::Context;
use comms::domain::service::ChannelServiceImpl;
@@ -280,6 +281,7 @@ async fn build_tool_context(
document_tool_context,
properties_tool_context,
email_tool_context,
+ schedule_tool_context: NoOpScheduleContext,
};
tracing::info!("initialized tool context");
diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.toml
index ff2dcf5063..829bb5dc31 100644
--- a/rust/cloud-storage/memory/Cargo.toml
+++ b/rust/cloud-storage/memory/Cargo.toml
@@ -20,8 +20,6 @@ sqlx = { workspace = true }
tokio = { workspace = true }
anyhow = { workspace = true }
axum = { workspace = true }
-aws-sdk-sqs = { workspace = true }
-call = { path = "../call", default-features = false, features = ["ports"] }
model_user = { path = "../model_user", features = ["axum"] }
tracing = { workspace = true }
utoipa = { workspace = true }
@@ -29,24 +27,4 @@ macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
macro_env_var = { path = "../macro_env_var" }
-# For building ToolServiceContext
-comms = { path = "../comms" }
-documents = { path = "../documents" }
-email = { path = "../email" }
-entity_access = { path = "../entity_access" }
-frecency = { path = "../frecency" }
-lexical_client = { path = "../lexical_client" }
-scribe = { path = "../scribe" }
-search_service_client = { path = "../search_service_client" }
-email_service_client = { path = "../email_service_client" }
-document_storage_service_client = { path = "../document_storage_service_client" }
-static_file_service_client = { path = "../static_file_service_client" }
-sync_service_client = { path = "../sync_service_client" }
-readonly_pool = { path = "../readonly_pool" }
-soup = { path = "../soup", features = ["all"] }
-properties = { path = "../properties" }
-macro_aws_config = { path = "../macro_aws_config" }
-sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail"] }
-
-
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/memory/src/config.rs b/rust/cloud-storage/memory/src/config.rs
index 9e91843f17..5a2ffed352 100644
--- a/rust/cloud-storage/memory/src/config.rs
+++ b/rust/cloud-storage/memory/src/config.rs
@@ -1,47 +1,16 @@
pub use macro_env::Environment;
-use macro_env_var::{env_var, maybe_env_var};
+use macro_env_var::env_var;
pub struct Config {
pub environment: Environment,
pub database_url: String,
pub user_id: String,
- pub internal_api_secret_key: String,
- pub document_storage_service_url: String,
- pub search_service_url: String,
- pub email_service_url: String,
- pub sync_service_url: String,
- pub static_file_service_url: String,
- pub lexical_service_url: String,
- pub document_storage_bucket: String,
- pub docx_document_upload_bucket: String,
- pub email_scheduled_queue: String,
- pub document_storage_service_cloudfront_distribution_url: String,
- pub document_storage_service_cloudfront_signer_public_key_id: String,
- pub document_storage_service_cloudfront_signer_private_key_secret_name: String,
}
env_var!(
pub struct EnvVars {
pub DatabaseUrl,
pub UserId,
- pub DocumentStorageServiceUrl,
- pub SearchServiceUrl,
- pub EmailServiceUrl,
- pub SyncServiceUrl,
- pub StaticFileServiceUrl,
- pub DocumentStorageBucket,
- pub DocxDocumentUploadBucket,
- pub EmailScheduledQueue,
- pub DocumentStorageServiceCloudfrontDistributionUrl,
- pub DocumentStorageServiceCloudfrontSignerPublicKeyId,
- pub DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
- }
-);
-
-maybe_env_var!(
- pub struct MaybeEnvVars {
- pub InternalApiSecretKey,
- pub LexicalServiceUrl,
}
);
@@ -49,50 +18,16 @@ impl Config {
pub fn from_env() -> anyhow::Result<Self> {
let environment = Environment::new_or_prod();
let env_vars = EnvVars::new()?;
- let maybe_env_vars = MaybeEnvVars::new();
let EnvVars {
database_url,
user_id,
- document_storage_service_url,
- search_service_url,
- email_service_url,
- sync_service_url,
- static_file_service_url,
- document_storage_bucket,
- docx_document_upload_bucket,
- email_scheduled_queue,
- document_storage_service_cloudfront_distribution_url,
- document_storage_service_cloudfront_signer_public_key_id,
- document_storage_service_cloudfront_signer_private_key_secret_name,
} = env_vars;
Ok(Self {
environment,
database_url: database_url.to_string(),
user_id: user_id.to_string(),
- internal_api_secret_key: maybe_env_vars
- .internal_api_secret_key
- .map(|v| v.to_string())
- .unwrap_or_else(|| "local".to_string()),
- document_storage_service_url: document_storage_service_url.to_string(),
- search_service_url: search_service_url.to_string(),
- email_service_url: email_service_url.to_string(),
- sync_service_url: sync_service_url.to_string(),
- static_file_service_url: static_file_service_url.to_string(),
- lexical_service_url: maybe_env_vars
- .lexical_service_url
- .map(|v| v.to_string())
- .unwrap_or_else(|| "http://localhost:8096".to_string()),
- document_storage_bucket: document_storage_bucket.to_string(),
- docx_document_upload_bucket: docx_document_upload_bucket.to_string(),
- email_scheduled_queue: email_scheduled_queue.to_string(),
- document_storage_service_cloudfront_distribution_url:
- document_storage_service_cloudfront_distribution_url.to_string(),
- document_storage_service_cloudfront_signer_public_key_id:
- document_storage_service_cloudfront_signer_public_key_id.to_string(),
- document_storage_service_cloudfront_signer_private_key_secret_name:
- document_storage_service_cloudfront_signer_private_key_secret_name.to_string(),
})
}
}
diff --git a/rust/cloud-storage/memory/src/lib.rs b/rust/cloud-storage/memory/src/lib.rs
index 3ca0751e31..3baa171ed8 100644
--- a/rust/cloud-storage/memory/src/lib.rs
+++ b/rust/cloud-storage/memory/src/lib.rs
@@ -1,5 +1,6 @@
+#![recursion_limit = "256"]
+
pub mod config;
-pub mod context;
pub mod domain;
pub mod inbound;
pub mod outbound;
diff --git a/rust/cloud-storage/memory/src/main.rs b/rust/cloud-storage/memory/src/main.rs
index d7b67ce89a..d8f4a7854f 100644
--- a/rust/cloud-storage/memory/src/main.rs
+++ b/rust/cloud-storage/memory/src/main.rs
@@ -1,8 +1,9 @@
-use ai_tools::all_tools;
+#![recursion_limit = "256"]
+
+use ai_tools::{all_tools, build_tool_service_context_from_env};
use anyhow::Context;
use macro_user_id::user_id::MacroUserIdStr;
use memory::config::Config;
-use memory::context::build_tool_service_context;
use memory::domain::{MemoryService, service::MemoryServiceImpl};
use memory::outbound::pg_memory_repo::PgMemoryRepo;
use sqlx::postgres::PgPoolOptions;
@@ -18,7 +19,7 @@ async fn main() -> anyhow::Result<()> {
.connect(&config.database_url)
.await?;
- let tool_context = build_tool_service_context(pool.clone(), &config).await?;
+ let tool_context = build_tool_service_context_from_env(pool.clone()).await?;
let tools = all_tools();
let memory_repo = PgMemoryRepo::new(pool.clone());
let memory_service = MemoryServiceImpl::new(pool, memory_repo, tool_context, tools);
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-01cb0b4b2fbbd64d2be9373d1e9e75b0085f5817ee4c3360f7cea76917fa5740.json b/rust/cloud-storage/scheduled_action/.sqlx/query-01cb0b4b2fbbd64d2be9373d1e9e75b0085f5817ee4c3360f7cea76917fa5740.json
new file mode 100644
index 0000000000..9e8e5b730a
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-01cb0b4b2fbbd64d2be9373d1e9e75b0085f5817ee4c3360f7cea76917fa5740.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action\n SET claimed = $1, updated_at = now()\n WHERE id = $2\n AND (claimed IS NULL OR claimed < $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "01cb0b4b2fbbd64d2be9373d1e9e75b0085f5817ee4c3360f7cea76917fa5740"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-0d9d272f0886376c4a756a4296517b933697934a2b3d52e931bcb2f1dc64ac87.json b/rust/cloud-storage/scheduled_action/.sqlx/query-0d9d272f0886376c4a756a4296517b933697934a2b3d52e931bcb2f1dc64ac87.json
new file mode 100644
index 0000000000..5be688e4c2
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-0d9d272f0886376c4a756a4296517b933697934a2b3d52e931bcb2f1dc64ac87.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, action_id, resource_id, start_time, end_time, is_success, result, created_at\n FROM action_execution_record\n WHERE action_id = $1\n ORDER BY start_time DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "action_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "resource_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "start_time",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "end_time",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "is_success",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "result",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "0d9d272f0886376c4a756a4296517b933697934a2b3d52e931bcb2f1dc64ac87"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7.json b/rust/cloud-storage/scheduled_action/.sqlx/query-1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7.json
new file mode 100644
index 0000000000..3001af3ce5
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM scheduled_action\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1787312f37ce2a63f3a448f70e719581607988c79c9d2f4ead58811d60d5bec7"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-4a158c278c77c87d5394e9cf1166ceff6eead17cf856cf45a6a49896626b6bdf.json b/rust/cloud-storage/scheduled_action/.sqlx/query-4a158c278c77c87d5394e9cf1166ceff6eead17cf856cf45a6a49896626b6bdf.json
new file mode 100644
index 0000000000..42a00e0acb
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-4a158c278c77c87d5394e9cf1166ceff6eead17cf856cf45a6a49896626b6bdf.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action\n SET next_run_at = $1, updated_at = now()\n WHERE id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4a158c278c77c87d5394e9cf1166ceff6eead17cf856cf45a6a49896626b6bdf"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-5e4e9cc4a9c2a48dcd4e3988d5dbe7b95b9ceab66d44b0a0158ae65aedd79d02.json b/rust/cloud-storage/scheduled_action/.sqlx/query-5e4e9cc4a9c2a48dcd4e3988d5dbe7b95b9ceab66d44b0a0158ae65aedd79d02.json
new file mode 100644
index 0000000000..c255288f22
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-5e4e9cc4a9c2a48dcd4e3988d5dbe7b95b9ceab66d44b0a0158ae65aedd79d02.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n updated_at = now()\n WHERE id = $8\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "schedule",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "timezone",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "task",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "claimed",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "next_run_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Timestamptz",
+ "Bool",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "5e4e9cc4a9c2a48dcd4e3988d5dbe7b95b9ceab66d44b0a0158ae65aedd79d02"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-60d9e2a257fd628f345cb615e9d6d201ca5190bdbca1c90001a98c46b789771f.json b/rust/cloud-storage/scheduled_action/.sqlx/query-60d9e2a257fd628f345cb615e9d6d201ca5190bdbca1c90001a98c46b789771f.json
new file mode 100644
index 0000000000..287c0eb3ce
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-60d9e2a257fd628f345cb615e9d6d201ca5190bdbca1c90001a98c46b789771f.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT schedule, timezone\n FROM scheduled_action\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "schedule",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "timezone",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "60d9e2a257fd628f345cb615e9d6d201ca5190bdbca1c90001a98c46b789771f"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-6450fb466802ad93f651d24054fd250abab1fda9e01dfd44d7e02e53f107816f.json b/rust/cloud-storage/scheduled_action/.sqlx/query-6450fb466802ad93f651d24054fd250abab1fda9e01dfd44d7e02e53f107816f.json
new file mode 100644
index 0000000000..63509f18c0
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-6450fb466802ad93f651d24054fd250abab1fda9e01dfd44d7e02e53f107816f.json
@@ -0,0 +1,89 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled\n FROM scheduled_action\n WHERE enabled\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "schedule",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "timezone",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "task",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "claimed",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "next_run_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "6450fb466802ad93f651d24054fd250abab1fda9e01dfd44d7e02e53f107816f"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-94762871e427a2adfd8fcf6f2655d567f40a1b54a6186e0aa064be0f18212c98.json b/rust/cloud-storage/scheduled_action/.sqlx/query-94762871e427a2adfd8fcf6f2655d567f40a1b54a6186e0aa064be0f18212c98.json
new file mode 100644
index 0000000000..1afc4b89dc
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-94762871e427a2adfd8fcf6f2655d567f40a1b54a6186e0aa064be0f18212c98.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO scheduled_action (owner, name, schedule, kind, timezone, task, next_run_at, enabled)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "schedule",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "timezone",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "task",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "claimed",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "next_run_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "94762871e427a2adfd8fcf6f2655d567f40a1b54a6186e0aa064be0f18212c98"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-b15f651be8f722d57f1c85ca4d9a14cae3fdde155d4f8c94418186d5a37f0686.json b/rust/cloud-storage/scheduled_action/.sqlx/query-b15f651be8f722d57f1c85ca4d9a14cae3fdde155d4f8c94418186d5a37f0686.json
new file mode 100644
index 0000000000..77467cfa54
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-b15f651be8f722d57f1c85ca4d9a14cae3fdde155d4f8c94418186d5a37f0686.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action\n SET updated_at = $1\n WHERE id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b15f651be8f722d57f1c85ca4d9a14cae3fdde155d4f8c94418186d5a37f0686"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-daefc7270b27ce0caef8b61a651c38d76dfd087a2a8032ff6ebce392d7892764.json b/rust/cloud-storage/scheduled_action/.sqlx/query-daefc7270b27ce0caef8b61a651c38d76dfd087a2a8032ff6ebce392d7892764.json
new file mode 100644
index 0000000000..5c8a8c15b1
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-daefc7270b27ce0caef8b61a651c38d76dfd087a2a8032ff6ebce392d7892764.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO action_execution_record (action_id, resource_id, start_time, end_time, is_success, result)\n VALUES ($1, $2, $3, $4, $5, $6)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "daefc7270b27ce0caef8b61a651c38d76dfd087a2a8032ff6ebce392d7892764"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-dd1e3498501c9aad2a5db8c9f55269928b43c4a9e523b84383bf9c7dc636c1fd.json b/rust/cloud-storage/scheduled_action/.sqlx/query-dd1e3498501c9aad2a5db8c9f55269928b43c4a9e523b84383bf9c7dc636c1fd.json
new file mode 100644
index 0000000000..6c18c195e9
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-dd1e3498501c9aad2a5db8c9f55269928b43c4a9e523b84383bf9c7dc636c1fd.json
@@ -0,0 +1,88 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled\n FROM scheduled_action\n WHERE owner = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "schedule",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "timezone",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "task",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "claimed",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "next_run_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "dd1e3498501c9aad2a5db8c9f55269928b43c4a9e523b84383bf9c7dc636c1fd"
+}
diff --git a/rust/cloud-storage/scheduled_action/.sqlx/query-e84c6b52fb4748ec73c01340862a1fa3c65711050239ca5d7bcd59b04f920894.json b/rust/cloud-storage/scheduled_action/.sqlx/query-e84c6b52fb4748ec73c01340862a1fa3c65711050239ca5d7bcd59b04f920894.json
new file mode 100644
index 0000000000..51a5fb5c98
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/.sqlx/query-e84c6b52fb4748ec73c01340862a1fa3c65711050239ca5d7bcd59b04f920894.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE scheduled_action\n SET claimed = NULL, updated_at = now()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e84c6b52fb4748ec73c01340862a1fa3c65711050239ca5d7bcd59b04f920894"
+}
diff --git a/rust/cloud-storage/scheduled_action/Cargo.toml b/rust/cloud-storage/scheduled_action/Cargo.toml
new file mode 100644
index 0000000000..cdaa91f971
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/Cargo.toml
@@ -0,0 +1,59 @@
+[package]
+name = "scheduled_action"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[[bin]]
+name = "service"
+path = "src/bins/service.rs"
+
+[[bin]]
+name = "scheduled_action_openapi"
+path = "src/bins/openapi.rs"
+
+[features]
+default = []
+local_auth = ["macro_middleware/local_auth"]
+
+[dependencies]
+serde = { workspace = true }
+serde_json = { workspace = true }
+macro_env_var = { path = "../macro_env_var" }
+sqlx = { workspace = true }
+macro_user_id = { path = "../macro_user_id"}
+cron = { version = "0.16.0" }
+anyhow = { workspace = true }
+macro_uuid = { path = "../macro_uuid"}
+chrono = { workspace = true}
+chrono-tz = { version = "0.10.4", features = ["serde"] }
+ai = { path = "../ai" }
+tokio = { workspace = true }
+futures = { workspace = true }
+tracing = { workspace = true }
+axum = { workspace = true }
+model_user = { path = "../model_user", features = ["axum"] }
+ai_tools = { path = "../ai_tools" }
+ai_toolset = { path = "../ai_toolset" }
+aws-sdk-sqs = { workspace = true }
+chat = { path = "../chat" }
+connection_gateway_client = { path = "../connection_gateway_client" }
+macro_db_client = { path = "../macro_db_client" }
+memory = { path = "../memory" }
+model = { path = "../model" }
+model-entity = { path = "../model-entity" }
+model_notifications = { path = "../model_notifications" }
+notification = { path = "../notification" }
+utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
+utoipa-swagger-ui = { workspace = true }
+
+macro_aws_config = { path = "../macro_aws_config" }
+macro_cors = { path = "../macro_cors" }
+macro_auth = { path = "../macro_auth" }
+macro_entrypoint = { path = "../macro_entrypoint" }
+macro_env = { path = "../macro_env" }
+macro_middleware = { path = "../macro_middleware", default-features = false, features = [
+ "auth",
+] }
+secretsmanager_client = { path = "../secretsmanager_client" }
+aws-sdk-secretsmanager = { workspace = true }
diff --git a/rust/cloud-storage/scheduled_action/TODO.md b/rust/cloud-storage/scheduled_action/TODO.md
new file mode 100644
index 0000000000..ba279aaa66
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/TODO.md
@@ -0,0 +1,34 @@
+[x] Multi Instance dispatcher
+[x] Memory in prompt
+ The memory crate needs to be included and used to do user memory.
+[x] Enable / Disable crons
+[x] Notifications
+ Notify user on completion
+[x] Remove cringe cron normalization
+[x] Good UI
+ [x] tab in agents
+ [x] cron entity
+ [x] view of stuff + history
+[~] Put tool context building in `ai_tools`
+ *cancer*
+[x] Live Updates
+ [x] Show when running
+ [x] Wire start / stop updates through connection gateway
+ [x] Track the block with connection gateway
+ [x] update infra
+ [x] Update history
+ - When an automation _starts_ the chat_id is returned -> send with the start event via connection gateway
+ [x] Show running indicator
+ [x] Prevent user from running automation multiple times at once
+
+# punt
+[] Stream agent
+ - Stream is the same as DCS
+[] Fix noops in `ai_tools`
+[] Make an infra file for tools that configures tools the same everywhere they're needed
+[] Real unified list for history
+[] Sharing / permissions
+[] Mention menu
+[] Delete schedules
+ [] right click menu on unified list
+ [] top bar
diff --git a/rust/cloud-storage/scheduled_action/justfile b/rust/cloud-storage/scheduled_action/justfile
new file mode 100644
index 0000000000..1c7f540489
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/justfile
@@ -0,0 +1,13 @@
+
+build:
+ cargo build
+
+check:
+ cargo clippy
+
+run:
+ #!/usr/bin/env bash
+ set -a
+ source .env
+ set +a
+ cargo run --bin service --features local_auth
diff --git a/rust/cloud-storage/scheduled_action/src/bins/openapi.rs b/rust/cloud-storage/scheduled_action/src/bins/openapi.rs
new file mode 100644
index 0000000000..848273f312
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/bins/openapi.rs
@@ -0,0 +1,8 @@
+#![allow(unused)]
+
+use scheduled_action::swagger::ApiDoc;
+use utoipa::OpenApi;
+
+fn main() {
+ println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());
+}
diff --git a/rust/cloud-storage/scheduled_action/src/bins/service.rs b/rust/cloud-storage/scheduled_action/src/bins/service.rs
new file mode 100644
index 0000000000..b1bf763dc4
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/bins/service.rs
@@ -0,0 +1,136 @@
+use std::sync::Arc;
+
+use ai_tools::build_tool_service_context_from_env;
+use anyhow::{Context, Result};
+use axum::Router;
+use connection_gateway_client::client::ConnectionGatewayClient;
+use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use macro_entrypoint::MacroEntrypoint;
+use macro_env::Environment;
+use macro_env_var::env_var;
+use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsQueue;
+use scheduled_action::domain::ports::ScheduledActionDispatcher;
+use scheduled_action::domain::service::ScheduledActionServiceImpl;
+use scheduled_action::inbound::axum_router::{
+ ScheduledActionRouterState, health, scheduled_action_router,
+};
+use scheduled_action::outbound::conn_gateway_live_updates::ConnGatewayLiveUpdates;
+use scheduled_action::outbound::inprocess_executor::InProcessExecutor;
+use scheduled_action::outbound::pg_polling_dispatcher::PgPollingDispatcher;
+use scheduled_action::outbound::pg_scheduled_action_repo::PgScheduledActionRepo;
+use scheduled_action::swagger::ApiDoc;
+use secretsmanager_client::SecretManager;
+use sqlx::postgres::PgPoolOptions;
+use utoipa::OpenApi;
+use utoipa_swagger_ui::SwaggerUi;
+
+env_var! {
+ pub struct EnvVars {
+ Port,
+ DatabaseUrl,
+ NotificationQueue,
+ ConnectionGatewayUrl,
+ }
+}
+
+#[tokio::main]
+#[tracing::instrument(err)]
+async fn main() -> Result<()> {
+ MacroEntrypoint::default().init();
+
+ let env = EnvVars::new().context("failed to read environment")?;
+ let environment = Environment::new_or_prod();
+
+ let db = PgPoolOptions::new()
+ .min_connections(3)
+ .max_connections(10)
+ .connect(&env.database_url)
+ .await
+ .context("failed to connect to macrodb")?;
+
+ let tool_context = build_tool_service_context_from_env(db.clone())
+ .await
+ .context("failed to build tool service context")?;
+
+ let aws_config = macro_aws_config::get_macro_aws_config().await;
+ let notification_ingress = Arc::new(SqsNotificationIngress {
+ queue: SqsQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ env.notification_queue.to_string(),
+ ),
+ });
+
+ let secretsmanager_client = secretsmanager_client::SecretsManager::new(
+ aws_sdk_secretsmanager::Client::new(&macro_aws_config::get_macro_aws_config().await),
+ );
+ let internal_api_secret = secretsmanager_client
+ .get_maybe_secret_value(environment, InternalApiSecretKey::new()?)
+ .await
+ .context("failed to fetch internal api secret")?;
+
+ let conn_gateway_client = Arc::new(ConnectionGatewayClient::new(
+ internal_api_secret.as_ref().to_string(),
+ env.connection_gateway_url.as_ref().to_string(),
+ ));
+ let live_updates = Arc::new(ConnGatewayLiveUpdates::new(Arc::clone(
+ &conn_gateway_client,
+ )));
+
+ let repo = Arc::new(PgScheduledActionRepo::new(db.clone()));
+
+ // The dispatcher consumes its executor, so build a second executor for the
+ // service to use when handling execute-now requests. Both executors share
+ // the underlying repo/pool/tool-context via cheap Arc/PgPool clones.
+ let dispatcher_executor = InProcessExecutor::new(
+ Arc::clone(&repo),
+ db.clone(),
+ tool_context.clone(),
+ Arc::clone(&notification_ingress),
+ Arc::clone(&live_updates),
+ );
+ let service_executor = Arc::new(InProcessExecutor::new(
+ Arc::clone(&repo),
+ db.clone(),
+ tool_context,
+ notification_ingress,
+ live_updates,
+ ));
+
+ let dispatcher = PgPollingDispatcher::new(Arc::clone(&repo), dispatcher_executor);
+ let (dispatcher_tx, _execution_rx) = dispatcher.begin_dispatch_loop();
+
+ let service = Arc::new(ScheduledActionServiceImpl::new(
+ Arc::clone(&repo),
+ service_executor,
+ dispatcher_tx,
+ ));
+
+ let jwt_args = JwtValidationArgs::new_with_secret_manager(environment, &secretsmanager_client)
+ .await
+ .context("failed to build jwt validation args")?;
+
+ let state = ScheduledActionRouterState { service };
+ let authed_routes = scheduled_action_router::<_, ()>(state).layer(
+ axum::middleware::from_fn_with_state(jwt_args, macro_middleware::auth::decode_jwt::handler),
+ );
+
+ let router = Router::new()
+ .route("/health", axum::routing::get(health))
+ .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()))
+ .merge(authed_routes)
+ .layer(macro_cors::cors_layer());
+
+ let addr = format!("0.0.0.0:{}", &*env.port);
+ let listener = tokio::net::TcpListener::bind(&addr)
+ .await
+ .with_context(|| format!("failed to bind {addr}"))?;
+
+ tracing::info!("scheduled_action service listening on {addr}");
+
+ axum::serve(listener, router.into_make_service())
+ .await
+ .context("server closed")?;
+ unreachable!();
+}
diff --git a/rust/cloud-storage/scheduled_action/src/domain.rs b/rust/cloud-storage/scheduled_action/src/domain.rs
new file mode 100644
index 0000000000..901e625fda
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/domain.rs
@@ -0,0 +1,3 @@
+pub mod models;
+pub mod ports;
+pub mod service;
diff --git a/rust/cloud-storage/scheduled_action/src/domain/models.rs b/rust/cloud-storage/scheduled_action/src/domain/models.rs
new file mode 100644
index 0000000000..575b8c526f
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/domain/models.rs
@@ -0,0 +1,205 @@
+use ai::types::Model;
+use anyhow::Result;
+use chrono::{DateTime, Duration, Utc};
+use chrono_tz::Tz;
+use cron::Schedule as CronSchedule;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::str::FromStr;
+use utoipa::ToSchema;
+
+pub const MAX_ACTION_TIME: Duration = Duration::minutes(20);
+
+#[derive(Serialize, Debug, Clone, ToSchema)]
+pub struct Schedule(String);
+
+impl Schedule {
+ /// Parse a cron expression in the 6-/7-field format required by the `cron`
+ /// crate (`sec min hour dom mon dow [year]`).
+ pub fn from_cron(cron: String) -> Result<Self> {
+ CronSchedule::from_str(&cron).map_err(anyhow::Error::from)?;
+ Ok(Self(cron))
+ }
+
+ pub fn as_cron(&self) -> CronSchedule {
+ CronSchedule::from_str(&self.0).expect("always valid schedule")
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ /// Next firing time after "now" in the given timezone, expressed in UTC.
+ pub fn next_run_after_now(&self, tz: Tz) -> Option<DateTime<Utc>> {
+ self.as_cron()
+ .upcoming(tz)
+ .next()
+ .map(|dt| dt.with_timezone(&Utc))
+ }
+}
+
+impl<'de> Deserialize<'de> for Schedule {
+ fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let s = String::deserialize(deserializer)?;
+ Schedule::from_cron(s).map_err(serde::de::Error::custom)
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
+pub enum ActionKind {
+ Agent,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+pub struct AgentTask {
+ pub model: Model,
+ pub prompt: String,
+ pub user_prompt: String,
+}
+
+/// Client-supplied payload for creating a scheduled action. The server fills
+/// in `id`, `owner` (from the authenticated user), timestamps, `claimed`, and
+/// `next_run_at` (derived from the cron).
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+pub struct CreateScheduledAction {
+ pub name: String,
+ pub schedule: Schedule,
+ pub kind: ActionKind,
+ #[schema(value_type = String)]
+ pub timezone: Tz,
+ #[schema(value_type = Object)]
+ pub task: Value,
+ pub enabled: bool,
+}
+
+/// Client-supplied payload for updating a scheduled action. Mirrors the fields
+/// the repository actually writes — `id`/`owner`/timestamps/`claimed`/
+/// `next_run_at` are not client-mutable.
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+pub struct UpdateScheduledAction {
+ pub name: String,
+ pub schedule: Schedule,
+ pub kind: ActionKind,
+ #[schema(value_type = String)]
+ pub timezone: Tz,
+ #[schema(value_type = Object)]
+ pub task: Value,
+ pub enabled: bool,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+pub struct ScheduledAction {
+ #[schema(value_type = Option<String>, format = Uuid)]
+ pub id: Option<Uuid>,
+ #[schema(value_type = String)]
+ pub owner: MacroUserIdStr<'static>,
+ pub name: String,
+ pub schedule: Schedule,
+ pub kind: ActionKind,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ #[schema(value_type = String)]
+ pub timezone: Tz,
+ #[schema(value_type = Object)]
+ pub task: Value,
+ pub claimed: Option<DateTime<Utc>>,
+ /// Time of the next scheduled firing (derived from the cron on write). UI
+ /// uses this to render "next run" without having to parse the cron itself.
+ pub next_run_at: DateTime<Utc>,
+ /// When false, the cron dispatcher skips this schedule. `run_now` remains
+ /// available regardless.
+ pub enabled: bool,
+}
+
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct InProgressExecution {
+ #[schema(value_type = String, format = Uuid)]
+ pub action_id: Uuid,
+ pub chat_id: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+pub struct ActionExecutionRecord {
+ #[schema(value_type = Option<String>, format = Uuid)]
+ pub id: Option<Uuid>,
+ #[schema(value_type = String, format = Uuid)]
+ pub action_id: Uuid,
+ /// ID of the primary resource produced by this run (e.g. a chat thread).
+ /// Opaque to the scheduler; the UI interprets it based on the action kind.
+ pub resource_id: Option<String>,
+ pub start_time: DateTime<Utc>,
+ pub end_time: DateTime<Utc>,
+ pub is_success: bool,
+ #[schema(value_type = Object)]
+ pub result: Value,
+ pub created_at: DateTime<Utc>,
+}
+
+#[derive(Debug)]
+pub enum DispatchEvent {
+ Create(ScheduledAction),
+ Update(ScheduledAction),
+ Delete(ScheduledAction),
+}
+
+/// Live status update for a scheduled-action run, broadcast via the connection
+/// gateway to the owner. Clients use the `chat_id` to navigate to the run
+/// transcript and the variant tag to toggle the running indicator.
+///
+/// Serialized with a `type` tag (`started`/`stopped`) and delivered over the
+/// single `scheduled_action_update` message type on the gateway.
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ScheduledActionUpdate {
+ Started {
+ #[schema(value_type = String)]
+ owner: MacroUserIdStr<'static>,
+ #[schema(value_type = String, format = Uuid)]
+ action_id: Uuid,
+ chat_id: String,
+ },
+ Stopped {
+ #[schema(value_type = String)]
+ owner: MacroUserIdStr<'static>,
+ #[schema(value_type = String, format = Uuid)]
+ action_id: Uuid,
+ chat_id: String,
+ is_success: bool,
+ },
+}
+
+impl ScheduledActionUpdate {
+ pub fn owner(&self) -> &MacroUserIdStr<'static> {
+ match self {
+ ScheduledActionUpdate::Started { owner, .. } => owner,
+ ScheduledActionUpdate::Stopped { owner, .. } => owner,
+ }
+ }
+}
+
+/// Message type on connection_gateway for live scheduled-action updates. The
+/// payload is a serialized [`ScheduledActionUpdate`]; the variant tag lives
+/// inside the payload so the wire surface stays as one message type.
+pub const SCHEDULED_ACTION_UPDATE_MESSAGE_TYPE: &str = "scheduled_action_update";
+
+/// Returned by the executor when a run cannot start because the action is
+/// already claimed by another in-flight execution. Callers at the HTTP
+/// boundary map this to 409 Conflict; the polling dispatcher treats it as a
+/// benign "another worker got there first" signal.
+#[derive(Debug)]
+pub struct AlreadyRunningError {
+ pub action_id: Uuid,
+}
+
+impl std::fmt::Display for AlreadyRunningError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "scheduled action {} is already running", self.action_id)
+ }
+}
+
+impl std::error::Error for AlreadyRunningError {}
diff --git a/rust/cloud-storage/scheduled_action/src/domain/ports.rs b/rust/cloud-storage/scheduled_action/src/domain/ports.rs
new file mode 100644
index 0000000000..57c79e88e1
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/domain/ports.rs
@@ -0,0 +1,113 @@
+use super::models::{
+ ActionExecutionRecord, DispatchEvent, InProgressExecution, ScheduledAction,
+ ScheduledActionUpdate,
+};
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use tokio::sync::mpsc::{Receiver, Sender};
+
+pub trait ScheduledActionRepo: Send + Sync + 'static {
+ fn create_action(
+ &self,
+ action: ScheduledAction,
+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+
+ fn get_actions(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<ScheduledAction>>> + Send;
+
+ /// Return the next `limit` enabled actions ordered by `next_run_at` ASC,
+ /// filtering out those currently claimed by another worker (i.e. claimed
+ /// within `MAX_ACTION_TIME`). Used by the polling dispatcher to find work.
+ fn get_next_unclaimed_actions(
+ &self,
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<ScheduledAction>>> + Send;
+
+ fn update_action(
+ &self,
+ action: ScheduledAction,
+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+
+ fn delete_action(
+ &self,
+ id: &Uuid,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ fn claim_action(&self, id: &Uuid) -> impl Future<Output = Result<()>> + Send;
+
+ fn release_action(&self, id: &Uuid) -> impl Future<Output = Result<()>> + Send;
+
+ fn create_execution_record(
+ &self,
+ record: ActionExecutionRecord,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ fn get_execution_records(
+ &self,
+ action_id: &Uuid,
+ ) -> impl Future<Output = Result<Vec<ActionExecutionRecord>>> + Send;
+
+ fn update_next_run_at(&self, id: &Uuid) -> impl Future<Output = Result<()>> + Send;
+
+ fn update_last_executed(
+ &self,
+ id: &Uuid,
+ executed_at: DateTime<Utc>,
+ ) -> impl Future<Output = Result<()>> + Send;
+}
+
+pub trait ScheduledActionService: Send + Sync + 'static {
+ fn create_action(
+ &self,
+ action: ScheduledAction,
+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+
+ fn get_actions(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<ScheduledAction>>> + Send;
+
+ fn update_action(
+ &self,
+ action: ScheduledAction,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+
+ fn delete_action(
+ &self,
+ id: &Uuid,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ fn execute_action_now(
+ &self,
+ id: &Uuid,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<InProgressExecution>> + Send;
+
+ fn get_execution_records(
+ &self,
+ id: &Uuid,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<ActionExecutionRecord>>> + Send;
+}
+
+pub trait ScheduledActionDispatcher {
+ fn begin_dispatch_loop(self) -> (Sender<DispatchEvent>, Receiver<InProgressExecution>);
+}
+
+pub trait ScheduledActionExecutor {
+ fn execute_action(
+ &self,
+ action: ScheduledAction,
+ ) -> impl Future<Output = Result<InProgressExecution>> + Send;
+}
+
+pub trait ScheduledActionLiveUpdate: Send + Sync + 'static {
+ fn publish_update(&self, update: ScheduledActionUpdate) -> impl Future<Output = ()> + Send;
+}
diff --git a/rust/cloud-storage/scheduled_action/src/domain/service.rs b/rust/cloud-storage/scheduled_action/src/domain/service.rs
new file mode 100644
index 0000000000..f9f93a3977
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/domain/service.rs
@@ -0,0 +1,105 @@
+use std::sync::Arc;
+
+use anyhow::{Result, bail};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use tokio::sync::mpsc::Sender;
+
+use super::models::{ActionExecutionRecord, DispatchEvent, InProgressExecution, ScheduledAction};
+use super::ports::{ScheduledActionExecutor, ScheduledActionRepo, ScheduledActionService};
+
+pub struct ScheduledActionServiceImpl<Rpo, Exe> {
+ repo: Arc<Rpo>,
+ executor: Arc<Exe>,
+ dispatcher_tx: Sender<DispatchEvent>,
+}
+
+impl<Rpo, Exe> ScheduledActionServiceImpl<Rpo, Exe> {
+ pub fn new(repo: Arc<Rpo>, executor: Arc<Exe>, dispatcher_tx: Sender<DispatchEvent>) -> Self {
+ Self {
+ repo,
+ executor,
+ dispatcher_tx,
+ }
+ }
+}
+
+impl<Rpo, Exe> ScheduledActionService for ScheduledActionServiceImpl<Rpo, Exe>
+where
+ Rpo: ScheduledActionRepo,
+ Exe: ScheduledActionExecutor + Send + Sync + 'static,
+{
+ async fn create_action(&self, action: ScheduledAction) -> Result<ScheduledAction> {
+ let created = self.repo.create_action(action).await?;
+ self.dispatcher_tx
+ .send(DispatchEvent::Create(created.clone()))
+ .await
+ .map_err(|e| anyhow::anyhow!("failed to dispatch create event: {e}"))?;
+ Ok(created)
+ }
+
+ async fn get_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ self.repo.get_actions(user_id).await
+ }
+
+ async fn update_action(
+ &self,
+ action: ScheduledAction,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> Result<ScheduledAction> {
+ let Some(id) = action.id else {
+ bail!("cannot update action without id");
+ };
+ let actions = self.repo.get_actions(macro_user_id).await?;
+ if !actions.iter().any(|a| a.id.as_ref() == Some(&id)) {
+ bail!("scheduled action {id} not found for user");
+ }
+
+ let updated = self.repo.update_action(action).await?;
+ self.dispatcher_tx
+ .send(DispatchEvent::Update(updated.clone()))
+ .await
+ .map_err(|e| anyhow::anyhow!("failed to dispatch update event: {e}"))?;
+ Ok(updated)
+ }
+
+ async fn delete_action(&self, id: &Uuid, macro_user_id: MacroUserIdStr<'static>) -> Result<()> {
+ let actions = self.repo.get_actions(macro_user_id.clone()).await?;
+ let Some(action) = actions.into_iter().find(|a| a.id.as_ref() == Some(id)) else {
+ bail!("scheduled action {id} not found for user");
+ };
+
+ self.repo.delete_action(id, macro_user_id).await?;
+ self.dispatcher_tx
+ .send(DispatchEvent::Delete(action))
+ .await
+ .map_err(|e| anyhow::anyhow!("failed to dispatch delete event: {e}"))?;
+ Ok(())
+ }
+
+ async fn execute_action_now(
+ &self,
+ id: &Uuid,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> Result<InProgressExecution> {
+ let actions = self.repo.get_actions(macro_user_id).await?;
+ let Some(action) = actions.into_iter().find(|a| a.id.as_ref() == Some(id)) else {
+ bail!("scheduled action {id} not found for user");
+ };
+
+ self.executor.execute_action(action).await
+ }
+
+ async fn get_execution_records(
+ &self,
+ id: &Uuid,
+ macro_user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<ActionExecutionRecord>> {
+ let actions = self.repo.get_actions(macro_user_id).await?;
+ if !actions.iter().any(|a| a.id.as_ref() == Some(id)) {
+ bail!("scheduled action {id} not found for user");
+ }
+
+ self.repo.get_execution_records(id).await
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/inbound.rs b/rust/cloud-storage/scheduled_action/src/inbound.rs
new file mode 100644
index 0000000000..2021071c60
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/inbound.rs
@@ -0,0 +1 @@
+pub mod axum_router;
diff --git a/rust/cloud-storage/scheduled_action/src/inbound/axum_router.rs b/rust/cloud-storage/scheduled_action/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..043c6f4a91
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/inbound/axum_router.rs
@@ -0,0 +1,258 @@
+use std::sync::Arc;
+
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::IntoResponse;
+use axum::routing::{get, post, put};
+use axum::{Json, Router};
+use chrono::Utc;
+use macro_uuid::Uuid;
+use model::response::EmptyResponse;
+use model_user::axum_extractor::MacroUserExtractor;
+
+use crate::domain::models::{
+ ActionExecutionRecord, AlreadyRunningError, CreateScheduledAction, InProgressExecution,
+ ScheduledAction, UpdateScheduledAction,
+};
+use crate::domain::ports::ScheduledActionService;
+
+pub struct ScheduledActionRouterState<S> {
+ pub service: Arc<S>,
+}
+
+impl<S> Clone for ScheduledActionRouterState<S> {
+ fn clone(&self) -> Self {
+ Self {
+ service: Arc::clone(&self.service),
+ }
+ }
+}
+
+pub fn scheduled_action_router<S, St>(state: ScheduledActionRouterState<S>) -> Router<St>
+where
+ S: ScheduledActionService + Send + Sync + 'static,
+ St: Send + Sync,
+{
+ Router::new()
+ .route(
+ "/scheduled-actions",
+ get(list_actions::<S>).post(create_action::<S>),
+ )
+ .route(
+ "/scheduled-actions/{id}",
+ put(update_action::<S>).delete(delete_action::<S>),
+ )
+ .route("/scheduled-actions/{id}/execute", post(execute_action::<S>))
+ .route("/scheduled-actions/{id}/history", get(list_history::<S>))
+ .with_state(state)
+}
+
+#[utoipa::path(
+ get,
+ path = "/health",
+ tag = "scheduled actions",
+ operation_id = "scheduled_action_health",
+ responses(
+ (status = 200, description = "health", body = EmptyResponse),
+ )
+)]
+pub async fn health() -> impl IntoResponse {
+ Json(EmptyResponse::default())
+}
+
+#[utoipa::path(
+ post,
+ path = "/scheduled-actions",
+ tag = "scheduled actions",
+ operation_id = "create_scheduled_action",
+ request_body = CreateScheduledAction,
+ responses(
+ (status = 201, body = ScheduledAction),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn create_action<S: ScheduledActionService + Send + Sync + 'static>(
+ State(state): State<ScheduledActionRouterState<S>>,
+ user: MacroUserExtractor,
+ Json(req): Json<CreateScheduledAction>,
+) -> Result<impl IntoResponse, ScheduledActionApiError> {
+ let now = Utc::now();
+ let next_run_at = req
+ .schedule
+ .next_run_after_now(req.timezone)
+ .ok_or_else(|| anyhow::anyhow!("schedule has no future firings"))?;
+ let action = ScheduledAction {
+ id: None,
+ owner: user.macro_user_id,
+ name: req.name,
+ schedule: req.schedule,
+ kind: req.kind,
+ created_at: now,
+ updated_at: now,
+ timezone: req.timezone,
+ task: req.task,
+ claimed: None,
+ next_run_at,
+ enabled: req.enabled,
+ };
+ let created = state.service.create_action(action).await?;
+ Ok((StatusCode::CREATED, Json(created)))
+}
+
+#[utoipa::path(
+ get,
+ path = "/scheduled-actions",
+ tag = "scheduled actions",
+ operation_id = "list_scheduled_actions",
+ responses(
+ (status = 200, body = Vec<ScheduledAction>),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn list_actions<S: ScheduledActionService + Send + Sync + 'static>(
+ State(state): State<ScheduledActionRouterState<S>>,
+ user: MacroUserExtractor,
+) -> Result<impl IntoResponse, ScheduledActionApiError> {
+ let actions = state.service.get_actions(user.macro_user_id).await?;
+ Ok(Json(actions))
+}
+
+#[utoipa::path(
+ put,
+ path = "/scheduled-actions/{id}",
+ tag = "scheduled actions",
+ operation_id = "update_scheduled_action",
+ params(("id" = String, Path, description = "ID of the scheduled action")),
+ request_body = UpdateScheduledAction,
+ responses(
+ (status = 200, body = ScheduledAction),
+ (status = 401, body = String),
+ (status = 404, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn update_action<S: ScheduledActionService + Send + Sync + 'static>(
+ State(state): State<ScheduledActionRouterState<S>>,
+ user: MacroUserExtractor,
+ Path(id): Path<Uuid>,
+ Json(req): Json<UpdateScheduledAction>,
+) -> Result<impl IntoResponse, ScheduledActionApiError> {
+ let now = Utc::now();
+ let next_run_at = req
+ .schedule
+ .next_run_after_now(req.timezone)
+ .ok_or_else(|| anyhow::anyhow!("schedule has no future firings"))?;
+ let action = ScheduledAction {
+ id: Some(id),
+ owner: user.macro_user_id.clone(),
+ name: req.name,
+ schedule: req.schedule,
+ kind: req.kind,
+ created_at: now,
+ updated_at: now,
+ timezone: req.timezone,
+ task: req.task,
+ claimed: None,
+ next_run_at,
+ enabled: req.enabled,
+ };
+ let updated = state
+ .service
+ .update_action(action, user.macro_user_id)
+ .await?;
+ Ok(Json(updated))
+}
+
+#[utoipa::path(
+ delete,
+ path = "/scheduled-actions/{id}",
+ tag = "scheduled actions",
+ operation_id = "delete_scheduled_action",
+ params(("id" = String, Path, description = "ID of the scheduled action")),
+ responses(
+ (status = 204),
+ (status = 401, body = String),
+ (status = 404, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn delete_action<S: ScheduledActionService + Send + Sync + 'static>(
+ State(state): State<ScheduledActionRouterState<S>>,
+ user: MacroUserExtractor,
+ Path(id): Path<Uuid>,
+) -> Result<impl IntoResponse, ScheduledActionApiError> {
+ state.service.delete_action(&id, user.macro_user_id).await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ post,
+ path = "/scheduled-actions/{id}/execute",
+ tag = "scheduled actions",
+ operation_id = "execute_scheduled_action_now",
+ params(("id" = String, Path, description = "ID of the scheduled action")),
+ responses(
+ (status = 200, body = InProgressExecution),
+ (status = 401, body = String),
+ (status = 404, body = String),
+ (status = 409, body = String, description = "Action is already running"),
+ (status = 500, body = String),
+ )
+)]
+pub async fn execute_action<S: ScheduledActionService + Send + Sync + 'static>(
+ State(state): State<ScheduledActionRouterState<S>>,
+ user: MacroUserExtractor,
+ Path(id): Path<Uuid>,
+) -> Result<impl IntoResponse, ScheduledActionApiError> {
+ let execution = state
+ .service
+ .execute_action_now(&id, user.macro_user_id)
+ .await?;
+ Ok(Json(execution))
+}
+
+#[utoipa::path(
+ get,
+ path = "/scheduled-actions/{id}/history",
+ tag = "scheduled actions",
+ operation_id = "list_scheduled_action_history",
+ params(("id" = String, Path, description = "ID of the scheduled action")),
+ responses(
+ (status = 200, body = Vec<ActionExecutionRecord>),
+ (status = 401, body = String),
+ (status = 404, body = String),
+ (status = 500, body = String),
+ )
+)]
+pub async fn list_history<S: ScheduledActionService + Send + Sync + 'static>(
+ State(state): State<ScheduledActionRouterState<S>>,
+ user: MacroUserExtractor,
+ Path(id): Path<Uuid>,
+) -> Result<impl IntoResponse, ScheduledActionApiError> {
+ let records = state
+ .service
+ .get_execution_records(&id, user.macro_user_id)
+ .await?;
+ Ok(Json(records))
+}
+
+pub struct ScheduledActionApiError(anyhow::Error);
+
+impl From<anyhow::Error> for ScheduledActionApiError {
+ fn from(err: anyhow::Error) -> Self {
+ Self(err)
+ }
+}
+
+impl IntoResponse for ScheduledActionApiError {
+ fn into_response(self) -> axum::response::Response {
+ if let Some(already_running) = self.0.downcast_ref::<AlreadyRunningError>() {
+ tracing::info!(error=%already_running, "scheduled action already running");
+ return (StatusCode::CONFLICT, already_running.to_string()).into_response();
+ }
+ tracing::error!(error=?self.0, "scheduled action api error");
+ (StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/lib.rs b/rust/cloud-storage/scheduled_action/src/lib.rs
new file mode 100644
index 0000000000..c411d162c7
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/lib.rs
@@ -0,0 +1,4 @@
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
+pub mod swagger;
diff --git a/rust/cloud-storage/scheduled_action/src/outbound.rs b/rust/cloud-storage/scheduled_action/src/outbound.rs
new file mode 100644
index 0000000000..8ca29def91
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound.rs
@@ -0,0 +1,5 @@
+pub mod conn_gateway_live_updates;
+pub mod inprocess_executor;
+pub mod pg_polling_dispatcher;
+pub mod pg_scheduled_action_repo;
+pub mod tokio_dispatcher;
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/conn_gateway_live_updates.rs b/rust/cloud-storage/scheduled_action/src/outbound/conn_gateway_live_updates.rs
new file mode 100644
index 0000000000..322a13e248
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/conn_gateway_live_updates.rs
@@ -0,0 +1,45 @@
+use std::sync::Arc;
+
+use connection_gateway_client::client::ConnectionGatewayClient;
+use model_entity::EntityType;
+
+use crate::domain::models::{SCHEDULED_ACTION_UPDATE_MESSAGE_TYPE, ScheduledActionUpdate};
+use crate::domain::ports::ScheduledActionLiveUpdate;
+
+/// Pushes scheduled-action status updates to the owner's live websocket
+/// connections via the connection gateway. Failures are logged and swallowed
+/// so that UI delivery problems never mark an otherwise-successful run as
+/// failed.
+pub struct ConnGatewayLiveUpdates {
+ client: Arc<ConnectionGatewayClient>,
+}
+
+impl ConnGatewayLiveUpdates {
+ pub fn new(client: Arc<ConnectionGatewayClient>) -> Self {
+ Self { client }
+ }
+}
+
+impl ScheduledActionLiveUpdate for ConnGatewayLiveUpdates {
+ async fn publish_update(&self, update: ScheduledActionUpdate) {
+ let owner_entity = EntityType::User.with_entity_str(update.owner().as_ref());
+ let payload = match serde_json::to_value(&update) {
+ Ok(v) => v,
+ Err(e) => {
+ tracing::error!(error=?e, ?update, "failed to serialize scheduled action update");
+ return;
+ }
+ };
+ if let Err(e) = self
+ .client
+ .batch_send_message(
+ SCHEDULED_ACTION_UPDATE_MESSAGE_TYPE.to_string(),
+ payload,
+ vec![owner_entity],
+ )
+ .await
+ {
+ tracing::error!(error=?e, ?update, "failed to send scheduled action update");
+ }
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
new file mode 100644
index 0000000000..28d93cb522
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
@@ -0,0 +1,199 @@
+use super::notify::notify_completion;
+use std::sync::Arc;
+
+use ai::tool::ToolLoop;
+use ai::types::{ChatMessage, ChatMessageContent, RequestBuilder, Role};
+use ai_tools::{ToolServiceContext, ToolSetWithPrompt, all_tools};
+use ai_toolset::RequestContext;
+use anyhow::{Context, Result};
+use chat::domain::models::CreateChatArgs;
+use chat::domain::ports::ChatRepo;
+use chat::outbound::postgres::PgChatRepo;
+use futures::StreamExt;
+use macro_db_client::dcs::create_chat_message::create_chat_message;
+use memory::domain::MemoryService;
+use memory::domain::service::MemoryServiceImpl;
+use memory::outbound::pg_memory_repo::PgMemoryRepo;
+use model::chat::NewChatMessage;
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsQueue;
+use sqlx::PgPool;
+
+use crate::domain::models::{AgentTask, ScheduledAction};
+
+/// Create the chat that will hold this run's transcript. Called synchronously
+/// by the executor so the chat_id can be returned to the caller and persisted
+/// on the execution record before the background task starts.
+pub async fn create_run_chat(db: &PgPool, action: &ScheduledAction) -> Result<String> {
+ create_chat(db, action).await
+}
+
+/// Runs the agent tool loop against an already-created chat. Stores the user
+/// prompt and the resulting conversation into that chat, then fires a
+/// best-effort notification so the owner knows the run finished.
+pub async fn run_agent_task(
+ db: &PgPool,
+ tool_context: &ToolServiceContext,
+ notification_ingress: &Arc<SqsNotificationIngress<SqsQueue>>,
+ action: &ScheduledAction,
+ chat_id: &str,
+) -> Result<()> {
+ let agent_task: AgentTask =
+ serde_json::from_value(action.task.clone()).context("invalid agent task definition")?;
+
+ store_user_message(db, chat_id, &agent_task).await?;
+
+ let messages = run_tool_loop(db, tool_context, action, &agent_task).await?;
+
+ let final_assistant_text = messages
+ .iter()
+ .rev()
+ .find(|m| m.role == Role::Assistant)
+ .and_then(|m| m.content.assistant_message_text());
+
+ store_conversation(db, chat_id, messages, &agent_task).await?;
+
+ if let Some(text) = final_assistant_text {
+ notify_completion(notification_ingress, chat_id, action, &text);
+ }
+
+ Ok(())
+}
+
+/// Fetch the owner's persisted memory to inject as system-prompt context.
+///
+/// [`MemoryServiceImpl::get_or_generate_memory`] returns the existing memory
+/// (if any) synchronously and spawns a background refresh when the memory is
+/// missing or stale, so this call does not block agent execution on generation.
+async fn fetch_user_memory(
+ db: &PgPool,
+ tool_context: &ToolServiceContext,
+ owner: &macro_user_id::user_id::MacroUserIdStr<'static>,
+) -> Option<String> {
+ let tools = all_tools();
+ let tools = ToolSetWithPrompt {
+ toolset: tools.toolset,
+ prompt: tools.prompt,
+ };
+ let memory_service = MemoryServiceImpl::new(
+ db.clone(),
+ PgMemoryRepo::new(db.clone()),
+ tool_context.clone(),
+ tools,
+ );
+ match memory_service.get_or_generate_memory(owner.clone()).await {
+ Ok(memory) => memory,
+ Err(e) => {
+ tracing::warn!(error=?e, %owner, "failed to fetch user memory; running without it");
+ None
+ }
+ }
+}
+
+async fn create_chat(db: &PgPool, action: &ScheduledAction) -> Result<String> {
+ let chat_repo = PgChatRepo::new(db.clone());
+ chat_repo
+ .create(
+ action.owner.clone(),
+ CreateChatArgs {
+ name: action.name.clone(),
+ project_id: None,
+ },
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!(e))
+}
+
+async fn store_user_message(db: &PgPool, chat_id: &str, agent_task: &AgentTask) -> Result<String> {
+ let now = chrono::Utc::now();
+ let message = NewChatMessage {
+ id: None,
+ content: ChatMessageContent::Text(agent_task.user_prompt.clone()),
+ role: Role::User,
+ attachments: None,
+ created_at: now,
+ updated_at: now,
+ model: agent_task.model,
+ };
+ create_chat_message(db.clone(), chat_id, message).await
+}
+
+async fn run_tool_loop(
+ db: &PgPool,
+ tool_context: &ToolServiceContext,
+ action: &ScheduledAction,
+ agent_task: &AgentTask,
+) -> Result<Vec<ChatMessage>> {
+ let tools = all_tools();
+ let user_memory = fetch_user_memory(db, tool_context, &action.owner).await;
+ let system_prompt = match user_memory {
+ Some(memory) => format!(
+ "{}\n<user_memory>\n{}\n</user_memory>\n{}",
+ tools.prompt, memory, agent_task.prompt
+ ),
+ None => format!("{}\n{}", tools.prompt, agent_task.prompt),
+ };
+ let request = RequestBuilder::new()
+ .model(agent_task.model)
+ .messages(vec![ChatMessage {
+ content: ChatMessageContent::Text(agent_task.user_prompt.clone()),
+ image_urls: None,
+ role: Role::User,
+ }])
+ .system_prompt(system_prompt)
+ .max_tokens(16000)
+ .build();
+
+ let request_context = RequestContext {
+ user_id: action.owner.clone(),
+ };
+
+ let mut chat = ToolLoop::new(tools.toolset, tool_context.clone()).chat();
+ let mut stream = chat
+ .send_message(request, request_context, action.owner.to_string())
+ .await
+ .context("failed to start agent stream")?;
+
+ let idle_timeout = std::time::Duration::from_secs(3 * 60);
+ loop {
+ match tokio::time::timeout(idle_timeout, stream.next()).await {
+ Ok(Some(Ok(_))) => {}
+ Ok(Some(Err(e))) => {
+ tracing::error!(error=?e, "agent stream error");
+ break;
+ }
+ Ok(None) => break,
+ Err(_) => {
+ tracing::error!("agent stream idle timeout");
+ break;
+ }
+ }
+ }
+
+ drop(stream);
+ Ok(chat.get_new_conversation_messages())
+}
+
+async fn store_conversation(
+ db: &PgPool,
+ chat_id: &str,
+ messages: Vec<ChatMessage>,
+ agent_task: &AgentTask,
+) -> Result<()> {
+ let now = chrono::Utc::now();
+ for message in messages {
+ let new_message = NewChatMessage {
+ id: None,
+ content: message.content,
+ role: message.role,
+ attachments: None,
+ created_at: now,
+ updated_at: now,
+ model: agent_task.model,
+ };
+ create_chat_message(db.clone(), chat_id, new_message)
+ .await
+ .context("failed to store conversation message")?;
+ }
+ Ok(())
+}
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/mod.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/mod.rs
new file mode 100644
index 0000000000..43603caeaf
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/mod.rs
@@ -0,0 +1,171 @@
+mod agent_task;
+mod notify;
+
+use std::sync::Arc;
+
+use ai_tools::ToolServiceContext;
+use anyhow::Result;
+use chrono::Utc;
+use notification::domain::service::SqsNotificationIngress;
+use notification::outbound::queue::SqsQueue;
+use serde_json::Value;
+use sqlx::PgPool;
+
+use crate::domain::models::{
+ ActionExecutionRecord, ActionKind, AlreadyRunningError, InProgressExecution, MAX_ACTION_TIME,
+ ScheduledAction, ScheduledActionUpdate,
+};
+use crate::domain::ports::{
+ ScheduledActionExecutor, ScheduledActionLiveUpdate, ScheduledActionRepo,
+};
+
+pub struct InProcessExecutor<Rpo: ScheduledActionRepo, Live: ScheduledActionLiveUpdate> {
+ repo: Arc<Rpo>,
+ db: PgPool,
+ tool_context: ToolServiceContext,
+ notification_ingress: Arc<SqsNotificationIngress<SqsQueue>>,
+ live_updates: Arc<Live>,
+}
+
+impl<Rpo: ScheduledActionRepo, Live: ScheduledActionLiveUpdate> InProcessExecutor<Rpo, Live> {
+ pub fn new(
+ repo: Arc<Rpo>,
+ db: PgPool,
+ tool_context: ToolServiceContext,
+ notification_ingress: Arc<SqsNotificationIngress<SqsQueue>>,
+ live_updates: Arc<Live>,
+ ) -> Self {
+ Self {
+ repo,
+ db,
+ tool_context,
+ notification_ingress,
+ live_updates,
+ }
+ }
+}
+
+fn try_claim(action: &ScheduledAction) -> Result<()> {
+ if let Some(claimed_at) = action.claimed {
+ let elapsed = Utc::now() - claimed_at;
+ if elapsed < MAX_ACTION_TIME {
+ return Err(anyhow::Error::new(AlreadyRunningError {
+ action_id: *action.id.as_ref().unwrap(),
+ }));
+ }
+ }
+ Ok(())
+}
+
+impl<Rpo, Live> ScheduledActionExecutor for InProcessExecutor<Rpo, Live>
+where
+ Rpo: ScheduledActionRepo + Send + Sync + 'static,
+ Live: ScheduledActionLiveUpdate,
+{
+ async fn execute_action(&self, action: ScheduledAction) -> Result<InProgressExecution> {
+ try_claim(&action)?;
+
+ let id = *action.id.as_ref().unwrap();
+ self.repo.claim_action(&id).await?;
+
+ // Create the chat up front so the caller gets a chat_id synchronously
+ // and the eventual execution record can link back to it.
+ let chat_id = match action.kind {
+ ActionKind::Agent => agent_task::create_run_chat(&self.db, &action).await?,
+ };
+
+ self.live_updates
+ .publish_update(ScheduledActionUpdate::Started {
+ owner: action.owner.clone(),
+ action_id: id,
+ chat_id: chat_id.clone(),
+ })
+ .await;
+
+ let execution = InProgressExecution {
+ action_id: id,
+ chat_id: Some(chat_id.clone()),
+ };
+
+ let repo = Arc::clone(&self.repo);
+ let db = self.db.clone();
+ let tool_context = self.tool_context.clone();
+ let notification_ingress = Arc::clone(&self.notification_ingress);
+ let live_updates = Arc::clone(&self.live_updates);
+ let start_time = Utc::now();
+ let record_resource_id = chat_id.clone();
+ tokio::spawn(async move {
+ let result =
+ run_job(&db, &tool_context, &notification_ingress, &action, &chat_id).await;
+ let end_time = Utc::now();
+ let is_success = result.is_ok();
+
+ let record = ActionExecutionRecord {
+ id: None,
+ action_id: id,
+ resource_id: Some(record_resource_id.clone()),
+ start_time,
+ end_time,
+ is_success,
+ result: match &result {
+ Ok(_) => Value::Null,
+ Err(e) => Value::String(e.to_string()),
+ },
+ created_at: end_time,
+ };
+
+ if let Err(e) = repo.create_execution_record(record).await {
+ tracing::error!(error=?e, action_id=?id, "failed to save execution record");
+ }
+
+ if let Err(e) = repo.update_last_executed(&id, end_time).await {
+ tracing::error!(error=?e, action_id=?id, "failed to update last executed time");
+ }
+
+ // Recompute next_run_at based on the cron, so the UI shows the
+ // upcoming run after the one we just completed. The repo fetches
+ // the current schedule + timezone itself and skips the update if
+ // there's no future fire time.
+ if let Err(e) = repo.update_next_run_at(&id).await {
+ tracing::error!(error=?e, action_id=?id, "failed to update next_run_at");
+ }
+
+ if let Err(e) = repo.release_action(&id).await {
+ tracing::error!(error=?e, action_id=?id, "failed to release action claim");
+ }
+
+ // Fire the stop event after release so that any follow-up "run
+ // now" the UI issues in response will not race the claim.
+ live_updates
+ .publish_update(ScheduledActionUpdate::Stopped {
+ owner: action.owner.clone(),
+ action_id: id,
+ chat_id: record_resource_id.clone(),
+ is_success,
+ })
+ .await;
+
+ if let Err(e) = &result {
+ tracing::error!(error=?e, action_id=?id, "scheduled action execution failed");
+ }
+ });
+
+ Ok(execution)
+ }
+}
+
+async fn run_job(
+ db: &PgPool,
+ tool_context: &ToolServiceContext,
+ notification_ingress: &Arc<SqsNotificationIngress<SqsQueue>>,
+ action: &ScheduledAction,
+ chat_id: &str,
+) -> Result<()> {
+ match action.kind {
+ ActionKind::Agent => {
+ agent_task::run_agent_task(db, tool_context, notification_ingress, action, chat_id)
+ .await?;
+ Ok(())
+ }
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/notify.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/notify.rs
new file mode 100644
index 0000000000..937fcc27ae
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/notify.rs
@@ -0,0 +1,43 @@
+use crate::domain::models::ScheduledAction;
+use model_entity::EntityType;
+use model_notifications::AiResponseMetadata;
+use notification::domain::models::SendNotificationRequestBuilder;
+use notification::domain::service::{NotificationIngress, SqsNotificationIngress};
+use notification::outbound::queue::SqsQueue;
+use std::collections::HashSet;
+use std::sync::Arc;
+/// Spawn a best-effort notification to the action owner announcing the run has
+/// completed. Mirrors the DCS chat-stream notification pattern (APNS + websocket
+/// via the connection gateway). Errors are logged and never propagated, since a
+/// notification failure should not mark the scheduled run as failed.
+pub fn notify_completion(
+ notification_ingress: &Arc<SqsNotificationIngress<SqsQueue>>,
+ chat_id: &str,
+ action: &ScheduledAction,
+ assistant_text: &str,
+) {
+ let ingress = Arc::clone(notification_ingress);
+ let chat_id = chat_id.to_string();
+ let owner = action.owner.clone();
+ let message_id = chat_id.clone();
+ let assistant_text = assistant_text.to_string();
+
+ tokio::spawn(async move {
+ let req = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Chat.with_entity_string(chat_id.clone()),
+ notification: AiResponseMetadata {
+ summary: assistant_text,
+ message_id,
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([owner]),
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway();
+
+ if let Err(e) = ingress.send_notification(req).await {
+ tracing::error!(error=?e, chat_id = %chat_id, "failed to send scheduled action completion notification");
+ }
+ });
+}
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/pg_polling_dispatcher.rs b/rust/cloud-storage/scheduled_action/src/outbound/pg_polling_dispatcher.rs
new file mode 100644
index 0000000000..86b549447d
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/pg_polling_dispatcher.rs
@@ -0,0 +1,117 @@
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use chrono::Utc;
+use tokio::sync::mpsc::{Receiver, Sender};
+
+use crate::domain::models::{DispatchEvent, InProgressExecution};
+use crate::domain::ports::{
+ ScheduledActionDispatcher, ScheduledActionExecutor, ScheduledActionRepo,
+};
+
+const BUFFER_SIZE: usize = 1024;
+/// Pull this many candidates per DB round trip. The dispatcher keeps pulling
+/// batches until a poll returns nothing due.
+const BATCH_SIZE: i64 = 10;
+/// Minimum wall time a batch must take before we pull again. This paces the
+/// polling loop and gives peer instances a chance to claim work when a backlog
+/// exists (preventing a single instance from draining the queue).
+const BATCH_MIN_DURATION: Duration = Duration::from_secs(30);
+
+/// A [`ScheduledActionDispatcher`] that polls Postgres for due actions rather
+/// than holding an in-memory cron schedule. Safe to run in multiple instances:
+/// coordination is done via [`ScheduledActionRepo::claim_action`], which is an
+/// atomic conditional UPDATE. The first instance to claim an action wins; peers
+/// see the stale-or-unclaimed filter exclude it on subsequent polls.
+///
+/// Polling cadence: each batch of up to [`BATCH_SIZE`] actions is processed,
+/// then the loop sleeps until [`BATCH_MIN_DURATION`] has elapsed from the batch
+/// start. This gives other dispatcher instances a chance to pick up work, and
+/// bounds DB load when there is nothing to do.
+///
+/// [`DispatchEvent`]s on the returned [`Sender`] are drained and dropped —
+/// polling reads state directly from the DB each tick, so create/update/delete
+/// events are redundant. The sender is only accepted to satisfy the trait
+/// contract shared with the in-memory dispatcher.
+pub struct PgPollingDispatcher<Rpo: ScheduledActionRepo, Exe: ScheduledActionExecutor> {
+ repo: Arc<Rpo>,
+ executor: Exe,
+}
+
+impl<Rpo, Exe> PgPollingDispatcher<Rpo, Exe>
+where
+ Rpo: ScheduledActionRepo,
+ Exe: ScheduledActionExecutor,
+{
+ pub fn new(repo: Arc<Rpo>, executor: Exe) -> Self {
+ Self { repo, executor }
+ }
+}
+
+impl<Rpo, Exe> ScheduledActionDispatcher for PgPollingDispatcher<Rpo, Exe>
+where
+ Rpo: ScheduledActionRepo + Send + Sync + 'static,
+ Exe: ScheduledActionExecutor + Send + 'static,
+{
+ fn begin_dispatch_loop(self) -> (Sender<DispatchEvent>, Receiver<InProgressExecution>) {
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<DispatchEvent>(BUFFER_SIZE);
+ let (extx, exrx) = tokio::sync::mpsc::channel::<InProgressExecution>(BUFFER_SIZE);
+
+ // Drain dispatch events — the polling loop pulls fresh state from the
+ // DB each tick, so create/update/delete notifications are not needed.
+ // We still must drain so service-side sends don't block on a full
+ // channel.
+ tokio::spawn(async move { while rx.recv().await.is_some() {} });
+
+ tokio::spawn(async move {
+ loop {
+ let batch_start = Instant::now();
+
+ match self.repo.get_next_unclaimed_actions(BATCH_SIZE).await {
+ Ok(candidates) => {
+ let now = Utc::now();
+ for action in candidates {
+ // Candidates come back sorted by next_run_at ASC.
+ // The first non-due one ends the batch — anything
+ // after it is also not yet due.
+ if action.next_run_at > now {
+ break;
+ }
+
+ let id = action.id;
+ // The executor atomically claims the row before
+ // running. If a peer instance claimed it between
+ // our pull and this call, the claim fails and we
+ // skip — that's the multi-instance contract.
+ match self.executor.execute_action(action).await {
+ Ok(execution) => {
+ let _ = extx.send(execution).await;
+ }
+ Err(e) => {
+ // Could be a benign race (peer claimed
+ // first) or a real execute failure. Both
+ // are non-fatal to the polling loop.
+ tracing::warn!(
+ error=?e,
+ action_id=?id,
+ "failed to execute scheduled action (may be claimed by peer)",
+ );
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "failed to poll for due scheduled actions");
+ }
+ }
+
+ let elapsed = batch_start.elapsed();
+ if elapsed < BATCH_MIN_DURATION {
+ tokio::time::sleep(BATCH_MIN_DURATION - elapsed).await;
+ }
+ }
+ });
+
+ (tx, exrx)
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/rust/cloud-storage/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
new file mode 100644
index 0000000000..b6c1043659
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
@@ -0,0 +1,360 @@
+use anyhow::{Result, bail};
+use chrono::{DateTime, Utc};
+use chrono_tz::Tz;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+use std::str::FromStr;
+
+use crate::domain::models::{
+ ActionExecutionRecord, ActionKind, AlreadyRunningError, MAX_ACTION_TIME, Schedule,
+ ScheduledAction,
+};
+use crate::domain::ports::ScheduledActionRepo;
+
+pub struct PgScheduledActionRepo {
+ pool: PgPool,
+}
+
+impl PgScheduledActionRepo {
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+fn parse_timezone(s: &str) -> Result<Tz> {
+ Tz::from_str(s).map_err(|e| anyhow::anyhow!("invalid timezone: {e}"))
+}
+
+fn parse_kind(s: &str) -> Result<ActionKind> {
+ match s {
+ "Agent" => Ok(ActionKind::Agent),
+ other => bail!("unknown action kind: {other}"),
+ }
+}
+
+fn kind_to_str(kind: &ActionKind) -> &'static str {
+ match kind {
+ ActionKind::Agent => "Agent",
+ }
+}
+
+impl ScheduledActionRepo for PgScheduledActionRepo {
+ async fn create_action(&self, action: ScheduledAction) -> Result<ScheduledAction> {
+ let owner = action.owner.to_string();
+ let timezone = action.timezone.to_string();
+ let kind = kind_to_str(&action.kind);
+
+ let row = sqlx::query!(
+ r#"
+ INSERT INTO scheduled_action (owner, name, schedule, kind, timezone, task, next_run_at, enabled)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled
+ "#,
+ owner,
+ action.name,
+ action.schedule.as_str(),
+ kind,
+ timezone,
+ action.task,
+ action.next_run_at,
+ action.enabled,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ Ok(ScheduledAction {
+ id: Some(row.id),
+ owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ name: row.name,
+ schedule: Schedule::from_cron(row.schedule)?,
+ kind: parse_kind(&row.kind)?,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ timezone: parse_timezone(&row.timezone)?,
+ task: row.task,
+ claimed: row.claimed,
+ next_run_at: row.next_run_at,
+ enabled: row.enabled,
+ })
+ }
+
+ async fn get_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ let owner = user_id.to_string();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled
+ FROM scheduled_action
+ WHERE owner = $1
+ "#,
+ owner,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|row| {
+ Ok(ScheduledAction {
+ id: Some(row.id),
+ owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ name: row.name,
+ schedule: Schedule::from_cron(row.schedule)?,
+ kind: parse_kind(&row.kind)?,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ timezone: parse_timezone(&row.timezone)?,
+ task: row.task,
+ claimed: row.claimed,
+ next_run_at: row.next_run_at,
+ enabled: row.enabled,
+ })
+ })
+ .collect()
+ }
+
+ async fn get_next_unclaimed_actions(&self, limit: i64) -> Result<Vec<ScheduledAction>> {
+ let stale_threshold = Utc::now() - MAX_ACTION_TIME;
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled
+ FROM scheduled_action
+ WHERE enabled
+ AND (claimed IS NULL OR claimed < $1)
+ ORDER BY next_run_at ASC
+ LIMIT $2
+ "#,
+ stale_threshold,
+ limit,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|row| {
+ Ok(ScheduledAction {
+ id: Some(row.id),
+ owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ name: row.name,
+ schedule: Schedule::from_cron(row.schedule)?,
+ kind: parse_kind(&row.kind)?,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ timezone: parse_timezone(&row.timezone)?,
+ task: row.task,
+ claimed: row.claimed,
+ next_run_at: row.next_run_at,
+ enabled: row.enabled,
+ })
+ })
+ .collect()
+ }
+
+ async fn update_action(&self, action: ScheduledAction) -> Result<ScheduledAction> {
+ let Some(id) = action.id else {
+ bail!("cannot update action without id");
+ };
+ let timezone = action.timezone.to_string();
+ let kind = kind_to_str(&action.kind);
+
+ let row = sqlx::query!(
+ r#"
+ UPDATE scheduled_action
+ SET name = $1,
+ schedule = $2,
+ kind = $3,
+ timezone = $4,
+ task = $5,
+ next_run_at = $6,
+ enabled = $7,
+ updated_at = now()
+ WHERE id = $8
+ RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at, updated_at, next_run_at, enabled
+ "#,
+ action.name,
+ action.schedule.as_str(),
+ kind,
+ timezone,
+ action.task,
+ action.next_run_at,
+ action.enabled,
+ id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ Ok(ScheduledAction {
+ id: Some(row.id),
+ owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ name: row.name,
+ schedule: Schedule::from_cron(row.schedule)?,
+ kind: parse_kind(&row.kind)?,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ timezone: parse_timezone(&row.timezone)?,
+ task: row.task,
+ claimed: row.claimed,
+ next_run_at: row.next_run_at,
+ enabled: row.enabled,
+ })
+ }
+
+ async fn delete_action(
+ &self,
+ id: &Uuid,
+ _macro_user_id: MacroUserIdStr<'static>,
+ ) -> Result<()> {
+ sqlx::query!(
+ r#"
+ DELETE FROM scheduled_action
+ WHERE id = $1
+ "#,
+ *id
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn claim_action(&self, id: &Uuid) -> Result<()> {
+ let now = Utc::now();
+ let stale_threshold = now - MAX_ACTION_TIME;
+
+ let result = sqlx::query!(
+ r#"
+ UPDATE scheduled_action
+ SET claimed = $1, updated_at = now()
+ WHERE id = $2
+ AND (claimed IS NULL OR claimed < $3)
+ "#,
+ now,
+ *id,
+ stale_threshold,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(anyhow::Error::new(AlreadyRunningError { action_id: *id }));
+ }
+
+ Ok(())
+ }
+
+ async fn release_action(&self, id: &Uuid) -> Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE scheduled_action
+ SET claimed = NULL, updated_at = now()
+ WHERE id = $1
+ "#,
+ *id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn create_execution_record(&self, record: ActionExecutionRecord) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO action_execution_record (action_id, resource_id, start_time, end_time, is_success, result)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ "#,
+ record.action_id,
+ record.resource_id,
+ record.start_time,
+ record.end_time,
+ record.is_success,
+ record.result,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn get_execution_records(&self, action_id: &Uuid) -> Result<Vec<ActionExecutionRecord>> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT id, action_id, resource_id, start_time, end_time, is_success, result, created_at
+ FROM action_execution_record
+ WHERE action_id = $1
+ ORDER BY start_time DESC
+ "#,
+ *action_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| ActionExecutionRecord {
+ id: Some(row.id),
+ action_id: row.action_id,
+ resource_id: row.resource_id,
+ start_time: row.start_time,
+ end_time: row.end_time,
+ is_success: row.is_success,
+ result: row.result,
+ created_at: row.created_at,
+ })
+ .collect())
+ }
+
+ async fn update_next_run_at(&self, id: &Uuid) -> Result<()> {
+ // Fetch the schedule + timezone so we can recompute `next_run_at`
+ // without the caller having to hold the action in memory.
+ let row = sqlx::query!(
+ r#"
+ SELECT schedule, timezone
+ FROM scheduled_action
+ WHERE id = $1
+ "#,
+ *id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ let tz = parse_timezone(&row.timezone)?;
+ let schedule = Schedule::from_cron(row.schedule)?;
+ let Some(next_run_at) = schedule.next_run_after_now(tz) else {
+ // No future fire time — leave next_run_at untouched.
+ return Ok(());
+ };
+
+ sqlx::query!(
+ r#"
+ UPDATE scheduled_action
+ SET next_run_at = $1, updated_at = now()
+ WHERE id = $2
+ "#,
+ next_run_at,
+ *id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn update_last_executed(&self, id: &Uuid, executed_at: DateTime<Utc>) -> Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE scheduled_action
+ SET updated_at = $1
+ WHERE id = $2
+ "#,
+ executed_at,
+ *id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/tokio_dispatcher.rs b/rust/cloud-storage/scheduled_action/src/outbound/tokio_dispatcher.rs
new file mode 100644
index 0000000000..21d4fd3c74
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/outbound/tokio_dispatcher.rs
@@ -0,0 +1,119 @@
+use std::collections::HashMap;
+use std::pin::Pin;
+
+use chrono::Utc;
+use futures::StreamExt;
+use futures::stream::FuturesUnordered;
+use macro_uuid::Uuid;
+use tokio::sync::mpsc::{Receiver, Sender};
+
+use crate::domain::models::{DispatchEvent, InProgressExecution, ScheduledAction};
+use crate::domain::ports::{ScheduledActionDispatcher, ScheduledActionExecutor};
+
+const BUFFER_SIZE: usize = 1024;
+
+type SleepFuture = Pin<Box<dyn Future<Output = (Uuid, u64)> + Send>>;
+
+struct TrackedAction {
+ action: ScheduledAction,
+ generation: u64,
+}
+
+pub struct TokioDispatcher<Exe: ScheduledActionExecutor> {
+ executor: Exe,
+}
+
+impl<Exe: ScheduledActionExecutor> TokioDispatcher<Exe> {
+ pub fn new(executor: Exe) -> Self {
+ Self { executor }
+ }
+}
+
+fn action_sleep(id: Uuid, action: &ScheduledAction, generation: u64) -> Option<SleepFuture> {
+ if !action.enabled {
+ return None;
+ }
+
+ let cron = action.schedule.as_cron();
+ let next = cron.upcoming(action.timezone).next()?;
+ let now = Utc::now().with_timezone(&action.timezone);
+ let duration = (next - now).to_std().unwrap_or(std::time::Duration::ZERO);
+
+ Some(Box::pin(async move {
+ tokio::time::sleep(duration).await;
+ (id, generation)
+ }))
+}
+
+impl<Exe> ScheduledActionDispatcher for TokioDispatcher<Exe>
+where
+ Exe: ScheduledActionExecutor + Send + 'static,
+{
+ fn begin_dispatch_loop(self) -> (Sender<DispatchEvent>, Receiver<InProgressExecution>) {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(BUFFER_SIZE);
+ let (extx, exrx) = tokio::sync::mpsc::channel::<InProgressExecution>(BUFFER_SIZE);
+
+ tokio::spawn(async move {
+ let mut actions: HashMap<Uuid, TrackedAction> = HashMap::new();
+ let mut futures: FuturesUnordered<SleepFuture> = FuturesUnordered::new();
+
+ loop {
+ tokio::select! {
+ Some((id, generation)) = futures.next() => {
+ let Some(tracked) = actions.get(&id) else {
+ continue;
+ };
+ if tracked.generation != generation {
+ continue;
+ }
+
+ let action = tracked.action.clone();
+ match self.executor.execute_action(action).await {
+ Ok(execution) => {
+ let _ = extx.send(execution).await;
+ }
+ Err(e) => {
+ tracing::error!(error=?e, action_id=?id, "failed to execute scheduled action");
+ }
+ }
+
+ if let Some(tracked) = actions.get(&id)
+ && let Some(fut) = action_sleep(id, &tracked.action, tracked.generation) {
+ futures.push(fut);
+ }
+ }
+ Some(event) = rx.recv() => {
+ match event {
+ DispatchEvent::Create(action) => {
+ let Some(id) = action.id else { continue };
+ let generation = 0u64;
+ if let Some(fut) = action_sleep(id, &action, generation) {
+ futures.push(fut);
+ }
+ actions.insert(id, TrackedAction { action, generation });
+ }
+ DispatchEvent::Update(action) => {
+ let Some(id) = action.id else { continue };
+ let generation = actions
+ .get(&id)
+ .map(|t| t.generation + 1)
+ .unwrap_or(0);
+ if let Some(fut) = action_sleep(id, &action, generation) {
+ futures.push(fut);
+ }
+ actions.insert(id, TrackedAction { action, generation });
+ }
+ DispatchEvent::Delete(action) => {
+ let Some(id) = action.id else { continue };
+ actions.remove(&id);
+ }
+ }
+ }
+ else => break,
+ }
+ }
+ });
+
+ (tx, exrx)
+ }
+}
diff --git a/rust/cloud-storage/scheduled_action/src/swagger.rs b/rust/cloud-storage/scheduled_action/src/swagger.rs
new file mode 100644
index 0000000000..51178b8aaf
--- /dev/null
+++ b/rust/cloud-storage/scheduled_action/src/swagger.rs
@@ -0,0 +1,52 @@
+use utoipa::OpenApi;
+
+#[allow(
+ unused_imports,
+ reason = "utoipa path macros require these generated symbols in scope"
+)]
+use crate::inbound::axum_router::{
+ __path_create_action, __path_delete_action, __path_execute_action, __path_health,
+ __path_list_actions, __path_list_history, __path_update_action,
+};
+
+use crate::domain::models::{
+ ActionExecutionRecord, ActionKind, AgentTask, CreateScheduledAction, InProgressExecution,
+ Schedule, ScheduledAction, ScheduledActionUpdate, UpdateScheduledAction,
+};
+use model::response::EmptyResponse;
+
+#[derive(OpenApi)]
+#[openapi(
+ info(
+ title = "scheduled_action",
+ description = "API for managing scheduled actions",
+ terms_of_service = "https://macro.com/terms",
+ ),
+ paths(
+ crate::inbound::axum_router::health,
+ crate::inbound::axum_router::list_actions,
+ crate::inbound::axum_router::create_action,
+ crate::inbound::axum_router::update_action,
+ crate::inbound::axum_router::delete_action,
+ crate::inbound::axum_router::execute_action,
+ crate::inbound::axum_router::list_history,
+ ),
+ components(
+ schemas(
+ ScheduledAction,
+ CreateScheduledAction,
+ UpdateScheduledAction,
+ Schedule,
+ ActionKind,
+ AgentTask,
+ InProgressExecution,
+ ActionExecutionRecord,
+ ScheduledActionUpdate,
+ EmptyResponse,
+ ),
+ ),
+ tags(
+ (name = "scheduled actions", description = "Scheduled action service")
+ )
+)]
+pub struct ApiDoc;