@stndrds/schema 1.0.0-alpha.112 → 1.0.0-alpha.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -551,1013 +551,1012 @@ interface BoundingBox {
551
551
  }
552
552
 
553
553
  /**
554
- * Message role in a conversation
554
+ * Scope of a permission rule.
555
+ * - `object`: Controls access to an entire object type (business data)
556
+ * - `system`: Controls access to platform resources (people, workspace)
555
557
  */
556
- type AIMessageRole = "user" | "assistant";
558
+ type PermissionScope = "object" | "system";
557
559
  /**
558
- * An AI model available for selection by the user.
559
- * Configured on the backend and exposed via GET /agent/models.
560
+ * Actions that can be performed on a resource.
560
561
  */
561
- interface AIAvailableModel {
562
- /** Model identifier (e.g. "claude-sonnet-4-6") */
563
- id: string;
564
- /** Provider name (e.g. "anthropic", "google") */
565
- provider: string;
566
- /** Display label (e.g. "Claude 4.6 Sonnet") */
567
- label: string;
568
- /** Whether this is the default model */
569
- isDefault?: boolean;
570
- }
562
+ type Action = "read" | "create" | "update" | "delete";
571
563
  /**
572
- * Tool call status during execution
564
+ * System resources that can be managed.
565
+ * - `people`: User profiles, invitations, roles and permissions
566
+ * - `workspace`: Object definitions, attributes, tenant settings, audit logs
567
+ * - `architect`: Architect settings, templates, and configurations
573
568
  */
574
- type AIToolCallStatus = "pending" | "running" | "streaming" | "success" | "error";
569
+ type SystemResource = "people" | "workspace" | "architect";
575
570
  /**
576
- * Tool call information for chat UI
571
+ * Preset access levels for simplified permission configuration.
572
+ * - `full`: All CRUD actions
573
+ * - `read-only`: Only read action
574
+ * - `none`: No actions
575
+ * - `custom`: Manual selection of individual actions
577
576
  */
578
- interface AIToolCall {
579
- /** Unique tool call ID */
580
- id: string;
581
- /** Tool name */
582
- name: string;
583
- /** Tool arguments */
584
- args?: Record<string, unknown>;
585
- /** Tool result (when complete) */
586
- result?: unknown;
587
- /** Error message if failed */
588
- error?: string;
589
- /** Execution status */
590
- status: AIToolCallStatus;
591
- }
577
+ type AccessLevel = "full" | "read-only" | "none" | "custom";
578
+ declare const ALL_ACTIONS: Action[];
592
579
  /**
593
- * Part type for message content
580
+ * Derive an AccessLevel from a list of actions.
594
581
  */
595
- type AIChatMessagePartType = "text" | "attachment" | "tool" | "thinking" | "reasoning" | "todo" | "question" | "error" | "approval" | "record" | "search-results" | (string & {});
582
+ declare function actionsToAccessLevel(actions: Action[]): AccessLevel;
596
583
  /**
597
- * Data for text part
584
+ * Convert an AccessLevel preset to its corresponding actions.
598
585
  */
599
- interface TextPartData {
600
- text: string;
601
- isStreaming?: boolean;
602
- }
586
+ declare function accessLevelToActions(level: Exclude<AccessLevel, "custom">): Action[];
603
587
  /**
604
- * Data for tool part (same as AIToolCall)
588
+ * Role definition - Groups permissions together.
589
+ *
590
+ * Roles are tenant-scoped and can be system-defined (immutable) or custom.
591
+ *
592
+ * @example
593
+ * ```typescript
594
+ * const ownerRole: Role = {
595
+ * id: "role-123",
596
+ * tenantId: "tenant-456",
597
+ * name: "owner",
598
+ * label: "Owner",
599
+ * description: "Full access to all platform features and data",
600
+ * system: true,
601
+ * createdAt: new Date(),
602
+ * updatedAt: new Date(),
603
+ * };
604
+ * ```
605
605
  */
606
- interface ToolPartData {
607
- id: string;
606
+ interface Role extends Timestamps {
607
+ id: Uuid;
608
+ tenantId: Uuid;
609
+ /**
610
+ * Technical name (unique per tenant, used in code).
611
+ * Examples: "owner", "member", "sales_manager"
612
+ */
608
613
  name: string;
609
- args?: Record<string, unknown>;
610
- result?: unknown;
611
- error?: string;
612
- status: AIToolCallStatus;
613
- /** Raw JSON string accumulating during tool-input streaming (cleared on tool_input_end) */
614
- partialInput?: string;
614
+ /**
615
+ * Display name shown in UI.
616
+ */
617
+ label: string;
618
+ /**
619
+ * Optional description of the role's purpose.
620
+ */
621
+ description?: string;
622
+ /**
623
+ * If true, this role cannot be modified or deleted.
624
+ * Used for built-in roles like "owner".
625
+ */
626
+ system: boolean;
615
627
  }
616
628
  /**
617
- * Data for thinking part
629
+ * Permission definition - Grants specific actions on a target.
630
+ *
631
+ * A permission belongs to a role and defines what actions are allowed
632
+ * on a specific target (object or system resource).
633
+ *
634
+ * @example
635
+ * ```typescript
636
+ * // Allow read and update on companies object
637
+ * const permission: Permission = {
638
+ * id: "perm-123",
639
+ * roleId: "role-456",
640
+ * scope: "object",
641
+ * target: "companies",
642
+ * actions: ["read", "update"],
643
+ * createdAt: new Date(),
644
+ * };
645
+ *
646
+ * // Wildcard permission for all objects
647
+ * const wildcardPerm: Permission = {
648
+ * id: "perm-789",
649
+ * roleId: "role-456",
650
+ * scope: "object",
651
+ * target: "*",
652
+ * actions: ["read", "create", "update", "delete"],
653
+ * createdAt: new Date(),
654
+ * };
655
+ * ```
618
656
  */
619
- interface ThinkingPartData {
620
- isStreaming: boolean;
621
- startTime?: number;
657
+ interface Permission {
658
+ id: Uuid;
659
+ roleId: Uuid;
660
+ /**
661
+ * Scope of this permission.
662
+ */
663
+ scope: PermissionScope;
664
+ /**
665
+ * Target of the permission.
666
+ * - For `object` scope: object name (e.g., "companies") or "*" for all
667
+ * - For `system` scope: system resource (e.g., "people", "workspace") or "*" for all
668
+ */
669
+ target: string;
670
+ /**
671
+ * Actions allowed on the target.
672
+ */
673
+ actions: Action[];
674
+ createdAt: Date;
622
675
  }
623
676
  /**
624
- * Data for reasoning part (Extended Thinking content)
677
+ * Links a user profile to a role within a tenant.
678
+ *
679
+ * A user can have multiple roles, and their permissions are additive (union).
680
+ *
681
+ * Note: `userProfileId` references UserProfile.id from the user_profiles table,
682
+ * NOT the auth provider ID (authId). This keeps permissions tied to the
683
+ * application's user management, not the authentication layer.
625
684
  */
626
- interface ReasoningPartData {
627
- /** Reasoning content (accumulated during streaming) */
628
- content: string;
629
- /** Whether reasoning is still streaming */
630
- isStreaming: boolean;
631
- /** Start timestamp for elapsed time display */
632
- startTime?: number;
685
+ interface UserRoleAssignment {
686
+ id: Uuid;
687
+ /**
688
+ * User profile ID (UserProfile.id from user_profiles table).
689
+ * This links to the application's user management system,
690
+ * not the auth provider's user ID.
691
+ */
692
+ userProfileId: Uuid;
693
+ roleId: Uuid;
694
+ tenantId: Uuid;
695
+ /**
696
+ * When the role was assigned.
697
+ */
698
+ assignedAt: Date;
699
+ /**
700
+ * User profile ID of who assigned this role (for audit trail).
701
+ */
702
+ assignedBy?: Uuid;
633
703
  }
634
704
  /**
635
- * A part of a chat message.
636
- * Parts are ordered chronologically as they arrive from the stream.
705
+ * Computed permissions for a user.
706
+ *
707
+ * This is the merged result of all roles assigned to a user.
708
+ * Returned by the API for permission checks.
637
709
  */
638
- interface AIChatMessagePart {
639
- /** Part type */
640
- type: AIChatMessagePartType;
641
- /** Unique part ID */
642
- id: string;
643
- /** Part-specific data */
644
- data: unknown;
710
+ interface EffectivePermissions {
711
+ /**
712
+ * Object-level permissions.
713
+ * Key is the object name, value is array of allowed actions.
714
+ * Special key "*" means permission applies to all objects.
715
+ */
716
+ objectPermissions: Record<string, Action[]>;
717
+ /**
718
+ * System-level permissions.
719
+ * Key is the system resource (people, workspace), value is array of allowed actions.
720
+ * Special key "*" means permission applies to all system resources.
721
+ */
722
+ systemPermissions: Record<string, Action[]>;
645
723
  }
646
724
  /**
647
- * Chat message for runtime/streaming.
648
- *
649
- * All content is represented as ordered parts (text, tools, thinking, etc.)
650
- * Parts are in chronological order as they arrive from the stream.
651
- *
652
- * Used in:
653
- * - useAgentChat hook
654
- * - AI chat UI components
655
- * - Stream processing
725
+ * Permissions for a specific object.
726
+ * Convenience type for frontend use.
656
727
  */
657
- interface AIChatMessage {
658
- /** Unique message ID */
659
- id: string;
660
- /** Message role */
661
- role: AIMessageRole;
662
- /** Ordered message parts (text, tools, thinking, etc.) */
663
- parts: AIChatMessagePart[];
664
- /** Whether the message is still streaming */
665
- isStreaming?: boolean;
666
- /** Message timestamp */
667
- timestamp?: Date;
668
- /** Error message if the message failed */
669
- error?: string;
728
+ interface ObjectPermissions {
729
+ canRead: boolean;
730
+ canCreate: boolean;
731
+ canUpdate: boolean;
732
+ canDelete: boolean;
670
733
  }
671
734
  /**
672
- * Question types supported by the agent
735
+ * Permissions for a specific system resource.
736
+ * Convenience type for frontend use.
673
737
  */
674
- type AIQuestionType = "text" | "choice" | "confirm" | "multiselect";
738
+ interface SystemPermissions {
739
+ canRead: boolean;
740
+ canCreate: boolean;
741
+ canUpdate: boolean;
742
+ canDelete: boolean;
743
+ }
675
744
  /**
676
- * Option for choice/multiselect questions
745
+ * Input for creating a new role.
746
+ * TenantId is automatically set from TenantContext.
677
747
  */
678
- interface AIQuestionOption {
679
- value: string;
748
+ interface CreateRoleInput {
749
+ name: string;
680
750
  label: string;
681
751
  description?: string;
682
752
  }
683
753
  /**
684
- * Question from the agent to the user
754
+ * Input for updating an existing role.
685
755
  */
686
- interface AIQuestion {
687
- /** Unique question ID */
688
- id: string;
689
- /** Question type */
690
- type: AIQuestionType;
691
- /** Question text */
692
- question: string;
693
- /** Options for choice/multiselect */
694
- options?: AIQuestionOption[];
695
- /** Placeholder for text input */
696
- placeholder?: string;
697
- /** Whether answer is required */
698
- required?: boolean;
699
- /** Min selections for multiselect */
700
- minSelections?: number;
701
- /** Max selections for multiselect */
702
- maxSelections?: number;
756
+ interface UpdateRoleInput {
757
+ label?: string;
758
+ description?: string;
703
759
  }
704
760
  /**
705
- * Answer format for questions
761
+ * Input for creating a permission.
706
762
  */
707
- type AIQuestionAnswer = {
708
- type: "text";
709
- value: string;
710
- } | {
711
- type: "choice";
712
- value: string;
713
- } | {
714
- type: "confirm";
715
- value: boolean;
716
- } | {
717
- type: "multiselect";
718
- value: string[];
719
- };
763
+ interface CreatePermissionInput {
764
+ scope: PermissionScope;
765
+ target: string;
766
+ /**
767
+ * Actions allowed on the target.
768
+ */
769
+ actions: Action[];
770
+ }
720
771
  /**
721
- * Option for batch questions
772
+ * Input for assigning a role to a user.
722
773
  */
723
- interface AIBatchQuestionOption {
724
- /** Value returned when selected */
725
- value: string;
726
- /** Display label */
727
- label: string;
774
+ interface AssignRoleInput {
775
+ /**
776
+ * User profile ID (UserProfile.id).
777
+ */
778
+ userProfileId: Uuid;
779
+ roleId: Uuid;
780
+ tenantId: Uuid;
781
+ assignedBy?: Uuid;
728
782
  }
783
+
729
784
  /**
730
- * Question in a batch (for ask_questions tool)
785
+ * A permission attached to an API key.
786
+ * Same format as RBAC permissions — reuses PermissionScope, Action, and target.
731
787
  */
732
- interface AIBatchQuestion {
733
- /** Unique question ID */
788
+ interface ApiKeyPermission {
789
+ scope: PermissionScope;
790
+ target: string;
791
+ actions: Action[];
792
+ }
793
+ interface ApiKey {
734
794
  id: string;
735
- /** Question text to display */
736
- question: string;
737
- /** Predefined options (if provided, displayed as buttons) */
738
- options?: AIBatchQuestionOption[];
739
- /** Allow custom text input in addition to options */
740
- allowCustomAnswer?: boolean;
741
- /** Placeholder for custom input field */
742
- placeholder?: string;
795
+ tenantId: string;
796
+ userProfileId: string | null;
797
+ name: string;
798
+ prefix: string;
799
+ permissions: ApiKeyPermission[];
800
+ expiresAt: string | null;
801
+ lastUsedAt: string | null;
802
+ revokedAt: string | null;
803
+ createdAt: string;
804
+ createdBy: string;
805
+ }
806
+ /** Returned only at creation time — the only time the plaintext secret is available. */
807
+ interface ApiKeyWithSecret extends ApiKey {
808
+ secret: string;
743
809
  }
744
810
  /**
745
- * Answer returned by the AgentQuestions widget
811
+ * Returned by validateKey provides everything downstream needs.
812
+ * Permissions are already intersected with user RBAC for personal keys.
746
813
  */
747
- interface AIBatchQuestionAnswer {
748
- /** True if user skipped all questions */
749
- skipped: boolean;
750
- /** Map of question ID to answer value */
751
- answers: Record<string, string>;
814
+ interface ApiKeyAuthContext {
815
+ tenantId: string;
816
+ userId: string | null;
817
+ keyId: string;
818
+ permissions: ApiKeyPermission[];
819
+ createdBy: string;
752
820
  }
821
+ interface CreateApiKeyInput {
822
+ name: string;
823
+ permissions: ApiKeyPermission[];
824
+ expiresAt?: string;
825
+ userProfileId?: string;
826
+ }
827
+
753
828
  /**
754
- * Todo item status
829
+ * Type of mentionable entity
755
830
  */
756
- type AITodoStatus = "pending" | "in_progress" | "completed" | "blocked";
831
+ type MentionEntityType = "user" | "record" | (string & {});
757
832
  /**
758
- * Todo item in a task list
833
+ * A mention reference stored with a message
759
834
  */
760
- interface AITodoItem {
835
+ interface MentionReference {
836
+ /** Unique ID for this mention instance */
761
837
  id: string;
762
- description: string;
763
- status: AITodoStatus;
764
- result?: string;
765
- updatedAt?: number;
838
+ /** Entity type (user, record, or custom) */
839
+ type: MentionEntityType;
840
+ /** Entity ID (user ID or record ID) */
841
+ entityId: string;
842
+ /** Display label at time of mention (cached for display even if entity is deleted) */
843
+ label: string;
844
+ /** Object name for records, undefined for users */
845
+ objectName?: string;
846
+ /** Start position in the message text */
847
+ startIndex: number;
848
+ /** End position in the message text */
849
+ endIndex: number;
766
850
  }
767
851
  /**
768
- * Todo list managed by the agent
852
+ * Context data for a mentioned entity (sent to AI)
769
853
  */
770
- interface AITodoList {
771
- items: AITodoItem[];
772
- progress: number;
773
- isComplete: boolean;
854
+ interface MentionedEntityContext {
855
+ /** Entity type */
856
+ type: MentionEntityType;
857
+ /** Entity ID */
858
+ entityId: string;
859
+ /** Display label */
860
+ label: string;
861
+ /** Object name for records */
862
+ objectName?: string;
863
+ /** Additional context data (record values, user details, etc.) */
864
+ data?: Record<string, unknown>;
774
865
  }
775
866
  /**
776
- * AI Usage Metrics record
867
+ * Full mention context for AI
777
868
  */
778
- interface AIUsageMetrics {
779
- id: string;
780
- tenantId: string;
781
- date: Date;
782
- requestCount: number;
783
- totalTokens: number;
784
- totalCost: number;
785
- providerBreakdown: Record<string, AIProviderMetrics>;
786
- toolUsage: Record<string, number>;
869
+ interface MentionedContext {
870
+ /** All mentioned entities with their context data */
871
+ entities: MentionedEntityContext[];
872
+ /** Summary text for AI system prompt */
873
+ summary: string;
787
874
  }
875
+
788
876
  /**
789
- * Provider-specific metrics
877
+ * Attribute Property Protection
878
+ *
879
+ * Defines which properties can be modified based on attribute type (custom vs system).
880
+ *
881
+ * Protection levels:
882
+ * 1. Identity properties: NEVER modifiable (defines attribute structure)
883
+ * 2. Behavior properties: Modifiable for custom attributes, PROTECTED for system attributes
884
+ * 3. Presentation properties: ALWAYS modifiable (display only, no logic impact)
790
885
  */
791
- interface AIProviderMetrics {
792
- requests: number;
793
- tokens: number;
794
- cost: number;
795
- }
796
886
  /**
797
- * Memory type for categorization
798
- *
799
- * - `soul`: Tenant identity and persona (admin-managed)
800
- * - `user`: Per-user facts and preferences
801
- * - `daily`: Auto-generated daily summaries
802
- * - `session`: Auto-generated conversation summaries
887
+ * Identity properties - Never modifiable
888
+ * These define the fundamental structure of the attribute.
803
889
  */
804
- type AIMemoryType = "soul" | "user" | "daily" | "session";
890
+ declare const IDENTITY_PROPERTIES: readonly ["name", "type"];
805
891
  /**
806
- * Advanced memory entry for OpenClaw-style memory system
892
+ * Behavior properties - Protected for system attributes
893
+ * These affect business logic and data integrity.
807
894
  */
808
- interface AIMemoryEntry {
809
- id: string;
810
- tenantId: string;
811
- userId: string | null;
812
- conversationId: string | null;
813
- type: AIMemoryType;
814
- content: string;
815
- embedding: number[] | null;
816
- importance: number;
817
- source: string;
818
- createdAt: Date;
819
- updatedAt: Date;
820
- expiresAt: Date | null;
821
- }
895
+ declare const BEHAVIOR_PROPERTIES: readonly ["required", "disabled", "hidden", "archived", "deprecated", "defaultValue", "config", "order", "unique"];
822
896
  /**
823
- * Compaction summary for conversation history compression
897
+ * Presentation properties - Always modifiable
898
+ * These only affect display, not logic.
824
899
  */
825
- interface AICompactionSummary {
826
- id: string;
827
- tenantId: string;
828
- userId: string;
829
- conversationId: string;
830
- summary: string;
831
- originalMessageCount: number;
832
- tokenCountBefore: number;
833
- tokenCountAfter: number;
834
- compactedAt: Date;
835
- }
900
+ declare const PRESENTATION_PROPERTIES: readonly ["label", "description", "placeholder", "icon"];
836
901
 
837
902
  /**
838
- * Scope of a permission rule.
839
- * - `object`: Controls access to an entire object type (business data)
840
- * - `system`: Controls access to platform resources (people, workspace)
903
+ * Type of resource that can be audited
841
904
  */
842
- type PermissionScope = "object" | "system";
905
+ type AuditResourceType = "record" | "object" | "attribute" | "user" | "role" | "settings" | "file";
843
906
  /**
844
- * Actions that can be performed on a resource.
907
+ * Actions that can be audited
845
908
  */
846
- type Action = "read" | "create" | "update" | "delete";
909
+ type AuditAction = "record.created" | "record.updated" | "record.deleted" | "record.restored" | "object.created" | "object.updated" | "object.deleted" | "attribute.created" | "attribute.updated" | "attribute.deleted" | "user.created" | "user.invited" | "user.updated" | "user.deleted" | "user.login" | "user.logout" | "role.created" | "role.updated" | "role.deleted" | "role.assigned" | "role.revoked" | "settings.updated" | "file.uploaded" | "file.updated" | "file.deleted";
847
910
  /**
848
- * System resources that can be managed.
849
- * - `people`: User profiles, invitations, roles and permissions
850
- * - `workspace`: Object definitions, attributes, tenant settings, audit logs
851
- * - `architect`: Architect settings, templates, and configurations
911
+ * Actor type - who performed the action
852
912
  */
853
- type SystemResource = "people" | "workspace" | "architect";
913
+ type AuditActorType = "user" | "system";
854
914
  /**
855
- * Preset access levels for simplified permission configuration.
856
- * - `full`: All CRUD actions
857
- * - `read-only`: Only read action
858
- * - `none`: No actions
859
- * - `custom`: Manual selection of individual actions
915
+ * Detail of a change on a field
860
916
  */
861
- type AccessLevel = "full" | "read-only" | "none" | "custom";
862
- declare const ALL_ACTIONS: Action[];
917
+ interface AuditChange {
918
+ /** Field name that was changed */
919
+ field: string;
920
+ /** Previous value (undefined for new fields) */
921
+ oldValue: unknown;
922
+ /** New value (undefined for deleted fields) */
923
+ newValue: unknown;
924
+ }
863
925
  /**
864
- * Derive an AccessLevel from a list of actions.
926
+ * Audit log entry - immutable record of an action
865
927
  */
866
- declare function actionsToAccessLevel(actions: Action[]): AccessLevel;
928
+ interface AuditLogEntry {
929
+ id: Uuid;
930
+ tenantId: Uuid;
931
+ /** User profile ID of the actor (null for system actions) */
932
+ actorId?: string;
933
+ /** Denormalized email for search (in case user is deleted) */
934
+ actorEmail?: string;
935
+ /** Type of actor */
936
+ actorType: AuditActorType;
937
+ action: AuditAction;
938
+ resourceType: AuditResourceType;
939
+ resourceId: Uuid;
940
+ /** Human-readable label (record name, object label, etc.) */
941
+ resourceLabel?: string;
942
+ /** Object technical name (e.g., "companies", "contacts") */
943
+ objectName?: string;
944
+ /** Object UUID */
945
+ objectId?: Uuid;
946
+ changes?: AuditChange[];
947
+ /** Extra context (IP, user-agent, requestId, etc.) */
948
+ metadata?: Record<string, unknown>;
949
+ createdAt: Date;
950
+ }
867
951
  /**
868
- * Convert an AccessLevel preset to its corresponding actions.
952
+ * Input for creating an audit log entry.
953
+ * Tenant ID is automatically set from execution context.
869
954
  */
870
- declare function accessLevelToActions(level: Exclude<AccessLevel, "custom">): Action[];
955
+ interface CreateAuditLogInput {
956
+ actorId?: string;
957
+ /** Denormalized actor email for display purposes. */
958
+ actorEmail?: string;
959
+ actorType?: AuditActorType;
960
+ action: AuditAction;
961
+ resourceType: AuditResourceType;
962
+ resourceId: string;
963
+ resourceLabel?: string;
964
+ objectName?: string;
965
+ objectId?: string;
966
+ changes?: AuditChange[];
967
+ metadata?: Record<string, unknown>;
968
+ }
871
969
  /**
872
- * Role definition - Groups permissions together.
873
- *
874
- * Roles are tenant-scoped and can be system-defined (immutable) or custom.
875
- *
876
- * @example
877
- * ```typescript
878
- * const ownerRole: Role = {
879
- * id: "role-123",
880
- * tenantId: "tenant-456",
881
- * name: "owner",
882
- * label: "Owner",
883
- * description: "Full access to all platform features and data",
884
- * system: true,
885
- * createdAt: new Date(),
886
- * updatedAt: new Date(),
887
- * };
888
- * ```
970
+ * Valid column names for sorting audit log entries.
971
+ * Maps to snake_case database column names used in Supabase queries.
889
972
  */
890
- interface Role extends Timestamps {
891
- id: Uuid;
892
- tenantId: Uuid;
893
- /**
894
- * Technical name (unique per tenant, used in code).
895
- * Examples: "owner", "member", "sales_manager"
896
- */
897
- name: string;
898
- /**
899
- * Display name shown in UI.
900
- */
901
- label: string;
902
- /**
903
- * Optional description of the role's purpose.
904
- */
905
- description?: string;
906
- /**
907
- * If true, this role cannot be modified or deleted.
908
- * Used for built-in roles like "owner".
909
- */
910
- system: boolean;
911
- }
973
+ type AuditSortField = "created_at" | "action" | "resource_type" | "actor_id" | "actor_email" | "object_name";
912
974
  /**
913
- * Permission definition - Grants specific actions on a target.
914
- *
915
- * A permission belongs to a role and defines what actions are allowed
916
- * on a specific target (object or system resource).
917
- *
918
- * @example
919
- * ```typescript
920
- * // Allow read and update on companies object
921
- * const permission: Permission = {
922
- * id: "perm-123",
923
- * roleId: "role-456",
924
- * scope: "object",
925
- * target: "companies",
926
- * actions: ["read", "update"],
927
- * createdAt: new Date(),
928
- * };
929
- *
930
- * // Wildcard permission for all objects
931
- * const wildcardPerm: Permission = {
932
- * id: "perm-789",
933
- * roleId: "role-456",
934
- * scope: "object",
935
- * target: "*",
936
- * actions: ["read", "create", "update", "delete"],
937
- * createdAt: new Date(),
938
- * };
939
- * ```
975
+ * Options for listing audit logs
940
976
  */
941
- interface Permission {
942
- id: Uuid;
943
- roleId: Uuid;
944
- /**
945
- * Scope of this permission.
946
- */
947
- scope: PermissionScope;
948
- /**
949
- * Target of the permission.
950
- * - For `object` scope: object name (e.g., "companies") or "*" for all
951
- * - For `system` scope: system resource (e.g., "people", "workspace") or "*" for all
952
- */
953
- target: string;
954
- /**
955
- * Actions allowed on the target.
956
- */
957
- actions: Action[];
958
- createdAt: Date;
977
+ interface AuditListOptions {
978
+ limit?: number;
979
+ offset?: number;
980
+ action?: AuditAction | AuditAction[];
981
+ resourceType?: AuditResourceType | AuditResourceType[];
982
+ objectName?: string;
983
+ actorId?: string;
984
+ from?: Date;
985
+ to?: Date;
986
+ sorts?: Array<{
987
+ field: AuditSortField;
988
+ direction: "asc" | "desc";
989
+ }>;
959
990
  }
960
991
  /**
961
- * Links a user profile to a role within a tenant.
962
- *
963
- * A user can have multiple roles, and their permissions are additive (union).
964
- *
965
- * Note: `userProfileId` references UserProfile.id from the user_profiles table,
966
- * NOT the auth provider ID (authId). This keeps permissions tied to the
967
- * application's user management, not the authentication layer.
992
+ * Options for AuditService
968
993
  */
969
- interface UserRoleAssignment {
970
- id: Uuid;
994
+ interface AuditServiceOptions {
971
995
  /**
972
- * User profile ID (UserProfile.id from user_profiles table).
973
- * This links to the application's user management system,
974
- * not the auth provider's user ID.
996
+ * If true, audit logging is async (fire-and-forget).
997
+ * Better performance but logs might be lost on crash.
998
+ * @default false
975
999
  */
976
- userProfileId: Uuid;
977
- roleId: Uuid;
978
- tenantId: Uuid;
1000
+ async?: boolean;
979
1001
  /**
980
- * When the role was assigned.
1002
+ * Batch size for async mode.
1003
+ * Logs are buffered and flushed when batch is full or after flushIntervalMs.
1004
+ * @default 10
981
1005
  */
982
- assignedAt: Date;
1006
+ batchSize?: number;
983
1007
  /**
984
- * User profile ID of who assigned this role (for audit trail).
1008
+ * Flush interval in ms for async mode.
1009
+ * @default 1000
985
1010
  */
986
- assignedBy?: Uuid;
1011
+ flushIntervalMs?: number;
987
1012
  }
988
- /**
989
- * Computed permissions for a user.
990
- *
991
- * This is the merged result of all roles assigned to a user.
992
- * Returned by the API for permission checks.
993
- */
994
- interface EffectivePermissions {
995
- /**
996
- * Object-level permissions.
997
- * Key is the object name, value is array of allowed actions.
998
- * Special key "*" means permission applies to all objects.
999
- */
1000
- objectPermissions: Record<string, Action[]>;
1001
- /**
1002
- * System-level permissions.
1003
- * Key is the system resource (people, workspace), value is array of allowed actions.
1004
- * Special key "*" means permission applies to all system resources.
1005
- */
1006
- systemPermissions: Record<string, Action[]>;
1013
+
1014
+ type AgentRunStatus = "pending" | "running" | "completed" | "failed" | "cancelled" | "paused";
1015
+ type AgentSessionStatus = "active" | "idle" | "completed" | "failed" | "cancelled" | "waiting_human" | "timeout" | "expired";
1016
+ type AgentSessionMode = "interactive" | "autonomous";
1017
+ type QuestionStatus = "pending" | "answered" | "timeout" | "cancelled";
1018
+ type TriggerEventType = "record.created" | "record.updated" | "record.deleted" | "record.field_changed" | "form.submitted" | "agent.completed" | "webhook" | "schedule";
1019
+ type AgentTriggerType = Extract<TriggerEventType, "record.created" | "record.updated" | "record.deleted">;
1020
+ type ProviderName = "anthropic" | "openai" | "google" | "mistral";
1021
+ interface ModelDefinition {
1022
+ provider: ProviderName;
1023
+ model: string;
1024
+ maxTokens?: number;
1007
1025
  }
1008
- /**
1009
- * Permissions for a specific object.
1010
- * Convenience type for frontend use.
1011
- */
1012
- interface ObjectPermissions {
1013
- canRead: boolean;
1014
- canCreate: boolean;
1015
- canUpdate: boolean;
1016
- canDelete: boolean;
1026
+ interface RetryPolicy {
1027
+ maxRetries: number;
1028
+ backoffMs: number;
1029
+ backoffMultiplier: number;
1017
1030
  }
1018
- /**
1019
- * Permissions for a specific system resource.
1020
- * Convenience type for frontend use.
1021
- */
1022
- interface SystemPermissions {
1023
- canRead: boolean;
1024
- canCreate: boolean;
1025
- canUpdate: boolean;
1026
- canDelete: boolean;
1031
+ interface AgentExecutionConfig {
1032
+ maxConcurrentRuns: number;
1033
+ retryPolicy: RetryPolicy;
1034
+ timeoutMs: number;
1035
+ costLimitUsd?: number;
1027
1036
  }
1028
1037
  /**
1029
- * Input for creating a new role.
1030
- * TenantId is automatically set from TenantContext.
1038
+ * Shared base config used by AgentDefinition, inline runs, and AgentSession.
1031
1039
  */
1032
- interface CreateRoleInput {
1033
- name: string;
1034
- label: string;
1035
- description?: string;
1036
- }
1037
- /**
1038
- * Input for updating an existing role.
1039
- */
1040
- interface UpdateRoleInput {
1041
- label?: string;
1042
- description?: string;
1040
+ interface AgentConfig {
1041
+ systemPrompt: string;
1042
+ model: ModelDefinition;
1043
+ tools?: string[];
1044
+ maxIterations?: number;
1045
+ timeoutMs?: number;
1046
+ canDelegate: boolean;
1047
+ maxDepth: number;
1048
+ maxTreeCostUsd?: number;
1049
+ critic?: CriticConfig;
1043
1050
  }
1044
- /**
1045
- * Input for creating a permission.
1046
- */
1047
- interface CreatePermissionInput {
1048
- scope: PermissionScope;
1049
- target: string;
1050
- /**
1051
- * Actions allowed on the target.
1052
- */
1053
- actions: Action[];
1051
+ interface CriticConfig {
1052
+ enabled: boolean;
1053
+ model?: ModelDefinition;
1054
+ systemPrompt?: string;
1055
+ maxRetries?: number;
1054
1056
  }
1055
- /**
1056
- * Input for assigning a role to a user.
1057
- */
1058
- interface AssignRoleInput {
1059
- /**
1060
- * User profile ID (UserProfile.id).
1061
- */
1062
- userProfileId: Uuid;
1063
- roleId: Uuid;
1064
- tenantId: Uuid;
1065
- assignedBy?: Uuid;
1057
+ interface RecordAgentTrigger {
1058
+ type: AgentTriggerType;
1059
+ objectId: string;
1060
+ filter?: Record<string, unknown>;
1066
1061
  }
1067
-
1062
+ interface FormSubmittedAgentTrigger {
1063
+ type: "form.submitted";
1064
+ formId?: string;
1065
+ formName?: string;
1066
+ filter?: Record<string, unknown>;
1067
+ }
1068
+ type AgentTrigger = RecordAgentTrigger | FormSubmittedAgentTrigger;
1068
1069
  /**
1069
- * A permission attached to an API key.
1070
- * Same format as RBAC permissions reuses PermissionScope, Action, and target.
1070
+ * Standalone trigger definition (replaces embedded AgentTrigger[]).
1071
+ * Triggers are now first-class entities with their own lifecycle.
1071
1072
  */
1072
- interface ApiKeyPermission {
1073
- scope: PermissionScope;
1074
- target: string;
1075
- actions: Action[];
1076
- }
1077
- interface ApiKey {
1073
+ interface AgentTriggerDefinition {
1078
1074
  id: string;
1079
1075
  tenantId: string;
1080
- userProfileId: string | null;
1076
+ definitionId: string;
1077
+ name?: string;
1078
+ eventType: TriggerEventType;
1079
+ objectId?: string;
1080
+ fieldPath?: string;
1081
+ formDefinitionId?: string;
1082
+ sourceAgentId?: string;
1083
+ webhookPath?: string;
1084
+ cronExpression?: string;
1085
+ timezone?: string;
1086
+ filter?: Record<string, unknown>;
1087
+ inputBuilder?: string;
1088
+ enabled: boolean;
1089
+ createdAt: Date;
1090
+ updatedAt: Date;
1091
+ }
1092
+ interface AgentSchedule {
1093
+ cron: string;
1094
+ timezone?: string;
1095
+ enabled: boolean;
1096
+ input?: Record<string, unknown>;
1097
+ inputBuilder?: string;
1098
+ }
1099
+ interface AgentMessageAttachment {
1100
+ id: string;
1081
1101
  name: string;
1082
- prefix: string;
1083
- permissions: ApiKeyPermission[];
1084
- expiresAt: string | null;
1085
- lastUsedAt: string | null;
1086
- revokedAt: string | null;
1087
- createdAt: string;
1088
- createdBy: string;
1102
+ mimeType: string;
1103
+ size: number;
1104
+ url?: string;
1089
1105
  }
1090
- /** Returned only at creation time — the only time the plaintext secret is available. */
1091
- interface ApiKeyWithSecret extends ApiKey {
1092
- secret: string;
1106
+ interface TimeoutPolicy {
1107
+ timeoutMs: number;
1108
+ action: "cancel" | "auto_decide" | "escalate";
1109
+ fallbackValue?: unknown;
1093
1110
  }
1094
- /**
1095
- * Returned by validateKey — provides everything downstream needs.
1096
- * Permissions are already intersected with user RBAC for personal keys.
1097
- */
1098
- interface ApiKeyAuthContext {
1111
+ interface AgentDefinition {
1112
+ id: string;
1099
1113
  tenantId: string;
1100
- userId: string | null;
1101
- keyId: string;
1102
- permissions: ApiKeyPermission[];
1114
+ name: string;
1115
+ icon?: string;
1116
+ description?: string;
1117
+ systemPrompt: string;
1118
+ model: ModelDefinition;
1119
+ tools?: string[];
1120
+ maxIterations?: number;
1121
+ schedule?: AgentSchedule;
1122
+ triggers?: AgentTrigger[];
1123
+ config: AgentExecutionConfig;
1103
1124
  createdBy: string;
1125
+ createdAt: Date;
1126
+ updatedAt: Date;
1127
+ deletedAt?: Date;
1128
+ canDelegate?: boolean;
1129
+ maxDepth?: number;
1130
+ maxTreeCostUsd?: number;
1131
+ critic?: CriticConfig;
1132
+ autoDecide?: boolean;
1133
+ fileIds?: string[];
1134
+ attachments?: File[];
1104
1135
  }
1105
- interface CreateApiKeyInput {
1106
- name: string;
1107
- permissions: ApiKeyPermission[];
1108
- expiresAt?: string;
1109
- userProfileId?: string;
1136
+ interface AgentRun {
1137
+ id: string;
1138
+ definitionId?: string;
1139
+ parentRunId?: string;
1140
+ depth: number;
1141
+ inlineConfig?: AgentConfig;
1142
+ tenantId: string;
1143
+ createdBy?: string;
1144
+ status: AgentRunStatus;
1145
+ retryCount: number;
1146
+ input: Record<string, unknown>;
1147
+ output?: Record<string, unknown>;
1148
+ error?: string;
1149
+ tokenUsage?: {
1150
+ input: number;
1151
+ output: number;
1152
+ };
1153
+ costUsd?: number;
1154
+ startedAt?: Date;
1155
+ completedAt?: Date;
1156
+ createdAt: Date;
1157
+ sessionId?: string;
1158
+ rootRunId?: string;
1159
+ triggerId?: string;
1160
+ treeCostUsd?: number;
1161
+ effectiveSystemPrompt?: string;
1110
1162
  }
1111
-
1112
- /**
1113
- * Type of mentionable entity
1114
- */
1115
- type MentionEntityType = "user" | "record" | (string & {});
1116
- /**
1117
- * A mention reference stored with a message
1118
- */
1119
- interface MentionReference {
1120
- /** Unique ID for this mention instance */
1163
+ interface AgentSession {
1121
1164
  id: string;
1122
- /** Entity type (user, record, or custom) */
1123
- type: MentionEntityType;
1124
- /** Entity ID (user ID or record ID) */
1125
- entityId: string;
1126
- /** Display label at time of mention (cached for display even if entity is deleted) */
1127
- label: string;
1128
- /** Object name for records, undefined for users */
1129
- objectName?: string;
1130
- /** Start position in the message text */
1131
- startIndex: number;
1132
- /** End position in the message text */
1133
- endIndex: number;
1165
+ tenantId: string;
1166
+ mode: AgentSessionMode;
1167
+ status: AgentSessionStatus;
1168
+ definitionId?: string;
1169
+ inlineConfig?: AgentConfig;
1170
+ parentSessionId?: string;
1171
+ rootSessionId: string;
1172
+ depth: number;
1173
+ missionPrompt?: string;
1174
+ treeCostUsd: number;
1175
+ name?: string;
1176
+ metadata?: Record<string, unknown>;
1177
+ createdBy?: string;
1178
+ createdAt: Date;
1179
+ updatedAt: Date;
1180
+ completedAt?: Date;
1181
+ expiresAt?: Date;
1182
+ archivedAt?: Date;
1134
1183
  }
1135
1184
  /**
1136
- * Context data for a mentioned entity (sent to AI)
1185
+ * Persisted message in an agent session.
1186
+ * Unified type for both interactive and autonomous sessions.
1137
1187
  */
1138
- interface MentionedEntityContext {
1139
- /** Entity type */
1140
- type: MentionEntityType;
1141
- /** Entity ID */
1142
- entityId: string;
1143
- /** Display label */
1144
- label: string;
1145
- /** Object name for records */
1146
- objectName?: string;
1147
- /** Additional context data (record values, user details, etc.) */
1148
- data?: Record<string, unknown>;
1188
+ interface AgentSessionMessage {
1189
+ id: string;
1190
+ sessionId: string;
1191
+ tenantId?: string;
1192
+ runId?: string;
1193
+ role: "user" | "assistant" | "system" | "tool";
1194
+ content: string;
1195
+ attachments?: AgentMessageAttachment[];
1196
+ mentions?: MentionReference[];
1197
+ toolCalls?: AgentToolCall[];
1198
+ model?: ModelDefinition;
1199
+ reasoning?: string;
1200
+ tokenUsage?: {
1201
+ input: number;
1202
+ output: number;
1203
+ };
1204
+ createdAt: Date;
1149
1205
  }
1150
- /**
1151
- * Full mention context for AI
1152
- */
1153
- interface MentionedContext {
1154
- /** All mentioned entities with their context data */
1155
- entities: MentionedEntityContext[];
1156
- /** Summary text for AI system prompt */
1157
- summary: string;
1206
+ interface AgentToolCall {
1207
+ id: string;
1208
+ name: string;
1209
+ arguments: Record<string, unknown>;
1210
+ result?: unknown;
1211
+ error?: string;
1212
+ durationMs?: number;
1213
+ }
1214
+ interface AgentContextEntry {
1215
+ id: string;
1216
+ rootRunId: string;
1217
+ runId: string;
1218
+ namespace: string;
1219
+ key: string;
1220
+ value: unknown;
1221
+ createdAt: Date;
1222
+ updatedAt: Date;
1223
+ }
1224
+ interface AgentQuestion {
1225
+ id: string;
1226
+ runId: string;
1227
+ sessionId?: string;
1228
+ tenantId: string;
1229
+ question: string;
1230
+ options?: string[];
1231
+ metadata?: Record<string, unknown>;
1232
+ status: QuestionStatus;
1233
+ response?: QuestionResponse;
1234
+ timeoutPolicy?: TimeoutPolicy;
1235
+ createdAt: Date;
1236
+ answeredAt?: Date;
1237
+ expiresAt?: Date;
1238
+ }
1239
+ interface QuestionResponse {
1240
+ answer: unknown;
1241
+ answeredBy?: string;
1242
+ source: "user" | "auto_decide" | "timeout";
1243
+ }
1244
+ interface RecordAgentEvent {
1245
+ type: AgentTriggerType;
1246
+ objectId: string;
1247
+ recordId: string;
1248
+ tenantId: string;
1249
+ data?: Record<string, unknown>;
1250
+ }
1251
+ interface FormSubmittedAgentEvent {
1252
+ type: "form.submitted";
1253
+ tenantId: string;
1254
+ formId: string;
1255
+ formName: string;
1256
+ submissionId: string;
1257
+ createdBy?: string;
1258
+ createdRecordIds: Record<string, string>;
1259
+ data: {
1260
+ formId: string;
1261
+ formName: string;
1262
+ submissionId: string;
1263
+ createdBy?: string;
1264
+ createdRecordIds: Record<string, string>;
1265
+ slotValues: Record<string, Record<string, unknown>>;
1266
+ stepValues: Record<string, Record<string, unknown>>;
1267
+ };
1268
+ }
1269
+ type AgentEvent = RecordAgentEvent | FormSubmittedAgentEvent;
1270
+ interface AgentDashboard {
1271
+ activeRuns: number;
1272
+ pendingRuns: number;
1273
+ failedToday: number;
1274
+ completedToday: number;
1275
+ totalCostToday: number;
1276
+ totalCostWeek: number;
1158
1277
  }
1159
-
1160
- /**
1161
- * Attribute Property Protection
1162
- *
1163
- * Defines which properties can be modified based on attribute type (custom vs system).
1164
- *
1165
- * Protection levels:
1166
- * 1. Identity properties: NEVER modifiable (defines attribute structure)
1167
- * 2. Behavior properties: Modifiable for custom attributes, PROTECTED for system attributes
1168
- * 3. Presentation properties: ALWAYS modifiable (display only, no logic impact)
1169
- */
1170
1278
  /**
1171
- * Identity properties - Never modifiable
1172
- * These define the fundamental structure of the attribute.
1279
+ * Message role in a conversation
1173
1280
  */
1174
- declare const IDENTITY_PROPERTIES: readonly ["name", "type"];
1281
+ type AIMessageRole = "user" | "assistant";
1175
1282
  /**
1176
- * Behavior properties - Protected for system attributes
1177
- * These affect business logic and data integrity.
1283
+ * An AI model available for selection by the user.
1284
+ * Configured on the backend and exposed via GET /agent/models.
1178
1285
  */
1179
- declare const BEHAVIOR_PROPERTIES: readonly ["required", "disabled", "hidden", "archived", "deprecated", "defaultValue", "config", "order", "unique"];
1286
+ interface AIAvailableModel {
1287
+ /** Model identifier (e.g. "claude-sonnet-4-6") */
1288
+ id: string;
1289
+ /** Provider name (e.g. "anthropic", "google") */
1290
+ provider: string;
1291
+ /** Display label (e.g. "Claude 4.6 Sonnet") */
1292
+ label: string;
1293
+ /** Whether this is the default model */
1294
+ isDefault?: boolean;
1295
+ }
1180
1296
  /**
1181
- * Presentation properties - Always modifiable
1182
- * These only affect display, not logic.
1297
+ * Tool call status during execution
1183
1298
  */
1184
- declare const PRESENTATION_PROPERTIES: readonly ["label", "description", "placeholder", "icon"];
1185
-
1299
+ type AIToolCallStatus = "pending" | "running" | "streaming" | "success" | "error";
1186
1300
  /**
1187
- * Type of resource that can be audited
1301
+ * Tool call information for chat UI
1188
1302
  */
1189
- type AuditResourceType = "record" | "object" | "attribute" | "user" | "role" | "settings" | "file";
1303
+ interface AIToolCall {
1304
+ /** Unique tool call ID */
1305
+ id: string;
1306
+ /** Tool name */
1307
+ name: string;
1308
+ /** Tool arguments */
1309
+ args?: Record<string, unknown>;
1310
+ /** Tool result (when complete) */
1311
+ result?: unknown;
1312
+ /** Error message if failed */
1313
+ error?: string;
1314
+ /** Execution status */
1315
+ status: AIToolCallStatus;
1316
+ }
1190
1317
  /**
1191
- * Actions that can be audited
1318
+ * Part type for message content
1192
1319
  */
1193
- type AuditAction = "record.created" | "record.updated" | "record.deleted" | "record.restored" | "object.created" | "object.updated" | "object.deleted" | "attribute.created" | "attribute.updated" | "attribute.deleted" | "user.created" | "user.invited" | "user.updated" | "user.deleted" | "user.login" | "user.logout" | "role.created" | "role.updated" | "role.deleted" | "role.assigned" | "role.revoked" | "settings.updated" | "file.uploaded" | "file.updated" | "file.deleted";
1320
+ type AIChatMessagePartType = "text" | "attachment" | "tool" | "thinking" | "reasoning" | "todo" | "question" | "error" | "approval" | "record" | "search-results" | (string & {});
1194
1321
  /**
1195
- * Actor type - who performed the action
1322
+ * Data for text part
1196
1323
  */
1197
- type AuditActorType = "user" | "system";
1324
+ interface TextPartData {
1325
+ text: string;
1326
+ isStreaming?: boolean;
1327
+ }
1198
1328
  /**
1199
- * Detail of a change on a field
1329
+ * Data for tool part (same as AIToolCall)
1200
1330
  */
1201
- interface AuditChange {
1202
- /** Field name that was changed */
1203
- field: string;
1204
- /** Previous value (undefined for new fields) */
1205
- oldValue: unknown;
1206
- /** New value (undefined for deleted fields) */
1207
- newValue: unknown;
1331
+ interface ToolPartData {
1332
+ id: string;
1333
+ name: string;
1334
+ args?: Record<string, unknown>;
1335
+ result?: unknown;
1336
+ error?: string;
1337
+ status: AIToolCallStatus;
1338
+ /** Raw JSON string accumulating during tool-input streaming (cleared on tool_input_end) */
1339
+ partialInput?: string;
1208
1340
  }
1209
1341
  /**
1210
- * Audit log entry - immutable record of an action
1342
+ * Data for thinking part
1211
1343
  */
1212
- interface AuditLogEntry {
1213
- id: Uuid;
1214
- tenantId: Uuid;
1215
- /** User profile ID of the actor (null for system actions) */
1216
- actorId?: string;
1217
- /** Denormalized email for search (in case user is deleted) */
1218
- actorEmail?: string;
1219
- /** Type of actor */
1220
- actorType: AuditActorType;
1221
- action: AuditAction;
1222
- resourceType: AuditResourceType;
1223
- resourceId: Uuid;
1224
- /** Human-readable label (record name, object label, etc.) */
1225
- resourceLabel?: string;
1226
- /** Object technical name (e.g., "companies", "contacts") */
1227
- objectName?: string;
1228
- /** Object UUID */
1229
- objectId?: Uuid;
1230
- changes?: AuditChange[];
1231
- /** Extra context (IP, user-agent, requestId, etc.) */
1232
- metadata?: Record<string, unknown>;
1233
- createdAt: Date;
1344
+ interface ThinkingPartData {
1345
+ isStreaming: boolean;
1346
+ startTime?: number;
1234
1347
  }
1235
1348
  /**
1236
- * Input for creating an audit log entry.
1237
- * Tenant ID is automatically set from execution context.
1349
+ * Data for reasoning part (Extended Thinking content)
1238
1350
  */
1239
- interface CreateAuditLogInput {
1240
- actorId?: string;
1241
- /** Denormalized actor email for display purposes. */
1242
- actorEmail?: string;
1243
- actorType?: AuditActorType;
1244
- action: AuditAction;
1245
- resourceType: AuditResourceType;
1246
- resourceId: string;
1247
- resourceLabel?: string;
1248
- objectName?: string;
1249
- objectId?: string;
1250
- changes?: AuditChange[];
1251
- metadata?: Record<string, unknown>;
1351
+ interface ReasoningPartData {
1352
+ /** Reasoning content (accumulated during streaming) */
1353
+ content: string;
1354
+ /** Whether reasoning is still streaming */
1355
+ isStreaming: boolean;
1356
+ /** Start timestamp for elapsed time display */
1357
+ startTime?: number;
1252
1358
  }
1253
1359
  /**
1254
- * Valid column names for sorting audit log entries.
1255
- * Maps to snake_case database column names used in Supabase queries.
1360
+ * A part of a chat message.
1361
+ * Parts are ordered chronologically as they arrive from the stream.
1256
1362
  */
1257
- type AuditSortField = "created_at" | "action" | "resource_type" | "actor_id" | "actor_email" | "object_name";
1363
+ interface AIChatMessagePart {
1364
+ /** Part type */
1365
+ type: AIChatMessagePartType;
1366
+ /** Unique part ID */
1367
+ id: string;
1368
+ /** Part-specific data */
1369
+ data: unknown;
1370
+ }
1258
1371
  /**
1259
- * Options for listing audit logs
1372
+ * Chat message for runtime/streaming.
1373
+ *
1374
+ * All content is represented as ordered parts (text, tools, thinking, etc.)
1375
+ * Parts are in chronological order as they arrive from the stream.
1376
+ *
1377
+ * Used in:
1378
+ * - useAgentChat hook
1379
+ * - AI chat UI components
1380
+ * - Stream processing
1260
1381
  */
1261
- interface AuditListOptions {
1262
- limit?: number;
1263
- offset?: number;
1264
- action?: AuditAction | AuditAction[];
1265
- resourceType?: AuditResourceType | AuditResourceType[];
1266
- objectName?: string;
1267
- actorId?: string;
1268
- from?: Date;
1269
- to?: Date;
1270
- sorts?: Array<{
1271
- field: AuditSortField;
1272
- direction: "asc" | "desc";
1273
- }>;
1382
+ interface AIChatMessage {
1383
+ /** Unique message ID */
1384
+ id: string;
1385
+ /** Message role */
1386
+ role: AIMessageRole;
1387
+ /** Ordered message parts (text, tools, thinking, etc.) */
1388
+ parts: AIChatMessagePart[];
1389
+ /** Whether the message is still streaming */
1390
+ isStreaming?: boolean;
1391
+ /** Message timestamp */
1392
+ timestamp?: Date;
1393
+ /** Error message if the message failed */
1394
+ error?: string;
1274
1395
  }
1275
1396
  /**
1276
- * Options for AuditService
1397
+ * Question types supported by the agent
1277
1398
  */
1278
- interface AuditServiceOptions {
1279
- /**
1280
- * If true, audit logging is async (fire-and-forget).
1281
- * Better performance but logs might be lost on crash.
1282
- * @default false
1283
- */
1284
- async?: boolean;
1285
- /**
1286
- * Batch size for async mode.
1287
- * Logs are buffered and flushed when batch is full or after flushIntervalMs.
1288
- * @default 10
1289
- */
1290
- batchSize?: number;
1291
- /**
1292
- * Flush interval in ms for async mode.
1293
- * @default 1000
1294
- */
1295
- flushIntervalMs?: number;
1296
- }
1297
-
1298
- type AgentRunStatus = "pending" | "running" | "completed" | "failed" | "cancelled" | "paused";
1299
- type AgentSessionStatus = "active" | "idle" | "completed" | "failed" | "cancelled" | "waiting_human" | "timeout" | "expired";
1300
- type AgentSessionMode = "interactive" | "autonomous";
1301
- type QuestionStatus = "pending" | "answered" | "timeout" | "cancelled";
1302
- type TriggerEventType = "record.created" | "record.updated" | "record.deleted" | "record.field_changed" | "form.submitted" | "agent.completed" | "webhook" | "schedule";
1303
- type AgentTriggerType = Extract<TriggerEventType, "record.created" | "record.updated" | "record.deleted">;
1304
- type ProviderName = "anthropic" | "openai" | "google" | "mistral";
1305
- interface ModelDefinition {
1306
- provider: ProviderName;
1307
- model: string;
1308
- maxTokens?: number;
1309
- }
1310
- interface RetryPolicy {
1311
- maxRetries: number;
1312
- backoffMs: number;
1313
- backoffMultiplier: number;
1314
- }
1315
- interface AgentExecutionConfig {
1316
- maxConcurrentRuns: number;
1317
- retryPolicy: RetryPolicy;
1318
- timeoutMs: number;
1319
- costLimitUsd?: number;
1320
- }
1399
+ type AIQuestionType = "text" | "choice" | "confirm" | "multiselect";
1321
1400
  /**
1322
- * Shared base config used by AgentDefinition, inline runs, and AgentSession.
1401
+ * Option for choice/multiselect questions
1323
1402
  */
1324
- interface AgentConfig {
1325
- systemPrompt: string;
1326
- model: ModelDefinition;
1327
- tools?: string[];
1328
- maxIterations?: number;
1329
- timeoutMs?: number;
1330
- canDelegate: boolean;
1331
- maxDepth: number;
1332
- maxTreeCostUsd?: number;
1333
- critic?: CriticConfig;
1334
- }
1335
- interface CriticConfig {
1336
- enabled: boolean;
1337
- model?: ModelDefinition;
1338
- systemPrompt?: string;
1339
- maxRetries?: number;
1340
- }
1341
- interface RecordAgentTrigger {
1342
- type: AgentTriggerType;
1343
- objectId: string;
1344
- filter?: Record<string, unknown>;
1345
- }
1346
- interface FormSubmittedAgentTrigger {
1347
- type: "form.submitted";
1348
- formId?: string;
1349
- formName?: string;
1350
- filter?: Record<string, unknown>;
1403
+ interface AIQuestionOption {
1404
+ value: string;
1405
+ label: string;
1406
+ description?: string;
1351
1407
  }
1352
- type AgentTrigger = RecordAgentTrigger | FormSubmittedAgentTrigger;
1353
1408
  /**
1354
- * Standalone trigger definition (replaces embedded AgentTrigger[]).
1355
- * Triggers are now first-class entities with their own lifecycle.
1409
+ * Question from the agent to the user
1356
1410
  */
1357
- interface AgentTriggerDefinition {
1358
- id: string;
1359
- tenantId: string;
1360
- definitionId: string;
1361
- name?: string;
1362
- eventType: TriggerEventType;
1363
- objectId?: string;
1364
- fieldPath?: string;
1365
- formDefinitionId?: string;
1366
- sourceAgentId?: string;
1367
- webhookPath?: string;
1368
- cronExpression?: string;
1369
- timezone?: string;
1370
- filter?: Record<string, unknown>;
1371
- inputBuilder?: string;
1372
- enabled: boolean;
1373
- createdAt: Date;
1374
- updatedAt: Date;
1375
- }
1376
- interface AgentSchedule {
1377
- cron: string;
1378
- timezone?: string;
1379
- enabled: boolean;
1380
- input?: Record<string, unknown>;
1381
- inputBuilder?: string;
1382
- }
1383
- interface AgentMessageAttachment {
1384
- id: string;
1385
- name: string;
1386
- mimeType: string;
1387
- size: number;
1388
- url?: string;
1389
- }
1390
- interface TimeoutPolicy {
1391
- timeoutMs: number;
1392
- action: "cancel" | "auto_decide" | "escalate";
1393
- fallbackValue?: unknown;
1394
- }
1395
- interface AgentDefinition {
1411
+ interface AIQuestion {
1412
+ /** Unique question ID */
1396
1413
  id: string;
1397
- tenantId: string;
1398
- name: string;
1399
- icon?: string;
1400
- description?: string;
1401
- systemPrompt: string;
1402
- model: ModelDefinition;
1403
- tools?: string[];
1404
- maxIterations?: number;
1405
- schedule?: AgentSchedule;
1406
- triggers?: AgentTrigger[];
1407
- config: AgentExecutionConfig;
1408
- createdBy: string;
1409
- createdAt: Date;
1410
- updatedAt: Date;
1411
- deletedAt?: Date;
1412
- canDelegate?: boolean;
1413
- maxDepth?: number;
1414
- maxTreeCostUsd?: number;
1415
- critic?: CriticConfig;
1416
- autoDecide?: boolean;
1417
- fileIds?: string[];
1418
- attachments?: File[];
1414
+ /** Question type */
1415
+ type: AIQuestionType;
1416
+ /** Question text */
1417
+ question: string;
1418
+ /** Options for choice/multiselect */
1419
+ options?: AIQuestionOption[];
1420
+ /** Placeholder for text input */
1421
+ placeholder?: string;
1422
+ /** Whether answer is required */
1423
+ required?: boolean;
1424
+ /** Min selections for multiselect */
1425
+ minSelections?: number;
1426
+ /** Max selections for multiselect */
1427
+ maxSelections?: number;
1419
1428
  }
1420
- interface AgentRun {
1421
- id: string;
1422
- definitionId?: string;
1423
- parentRunId?: string;
1424
- depth: number;
1425
- inlineConfig?: AgentConfig;
1426
- tenantId: string;
1427
- createdBy?: string;
1428
- status: AgentRunStatus;
1429
- retryCount: number;
1430
- input: Record<string, unknown>;
1431
- output?: Record<string, unknown>;
1432
- error?: string;
1433
- tokenUsage?: {
1434
- input: number;
1435
- output: number;
1436
- };
1437
- costUsd?: number;
1438
- startedAt?: Date;
1439
- completedAt?: Date;
1440
- createdAt: Date;
1441
- sessionId?: string;
1442
- rootRunId?: string;
1443
- triggerId?: string;
1444
- treeCostUsd?: number;
1445
- effectiveSystemPrompt?: string;
1429
+ /**
1430
+ * Answer format for questions
1431
+ */
1432
+ type AIQuestionAnswer = {
1433
+ type: "text";
1434
+ value: string;
1435
+ } | {
1436
+ type: "choice";
1437
+ value: string;
1438
+ } | {
1439
+ type: "confirm";
1440
+ value: boolean;
1441
+ } | {
1442
+ type: "multiselect";
1443
+ value: string[];
1444
+ };
1445
+ /**
1446
+ * Option for batch questions
1447
+ */
1448
+ interface AIBatchQuestionOption {
1449
+ /** Value returned when selected */
1450
+ value: string;
1451
+ /** Display label */
1452
+ label: string;
1446
1453
  }
1447
- interface AgentSession {
1448
- id: string;
1449
- tenantId: string;
1450
- mode: AgentSessionMode;
1451
- status: AgentSessionStatus;
1452
- definitionId?: string;
1453
- inlineConfig?: AgentConfig;
1454
- parentSessionId?: string;
1455
- rootSessionId: string;
1456
- depth: number;
1457
- missionPrompt?: string;
1458
- treeCostUsd: number;
1459
- name?: string;
1460
- metadata?: Record<string, unknown>;
1461
- createdBy?: string;
1462
- createdAt: Date;
1463
- updatedAt: Date;
1464
- completedAt?: Date;
1465
- expiresAt?: Date;
1466
- archivedAt?: Date;
1454
+ /**
1455
+ * Question in a batch (for ask_questions tool)
1456
+ */
1457
+ interface AIBatchQuestion {
1458
+ /** Unique question ID */
1459
+ id: string;
1460
+ /** Question text to display */
1461
+ question: string;
1462
+ /** Predefined options (if provided, displayed as buttons) */
1463
+ options?: AIBatchQuestionOption[];
1464
+ /** Allow custom text input in addition to options */
1465
+ allowCustomAnswer?: boolean;
1466
+ /** Placeholder for custom input field */
1467
+ placeholder?: string;
1467
1468
  }
1468
1469
  /**
1469
- * Persisted message in an agent session.
1470
- * Unified type for both interactive and autonomous sessions.
1470
+ * Answer returned by the AgentQuestions widget
1471
1471
  */
1472
- interface AgentSessionMessage {
1473
- id: string;
1474
- sessionId: string;
1475
- tenantId?: string;
1476
- runId?: string;
1477
- role: "user" | "assistant" | "system" | "tool";
1478
- content: string;
1479
- attachments?: AgentMessageAttachment[];
1480
- mentions?: MentionReference[];
1481
- toolCalls?: AgentToolCall[];
1482
- model?: ModelDefinition;
1483
- reasoning?: string;
1484
- tokenUsage?: {
1485
- input: number;
1486
- output: number;
1487
- };
1488
- createdAt: Date;
1472
+ interface AIBatchQuestionAnswer {
1473
+ /** True if user skipped all questions */
1474
+ skipped: boolean;
1475
+ /** Map of question ID to answer value */
1476
+ answers: Record<string, string>;
1489
1477
  }
1490
- interface AgentToolCall {
1478
+ /**
1479
+ * Todo item status
1480
+ */
1481
+ type AITodoStatus = "pending" | "in_progress" | "completed" | "blocked";
1482
+ /**
1483
+ * Todo item in a task list
1484
+ */
1485
+ interface AITodoItem {
1491
1486
  id: string;
1492
- name: string;
1493
- arguments: Record<string, unknown>;
1494
- result?: unknown;
1495
- error?: string;
1496
- durationMs?: number;
1487
+ description: string;
1488
+ status: AITodoStatus;
1489
+ result?: string;
1490
+ updatedAt?: number;
1497
1491
  }
1498
- interface AgentContextEntry {
1499
- id: string;
1500
- rootRunId: string;
1501
- runId: string;
1502
- namespace: string;
1503
- key: string;
1504
- value: unknown;
1505
- createdAt: Date;
1506
- updatedAt: Date;
1492
+ /**
1493
+ * Todo list managed by the agent
1494
+ */
1495
+ interface AITodoList {
1496
+ items: AITodoItem[];
1497
+ progress: number;
1498
+ isComplete: boolean;
1507
1499
  }
1508
- interface AgentQuestion {
1500
+ /**
1501
+ * AI Usage Metrics record
1502
+ */
1503
+ interface AIUsageMetrics {
1509
1504
  id: string;
1510
- runId: string;
1511
- sessionId?: string;
1512
1505
  tenantId: string;
1513
- question: string;
1514
- options?: string[];
1515
- metadata?: Record<string, unknown>;
1516
- status: QuestionStatus;
1517
- response?: QuestionResponse;
1518
- timeoutPolicy?: TimeoutPolicy;
1519
- createdAt: Date;
1520
- answeredAt?: Date;
1521
- expiresAt?: Date;
1506
+ date: Date;
1507
+ requestCount: number;
1508
+ totalTokens: number;
1509
+ totalCost: number;
1510
+ providerBreakdown: Record<string, AIProviderMetrics>;
1511
+ toolUsage: Record<string, number>;
1522
1512
  }
1523
- interface QuestionResponse {
1524
- answer: unknown;
1525
- answeredBy?: string;
1526
- source: "user" | "auto_decide" | "timeout";
1513
+ /**
1514
+ * Provider-specific metrics
1515
+ */
1516
+ interface AIProviderMetrics {
1517
+ requests: number;
1518
+ tokens: number;
1519
+ cost: number;
1527
1520
  }
1528
- interface RecordAgentEvent {
1529
- type: AgentTriggerType;
1530
- objectId: string;
1531
- recordId: string;
1521
+ /**
1522
+ * Memory type for categorization
1523
+ *
1524
+ * - `soul`: Tenant identity and persona (admin-managed)
1525
+ * - `user`: Per-user facts and preferences
1526
+ * - `daily`: Auto-generated daily summaries
1527
+ * - `session`: Auto-generated conversation summaries
1528
+ */
1529
+ type AIMemoryType = "soul" | "user" | "daily" | "session";
1530
+ /**
1531
+ * Advanced memory entry for OpenClaw-style memory system
1532
+ */
1533
+ interface AIMemoryEntry {
1534
+ id: string;
1532
1535
  tenantId: string;
1533
- data?: Record<string, unknown>;
1536
+ userId: string | null;
1537
+ conversationId: string | null;
1538
+ type: AIMemoryType;
1539
+ content: string;
1540
+ embedding: number[] | null;
1541
+ importance: number;
1542
+ source: string;
1543
+ createdAt: Date;
1544
+ updatedAt: Date;
1545
+ expiresAt: Date | null;
1534
1546
  }
1535
- interface FormSubmittedAgentEvent {
1536
- type: "form.submitted";
1547
+ /**
1548
+ * Compaction summary for conversation history compression
1549
+ */
1550
+ interface AICompactionSummary {
1551
+ id: string;
1537
1552
  tenantId: string;
1538
- formId: string;
1539
- formName: string;
1540
- submissionId: string;
1541
- createdBy?: string;
1542
- createdRecordIds: Record<string, string>;
1543
- data: {
1544
- formId: string;
1545
- formName: string;
1546
- submissionId: string;
1547
- createdBy?: string;
1548
- createdRecordIds: Record<string, string>;
1549
- slotValues: Record<string, Record<string, unknown>>;
1550
- stepValues: Record<string, Record<string, unknown>>;
1551
- };
1552
- }
1553
- type AgentEvent = RecordAgentEvent | FormSubmittedAgentEvent;
1554
- interface AgentDashboard {
1555
- activeRuns: number;
1556
- pendingRuns: number;
1557
- failedToday: number;
1558
- completedToday: number;
1559
- totalCostToday: number;
1560
- totalCostWeek: number;
1553
+ userId: string;
1554
+ conversationId: string;
1555
+ summary: string;
1556
+ originalMessageCount: number;
1557
+ tokenCountBefore: number;
1558
+ tokenCountAfter: number;
1559
+ compactedAt: Date;
1561
1560
  }
1562
1561
 
1563
1562
  /**
@@ -2775,6 +2774,76 @@ interface InviteUserInput {
2775
2774
  redirectTo?: string;
2776
2775
  }
2777
2776
 
2777
+ interface AddAttributeInput {
2778
+ name: string;
2779
+ label: string;
2780
+ type: AttributeType;
2781
+ required?: boolean;
2782
+ unique?: boolean;
2783
+ description?: string;
2784
+ placeholder?: string;
2785
+ icon?: IconName;
2786
+ defaultValue?: unknown;
2787
+ metadata?: Record<string, unknown>;
2788
+ [key: string]: unknown;
2789
+ }
2790
+ interface CreateCustomObjectInput {
2791
+ name: string;
2792
+ label: string;
2793
+ pluralLabel?: string;
2794
+ labelExpression: string;
2795
+ description?: string;
2796
+ icon?: IconName;
2797
+ attributes?: (Attribute | {
2798
+ build: () => Attribute;
2799
+ })[];
2800
+ metadata?: Record<string, unknown>;
2801
+ }
2802
+ interface UpdateObjectInput {
2803
+ label?: string;
2804
+ pluralLabel?: string;
2805
+ description?: string;
2806
+ icon?: IconName;
2807
+ labelExpression?: string;
2808
+ metadata?: Record<string, unknown>;
2809
+ }
2810
+ interface CreateViewInput {
2811
+ objectName: string;
2812
+ type: ViewType;
2813
+ name: string;
2814
+ label: string;
2815
+ description?: string;
2816
+ icon?: IconName;
2817
+ config: ViewConfig;
2818
+ default?: boolean;
2819
+ metadata?: Record<string, unknown>;
2820
+ }
2821
+ interface UpdateViewInput {
2822
+ label?: string;
2823
+ description?: string;
2824
+ icon?: IconName;
2825
+ config?: ViewConfig;
2826
+ default?: boolean;
2827
+ metadata?: Record<string, unknown>;
2828
+ }
2829
+ interface RelationOption {
2830
+ id: string;
2831
+ objectId: string;
2832
+ objectName: string;
2833
+ objectLabel: string;
2834
+ objectIcon?: string;
2835
+ label: string;
2836
+ }
2837
+ interface RelationOptionsResponse {
2838
+ options: RelationOption[];
2839
+ hasMore: boolean;
2840
+ total: number;
2841
+ }
2842
+ interface StreamEventMessagePersisted {
2843
+ type: "message_persisted";
2844
+ message: AgentSessionMessage;
2845
+ }
2846
+
2778
2847
  /**
2779
2848
  * Utility functions for working with objects.
2780
2849
  * Provides type-safe helpers to avoid common anti-patterns like Object.keys().length checks.
@@ -5994,4 +6063,108 @@ declare class FormRegistry {
5994
6063
 
5995
6064
  declare const formRegistry: FormRegistry;
5996
6065
 
5997
- export { type AIAvailableModel, type AIBatchQuestion, type AIBatchQuestionAnswer, type AIBatchQuestionOption, type AIChatMessage, type AIChatMessagePart, type AIChatMessagePartType, type AICompactionSummary, type AIMemoryEntry, type AIMemoryType, type AIMessageRole, type AIProviderMetrics, type AIQuestion, type AIQuestionAnswer, type AIQuestionOption, type AIQuestionType, type AITodoItem, type AITodoList, type AITodoStatus, type AIToolCall, type AIToolCallStatus, type AIUsageMetrics, ALL_ACTIONS, ALL_SYSTEM_RESOURCES, AccessDeniedError, type AccessLevel, type Action, ActivityTabConfig, type AgentConfig, type AgentContextEntry, type AgentDashboard, type AgentDefinition, type AgentEvent, type AgentExecutionConfig, type AgentMessageAttachment, type AgentQuestion, type AgentRun, type AgentRunStatus, type AgentSchedule, type AgentSession, type AgentSessionMessage, type AgentSessionMode, type AgentSessionStatus, type AgentToolCall, type AgentTrigger, type AgentTriggerDefinition, type AgentTriggerType, type ApiKey, type ApiKeyAuthContext, type ApiKeyPermission, type ApiKeyWithSecret, type AssignRoleInput, Attribute, AttributeGroupField, AttributeInUseError, AttributeNotFoundError, AttributeType, type AttributeUsage, type AuditAction, type AuditActorType, type AuditChange, type AuditListOptions, type AuditLogEntry, type AuditResourceType, type AuditServiceOptions, type AuditSortField, BEHAVIOR_PROPERTIES, BilateralConfig, type BoundingBox, type BuilderConfig, CheckboxAttribute, CompletionStatus, ConcurrentModificationError, ConfigOverrides, type CreateApiKeyInput, type CreateAuditLogInput, type CreateDBAttribute, type CreateDBForm, type CreateDBFormSubmission, type CreateDBObject, type CreateDBView, type CreateDBViewOverlay, type CreateDocument, type CreateDocumentSlot, type CreateFile, CreateMode, type CreateObjectRecord, type CreatePermissionInput, type CreateProcessingJob, type CreateRoleInput, type CreateSandboxExecution, type CreateUserProfile, type CriticConfig, Currency, CurrencyAttribute, type CustomAttributeValue, CustomTabConfig, type DBAttribute, type DBForm, type DBFormSubmission, type DBObject, type DBView, type DBViewOverlay, DB_COLUMN_FIELDS, DEFAULT_ROLES, DEFAULT_ROLE_DESCRIPTIONS, DEFAULT_ROLE_LABELS, DEFAULT_ROLE_PERMISSIONS, DateAttribute, type DefaultRoleName, DetailViewBuilder, DetailViewConfig, DetailViewDefinition, DetailViewLayout, type Document, DocumentAttribute, type DocumentListOptions, type DocumentSlot, DocumentsTabConfig, DuplicateError, EMPTY_VALUE_PLACEHOLDER, type EffectivePermissions, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, FORM_FORBIDDEN_ATTRIBUTE_TYPES, FeatureFlagDefinition, FeatureFlagsRepository, FeatureGate, Field, FieldGroup, type File, FileAttribute, type FileListOptions, type FileVisibility, FilterState, FlagLevel, FlagRegistry, FlagService, FlagValueType, ForbiddenError, FormBuilder, type FormDefinition, type FormFieldRef, type FormFieldsRow, type FormFreeFieldRef, type FormHeadingRow, FormRegistry, type FormRow, FormRowBuilder, type FormSeparatorRow, type FormSlot, type FormSlotFieldRef, type FormStatus, type FormStep, FormStepBuilder, type FormSubmission, type FormSubmissionStatus, type FormSubmittedAgentEvent, type FormSubmittedAgentTrigger, type FormTextRow, FormulaAttribute, FormulaReturnType, type GeocodingAdapter, type GeocodingAutocompleteParams, type GeocodingParams, type GeocodingSuggestion, type GlobalSearchGroupedOptions, type GlobalSearchGroupedResult, type GlobalSearchOptions, type GlobalSearchResultItem, Group, GroupBuilder, IDENTITY_PROPERTIES, type InferAttributeValue, type InviteUserInput, type ListOptions, ListViewBuilder, ListViewConfig, ListViewDefinition, ListViewTab, ListViewTabConfigBuilder, Location, LocationAttribute, LocationGranularity, MemoryNotFoundError, type MentionEntityType, type MentionReference, type MentionedContext, type MentionedEntityContext, MigrationDefinition, type ModelDefinition, MultiRelationAttribute, MultiselectAttribute, NoopGeocodingAdapter, NotFoundError, NotImplementedError, NumberAttribute, ObjectBuilder, ObjectDefinition, ObjectNotFoundError, type ObjectPermissions, ObjectRecord, ObjectReferencedError, type OcrAdapter, type OcrInput, type OcrOptions, type OcrPage, type OcrResult, type OcrTextBlock, type OperationResult, Option, PRESENTATION_PROPERTIES, type Permission, type PermissionScope, Phone, PhoneAttribute, type PolicyContext, PolicyViolationError, type ProcessingJob, type ProcessingJobStatus, type ProcessingJobType, type ProcessingStatus, ProtectedResourceError, ProtectedRoleError, type ProviderName, type QuestionResponse, type QuestionStatus, RatingAttribute, type ReasoningPartData, type RecordAgentEvent, type RecordAgentTrigger, type RecordMetadata, RecordNotFoundError, type RecordPolicy, type RecordReference, RecordReferencedError, RelationAttribute, RelationGroup, RelationGroupBuilder, RelationTarget, RepositoryError, type RepositoryOperation, ResolvedFlag, type RetryPolicy, type ReverseGeocodingParams, RichtextAttribute, RichtextFeature, RichtextTabConfig, type Role, RoleNotFoundError, RollupAttribute, RollupFunction, STANDARD_SCHEMA_VENDOR, SYSTEM_ATTRIBUTES, SYSTEM_RESOURCES, SYSTEM_RESOURCE_LABELS, type SandboxExecution, type SandboxExecutionInput, type SandboxExecutionResult, type SandboxExecutionStatus, type SandboxMode, type SandboxTrigger, SchemaError, SchemaErrorCode, type SearchOptions, SelectAttribute, SidePanelConfig, SingleRelationAttribute, type SlotMode, type SlotStatus, SortRule, type StandardSchemaIssue, type StandardSchemaResult, StaticFlagDefault, StatusAttribute, StorageError, type StorageOperation, type StorageProvider, SyncError, type SystemAttribute, type SystemFields, type SystemPermissions, type SystemResource, Tab, TabBuilder, TableTab, TableTabConfig, TenantId, TextAreaAttribute, TextAttribute, type TextPartData, type ThinkingPartData, type TimeoutPolicy, Timestamps, type ToolPartData, type TriggerEventType, USER_STATUSES, type UpdateDBAttribute, type UpdateDBForm, type UpdateDBFormSubmission, type UpdateDBObject, type UpdateDBView, type UpdateDBViewOverlay, type UpdateDocument, type UpdateDocumentSlot, type UpdateFile, type UpdateProcessingJob, type UpdateRoleInput, type UpdateUserProfile, type UpsertDBAttribute, type UpsertDBObject, type UpsertDBView, UserAttribute, type UserProfile, type UserRoleAssignment, type UserStatus, Uuid, ValidationError, type ValidationErrorDetail, ViewConfig, ViewDefinition, ViewType, type WithCustomAttributes$1 as WithCustomAttributes, accessLevelToActions, actionsToAccessLevel, applyPipes, booleanFlag, checkbox, createFlagRegistry, createFlagService, createStandardSchemaProps, currency, date, detailView, document, extractAttributeNames, file, flagRegistry, form, formRegistry, formatAttributeValue, formula, generateDefaultDetailView, generateDefaultListView, getActiveTab, getErrorMessage, getSystemAttributeList, group, isAttributeInUseError, isDefaultRole, isEmptyObject, isFormDefinition, isFormFieldsRow, isFormFreeFieldRef, isFormHeadingRow, isFormSeparatorRow, isFormSlotFieldRef, isFormTextRow, isLabelExpression, isNotEmpty, isNotFoundError, isObjectReferencedError, isProtectedResourceError, isRecordReferencedError, isSchemaError, isStandardSchema, isValidationError, jsonFlag, listView, location, multiselect, number, numberFlag, object, phone, rating, registry, relation, relationGroup, renderLabelExpression, resetViewToDefault, richtext, rollup, select, status, stringFlag, text, textarea, toUndefinedIfEmpty, user, validateAttributeName, viewRegistry };
6066
+ /**
6067
+ * Event types emitted by write paths.
6068
+ * New types are added as handlers are implemented.
6069
+ */
6070
+ type EventType = "record.created" | "record.updated" | "record.deleted" | "record.restored" | "form.submitted";
6071
+ /**
6072
+ * Typed payload map — each event type has a specific data shape.
6073
+ */
6074
+ interface EventDataMap {
6075
+ "record.created": {
6076
+ objectId: string;
6077
+ objectName: string;
6078
+ recordId: string;
6079
+ values: Record<string, unknown>;
6080
+ };
6081
+ "record.updated": {
6082
+ objectId: string;
6083
+ objectName: string;
6084
+ recordId: string;
6085
+ /** Only the names of fields that changed */
6086
+ changedFields: string[];
6087
+ /** Only the changed fields' previous values */
6088
+ oldValues: Record<string, unknown>;
6089
+ /** Only the changed fields' new values */
6090
+ newValues: Record<string, unknown>;
6091
+ };
6092
+ "record.deleted": {
6093
+ objectId: string;
6094
+ objectName: string;
6095
+ recordId: string;
6096
+ };
6097
+ "record.restored": {
6098
+ objectId: string;
6099
+ objectName: string;
6100
+ recordId: string;
6101
+ };
6102
+ "form.submitted": {
6103
+ formId: string;
6104
+ formName: string;
6105
+ submissionId: string;
6106
+ createdBy: string | null;
6107
+ createdRecordIds: Record<string, string>;
6108
+ slotValues: Record<string, Record<string, unknown>>;
6109
+ stepValues: Record<string, Record<string, unknown>>;
6110
+ };
6111
+ }
6112
+ /**
6113
+ * A typed domain event.
6114
+ * The generic parameter T narrows `data` to the correct payload shape.
6115
+ */
6116
+ interface DomainEvent<T extends EventType = EventType> {
6117
+ id: string;
6118
+ type: T;
6119
+ tenantId: string;
6120
+ userId: string | null;
6121
+ timestamp: string;
6122
+ data: EventDataMap[T];
6123
+ }
6124
+
6125
+ interface FormulaResult {
6126
+ value: unknown;
6127
+ error?: string;
6128
+ }
6129
+ declare function evaluateFormula(expression: string, values: Record<string, unknown>): unknown;
6130
+ declare function evaluateFormulaWithResult(expression: string, values: Record<string, unknown>): FormulaResult;
6131
+ declare function formatFormulaResult(value: unknown, returnType: FormulaReturnType, decimals?: number): unknown;
6132
+ declare function evaluateFormulaAttribute(attr: FormulaAttribute, values: Record<string, unknown>): unknown;
6133
+ declare function validateFormulaExpression(expression: string): {
6134
+ valid: boolean;
6135
+ error?: string;
6136
+ };
6137
+ declare function extractFormulaVariables(expression: string): string[];
6138
+ declare function extractRelationReferences(expression: string): string[];
6139
+ declare function extractRelationNames(expression: string): string[];
6140
+ declare function hasRelationReferences(expression: string): boolean;
6141
+ declare function flattenRelationsForEval(resolvedRelations: Record<string, Record<string, unknown>>): Record<string, unknown>;
6142
+
6143
+ type PathSegmentType = "relation" | "attribute";
6144
+ type PathCardinality = "one" | "many";
6145
+ interface PathSegment {
6146
+ name: string;
6147
+ type: PathSegmentType;
6148
+ cardinality?: PathCardinality;
6149
+ targetObject?: string;
6150
+ }
6151
+ declare class InvalidPathError extends Error {
6152
+ readonly path: string;
6153
+ readonly segment: string;
6154
+ readonly reason: string;
6155
+ constructor(path: string, segment: string, reason: string);
6156
+ }
6157
+ declare class MaxDepthExceededError extends Error {
6158
+ readonly path: string;
6159
+ readonly maxDepth: number;
6160
+ constructor(path: string, maxDepth: number);
6161
+ }
6162
+ type SchemaResolver = (objectName: string) => Promise<ObjectDefinition | null>;
6163
+ declare function parsePath(path: string, startSchema: ObjectDefinition, getSchema: SchemaResolver, maxDepth?: number): Promise<PathSegment[]>;
6164
+ declare function validatePath(path: string, startSchema: ObjectDefinition, getSchema: SchemaResolver, maxDepth?: number): Promise<boolean>;
6165
+ declare function pathHasManyCardinality(segments: PathSegment[]): boolean;
6166
+ declare function getPathDepth(segments: PathSegment[]): number;
6167
+ declare function getTargetAttributeName(path: string): string;
6168
+ declare function getRelationPath(path: string): string | null;
6169
+
6170
+ export { type AIAvailableModel, type AIBatchQuestion, type AIBatchQuestionAnswer, type AIBatchQuestionOption, type AIChatMessage, type AIChatMessagePart, type AIChatMessagePartType, type AICompactionSummary, type AIMemoryEntry, type AIMemoryType, type AIMessageRole, type AIProviderMetrics, type AIQuestion, type AIQuestionAnswer, type AIQuestionOption, type AIQuestionType, type AITodoItem, type AITodoList, type AITodoStatus, type AIToolCall, type AIToolCallStatus, type AIUsageMetrics, ALL_ACTIONS, ALL_SYSTEM_RESOURCES, AccessDeniedError, type AccessLevel, type Action, ActivityTabConfig, type AddAttributeInput, type AgentConfig, type AgentContextEntry, type AgentDashboard, type AgentDefinition, type AgentEvent, type AgentExecutionConfig, type AgentMessageAttachment, type AgentQuestion, type AgentRun, type AgentRunStatus, type AgentSchedule, type AgentSession, type AgentSessionMessage, type AgentSessionMode, type AgentSessionStatus, type AgentToolCall, type AgentTrigger, type AgentTriggerDefinition, type AgentTriggerType, type ApiKey, type ApiKeyAuthContext, type ApiKeyPermission, type ApiKeyWithSecret, type AssignRoleInput, Attribute, AttributeGroupField, AttributeInUseError, AttributeNotFoundError, AttributeType, type AttributeUsage, type AuditAction, type AuditActorType, type AuditChange, type AuditListOptions, type AuditLogEntry, type AuditResourceType, type AuditServiceOptions, type AuditSortField, BEHAVIOR_PROPERTIES, BilateralConfig, type BoundingBox, type BuilderConfig, CheckboxAttribute, CompletionStatus, ConcurrentModificationError, ConfigOverrides, type CreateApiKeyInput, type CreateAuditLogInput, type CreateCustomObjectInput, type CreateDBAttribute, type CreateDBForm, type CreateDBFormSubmission, type CreateDBObject, type CreateDBView, type CreateDBViewOverlay, type CreateDocument, type CreateDocumentSlot, type CreateFile, CreateMode, type CreateObjectRecord, type CreatePermissionInput, type CreateProcessingJob, type CreateRoleInput, type CreateSandboxExecution, type CreateUserProfile, type CreateViewInput, type CriticConfig, Currency, CurrencyAttribute, type CustomAttributeValue, CustomTabConfig, type DBAttribute, type DBForm, type DBFormSubmission, type DBObject, type DBView, type DBViewOverlay, DB_COLUMN_FIELDS, DEFAULT_ROLES, DEFAULT_ROLE_DESCRIPTIONS, DEFAULT_ROLE_LABELS, DEFAULT_ROLE_PERMISSIONS, DateAttribute, type DefaultRoleName, DetailViewBuilder, DetailViewConfig, DetailViewDefinition, DetailViewLayout, type Document, DocumentAttribute, type DocumentListOptions, type DocumentSlot, DocumentsTabConfig, type DomainEvent, DuplicateError, EMPTY_VALUE_PLACEHOLDER, type EffectivePermissions, type EventDataMap, type EventType, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, FORM_FORBIDDEN_ATTRIBUTE_TYPES, FeatureFlagDefinition, FeatureFlagsRepository, FeatureGate, Field, FieldGroup, type File, FileAttribute, type FileListOptions, type FileVisibility, FilterState, FlagLevel, FlagRegistry, FlagService, FlagValueType, ForbiddenError, FormBuilder, type FormDefinition, type FormFieldRef, type FormFieldsRow, type FormFreeFieldRef, type FormHeadingRow, FormRegistry, type FormRow, FormRowBuilder, type FormSeparatorRow, type FormSlot, type FormSlotFieldRef, type FormStatus, type FormStep, FormStepBuilder, type FormSubmission, type FormSubmissionStatus, type FormSubmittedAgentEvent, type FormSubmittedAgentTrigger, type FormTextRow, FormulaAttribute, type FormulaResult, FormulaReturnType, type GeocodingAdapter, type GeocodingAutocompleteParams, type GeocodingParams, type GeocodingSuggestion, type GlobalSearchGroupedOptions, type GlobalSearchGroupedResult, type GlobalSearchOptions, type GlobalSearchResultItem, Group, GroupBuilder, IDENTITY_PROPERTIES, type InferAttributeValue, InvalidPathError, type InviteUserInput, type ListOptions, ListViewBuilder, ListViewConfig, ListViewDefinition, ListViewTab, ListViewTabConfigBuilder, Location, LocationAttribute, LocationGranularity, MaxDepthExceededError, MemoryNotFoundError, type MentionEntityType, type MentionReference, type MentionedContext, type MentionedEntityContext, MigrationDefinition, type ModelDefinition, MultiRelationAttribute, MultiselectAttribute, NoopGeocodingAdapter, NotFoundError, NotImplementedError, NumberAttribute, ObjectBuilder, ObjectDefinition, ObjectNotFoundError, type ObjectPermissions, ObjectRecord, ObjectReferencedError, type OcrAdapter, type OcrInput, type OcrOptions, type OcrPage, type OcrResult, type OcrTextBlock, type OperationResult, Option, PRESENTATION_PROPERTIES, type PathCardinality, type PathSegment, type PathSegmentType, type Permission, type PermissionScope, Phone, PhoneAttribute, type PolicyContext, PolicyViolationError, type ProcessingJob, type ProcessingJobStatus, type ProcessingJobType, type ProcessingStatus, ProtectedResourceError, ProtectedRoleError, type ProviderName, type QuestionResponse, type QuestionStatus, RatingAttribute, type ReasoningPartData, type RecordAgentEvent, type RecordAgentTrigger, type RecordMetadata, RecordNotFoundError, type RecordPolicy, type RecordReference, RecordReferencedError, RelationAttribute, RelationGroup, RelationGroupBuilder, type RelationOption, type RelationOptionsResponse, RelationTarget, RepositoryError, type RepositoryOperation, ResolvedFlag, type RetryPolicy, type ReverseGeocodingParams, RichtextAttribute, RichtextFeature, RichtextTabConfig, type Role, RoleNotFoundError, RollupAttribute, RollupFunction, STANDARD_SCHEMA_VENDOR, SYSTEM_ATTRIBUTES, SYSTEM_RESOURCES, SYSTEM_RESOURCE_LABELS, type SandboxExecution, type SandboxExecutionInput, type SandboxExecutionResult, type SandboxExecutionStatus, type SandboxMode, type SandboxTrigger, SchemaError, SchemaErrorCode, type SchemaResolver, type SearchOptions, SelectAttribute, SidePanelConfig, SingleRelationAttribute, type SlotMode, type SlotStatus, SortRule, type StandardSchemaIssue, type StandardSchemaResult, StaticFlagDefault, StatusAttribute, StorageError, type StorageOperation, type StorageProvider, type StreamEventMessagePersisted, SyncError, type SystemAttribute, type SystemFields, type SystemPermissions, type SystemResource, Tab, TabBuilder, TableTab, TableTabConfig, TenantId, TextAreaAttribute, TextAttribute, type TextPartData, type ThinkingPartData, type TimeoutPolicy, Timestamps, type ToolPartData, type TriggerEventType, USER_STATUSES, type UpdateDBAttribute, type UpdateDBForm, type UpdateDBFormSubmission, type UpdateDBObject, type UpdateDBView, type UpdateDBViewOverlay, type UpdateDocument, type UpdateDocumentSlot, type UpdateFile, type UpdateObjectInput, type UpdateProcessingJob, type UpdateRoleInput, type UpdateUserProfile, type UpdateViewInput, type UpsertDBAttribute, type UpsertDBObject, type UpsertDBView, UserAttribute, type UserProfile, type UserRoleAssignment, type UserStatus, Uuid, ValidationError, type ValidationErrorDetail, ViewConfig, ViewDefinition, ViewType, type WithCustomAttributes$1 as WithCustomAttributes, accessLevelToActions, actionsToAccessLevel, applyPipes, booleanFlag, checkbox, createFlagRegistry, createFlagService, createStandardSchemaProps, currency, date, detailView, document, evaluateFormula, evaluateFormulaAttribute, evaluateFormulaWithResult, extractAttributeNames, extractFormulaVariables, extractRelationNames, extractRelationReferences, file, flagRegistry, flattenRelationsForEval, form, formRegistry, formatAttributeValue, formatFormulaResult, formula, generateDefaultDetailView, generateDefaultListView, getActiveTab, getErrorMessage, getPathDepth, getRelationPath, getSystemAttributeList, getTargetAttributeName, group, hasRelationReferences, isAttributeInUseError, isDefaultRole, isEmptyObject, isFormDefinition, isFormFieldsRow, isFormFreeFieldRef, isFormHeadingRow, isFormSeparatorRow, isFormSlotFieldRef, isFormTextRow, isLabelExpression, isNotEmpty, isNotFoundError, isObjectReferencedError, isProtectedResourceError, isRecordReferencedError, isSchemaError, isStandardSchema, isValidationError, jsonFlag, listView, location, multiselect, number, numberFlag, object, parsePath, pathHasManyCardinality, phone, rating, registry, relation, relationGroup, renderLabelExpression, resetViewToDefault, richtext, rollup, select, status, stringFlag, text, textarea, toUndefinedIfEmpty, user, validateAttributeName, validateFormulaExpression, validatePath, viewRegistry };