@elevasis/ui 1.3.7 → 1.5.0

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.
Files changed (56) hide show
  1. package/dist/{CoreAuthKitInner-3J4RVQO6.js → CoreAuthKitInner-Y6LQYIPX.js} +1 -0
  2. package/dist/api/index.js +1 -0
  3. package/dist/auth/context.js +1 -0
  4. package/dist/auth/index.js +1 -0
  5. package/dist/charts/index.d.ts +96 -0
  6. package/dist/charts/index.js +384 -0
  7. package/dist/chunk-54S7KNJV.js +112 -0
  8. package/dist/{chunk-6IX5JZEH.js → chunk-G4TAF3T6.js} +166 -1
  9. package/dist/{chunk-Y2I5JJ3N.js → chunk-K3YVC5RW.js} +2 -2
  10. package/dist/chunk-KB5NKPTN.js +1455 -0
  11. package/dist/chunk-MLKGABMK.js +7 -0
  12. package/dist/{chunk-GIFAF5ZS.js → chunk-MS45MNFM.js} +6 -1
  13. package/dist/chunk-R56VC63S.js +129 -0
  14. package/dist/chunk-TYV5NJV2.js +1 -0
  15. package/dist/{chunk-JQLT6HBI.js → chunk-YJFTZUJJ.js} +22 -2
  16. package/dist/components/index.css +486 -0
  17. package/dist/components/index.d.ts +2047 -1
  18. package/dist/components/index.js +3350 -0
  19. package/dist/components/navigation/index.js +1 -0
  20. package/dist/execution/index.d.ts +15 -3
  21. package/dist/execution/index.js +2 -1
  22. package/dist/graph/index.js +2 -1
  23. package/dist/hooks/index.d.ts +270 -0
  24. package/dist/hooks/index.js +3 -2
  25. package/dist/hooks/published.d.ts +546 -2
  26. package/dist/hooks/published.js +3 -2
  27. package/dist/index.css +62 -0
  28. package/dist/index.d.ts +351 -4
  29. package/dist/index.js +12 -1038
  30. package/dist/initialization/index.d.ts +270 -0
  31. package/dist/initialization/index.js +1 -0
  32. package/dist/layout/index.css +44 -0
  33. package/dist/layout/index.d.ts +330 -0
  34. package/dist/layout/index.js +1440 -0
  35. package/dist/organization/index.js +1 -0
  36. package/dist/profile/index.d.ts +270 -0
  37. package/dist/profile/index.js +1 -0
  38. package/dist/provider/index.css +61 -0
  39. package/dist/provider/index.d.ts +54 -2
  40. package/dist/provider/index.js +5 -3
  41. package/dist/provider/published.d.ts +6 -0
  42. package/dist/provider/published.js +3 -2
  43. package/dist/router/context.js +1 -0
  44. package/dist/router/index.js +1 -0
  45. package/dist/sse/index.js +1 -1
  46. package/dist/supabase/index.d.ts +525 -0
  47. package/dist/supabase/index.js +1 -0
  48. package/dist/theme/index.d.ts +107 -0
  49. package/dist/theme/index.js +3 -0
  50. package/dist/typeform/index.js +1 -0
  51. package/dist/typeform/schemas.js +1 -0
  52. package/dist/types/index.d.ts +3664 -354
  53. package/dist/utils/index.js +1 -0
  54. package/package.json +64 -3
  55. package/dist/chunk-XXDDMASA.js +0 -170
  56. /package/dist/{chunk-BUZONXAW.js → chunk-ARQRKA6J.js} +0 -0
@@ -62,6 +62,12 @@ interface ExecutionPathContext$1 {
62
62
  executionPath: string[];
63
63
  }
64
64
  type WorkflowLogContext$1 = WorkflowExecutionContext$1 | WorkflowFailureContext$1 | StepStartedContext$1 | StepCompletedContext$1 | StepFailedContext$1 | ConditionalRouteContext$1 | ExecutionPathContext$1;
65
+ interface WorkflowLogMessage {
66
+ level: ExecutionLogLevel$1;
67
+ message: string;
68
+ timestamp: number;
69
+ context?: WorkflowLogContext$1;
70
+ }
65
71
 
66
72
  /**
67
73
  * Agent-specific logging types
@@ -217,7 +223,7 @@ type FormFieldType$1 = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' |
217
223
  /**
218
224
  * Serialized form field for API responses
219
225
  */
220
- interface SerializedFormField {
226
+ interface SerializedFormField$1 {
221
227
  name: string;
222
228
  label: string;
223
229
  type: FormFieldType$1;
@@ -235,16 +241,16 @@ interface SerializedFormField {
235
241
  /**
236
242
  * Serialized form schema for API responses
237
243
  */
238
- interface SerializedFormSchema {
244
+ interface SerializedFormSchema$1 {
239
245
  title?: string;
240
246
  description?: string;
241
- fields: SerializedFormField[];
247
+ fields: SerializedFormField$1[];
242
248
  layout?: 'vertical' | 'horizontal' | 'grid';
243
249
  }
244
250
  /**
245
251
  * Serialized execution form schema for API responses
246
252
  */
247
- interface SerializedExecutionFormSchema extends SerializedFormSchema {
253
+ interface SerializedExecutionFormSchema$1 extends SerializedFormSchema$1 {
248
254
  fieldMappings?: Record<string, string>;
249
255
  submitButton?: {
250
256
  label?: string;
@@ -255,7 +261,7 @@ interface SerializedExecutionFormSchema extends SerializedFormSchema {
255
261
  /**
256
262
  * Serialized schedule config for API responses
257
263
  */
258
- interface SerializedScheduleConfig {
264
+ interface SerializedScheduleConfig$1 {
259
265
  enabled: boolean;
260
266
  defaultSchedule?: string;
261
267
  allowedPatterns?: string[];
@@ -263,23 +269,23 @@ interface SerializedScheduleConfig {
263
269
  /**
264
270
  * Serialized webhook config for API responses
265
271
  */
266
- interface SerializedWebhookConfig {
272
+ interface SerializedWebhookConfig$1 {
267
273
  enabled: boolean;
268
274
  payloadSchema?: unknown;
269
275
  }
270
276
  /**
271
277
  * Serialized execution interface for API responses
272
278
  */
273
- interface SerializedExecutionInterface {
274
- form: SerializedExecutionFormSchema;
275
- schedule?: SerializedScheduleConfig;
276
- webhook?: SerializedWebhookConfig;
279
+ interface SerializedExecutionInterface$1 {
280
+ form: SerializedExecutionFormSchema$1;
281
+ schedule?: SerializedScheduleConfig$1;
282
+ webhook?: SerializedWebhookConfig$1;
277
283
  }
278
284
  /**
279
285
  * Serialized agent definition (JSON-safe)
280
286
  * Result of serializeDefinition(AgentDefinition)
281
287
  */
282
- interface SerializedAgentDefinition {
288
+ interface SerializedAgentDefinition$1 {
283
289
  config: {
284
290
  resourceId: string;
285
291
  name: string;
@@ -328,13 +334,13 @@ interface SerializedAgentDefinition {
328
334
  }>;
329
335
  };
330
336
  metricsConfig?: object;
331
- interface?: SerializedExecutionInterface;
337
+ interface?: SerializedExecutionInterface$1;
332
338
  }
333
339
  /**
334
340
  * Serialized workflow definition (JSON-safe)
335
341
  * Result of serializeDefinition(WorkflowDefinition)
336
342
  */
337
- interface SerializedWorkflowDefinition {
343
+ interface SerializedWorkflowDefinition$1 {
338
344
  config: {
339
345
  resourceId: string;
340
346
  name: string;
@@ -366,7 +372,33 @@ interface SerializedWorkflowDefinition {
366
372
  outputSchema?: object;
367
373
  };
368
374
  metricsConfig?: object;
369
- interface?: SerializedExecutionInterface;
375
+ interface?: SerializedExecutionInterface$1;
376
+ }
377
+
378
+ /**
379
+ * Workflow step state
380
+ * Aggregates step context events with timing and logs
381
+ */
382
+ interface StepState {
383
+ stepId: string;
384
+ stepName: string;
385
+ status: 'pending' | 'running' | 'completed' | 'failed';
386
+ startTime?: number;
387
+ endTime?: number;
388
+ duration?: number;
389
+ input?: unknown;
390
+ output?: unknown;
391
+ error?: unknown;
392
+ logs: WorkflowLogMessage[];
393
+ }
394
+ /**
395
+ * Complete workflow execution data for node visualization
396
+ * Parsed from execution logs
397
+ */
398
+ interface WorkflowNodeVisualizerData {
399
+ steps: StepState[];
400
+ totalDuration: number;
401
+ isRunning: boolean;
370
402
  }
371
403
 
372
404
  /**
@@ -378,13 +410,13 @@ interface SerializedWorkflowDefinition {
378
410
  * Use-case agnostic types that describe the purpose of each entry
379
411
  * Memory types mirror action types for clarity and filtering
380
412
  */
381
- type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'delegation-result' | 'error';
413
+ type MemoryEntryType$1 = 'context' | 'input' | 'reasoning' | 'tool-result' | 'delegation-result' | 'error';
382
414
  /**
383
415
  * Memory entry - represents a single entry in agent memory
384
416
  * Stored in agent memory, translated by adapters to vendor-specific formats
385
417
  */
386
- interface MemoryEntry {
387
- type: MemoryEntryType;
418
+ interface MemoryEntry$1 {
419
+ type: MemoryEntryType$1;
388
420
  content: string;
389
421
  timestamp: number;
390
422
  turnNumber: number | null;
@@ -394,20 +426,20 @@ interface MemoryEntry {
394
426
  * Agent memory - Self-orchestrated memory with session + working storage
395
427
  * Agent has full control over what persists, framework handles auto-compaction
396
428
  */
397
- interface AgentMemory {
429
+ interface AgentMemory$1 {
398
430
  /**
399
431
  * Session memory - Persists for session/conversation duration
400
432
  * Never auto-trimmed by framework
401
433
  * Agent-managed key-value store for critical information
402
434
  * Agent provides strings, framework wraps in MemoryEntry
403
435
  */
404
- sessionMemory: Record<string, MemoryEntry>;
436
+ sessionMemory: Record<string, MemoryEntry$1>;
405
437
  /**
406
438
  * Working memory - Execution history
407
439
  * Automatically compacted by framework when needed
408
440
  * Agent doesn't control compaction
409
441
  */
410
- history: MemoryEntry[];
442
+ history: MemoryEntry$1[];
411
443
  }
412
444
 
413
445
  type Json = string | number | boolean | null | {
@@ -1553,6 +1585,276 @@ type Database = {
1553
1585
  }
1554
1586
  ];
1555
1587
  };
1588
+ delivery_deliverables: {
1589
+ Row: {
1590
+ completed_at: string | null;
1591
+ created_at: string;
1592
+ description: string | null;
1593
+ due_date: string | null;
1594
+ engagement_id: string;
1595
+ file_url: string | null;
1596
+ id: string;
1597
+ metadata: Json | null;
1598
+ milestone_id: string | null;
1599
+ name: string;
1600
+ organization_id: string;
1601
+ status: string;
1602
+ type: string;
1603
+ updated_at: string;
1604
+ };
1605
+ Insert: {
1606
+ completed_at?: string | null;
1607
+ created_at?: string;
1608
+ description?: string | null;
1609
+ due_date?: string | null;
1610
+ engagement_id: string;
1611
+ file_url?: string | null;
1612
+ id?: string;
1613
+ metadata?: Json | null;
1614
+ milestone_id?: string | null;
1615
+ name: string;
1616
+ organization_id: string;
1617
+ status?: string;
1618
+ type?: string;
1619
+ updated_at?: string;
1620
+ };
1621
+ Update: {
1622
+ completed_at?: string | null;
1623
+ created_at?: string;
1624
+ description?: string | null;
1625
+ due_date?: string | null;
1626
+ engagement_id?: string;
1627
+ file_url?: string | null;
1628
+ id?: string;
1629
+ metadata?: Json | null;
1630
+ milestone_id?: string | null;
1631
+ name?: string;
1632
+ organization_id?: string;
1633
+ status?: string;
1634
+ type?: string;
1635
+ updated_at?: string;
1636
+ };
1637
+ Relationships: [
1638
+ {
1639
+ foreignKeyName: "delivery_deliverables_engagement_id_fkey";
1640
+ columns: ["engagement_id"];
1641
+ isOneToOne: false;
1642
+ referencedRelation: "delivery_engagements";
1643
+ referencedColumns: ["id"];
1644
+ },
1645
+ {
1646
+ foreignKeyName: "delivery_deliverables_milestone_id_fkey";
1647
+ columns: ["milestone_id"];
1648
+ isOneToOne: false;
1649
+ referencedRelation: "delivery_milestones";
1650
+ referencedColumns: ["id"];
1651
+ },
1652
+ {
1653
+ foreignKeyName: "delivery_deliverables_organization_id_fkey";
1654
+ columns: ["organization_id"];
1655
+ isOneToOne: false;
1656
+ referencedRelation: "organizations";
1657
+ referencedColumns: ["id"];
1658
+ }
1659
+ ];
1660
+ };
1661
+ delivery_engagements: {
1662
+ Row: {
1663
+ actual_end_date: string | null;
1664
+ client_company_id: string | null;
1665
+ contract_value: number | null;
1666
+ created_at: string;
1667
+ deal_id: string | null;
1668
+ description: string | null;
1669
+ id: string;
1670
+ metadata: Json | null;
1671
+ name: string;
1672
+ organization_id: string;
1673
+ start_date: string | null;
1674
+ status: string;
1675
+ target_end_date: string | null;
1676
+ updated_at: string;
1677
+ };
1678
+ Insert: {
1679
+ actual_end_date?: string | null;
1680
+ client_company_id?: string | null;
1681
+ contract_value?: number | null;
1682
+ created_at?: string;
1683
+ deal_id?: string | null;
1684
+ description?: string | null;
1685
+ id?: string;
1686
+ metadata?: Json | null;
1687
+ name: string;
1688
+ organization_id: string;
1689
+ start_date?: string | null;
1690
+ status?: string;
1691
+ target_end_date?: string | null;
1692
+ updated_at?: string;
1693
+ };
1694
+ Update: {
1695
+ actual_end_date?: string | null;
1696
+ client_company_id?: string | null;
1697
+ contract_value?: number | null;
1698
+ created_at?: string;
1699
+ deal_id?: string | null;
1700
+ description?: string | null;
1701
+ id?: string;
1702
+ metadata?: Json | null;
1703
+ name?: string;
1704
+ organization_id?: string;
1705
+ start_date?: string | null;
1706
+ status?: string;
1707
+ target_end_date?: string | null;
1708
+ updated_at?: string;
1709
+ };
1710
+ Relationships: [
1711
+ {
1712
+ foreignKeyName: "delivery_engagements_client_company_id_fkey";
1713
+ columns: ["client_company_id"];
1714
+ isOneToOne: false;
1715
+ referencedRelation: "acq_companies";
1716
+ referencedColumns: ["id"];
1717
+ },
1718
+ {
1719
+ foreignKeyName: "delivery_engagements_deal_id_fkey";
1720
+ columns: ["deal_id"];
1721
+ isOneToOne: false;
1722
+ referencedRelation: "acq_deals";
1723
+ referencedColumns: ["id"];
1724
+ },
1725
+ {
1726
+ foreignKeyName: "delivery_engagements_organization_id_fkey";
1727
+ columns: ["organization_id"];
1728
+ isOneToOne: false;
1729
+ referencedRelation: "organizations";
1730
+ referencedColumns: ["id"];
1731
+ }
1732
+ ];
1733
+ };
1734
+ delivery_milestones: {
1735
+ Row: {
1736
+ checklist: Json | null;
1737
+ completed_at: string | null;
1738
+ created_at: string;
1739
+ description: string | null;
1740
+ due_date: string | null;
1741
+ engagement_id: string;
1742
+ id: string;
1743
+ metadata: Json | null;
1744
+ name: string;
1745
+ organization_id: string;
1746
+ sequence: number;
1747
+ status: string;
1748
+ updated_at: string;
1749
+ };
1750
+ Insert: {
1751
+ checklist?: Json | null;
1752
+ completed_at?: string | null;
1753
+ created_at?: string;
1754
+ description?: string | null;
1755
+ due_date?: string | null;
1756
+ engagement_id: string;
1757
+ id?: string;
1758
+ metadata?: Json | null;
1759
+ name: string;
1760
+ organization_id: string;
1761
+ sequence?: number;
1762
+ status?: string;
1763
+ updated_at?: string;
1764
+ };
1765
+ Update: {
1766
+ checklist?: Json | null;
1767
+ completed_at?: string | null;
1768
+ created_at?: string;
1769
+ description?: string | null;
1770
+ due_date?: string | null;
1771
+ engagement_id?: string;
1772
+ id?: string;
1773
+ metadata?: Json | null;
1774
+ name?: string;
1775
+ organization_id?: string;
1776
+ sequence?: number;
1777
+ status?: string;
1778
+ updated_at?: string;
1779
+ };
1780
+ Relationships: [
1781
+ {
1782
+ foreignKeyName: "delivery_milestones_engagement_id_fkey";
1783
+ columns: ["engagement_id"];
1784
+ isOneToOne: false;
1785
+ referencedRelation: "delivery_engagements";
1786
+ referencedColumns: ["id"];
1787
+ },
1788
+ {
1789
+ foreignKeyName: "delivery_milestones_organization_id_fkey";
1790
+ columns: ["organization_id"];
1791
+ isOneToOne: false;
1792
+ referencedRelation: "organizations";
1793
+ referencedColumns: ["id"];
1794
+ }
1795
+ ];
1796
+ };
1797
+ delivery_notes: {
1798
+ Row: {
1799
+ content: string;
1800
+ created_at: string;
1801
+ created_by: string | null;
1802
+ engagement_id: string;
1803
+ id: string;
1804
+ metadata: Json | null;
1805
+ occurred_at: string;
1806
+ organization_id: string;
1807
+ summary: string | null;
1808
+ type: string;
1809
+ };
1810
+ Insert: {
1811
+ content: string;
1812
+ created_at?: string;
1813
+ created_by?: string | null;
1814
+ engagement_id: string;
1815
+ id?: string;
1816
+ metadata?: Json | null;
1817
+ occurred_at?: string;
1818
+ organization_id: string;
1819
+ summary?: string | null;
1820
+ type?: string;
1821
+ };
1822
+ Update: {
1823
+ content?: string;
1824
+ created_at?: string;
1825
+ created_by?: string | null;
1826
+ engagement_id?: string;
1827
+ id?: string;
1828
+ metadata?: Json | null;
1829
+ occurred_at?: string;
1830
+ organization_id?: string;
1831
+ summary?: string | null;
1832
+ type?: string;
1833
+ };
1834
+ Relationships: [
1835
+ {
1836
+ foreignKeyName: "delivery_notes_created_by_fkey";
1837
+ columns: ["created_by"];
1838
+ isOneToOne: false;
1839
+ referencedRelation: "users";
1840
+ referencedColumns: ["id"];
1841
+ },
1842
+ {
1843
+ foreignKeyName: "delivery_notes_engagement_id_fkey";
1844
+ columns: ["engagement_id"];
1845
+ isOneToOne: false;
1846
+ referencedRelation: "delivery_engagements";
1847
+ referencedColumns: ["id"];
1848
+ },
1849
+ {
1850
+ foreignKeyName: "delivery_notes_organization_id_fkey";
1851
+ columns: ["organization_id"];
1852
+ isOneToOne: false;
1853
+ referencedRelation: "organizations";
1854
+ referencedColumns: ["id"];
1855
+ }
1856
+ ];
1857
+ };
1556
1858
  deployments: {
1557
1859
  Row: {
1558
1860
  compiled_docs: Json | null;
@@ -2483,6 +2785,9 @@ type Tables<DefaultSchemaTableNameOrOptions extends keyof (DefaultSchema["Tables
2483
2785
  } ? R : never : never;
2484
2786
 
2485
2787
  type SupabaseUserProfile = Tables<'users'>;
2788
+ type SupabaseApiKey = Tables<'api_keys'>;
2789
+ /** API response type for API key list items (omits sensitive key_hash) */
2790
+ type ApiKeyListItem = Omit<SupabaseApiKey, 'key_hash'>;
2486
2791
 
2487
2792
  /**
2488
2793
  * Origin resource type - where an execution/task originated from.
@@ -2509,8 +2814,8 @@ interface ScheduleOriginTracking {
2509
2814
  originResourceType?: OriginResourceType$1;
2510
2815
  originResourceId?: string;
2511
2816
  }
2512
- type TaskScheduleConfig = RecurringScheduleConfig | RelativeScheduleConfig | AbsoluteScheduleConfig;
2513
- interface RecurringScheduleConfig {
2817
+ type TaskScheduleConfig = RecurringScheduleConfig$1 | RelativeScheduleConfig$1 | AbsoluteScheduleConfig$1;
2818
+ interface RecurringScheduleConfig$1 {
2514
2819
  type: 'recurring';
2515
2820
  cron?: string;
2516
2821
  interval?: 'daily' | 'weekly' | 'monthly';
@@ -2520,24 +2825,24 @@ interface RecurringScheduleConfig {
2520
2825
  endAt?: string | null;
2521
2826
  overduePolicy?: 'skip' | 'execute';
2522
2827
  }
2523
- interface RelativeScheduleConfig {
2828
+ interface RelativeScheduleConfig$1 {
2524
2829
  type: 'relative';
2525
2830
  anchorAt: string;
2526
2831
  anchorLabel?: string;
2527
- items: RelativeScheduleItem[];
2832
+ items: RelativeScheduleItem$1[];
2528
2833
  overduePolicy?: 'skip' | 'execute';
2529
2834
  }
2530
- interface RelativeScheduleItem {
2835
+ interface RelativeScheduleItem$1 {
2531
2836
  offset: string;
2532
2837
  payload: Record<string, unknown>;
2533
2838
  label?: string;
2534
2839
  }
2535
- interface AbsoluteScheduleConfig {
2840
+ interface AbsoluteScheduleConfig$1 {
2536
2841
  type: 'absolute';
2537
- items: AbsoluteScheduleItem[];
2842
+ items: AbsoluteScheduleItem$1[];
2538
2843
  overduePolicy?: 'skip' | 'execute';
2539
2844
  }
2540
- interface AbsoluteScheduleItem {
2845
+ interface AbsoluteScheduleItem$1 {
2541
2846
  runAt: string;
2542
2847
  payload: Record<string, unknown>;
2543
2848
  label?: string;
@@ -2560,7 +2865,7 @@ interface TaskSchedule extends ScheduleOriginTracking {
2560
2865
  updatedAt: Date;
2561
2866
  }
2562
2867
 
2563
- type MessageType = MessageEvent['type'];
2868
+ type MessageType = MessageEvent$1['type'];
2564
2869
  /**
2565
2870
  * Session Data Transfer Object (DTO)
2566
2871
  * Transform type for API responses (snake_case DB → camelCase frontend)
@@ -2574,7 +2879,7 @@ interface SessionDTO {
2574
2879
  turnCount: number;
2575
2880
  isEnded: boolean;
2576
2881
  title?: string | null;
2577
- memorySnapshot?: AgentMemory;
2882
+ memorySnapshot?: AgentMemory$1;
2578
2883
  metadata?: Record<string, unknown> | null;
2579
2884
  createdAt: Date;
2580
2885
  updatedAt: Date;
@@ -2585,7 +2890,7 @@ interface ChatMessage {
2585
2890
  role: 'user' | 'assistant';
2586
2891
  messageType: MessageType;
2587
2892
  text: string;
2588
- metadata?: MessageEvent;
2893
+ metadata?: MessageEvent$1;
2589
2894
  turnNumber: number;
2590
2895
  messageIndex?: number;
2591
2896
  createdAt: Date;
@@ -2657,6 +2962,29 @@ interface UserConfig {
2657
2962
  };
2658
2963
  }
2659
2964
 
2965
+ /**
2966
+ * Memberships Domain - Zod Validation Schemas
2967
+ *
2968
+ * Validation schemas for membership management endpoints.
2969
+ * Includes request bodies, query params, and path params.
2970
+ *
2971
+ * Security:
2972
+ * - All schemas use .strict() to prevent mass assignment attacks
2973
+ * - UUID validation prevents invalid references
2974
+ * - Role enum validation prevents privilege escalation
2975
+ * - organizationId never accepted in body (from JWT when needed)
2976
+ */
2977
+
2978
+ /**
2979
+ * Membership status validation
2980
+ * Note: Database constraint only allows 'active' | 'inactive'
2981
+ */
2982
+ declare const MembershipStatusSchema: z.ZodEnum<{
2983
+ active: "active";
2984
+ inactive: "inactive";
2985
+ }>;
2986
+ type MembershipStatus = z.infer<typeof MembershipStatusSchema>;
2987
+
2660
2988
  /**
2661
2989
  * Organization Membership types based on WorkOS API
2662
2990
  */
@@ -2672,6 +3000,15 @@ interface OrganizationMembership {
2672
3000
  createdAt: string;
2673
3001
  updatedAt: string;
2674
3002
  }
3003
+ interface ListMembershipsParams {
3004
+ userId?: string;
3005
+ organizationId?: string;
3006
+ statuses?: MembershipStatus[];
3007
+ limit?: number;
3008
+ before?: string;
3009
+ after?: string;
3010
+ order?: 'asc' | 'desc';
3011
+ }
2675
3012
  /**
2676
3013
  * Extended membership with user and organization details for UI
2677
3014
  */
@@ -2709,7 +3046,7 @@ interface MembershipWithDetails extends OrganizationMembership {
2709
3046
  * Structured action metadata attached to assistant messages.
2710
3047
  * Frontend reads this instead of parsing text prefixes.
2711
3048
  */
2712
- type AssistantAction = {
3049
+ type AssistantAction$1 = {
2713
3050
  kind: 'navigate';
2714
3051
  path: string;
2715
3052
  reason: string;
@@ -2719,13 +3056,13 @@ type AssistantAction = {
2719
3056
  statusFilter: string | null;
2720
3057
  searchQuery: string | null;
2721
3058
  };
2722
- type MessageEvent = {
3059
+ type MessageEvent$1 = {
2723
3060
  type: 'user_message';
2724
3061
  text: string;
2725
3062
  } | {
2726
3063
  type: 'assistant_message';
2727
3064
  text: string;
2728
- _action?: AssistantAction;
3065
+ _action?: AssistantAction$1;
2729
3066
  } | {
2730
3067
  type: 'agent:started';
2731
3068
  } | {
@@ -2756,7 +3093,7 @@ type MessageEvent = {
2756
3093
  * AgentConfig and WorkflowConfig now extend ResourceDefinition directly.
2757
3094
  * See packages/core/src/registry/types.ts for the base interface definition.
2758
3095
  */
2759
- type AIResourceDefinition = SerializedWorkflowDefinition | SerializedAgentDefinition;
3096
+ type AIResourceDefinition = SerializedWorkflowDefinition$1 | SerializedAgentDefinition$1;
2760
3097
 
2761
3098
  /**
2762
3099
  * Resource Registry type definitions
@@ -2765,17 +3102,17 @@ type AIResourceDefinition = SerializedWorkflowDefinition | SerializedAgentDefini
2765
3102
  /**
2766
3103
  * Environment/deployment status for resources
2767
3104
  */
2768
- type ResourceStatus = 'dev' | 'prod';
3105
+ type ResourceStatus$1 = 'dev' | 'prod';
2769
3106
  /**
2770
3107
  * All resource types in the platform
2771
3108
  * Used as the discriminator field in ResourceDefinition
2772
3109
  */
2773
- type ResourceType = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human';
3110
+ type ResourceType$1 = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human';
2774
3111
  /**
2775
3112
  * Base interface for ALL platform resources
2776
3113
  * Shared by both executable (agents, workflows) and non-executable (triggers, integrations, etc.) resources
2777
3114
  */
2778
- interface ResourceDefinition {
3115
+ interface ResourceDefinition$1 {
2779
3116
  /** Unique resource identifier */
2780
3117
  resourceId: string;
2781
3118
  /** Display name */
@@ -2785,11 +3122,11 @@ interface ResourceDefinition {
2785
3122
  /** Version for change tracking and evolution */
2786
3123
  version: string;
2787
3124
  /** Resource type discriminator */
2788
- type: ResourceType;
3125
+ type: ResourceType$1;
2789
3126
  /** Environment/deployment status */
2790
- status: ResourceStatus;
3127
+ status: ResourceStatus$1;
2791
3128
  /** Domain tags for filtering and organization */
2792
- domains?: ResourceDomain[];
3129
+ domains?: ResourceDomain$1[];
2793
3130
  /** Whether the agent supports multi-turn sessions (agents only) */
2794
3131
  sessionCapable?: boolean;
2795
3132
  /** Whether the resource is local (monorepo) or remote (externally deployed) */
@@ -2803,7 +3140,7 @@ interface ResourceDefinition {
2803
3140
  * Centralized domain constants and definitions for all organization resources.
2804
3141
  */
2805
3142
 
2806
- declare const DOMAINS: {
3143
+ declare const DOMAINS$1: {
2807
3144
  readonly INBOUND_PIPELINE: "inbound-pipeline";
2808
3145
  readonly LEAD_GEN_PIPELINE: "lead-gen-pipeline";
2809
3146
  readonly SUPPORT: "support";
@@ -2823,28 +3160,49 @@ declare const DOMAINS: {
2823
3160
  * ResourceDomain - Strongly typed domain identifier
2824
3161
  * Use this type for all domain references to ensure compile-time validation.
2825
3162
  */
2826
- type ResourceDomain = (typeof DOMAINS)[keyof typeof DOMAINS];
3163
+ type ResourceDomain$1 = (typeof DOMAINS$1)[keyof typeof DOMAINS$1];
2827
3164
 
2828
3165
  type ExecutionStatus$1 = 'pending' | 'running' | 'completed' | 'failed' | 'warning';
2829
- interface APIExecutionSummary {
3166
+ interface APIExecutionSummary$1 {
2830
3167
  id: string;
2831
3168
  status: ExecutionStatus$1;
2832
3169
  startTime: number;
2833
3170
  endTime?: number;
2834
- resourceStatus?: ResourceStatus;
3171
+ resourceStatus?: ResourceStatus$1;
2835
3172
  }
2836
- interface APIExecutionDetail extends APIExecutionSummary {
3173
+ interface APIExecutionDetail extends APIExecutionSummary$1 {
2837
3174
  executionLogs: ExecutionLogMessage$1[];
2838
3175
  input?: unknown;
2839
3176
  result?: unknown;
2840
3177
  error?: string;
2841
- resourceStatus: ResourceStatus;
3178
+ resourceStatus: ResourceStatus$1;
2842
3179
  apiVersion?: string | null;
2843
3180
  resourceVersion?: string | null;
2844
3181
  sdkVersion?: string | null;
2845
3182
  }
2846
3183
  interface APIExecutionListResponse {
2847
- executions: APIExecutionSummary[];
3184
+ executions: APIExecutionSummary$1[];
3185
+ }
3186
+
3187
+ /**
3188
+ * Deployment types — browser-safe
3189
+ *
3190
+ * Canonical API response types for the deployment resource.
3191
+ * The API's transformRow converts snake_case DB columns to these camelCase fields.
3192
+ */
3193
+ type DeploymentStatus = 'deploying' | 'active' | 'failed' | 'rolled_back' | 'stopped';
3194
+ interface Deployment {
3195
+ id: string;
3196
+ organizationId: string;
3197
+ status: DeploymentStatus;
3198
+ sdkVersion: string;
3199
+ deploymentVersion: string | null;
3200
+ port: number | null;
3201
+ pid: number | null;
3202
+ tarballPath: string | null;
3203
+ errorMessage: string | null;
3204
+ createdAt: string;
3205
+ updatedAt: string;
2848
3206
  }
2849
3207
 
2850
3208
  /**
@@ -3094,22 +3452,96 @@ interface AgentToolCallEvent {
3094
3452
  type AgentLogContext = AgentLifecycleEvent | AgentIterationEvent | AgentToolCallEvent
3095
3453
 
3096
3454
  /**
3097
- * Base execution logger for Execution Engine
3455
+ * Data for lifecycle 'started' events
3098
3456
  */
3099
- type ExecutionLogLevel = 'debug' | 'info' | 'warn' | 'error'
3100
-
3101
-
3102
- // Union type for all contexts
3103
- type LogContext = WorkflowLogContext | AgentLogContext
3457
+ interface AgentLifecycleStartedData {
3458
+ startTime: number
3459
+ iteration?: number
3460
+ }
3104
3461
 
3105
- // Updated interface with consolidated context
3106
- interface ExecutionLogMessage {
3107
- level: ExecutionLogLevel
3462
+ /**
3463
+ * Data for lifecycle 'completed' events
3464
+ */
3465
+ interface AgentLifecycleCompletedData {
3466
+ startTime: number
3467
+ endTime: number
3468
+ duration: number
3469
+ iteration?: number
3470
+ attempts?: number
3471
+ memorySize?: {
3472
+ sessionMemoryKeys: number
3473
+ historyEntries: number
3474
+ }
3475
+ }
3476
+
3477
+ /**
3478
+ * Data for lifecycle 'failed' events
3479
+ */
3480
+ interface AgentLifecycleFailedData {
3481
+ startTime: number
3482
+ endTime: number
3483
+ duration: number
3484
+ error: string
3485
+ iteration?: number
3486
+ }
3487
+
3488
+ /**
3489
+ * Scoped logger for agent execution
3490
+ * Captures logger and agentId to eliminate repetitive parameter passing
3491
+ *
3492
+ * Type-safe lifecycle logging with stage-specific required fields
3493
+ */
3494
+ interface AgentScopedLogger {
3495
+ lifecycle(lifecycle: AgentLifecycle, stage: 'started', data: AgentLifecycleStartedData): void
3496
+ lifecycle(lifecycle: AgentLifecycle, stage: 'completed', data: AgentLifecycleCompletedData): void
3497
+ lifecycle(lifecycle: AgentLifecycle, stage: 'failed', data: AgentLifecycleFailedData): void
3498
+ reasoning(output: string, iteration: number, startTime: number, endTime: number, duration: number): void
3499
+ action(
3500
+ actionType: string,
3501
+ message: string,
3502
+ iteration: number,
3503
+ startTime: number,
3504
+ endTime: number,
3505
+ duration: number
3506
+ ): void
3507
+ toolCall(
3508
+ toolName: string,
3509
+ iteration: number,
3510
+ startTime: number,
3511
+ endTime: number,
3512
+ duration: number,
3513
+ success: boolean,
3514
+ error?: string,
3515
+ input?: unknown,
3516
+ output?: unknown
3517
+ ): void
3518
+ }
3519
+
3520
+ /**
3521
+ * Base execution logger for Execution Engine
3522
+ */
3523
+ type ExecutionLogLevel = 'debug' | 'info' | 'warn' | 'error'
3524
+
3525
+
3526
+ // Union type for all contexts
3527
+ type LogContext = WorkflowLogContext | AgentLogContext
3528
+
3529
+ // Updated interface with consolidated context
3530
+ interface ExecutionLogMessage {
3531
+ level: ExecutionLogLevel
3108
3532
  message: string
3109
3533
  timestamp: number
3110
3534
  context?: LogContext
3111
3535
  }
3112
3536
 
3537
+ // Logger interface - any logger implementation must satisfy this
3538
+ interface IExecutionLogger {
3539
+ debug(message: string, context?: LogContext): void
3540
+ info(message: string, context?: LogContext): void
3541
+ warn(message: string, context?: LogContext): void
3542
+ error(message: string, context?: LogContext): void
3543
+ }
3544
+
3113
3545
  /**
3114
3546
  * Shared form field types for dynamic form generation
3115
3547
  * Used by: Command Queue, Execution Runner UI, future form-based features
@@ -3187,427 +3619,2716 @@ interface FormSchema {
3187
3619
  */
3188
3620
  type ExecutionErrorCategory = 'llm' | 'tool' | 'workflow' | 'agent' | 'validation' | 'system'
3189
3621
 
3190
- // ============================================================================
3191
- // API Request/Response Types (Dashboard Observability)
3192
- // ============================================================================
3622
+ /**
3623
+ * Memory type definitions
3624
+ * Types for agent memory management with semantic entry types
3625
+ */
3193
3626
 
3194
3627
  /**
3195
- * Time range selector for dashboard metrics
3628
+ * Semantic memory entry types
3629
+ * Use-case agnostic types that describe the purpose of each entry
3630
+ * Memory types mirror action types for clarity and filtering
3196
3631
  */
3197
- type TimeRange = '1h' | '24h' | '7d' | '30d'
3632
+ type MemoryEntryType =
3633
+ | 'context' // Pre-loaded context entry (before execution)
3634
+ | 'input' // User request or event payload
3635
+ | 'reasoning' // LLM thought process
3636
+ | 'tool-result' // Result from tool execution
3637
+ | 'delegation-result' // Result from sub-agent delegation (future)
3638
+ | 'error' // Error from failed action (tool error, validation error, etc.)
3198
3639
 
3199
3640
  /**
3200
- * Execution health metrics response
3201
- * Success rate, P95 duration, execution counts, and trend data
3202
- * trendData includes executionCount for throughput visualization (eliminates separate API call)
3641
+ * Memory entry - represents a single entry in agent memory
3642
+ * Stored in agent memory, translated by adapters to vendor-specific formats
3203
3643
  */
3204
- interface ExecutionHealthMetrics {
3205
- successRate: number
3206
- p95Duration: number
3207
- totalExecutions: number
3208
- trendData: Array<{
3209
- time: string
3210
- rate: number
3211
- successCount: number
3212
- errorCount: number
3213
- warningCount: number
3214
- executionCount: number
3215
- }>
3216
- statusCounts: { success: number; failed: number; pending: number; warning: number }
3217
- peakPeriod: string
3218
- granularity: 'hour' | 'day'
3644
+ interface MemoryEntry {
3645
+ type: MemoryEntryType
3646
+ content: string
3647
+ timestamp: number
3648
+ turnNumber: number | null // Which turn/execution created this entry (1, 2, 3... for session turns, null for session memory or one-off executions)
3649
+ iterationNumber: number | null // Which iteration created this entry (0 = pre-iteration input, null = session memory/non-iteration-specific)
3219
3650
  }
3220
3651
 
3221
3652
  /**
3222
- * Error analysis metrics response
3223
- * Error categories and top failing resources
3653
+ * Agent memory - Self-orchestrated memory with session + working storage
3654
+ * Agent has full control over what persists, framework handles auto-compaction
3224
3655
  */
3225
- interface ErrorAnalysisMetrics {
3226
- totalErrors: number
3227
- errorsByCategory: Array<{
3228
- category: string
3229
- count: number
3230
- percentage: number
3231
- }>
3232
- topFailingResources: Array<{
3233
- resourceId: string
3234
- name: string
3235
- errorCount: number
3236
- failureRate: number
3237
- }>
3656
+ interface AgentMemory {
3657
+ /**
3658
+ * Session memory - Persists for session/conversation duration
3659
+ * Never auto-trimmed by framework
3660
+ * Agent-managed key-value store for critical information
3661
+ * Agent provides strings, framework wraps in MemoryEntry
3662
+ */
3663
+ sessionMemory: Record<string, MemoryEntry>
3664
+
3665
+ /**
3666
+ * Working memory - Execution history
3667
+ * Automatically compacted by framework when needed
3668
+ * Agent doesn't control compaction
3669
+ */
3670
+ history: MemoryEntry[]
3238
3671
  }
3239
3672
 
3240
3673
  /**
3241
- * Business impact metrics response
3242
- * ROI, labor savings, and cost analysis
3674
+ * Memory status for agent awareness
3243
3675
  */
3244
- interface BusinessImpactMetrics {
3245
- totalSavingsUsd: number
3246
- totalCostUsd: number
3247
- netSavingsUsd: number
3248
- roi: number
3676
+ interface MemoryStatus {
3677
+ // Session memory
3678
+ sessionMemoryKeys: number // Current count
3679
+ sessionMemoryLimit: number // Max allowed (default: 10)
3680
+ currentKeys: string[] // List of keys currently stored
3681
+
3682
+ // History memory (token-based)
3683
+ historyPercent: number // 0-100 (percentage of token budget used)
3684
+ historyTokens: number // Current token count
3685
+ tokenBudget: number // Total token budget for memory
3249
3686
  }
3250
3687
 
3251
3688
  /**
3252
- * Cost breakdown metrics response
3253
- * Per-resource cost analysis
3689
+ * Memory constraints (optional limits)
3254
3690
  */
3255
- interface CostBreakdownMetrics {
3256
- resources: Array<{
3257
- resourceId: string
3258
- totalCostUsd: number
3259
- executionCount: number
3260
- avgCostUsd: number
3261
- }>
3691
+ interface MemoryConstraints {
3692
+ maxSessionMemoryKeys?: number // Max session memory keys (default: 10)
3693
+ maxMemoryTokens?: number // Total token budget for all memory (default: 14000)
3262
3694
  }
3263
3695
 
3264
3696
  /**
3265
- * Dashboard metrics response
3266
- * Aggregates core observability metrics in a single response
3267
- * Note: Throughput data is now included in executionHealth.trendData.executionCount
3697
+ * Generic LLM Types
3698
+ * Universal interfaces for LLM interaction across all resource types
3268
3699
  */
3269
- interface DashboardMetrics {
3270
- executionHealth: ExecutionHealthMetrics
3271
- costBreakdown: CostBreakdownMetrics
3272
- businessImpact: BusinessImpactMetrics
3273
- /** ISO timestamp of the currently active deployment, or null if none */
3274
- activeDeploymentDate: string | null
3275
- /** Deployment version of the active deployment, or null if none */
3276
- activeDeploymentVersion: string | null
3277
- }
3278
3700
 
3279
3701
  // ============================================================================
3280
- // Error Tracking Types
3702
+ // Message Format (OpenAI-compatible)
3281
3703
  // ============================================================================
3282
3704
 
3283
3705
  /**
3284
- * Error record for list view (ErrorBreakdownTable)
3706
+ * Standard chat message format
3707
+ * Compatible with OpenAI, Anthropic, and other providers
3285
3708
  */
3286
- interface ErrorRecord {
3287
- id: string // execution_errors.id
3288
- timestamp: string // occurred_at
3289
- errorType: string // error_type
3290
- message: string // error_message
3291
- executionId: string // execution_id
3292
- resourceId: string // execution_logs.resource_id (via JOIN)
3293
- resourceName: string // execution_logs.resource_id (TODO: resolve via registry)
3294
- severity: 'critical' | 'warning' | 'info'
3295
- category: ExecutionErrorCategory // error_category (moved from metadata to dedicated column)
3296
- resolved: boolean // resolved flag (human acknowledgment, does not affect execution status)
3297
- resolvedAt: string | null // timestamp when resolved
3298
- resolvedBy: string | null // user ID who resolved
3709
+ interface LLMMessage {
3710
+ role: 'system' | 'user' | 'assistant'
3711
+ content: string
3299
3712
  }
3300
3713
 
3301
- /**
3302
- * Full error detail for modal view (ErrorDetailsModal)
3303
- */
3304
- interface ErrorDetailFull extends ErrorRecord {
3305
- stackTrace?: string // error_stack_trace
3306
- retryAttempt?: number // metadata.retryAttempt
3307
- stepName?: string // metadata.stepName
3308
- stepSequence?: number // metadata.stepSequence
3309
- errorContext?: Record<string, unknown> // metadata.errorContext
3310
- executionContext?: Record<string, unknown> // metadata.executionContext
3311
- }
3714
+ // ============================================================================
3715
+ // Generic Request/Response
3716
+ // ============================================================================
3312
3717
 
3313
3718
  /**
3314
- * Error details API response (paginated)
3719
+ * Generic LLM generation request
3720
+ * Usable by agents, workflows, tools, etc.
3315
3721
  */
3316
- interface ErrorDetailResponse {
3317
- errors: ErrorRecord[]
3318
- total: number
3319
- page: number
3320
- limit: number
3722
+ interface LLMGenerateRequest {
3723
+ // Prompt (required)
3724
+ messages: LLMMessage[]
3725
+
3726
+ // Output structure (required)
3727
+ responseSchema: unknown // JSON Schema for structured output
3728
+
3729
+ // Constraints (optional)
3730
+ /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
3731
+ maxOutputTokens?: number
3732
+ temperature?: number
3733
+ topP?: number
3734
+
3735
+ // Cancellation (optional)
3736
+ signal?: AbortSignal // Execution-level abort signal, composed with per-call timeout in base adapters
3321
3737
  }
3322
3738
 
3323
3739
  /**
3324
- * Error trend data for time-series charts
3740
+ * Generic LLM generation response
3741
+ * Usage field is internal-only (stripped by UniversalLLMAdapter wrapper)
3325
3742
  */
3326
- interface ErrorTrend {
3327
- time: string // Time bucket (ISO timestamp)
3328
- errorCount: number // Total errors in bucket
3329
- criticalCount: number // Critical errors in bucket
3330
- warningCount: number // Warning errors in bucket
3331
- infoCount: number // Info errors in bucket
3743
+ interface LLMGenerateResponse<T = unknown> {
3744
+ output: T // Parsed structured output (validated against responseSchema)
3745
+
3746
+ // Internal use only (for observability tracking)
3747
+ // Not exposed in public interface - wrapper extracts this
3748
+ usage?: {
3749
+ inputTokens: number
3750
+ outputTokens: number
3751
+ totalTokens: number
3752
+ }
3753
+
3754
+ // Actual cost from provider in USD (when available)
3755
+ // Currently only OpenRouter provides this via usage accounting
3756
+ cost?: number
3332
3757
  }
3333
3758
 
3334
3759
  // ============================================================================
3335
- // Cost Analytics Types (Time-Series)
3760
+ // LLM Adapter Interface
3336
3761
  // ============================================================================
3337
3762
 
3338
3763
  /**
3339
- * Cost trend data point for time-series charts
3340
- * Represents a single time bucket (hour or day)
3764
+ * LLM Adapter interface
3765
+ * Generic primitive for all resource types (agents, workflows, tools)
3766
+ *
3767
+ * Design principles:
3768
+ * - Single method: generate() - the core LLM primitive
3769
+ * - Generic return type for type safety
3770
+ * - Universal format (not agent-specific)
3771
+ * - Standard message-based input (OpenAI-compatible)
3341
3772
  */
3342
- interface CostTrendDataPoint {
3343
- time: string // ISO timestamp (bucket start)
3344
- totalCostUsd: number
3345
- executionCount: number
3346
- avgCostPerExecution: number
3773
+ interface LLMAdapter {
3774
+ /**
3775
+ * Generate structured output from prompt using LLM
3776
+ *
3777
+ * @param request - Generation request with messages and response schema
3778
+ * @returns Generated output (typed) with optional usage metadata
3779
+ */
3780
+ generate<T = unknown>(request: LLMGenerateRequest): Promise<LLMGenerateResponse<T>>
3347
3781
  }
3348
3782
 
3349
3783
  /**
3350
- * Cost trends response (time-series data)
3784
+ * Model Configuration
3785
+ * Centralized model information, configuration, options, constraints, and validation
3786
+ * Single source of truth for all model-related definitions
3787
+ * Update manually when pricing changes or new models are added
3351
3788
  */
3352
- interface CostTrendsResponse {
3353
- trendData: CostTrendDataPoint[]
3354
- granularity: 'hour' | 'day'
3355
- totalCostUsd: number
3356
- totalExecutions: number
3357
- }
3789
+
3790
+
3791
+
3792
+ // ============================================================================
3793
+ // Model Types
3794
+ // ============================================================================
3358
3795
 
3359
3796
  /**
3360
- * Cost summary response with MTD and projections
3797
+ * Supported Open AI models (direct SDK access)
3361
3798
  */
3362
- interface CostSummaryResponse {
3363
- current: {
3364
- totalCostUsd: number
3365
- executionCount: number
3366
- }
3367
- previous: {
3368
- totalCostUsd: number
3369
- executionCount: number
3370
- }
3371
- mtd: {
3372
- totalCostUsd: number
3373
- daysElapsed: number
3374
- }
3375
- projection: {
3376
- monthlyCostUsd: number
3377
- confidence: 'low' | 'medium' | 'high'
3378
- }
3379
- trend: {
3380
- changePercent: number
3381
- direction: 'up' | 'down' | 'flat'
3382
- }
3383
- }
3799
+ type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano'
3384
3800
 
3385
3801
  /**
3386
- * Cost by model data for model-level breakdown
3802
+ * Supported OpenRouter models (explicit union for type safety)
3387
3803
  */
3388
- interface CostByModelData {
3389
- model: string
3390
- totalCostUsd: number
3391
- callCount: number
3392
- totalInputTokens: number
3393
- totalOutputTokens: number
3394
- avgCostPerCall: number
3395
- }
3804
+ type OpenRouterModel = 'openrouter/z-ai/glm-5'
3396
3805
 
3397
3806
  /**
3398
- * Cost by model response
3807
+ * Supported Google models (direct SDK access)
3399
3808
  */
3400
- interface CostByModelResponse {
3401
- models: CostByModelData[]
3402
- totalCostUsd: number
3403
- totalCallCount: number
3404
- }
3809
+ type GoogleModel = 'gemini-3-flash-preview' | 'gemini-3.1-flash-lite-preview'
3405
3810
 
3406
3811
  /**
3407
- * Action configuration for HITL tasks
3408
- * Defines available user actions and their behavior
3812
+ * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
3409
3813
  */
3410
- interface ActionConfig {
3411
- /** Unique action identifier (e.g., 'approve', 'retry', 'escalate') */
3412
- id: string
3814
+ type AnthropicModel = 'claude-sonnet-4-5'
3413
3815
 
3414
- /** Display label for UI button */
3415
- label: string
3816
+ /** Supported LLM models */
3817
+ type LLMModel = OpenAIModel | OpenRouterModel | GoogleModel | AnthropicModel | 'mock'
3416
3818
 
3417
- /** Button variant/style */
3418
- type: 'primary' | 'secondary' | 'danger' | 'outline'
3819
+ // ============================================================================
3820
+ // Model Configuration Schemas (Schema-First - Single Source of Truth)
3821
+ // ============================================================================
3419
3822
 
3420
- /** Tabler icon name (e.g., 'IconCheck', 'IconRefresh') */
3421
- icon?: string
3823
+ /**
3824
+ * GPT-5 model options schema
3825
+ */
3826
+ declare const GPT5OptionsSchema = z.object({
3827
+ reasoning_effort: z.enum(['minimal', 'low', 'medium', 'high']).optional(),
3828
+ verbosity: z.enum(['low', 'medium', 'high']).optional()
3829
+ })
3422
3830
 
3423
- /** Button color (Mantine theme colors) */
3424
- color?: string
3831
+ /**
3832
+ * OpenRouter model options schema
3833
+ * OpenRouter-specific options for routing and transforms
3834
+ */
3835
+ declare const OpenRouterOptionsSchema = z.object({
3836
+ /** Optional transforms to apply (e.g., 'middle-out' for long context) */
3837
+ transforms: z.array(z.string()).optional(),
3838
+ /** Routing strategy (e.g., 'fallback' for automatic provider failover) */
3839
+ route: z.enum(['fallback']).optional()
3840
+ })
3425
3841
 
3426
- /** Button variant (Mantine button variant, e.g., 'light', 'filled', 'outline') */
3427
- variant?: string
3842
+ /**
3843
+ * Google model options schema
3844
+ * Gemini 3 specific options for thinking depth control
3845
+ */
3846
+ declare const GoogleOptionsSchema = z.object({
3847
+ /** Thinking level for Gemini 3 models (controls reasoning depth) */
3848
+ thinkingLevel: z.enum(['minimal', 'low', 'medium', 'high']).optional()
3849
+ })
3428
3850
 
3429
- /** Execution target (agent/workflow to invoke) */
3430
- target?: {
3431
- resourceType: 'agent' | 'workflow'
3432
- resourceId: string
3433
- /**
3434
- * Optional session ID for agent continuation.
3435
- * If provided, invokes a new turn on the existing session instead of standalone execution.
3436
- * Only valid when resourceType is 'agent'.
3437
- */
3438
- sessionId?: string
3439
- }
3440
-
3441
- /** Form schema for collecting action-specific data */
3442
- form?: FormSchema
3851
+ /**
3852
+ * Anthropic model options schema
3853
+ * Currently empty - future options: budget_tokens for extended thinking
3854
+ */
3855
+ declare const AnthropicOptionsSchema = z.object({})
3443
3856
 
3444
- /** Payload template for pre-filling forms */
3445
- payloadTemplate?: unknown
3857
+ /**
3858
+ * Infer TypeScript types from schemas
3859
+ */
3860
+ type GPT5Options = z.infer<typeof GPT5OptionsSchema>
3861
+ type MockOptions = Record<string, never>
3862
+ type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>
3863
+ type GoogleOptions = z.infer<typeof GoogleOptionsSchema>
3864
+ type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>
3865
+ type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | GoogleOptions | AnthropicOptions
3446
3866
 
3447
- /** Requires confirmation dialog */
3448
- requiresConfirmation?: boolean
3867
+ // ============================================================================
3868
+ // Model Configuration
3869
+ // ============================================================================
3449
3870
 
3450
- /** Confirmation message */
3451
- confirmationMessage?: string
3871
+ /**
3872
+ * Model configuration for LLM execution
3873
+ * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
3874
+ */
3875
+ interface ModelConfig {
3876
+ model: LLMModel
3877
+ provider: 'openai' | 'anthropic' | 'openrouter' | 'google' | 'mock'
3878
+ apiKey: string
3879
+ temperature?: number
3880
+ /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
3881
+ maxOutputTokens?: number
3882
+ topP?: number
3452
3883
 
3453
- /** Help text / tooltip */
3454
- description?: string
3884
+ /**
3885
+ * Model-specific options (flat structure)
3886
+ * Options are model-specific, not vendor-specific
3887
+ * Available options defined in MODEL_INFO per model
3888
+ * Validated at build time via validateModelOptions()
3889
+ */
3890
+ modelOptions?: ModelSpecificOptions
3455
3891
  }
3456
3892
 
3457
3893
  /**
3458
- * Origin resource type - where an execution/task originated from.
3459
- * Used for audit trails and tracking execution lineage.
3894
+ * Memory Manager
3895
+ * Encapsulates all memory operations with ultra-simple agent API
3896
+ * Agent provides strings, framework handles wrapping and auto-compaction
3460
3897
  */
3461
- type OriginResourceType = 'agent' | 'workflow' | 'scheduler' | 'api'
3898
+
3899
+
3462
3900
 
3463
3901
  /**
3464
- * Origin tracking metadata - who/what created this execution/task.
3465
- * Used by both TaskScheduler and CommandQueue for complete audit trails.
3902
+ * Memory Manager - Agent memory orchestration
3903
+ * Provides ultra-simple API for agents (strings only)
3904
+ * Handles automatic compaction and token management
3466
3905
  */
3467
- interface OriginTracking {
3468
- originExecutionId: string
3469
- originResourceType: OriginResourceType
3470
- originResourceId: string
3906
+ declare class MemoryManager {
3907
+ private cachedSnapshot?: AgentMemory
3908
+
3909
+ constructor(
3910
+ private memory: AgentMemory,
3911
+ private constraints: MemoryConstraints = {},
3912
+ private logger?: AgentScopedLogger
3913
+ ) {}
3914
+
3915
+ // === Agent Operations (Ultra-Simple) ===
3916
+
3917
+ /**
3918
+ * Set session memory entry (agent provides string, framework wraps it)
3919
+ * @param key - Session memory key
3920
+ * @param content - String content from agent
3921
+ */
3922
+ set(key: string, content: string): void {
3923
+ // Check single entry token limit
3924
+ const entryTokens = estimateTokens(content)
3925
+ if (entryTokens > MAX_SINGLE_ENTRY_TOKENS) {
3926
+ const truncateTime = Date.now()
3927
+ this.logger?.action(
3928
+ 'memory-truncate',
3929
+ `Single entry exceeds token limit (${entryTokens}/${MAX_SINGLE_ENTRY_TOKENS}): ${key}`,
3930
+ 0,
3931
+ truncateTime,
3932
+ truncateTime,
3933
+ 0
3934
+ )
3935
+ // Truncate content to fit limit
3936
+ const maxChars = MAX_SINGLE_ENTRY_TOKENS * 4
3937
+ content = content.slice(0, maxChars) + '... [truncated]'
3938
+ }
3939
+
3940
+ this.memory.sessionMemory[key] = {
3941
+ type: 'context',
3942
+ content,
3943
+ timestamp: Date.now(),
3944
+ turnNumber: null, // Session memory entries are not turn-specific
3945
+ iterationNumber: null // Session memory entries are not iteration-specific
3946
+ }
3947
+ }
3948
+
3949
+ /**
3950
+ * Get session memory entry content
3951
+ * @param key - Session memory key
3952
+ * @returns String content if exists, undefined otherwise
3953
+ */
3954
+ get(key: string): string | undefined {
3955
+ const entry = this.memory.sessionMemory[key]
3956
+ return entry?.content
3957
+ }
3958
+
3959
+ /**
3960
+ * Delete session memory entry
3961
+ * @param key - Key to delete
3962
+ * @returns True if key existed and was deleted
3963
+ */
3964
+ delete(key: string): boolean {
3965
+ if (key in this.memory.sessionMemory) {
3966
+ delete this.memory.sessionMemory[key]
3967
+ return true
3968
+ }
3969
+ return false
3970
+ }
3971
+
3972
+ // === Framework Operations (Automatic) ===
3973
+
3974
+ /**
3975
+ * Add entry to history (called by framework after tool results, reasoning, etc.)
3976
+ * Automatically sets timestamp to current time
3977
+ * @param entry - Memory entry to add (without timestamp - auto-generated)
3978
+ */
3979
+ addToHistory(entry: Omit<MemoryEntry, 'timestamp'>): void {
3980
+ // Validate turnNumber is provided for history entries (use null for session memory)
3981
+ if (entry.turnNumber === undefined && entry.type !== 'context') {
3982
+ throw new AgentMemoryValidationError('turnNumber required for history entries (use null for session memory)', {
3983
+ entryType: entry.type,
3984
+ missingField: 'turnNumber',
3985
+ iterationNumber: entry.iterationNumber
3986
+ })
3987
+ }
3988
+
3989
+ // Truncate tool-result content if it exceeds the tool result token limit
3990
+ let content = entry.content
3991
+ if (entry.type === 'tool-result') {
3992
+ const before = content
3993
+ content = truncateToolResult(content, MAX_TOOL_RESULT_TOKENS)
3994
+ if (content !== before) {
3995
+ const truncateTime = Date.now()
3996
+ this.logger?.action(
3997
+ 'memory-tool-result-truncate',
3998
+ `Tool result truncated (${estimateTokens(before)} -> ${MAX_TOOL_RESULT_TOKENS} tokens)`,
3999
+ entry.iterationNumber ?? 0,
4000
+ truncateTime,
4001
+ truncateTime,
4002
+ 0
4003
+ )
4004
+ }
4005
+ }
4006
+
4007
+ this.memory.history.push({
4008
+ ...entry,
4009
+ content,
4010
+ timestamp: Date.now()
4011
+ })
4012
+ // Auto-compact after adding (if needed)
4013
+ this.autoCompact()
4014
+ }
4015
+
4016
+ /**
4017
+ * Auto-compact history if approaching token budget
4018
+ * Uses preserve-anchors strategy: keep first + recent entries
4019
+ */
4020
+ autoCompact(): void {
4021
+ const status = this.getStatus()
4022
+
4023
+ // Auto-compact when at 100% of token budget
4024
+ if (status.historyPercent >= 100) {
4025
+ const before = this.memory.history.length
4026
+
4027
+ // Preserve-anchors strategy: first entry + last 10 entries
4028
+ this.memory.history = [
4029
+ this.memory.history[0], // First (original input)
4030
+ ...this.memory.history.slice(-10) // Last 10
4031
+ ]
4032
+
4033
+ const compactTime = Date.now()
4034
+ this.logger?.action(
4035
+ 'memory-auto-compact',
4036
+ `Auto-compacted: ${before} -> ${this.memory.history.length} entries`,
4037
+ 0,
4038
+ compactTime,
4039
+ compactTime,
4040
+ 0
4041
+ )
4042
+ }
4043
+ }
4044
+
4045
+ /**
4046
+ * Enforce hard limits (called before LLM request)
4047
+ * Emergency fallback if agent exceeds limits
4048
+ */
4049
+ enforceHardLimits(): void {
4050
+ const maxSessionMemoryKeys = this.constraints.maxSessionMemoryKeys || MAX_SESSION_MEMORY_KEYS
4051
+
4052
+ // Check session memory count
4053
+ const sessionMemoryKeys = Object.keys(this.memory.sessionMemory)
4054
+ if (sessionMemoryKeys.length > maxSessionMemoryKeys) {
4055
+ const limitTime = Date.now()
4056
+ this.logger?.action(
4057
+ 'memory-limit-exceeded',
4058
+ `Session memory exceeds hard limit (${sessionMemoryKeys.length}/${maxSessionMemoryKeys})`,
4059
+ 0,
4060
+ limitTime,
4061
+ limitTime,
4062
+ 0
4063
+ )
4064
+
4065
+ // Remove oldest entries by timestamp
4066
+ const sorted = Object.entries(this.memory.sessionMemory).sort((a, b) => a[1].timestamp - b[1].timestamp)
4067
+
4068
+ this.memory.sessionMemory = Object.fromEntries(sorted.slice(-maxSessionMemoryKeys))
4069
+ }
4070
+
4071
+ // Check total token budget (emergency compaction)
4072
+ const status = this.getStatus()
4073
+ const maxTokens = this.constraints.maxMemoryTokens || MAX_MEMORY_TOKENS
4074
+
4075
+ if (status.historyTokens > maxTokens) {
4076
+ const before = this.memory.history.length
4077
+ const emergencyStartTime = Date.now()
4078
+ this.logger?.action(
4079
+ 'memory-emergency',
4080
+ `Total memory exceeds token budget (${status.historyTokens}/${maxTokens}), forcing emergency compaction`,
4081
+ 0,
4082
+ emergencyStartTime,
4083
+ emergencyStartTime,
4084
+ 0
4085
+ )
4086
+
4087
+ // Emergency: Aggressively compact history
4088
+ this.memory.history = [
4089
+ this.memory.history[0],
4090
+ ...this.memory.history.slice(-5) // Keep only last 5
4091
+ ]
4092
+
4093
+ const emergencyEndTime = Date.now()
4094
+ this.logger?.action(
4095
+ 'memory-emergency-compact',
4096
+ `Emergency compaction: ${before} -> ${this.memory.history.length} entries`,
4097
+ 0,
4098
+ emergencyStartTime,
4099
+ emergencyEndTime,
4100
+ emergencyEndTime - emergencyStartTime
4101
+ )
4102
+ }
4103
+ }
4104
+
4105
+ /**
4106
+ * Get history length (for logging and introspection)
4107
+ * @returns Number of entries in history
4108
+ */
4109
+ getHistoryLength(): number {
4110
+ return this.memory.history.length
4111
+ }
4112
+
4113
+ /**
4114
+ * Get memory status for agent awareness
4115
+ * @returns Memory status with token usage and key counts
4116
+ */
4117
+ getStatus(): MemoryStatus {
4118
+ const sessionMemoryKeys = Object.keys(this.memory.sessionMemory)
4119
+
4120
+ // Calculate tokens
4121
+ const sessionMemoryContent = Object.values(this.memory.sessionMemory)
4122
+ .map((entry) => entry.content)
4123
+ .join('')
4124
+ const historyContent = this.memory.history.map((entry) => entry.content).join('')
4125
+ const sessionMemoryTokens = estimateTokens(sessionMemoryContent)
4126
+ const historyTokens = estimateTokens(historyContent)
4127
+ const totalTokens = sessionMemoryTokens + historyTokens
4128
+
4129
+ // Token budget
4130
+ const tokenBudget = this.constraints.maxMemoryTokens || MAX_MEMORY_TOKENS
4131
+ const sessionMemoryLimit = this.constraints.maxSessionMemoryKeys || MAX_SESSION_MEMORY_KEYS
4132
+
4133
+ return {
4134
+ sessionMemoryKeys: sessionMemoryKeys.length,
4135
+ sessionMemoryLimit,
4136
+ currentKeys: sessionMemoryKeys,
4137
+ historyPercent: Math.round((totalTokens / tokenBudget) * 100),
4138
+ historyTokens: totalTokens,
4139
+ tokenBudget
4140
+ }
4141
+ }
4142
+
4143
+ /**
4144
+ * Create memory snapshot for persistence
4145
+ * Caches snapshot internally for later retrieval
4146
+ * @returns Deep copy of current memory state
4147
+ */
4148
+ toSnapshot(): AgentMemory {
4149
+ this.cachedSnapshot = structuredClone(this.memory)
4150
+ return this.cachedSnapshot
4151
+ }
4152
+
4153
+ /**
4154
+ * Get cached memory snapshot
4155
+ * Returns snapshot created by toSnapshot()
4156
+ * @returns Cached snapshot (undefined if toSnapshot() not called yet)
4157
+ */
4158
+ getSnapshot(): AgentMemory | undefined {
4159
+ return this.cachedSnapshot
4160
+ }
4161
+
4162
+ /**
4163
+ * Build context string for LLM
4164
+ * Serializes sessionmemory + history memory with clear sections
4165
+ * Shows current iteration entries FIRST (reverse chronological) for LLM attention
4166
+ * @param currentIteration - Current iteration number (0 = pre-iteration)
4167
+ * @param currentTurn - Current turn number (optional, for session context filtering)
4168
+ * @returns Formatted memory context for LLM prompt
4169
+ */
4170
+ toContext(currentIteration: number, currentTurn?: number): string {
4171
+ const status = this.getStatus()
4172
+
4173
+ // Split by turn and iteration number
4174
+ // DUAL FILTERING: Turn scope first (if provided), then iteration scope
4175
+ // null iterations are session memory entries (excluded from history context)
4176
+ // undefined/null turnNumbers are treated as legacy entries (pre-migration) or one-off executions
4177
+ const currentContext = this.memory.history
4178
+ .filter(
4179
+ (entry) =>
4180
+ (!currentTurn || entry.turnNumber === currentTurn || entry.turnNumber === undefined) &&
4181
+ entry.iterationNumber === currentIteration
4182
+ )
4183
+ .reverse() // Most recent first (LLM positional bias)
4184
+
4185
+ const earlierContext = this.memory.history.filter(
4186
+ (entry) =>
4187
+ (!currentTurn || entry.turnNumber === currentTurn || entry.turnNumber === undefined) &&
4188
+ entry.iterationNumber !== null &&
4189
+ entry.iterationNumber < currentIteration
4190
+ )
4191
+ // Earlier entries stay chronological
4192
+
4193
+ // Format entry with simple label
4194
+ const formatEntry = (entry: MemoryEntry): string => {
4195
+ const label = `[${entry.type.toUpperCase()}]`
4196
+ return `${label}\n${entry.content}`
4197
+ }
4198
+
4199
+ // Serialize session memory
4200
+ const sessionMemoryContext = Object.entries(this.memory.sessionMemory)
4201
+ .map(([key, entry]) => `[SESSION:${key}]\n${entry.content}`)
4202
+ .join('\n\n')
4203
+
4204
+ const currentSection = currentContext.map(formatEntry).join('\n\n')
4205
+ const earlierSection =
4206
+ earlierContext.length > 0 ? earlierContext.map(formatEntry).join('\n\n') : '(no earlier context)'
4207
+
4208
+ return `
4209
+ === MEMORY STATUS ===
4210
+ ${status.sessionMemoryKeys}/${status.sessionMemoryLimit} session keys
4211
+ ${status.historyPercent}% of token budget
4212
+
4213
+ === SESSION MEMORY (Persists for conversation) ===
4214
+ ${sessionMemoryContext || '(empty)'}
4215
+
4216
+ === ITERATION ${currentIteration} - CURRENT CONTEXT ===
4217
+
4218
+ ${currentSection}
4219
+
4220
+ === EARLIER CONTEXT ===
4221
+
4222
+ ${earlierSection}
4223
+ `.trim()
4224
+ }
3471
4225
  }
3472
4226
 
3473
4227
  /**
3474
- * Command queue task with flexible action system
4228
+ * AIUsageCollector
4229
+ * Centralized token tracking that aggregates usage across all LLM calls in an execution
3475
4230
  */
3476
- interface Task extends OriginTracking {
3477
- id: string
3478
- organizationId: string
4231
+ declare class AIUsageCollector {
4232
+ private model: LLMModel = 'gpt-5' // Default, will be overwritten on first record()
4233
+ private calls: AICallRecord[] = []
4234
+ private callSequence: number = 0
3479
4235
 
3480
- // NEW: Flexible action system
3481
- actions: ActionConfig[]
3482
- context: unknown
3483
- selectedAction?: string
3484
- actionPayload?: unknown
4236
+ /**
4237
+ * Record a single AI call with usage metrics
4238
+ *
4239
+ * @param usage - Token usage and latency data from LLM adapter
4240
+ * @param callType - Type discriminator (agent-reasoning, tool, etc.)
4241
+ * @param context - Optional typed context specific to callType
4242
+ */
4243
+ record(usage: LLMUsageData, callType: BaseAICall['callType'] = 'other', context?: AICallContext): void {
4244
+ this.callSequence++
4245
+ this.model = usage.model
4246
+
4247
+ // Use actual cost from provider (e.g., OpenRouter) if available, otherwise calculate
4248
+ const costUsd = usage.cost ?? calculateCost(usage.model, usage.inputTokens, usage.outputTokens)
4249
+
4250
+ this.calls.push({
4251
+ callSequence: this.callSequence,
4252
+ callType,
4253
+ model: usage.model,
4254
+ inputTokens: usage.inputTokens,
4255
+ outputTokens: usage.outputTokens,
4256
+ costUsd,
4257
+ latencyMs: usage.latencyMs,
4258
+ context
4259
+ })
4260
+ }
3485
4261
 
3486
- // Task metadata
3487
- description?: string
3488
- priority: number
4262
+ /**
4263
+ * Get aggregated summary of all AI calls
4264
+ */
4265
+ getSummary(): AIUsageSummary {
4266
+ const totalInputTokens = this.calls.reduce((sum, c) => sum + c.inputTokens, 0)
4267
+ const totalOutputTokens = this.calls.reduce((sum, c) => sum + c.outputTokens, 0)
4268
+ const totalCostUsd = this.calls.reduce((sum, c) => sum + c.costUsd, 0)
4269
+
4270
+ return {
4271
+ model: this.model,
4272
+ totalInputTokens,
4273
+ totalOutputTokens,
4274
+ totalTokens: totalInputTokens + totalOutputTokens,
4275
+ totalCostUsd,
4276
+ callCount: this.calls.length,
4277
+ calls: this.calls
4278
+ }
4279
+ }
3489
4280
 
3490
- /** Optional checkpoint identifier for grouping related human approval tasks */
3491
- humanCheckpoint?: string
4281
+ /**
4282
+ * Check if any usage has been recorded
4283
+ */
4284
+ hasUsage(): boolean {
4285
+ return this.calls.length > 0
4286
+ }
4287
+ }
3492
4288
 
3493
- // Status (updated to include 'completed')
3494
- status: TaskStatus
4289
+ /**
4290
+ * MetricsCollector
4291
+ * Tracks execution timing and ROI metrics
4292
+ */
4293
+ declare class MetricsCollector {
4294
+ private timings: Map<string, number> = new Map()
4295
+ private durationMs?: number
3495
4296
 
3496
4297
  /**
3497
- * Target resource tracking mirrors origin columns.
3498
- * Set when task is created; patchable to redirect execution to a different resource.
4298
+ * Start a timer with a label
3499
4299
  */
3500
- targetResourceId?: string
3501
- targetResourceType?: 'agent' | 'workflow'
4300
+ startTimer(label: string): void {
4301
+ this.timings.set(label, Date.now())
4302
+ }
3502
4303
 
3503
4304
  /**
3504
- * Execution ID for the action that runs AFTER user approval.
3505
- * NULL until execution starts.
3506
- *
3507
- * Naming distinction:
3508
- * - originExecutionId = Parent execution that CREATED the HITL task
3509
- * - targetExecutionId = Child execution that RUNS AFTER user approval
4305
+ * End a timer and calculate duration
4306
+ * If label is 'execution', stores duration for metrics summary
3510
4307
  */
3511
- targetExecutionId?: string
4308
+ endTimer(label: string): number | null {
4309
+ const start = this.timings.get(label)
4310
+ if (!start) return null
3512
4311
 
3513
- createdAt: Date
3514
- completedAt?: Date
3515
- completedBy?: string
3516
- expiresAt?: Date
3517
- idempotencyKey?: string | null
4312
+ const duration = Date.now() - start
4313
+
4314
+ if (label === 'execution') {
4315
+ this.durationMs = duration
4316
+ }
4317
+
4318
+ this.timings.delete(label)
4319
+ return duration
4320
+ }
4321
+
4322
+ /**
4323
+ * Build execution metrics summary with optional ROI calculation
4324
+ */
4325
+ buildExecutionMetrics(metricsConfig?: ResourceMetricsConfig): ExecutionMetricsSummary {
4326
+ const automationSavingsUsd = metricsConfig
4327
+ ? (metricsConfig.estimatedManualMinutes / 60) * metricsConfig.hourlyLaborRateUsd
4328
+ : undefined
4329
+
4330
+ return {
4331
+ durationMs: this.durationMs,
4332
+ automationSavingsUsd
4333
+ }
4334
+ }
4335
+ }
4336
+
4337
+ // ============================================================================
4338
+ // AI Call Tracking Types (SSOT)
4339
+ // ============================================================================
4340
+
4341
+ interface BaseAICall {
4342
+ callSequence: number // 1, 2, 3... (execution-wide universal counter)
4343
+ callType: 'agent-reasoning' | 'agent-completion' | 'workflow-step' | 'tool' | 'other'
4344
+ model: LLMModel
4345
+ inputTokens: number
4346
+ outputTokens: number
4347
+ costUsd: number // Cost in USD with full decimal precision
4348
+ latencyMs: number
4349
+ context?: AICallContext
4350
+ }
4351
+
4352
+ type AICallContext =
4353
+ | AgentReasoningContext
4354
+ | AgentCompletionContext
4355
+ | WorkflowStepContext
4356
+ | ToolCallContext
4357
+ | OtherCallContext
4358
+
4359
+ interface AgentReasoningContext {
4360
+ type: 'agent-reasoning'
4361
+ iteration: number
4362
+ actionsPlanned?: string[]
4363
+ sessionId?: string
4364
+ turnNumber?: number
4365
+ }
4366
+
4367
+ interface AgentCompletionContext {
4368
+ type: 'agent-completion'
4369
+ attempt: 1 | 2
4370
+ validationFailed?: boolean
4371
+ sessionId?: string
4372
+ turnNumber?: number
4373
+ }
4374
+
4375
+ interface WorkflowStepContext {
4376
+ type: 'workflow-step'
4377
+ stepId: string
4378
+ stepName?: string
4379
+ stepSequence?: number
4380
+ }
4381
+
4382
+ interface ToolCallContext {
4383
+ type: 'tool'
4384
+ toolName: string
4385
+ parentIteration?: number
4386
+ parentStepId?: string
3518
4387
  }
3519
4388
 
4389
+ interface OtherCallContext {
4390
+ type: 'other'
4391
+ description?: string
4392
+ metadata?: Record<string, unknown>
4393
+ }
4394
+
4395
+ type AICallRecord = BaseAICall
4396
+
4397
+ // ============================================================================
4398
+ // LLM Usage Data (from adapters)
4399
+ // ============================================================================
4400
+
3520
4401
  /**
3521
- * Task status values
3522
- * - pending: awaiting action
3523
- * - processing: execution in progress after user approval
3524
- * - completed: action was taken and execution succeeded
3525
- * - failed: execution failed, task can be retried
3526
- * - expired: timed out before action
4402
+ * Raw LLM usage data returned by adapters
4403
+ * Used as input to AIUsageCollector.record()
3527
4404
  */
3528
- type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'expired'
4405
+ interface LLMUsageData {
4406
+ model: LLMModel
4407
+ inputTokens: number
4408
+ outputTokens: number
4409
+ latencyMs: number
4410
+ /** Actual cost from provider in USD (when available, e.g., OpenRouter) */
4411
+ cost?: number
4412
+ }
4413
+
4414
+ // ============================================================================
4415
+ // AI Usage Summary
4416
+ // ============================================================================
4417
+
4418
+ interface AIUsageSummary {
4419
+ model: LLMModel
4420
+ totalInputTokens: number
4421
+ totalOutputTokens: number
4422
+ totalTokens: number
4423
+ totalCostUsd: number // Total cost in USD with full decimal precision
4424
+ callCount: number
4425
+ calls: AICallRecord[]
4426
+ }
4427
+
4428
+ // ============================================================================
4429
+ // Execution Metrics
4430
+ // ============================================================================
4431
+
4432
+ interface ExecutionMetricsSummary {
4433
+ durationMs?: number
4434
+ automationSavingsUsd?: number // Automation savings in USD with full decimal precision
4435
+ }
4436
+
4437
+ // ============================================================================
4438
+ // Resource Metrics Configuration
4439
+ // ============================================================================
4440
+
4441
+ interface ResourceMetricsConfig {
4442
+ estimatedManualMinutes: number
4443
+ hourlyLaborRateUsd: number // Hourly rate in USD (e.g., 75.00 for $75/hour)
4444
+ confidenceLevel?: 'low' | 'medium' | 'high'
4445
+ notes?: string
4446
+ }
4447
+
4448
+ // ============================================================================
4449
+ // API Request/Response Types (Dashboard Observability)
4450
+ // ============================================================================
3529
4451
 
3530
4452
  /**
3531
- * Parameters for patching mutable metadata on a task
4453
+ * Time range selector for dashboard metrics
3532
4454
  */
3533
- interface PatchTaskParams {
3534
- humanCheckpoint?: string | null
3535
- description?: string
3536
- priority?: number
3537
- context?: Record<string, unknown>
3538
- actions?: unknown[]
3539
- targetResourceId?: string | null
3540
- targetResourceType?: 'agent' | 'workflow' | null
3541
- targetExecutionId?: string
3542
- status?: 'pending' | 'failed' | 'completed'
4455
+ type TimeRange = '1h' | '24h' | '7d' | '30d'
4456
+
4457
+ /**
4458
+ * Execution health metrics response
4459
+ * Success rate, P95 duration, execution counts, and trend data
4460
+ * trendData includes executionCount for throughput visualization (eliminates separate API call)
4461
+ */
4462
+ interface ExecutionHealthMetrics {
4463
+ successRate: number
4464
+ p95Duration: number
4465
+ totalExecutions: number
4466
+ trendData: Array<{
4467
+ time: string
4468
+ rate: number
4469
+ successCount: number
4470
+ errorCount: number
4471
+ warningCount: number
4472
+ executionCount: number
4473
+ }>
4474
+ statusCounts: { success: number; failed: number; pending: number; warning: number }
4475
+ peakPeriod: string
4476
+ granularity: 'hour' | 'day'
3543
4477
  }
3544
4478
 
3545
4479
  /**
3546
- * Checkpoint list item for sidebar grouping
3547
- * The id field contains the resourceId of the human checkpoint
4480
+ * Error analysis metrics response
4481
+ * Error categories and top failing resources
3548
4482
  */
3549
- interface CheckpointListItem {
3550
- /** Human checkpoint resourceId (or 'ungrouped' for tasks without checkpoint) */
3551
- id: string
3552
- /** Display name (same as id, or "Ungrouped" for null) */
3553
- name: string
3554
- /** Task count for this checkpoint */
3555
- count: number
4483
+ interface ErrorAnalysisMetrics {
4484
+ totalErrors: number
4485
+ errorsByCategory: Array<{
4486
+ category: string
4487
+ count: number
4488
+ percentage: number
4489
+ }>
4490
+ topFailingResources: Array<{
4491
+ resourceId: string
4492
+ name: string
4493
+ errorCount: number
4494
+ failureRate: number
4495
+ }>
3556
4496
  }
3557
4497
 
3558
4498
  /**
3559
- * Status counts for pie chart display
4499
+ * Business impact metrics response
4500
+ * ROI, labor savings, and cost analysis
3560
4501
  */
3561
- interface StatusCounts {
4502
+ interface BusinessImpactMetrics {
4503
+ totalSavingsUsd: number
4504
+ totalCostUsd: number
4505
+ netSavingsUsd: number
4506
+ roi: number
4507
+ }
4508
+
4509
+ /**
4510
+ * Cost breakdown metrics response
4511
+ * Per-resource cost analysis
4512
+ */
4513
+ interface CostBreakdownMetrics {
4514
+ resources: Array<{
4515
+ resourceId: string
4516
+ totalCostUsd: number
4517
+ executionCount: number
4518
+ avgCostUsd: number
4519
+ }>
4520
+ }
4521
+
4522
+ /**
4523
+ * Detailed execution metrics response
4524
+ * Full execution metrics with AI call breakdown
4525
+ */
4526
+ interface ExecutionMetricsDetail {
4527
+ executionId: string
4528
+ organizationId: string
4529
+ resourceId: string
4530
+ totalInputTokens: number
4531
+ totalOutputTokens: number
4532
+ totalCostUsd: number
4533
+ aiCallCount: number
4534
+ aiCalls: AICallRecord[]
4535
+ durationMs?: number
4536
+ automationSavingsUsd?: number
4537
+ createdAt: string
4538
+ }
4539
+
4540
+ /**
4541
+ * Dashboard metrics response
4542
+ * Aggregates core observability metrics in a single response
4543
+ * Note: Throughput data is now included in executionHealth.trendData.executionCount
4544
+ */
4545
+ interface DashboardMetrics {
4546
+ executionHealth: ExecutionHealthMetrics
4547
+ costBreakdown: CostBreakdownMetrics
4548
+ businessImpact: BusinessImpactMetrics
4549
+ /** ISO timestamp of the currently active deployment, or null if none */
4550
+ activeDeploymentDate: string | null
4551
+ /** Deployment version of the active deployment, or null if none */
4552
+ activeDeploymentVersion: string | null
4553
+ }
4554
+
4555
+ // ============================================================================
4556
+ // Error Tracking Types
4557
+ // ============================================================================
4558
+
4559
+ /**
4560
+ * Error record for list view (ErrorBreakdownTable)
4561
+ */
4562
+ interface ErrorRecord {
4563
+ id: string // execution_errors.id
4564
+ timestamp: string // occurred_at
4565
+ errorType: string // error_type
4566
+ message: string // error_message
4567
+ executionId: string // execution_id
4568
+ resourceId: string // execution_logs.resource_id (via JOIN)
4569
+ resourceName: string // execution_logs.resource_id (TODO: resolve via registry)
4570
+ severity: 'critical' | 'warning' | 'info'
4571
+ category: ExecutionErrorCategory // error_category (moved from metadata to dedicated column)
4572
+ resolved: boolean // resolved flag (human acknowledgment, does not affect execution status)
4573
+ resolvedAt: string | null // timestamp when resolved
4574
+ resolvedBy: string | null // user ID who resolved
4575
+ }
4576
+
4577
+ /**
4578
+ * Full error detail for modal view (ErrorDetailsModal)
4579
+ */
4580
+ interface ErrorDetailFull extends ErrorRecord {
4581
+ stackTrace?: string // error_stack_trace
4582
+ retryAttempt?: number // metadata.retryAttempt
4583
+ stepName?: string // metadata.stepName
4584
+ stepSequence?: number // metadata.stepSequence
4585
+ errorContext?: Record<string, unknown> // metadata.errorContext
4586
+ executionContext?: Record<string, unknown> // metadata.executionContext
4587
+ }
4588
+
4589
+ /**
4590
+ * Error details API response (paginated)
4591
+ */
4592
+ interface ErrorDetailResponse {
4593
+ errors: ErrorRecord[]
4594
+ total: number
4595
+ page: number
4596
+ limit: number
4597
+ }
4598
+
4599
+ /**
4600
+ * Error trend data for time-series charts
4601
+ */
4602
+ interface ErrorTrend {
4603
+ time: string // Time bucket (ISO timestamp)
4604
+ errorCount: number // Total errors in bucket
4605
+ criticalCount: number // Critical errors in bucket
4606
+ warningCount: number // Warning errors in bucket
4607
+ infoCount: number // Info errors in bucket
4608
+ }
4609
+
4610
+ /**
4611
+ * Failing resource data for health monitoring
4612
+ */
4613
+ interface FailingResource {
4614
+ resourceId: string
4615
+ resourceName: string // TODO: Resolve via registry
4616
+ errorCount: number
4617
+ criticalCount: number
4618
+ warningCount: number
4619
+ mostCommonError: string
4620
+ }
4621
+
4622
+ // ============================================================================
4623
+ // Recent Executions by Resource Types (Dashboard)
4624
+ // ============================================================================
4625
+
4626
+ /**
4627
+ * Summary of executions for a single resource
4628
+ * Used by RecentExecutionsByResource dashboard component
4629
+ */
4630
+ interface ResourceExecutionSummary {
4631
+ resourceId: string // resource_id from execution_logs
4632
+ resourceType: string // Inferred from resource definitions (resolved by frontend)
4633
+ resourceName: string | null // From resource registry lookup (resolved by frontend)
4634
+ lastExecution: string // ISO timestamp (MAX started_at)
4635
+ totalExecutions: number // COUNT(*)
4636
+ successCount: number // COUNT WHERE status='completed' OR status='warning'
4637
+ failureCount: number // COUNT WHERE status='failed'
4638
+ warningCount: number // COUNT WHERE status='warning' (subset of success)
4639
+ successRate: number // (successCount / totalExecutions) * 100
4640
+ }
4641
+
4642
+ /**
4643
+ * Response from getRecentExecutionsByResource endpoint
4644
+ */
4645
+ interface RecentExecutionsByResourceResponse {
4646
+ resources: ResourceExecutionSummary[]
4647
+ }
4648
+
4649
+ // ============================================================================
4650
+ // Per-Resource Health Types (Dashboard Recent Activity)
4651
+ // ============================================================================
4652
+
4653
+ /** Resource identifier for health queries */
4654
+ interface ResourceIdentifier {
4655
+ entityType: string // 'workflow' | 'agent'
4656
+ entityId: string // Resource ID
4657
+ }
4658
+
4659
+ /** Time-bucketed health data point */
4660
+ interface ResourceHealthDataPoint {
4661
+ time: string // ISO timestamp (bucket start)
4662
+ success: number // Success count in bucket (completed + warning)
4663
+ failure: number // Failure count in bucket
4664
+ warning: number // Warning count in bucket (subset of success)
4665
+ rate: number // Success rate (0-100)
4666
+ }
4667
+
4668
+ /** Health data for a single resource */
4669
+ interface ResourceHealth {
4670
+ entityType: string
4671
+ entityId: string
4672
+ entityName: string | null
4673
+ trendData: ResourceHealthDataPoint[]
4674
+ summary: {
4675
+ total: number
4676
+ successRate: number
4677
+ }
4678
+ }
4679
+
4680
+ /** Batch response with all requested resources */
4681
+ interface ResourcesHealthResponse {
4682
+ resources: ResourceHealth[]
4683
+ }
4684
+
4685
+ // ============================================================================
4686
+ // Cost Analytics Types (Time-Series)
4687
+ // ============================================================================
4688
+
4689
+ /**
4690
+ * Cost trend data point for time-series charts
4691
+ * Represents a single time bucket (hour or day)
4692
+ */
4693
+ interface CostTrendDataPoint {
4694
+ time: string // ISO timestamp (bucket start)
4695
+ totalCostUsd: number
4696
+ executionCount: number
4697
+ avgCostPerExecution: number
4698
+ }
4699
+
4700
+ /**
4701
+ * Cost trends response (time-series data)
4702
+ */
4703
+ interface CostTrendsResponse {
4704
+ trendData: CostTrendDataPoint[]
4705
+ granularity: 'hour' | 'day'
4706
+ totalCostUsd: number
4707
+ totalExecutions: number
4708
+ }
4709
+
4710
+ /**
4711
+ * Cost summary response with MTD and projections
4712
+ */
4713
+ interface CostSummaryResponse {
4714
+ current: {
4715
+ totalCostUsd: number
4716
+ executionCount: number
4717
+ }
4718
+ previous: {
4719
+ totalCostUsd: number
4720
+ executionCount: number
4721
+ }
4722
+ mtd: {
4723
+ totalCostUsd: number
4724
+ daysElapsed: number
4725
+ }
4726
+ projection: {
4727
+ monthlyCostUsd: number
4728
+ confidence: 'low' | 'medium' | 'high'
4729
+ }
4730
+ trend: {
4731
+ changePercent: number
4732
+ direction: 'up' | 'down' | 'flat'
4733
+ }
4734
+ }
4735
+
4736
+ /**
4737
+ * Cost by model data for model-level breakdown
4738
+ */
4739
+ interface CostByModelData {
4740
+ model: string
4741
+ totalCostUsd: number
4742
+ callCount: number
4743
+ totalInputTokens: number
4744
+ totalOutputTokens: number
4745
+ avgCostPerCall: number
4746
+ }
4747
+
4748
+ /**
4749
+ * Cost by model response
4750
+ */
4751
+ interface CostByModelResponse {
4752
+ models: CostByModelData[]
4753
+ totalCostUsd: number
4754
+ totalCallCount: number
4755
+ }
4756
+
4757
+ /**
4758
+ * Knowledge Map Types
4759
+ *
4760
+ * Enables agents to navigate organizational knowledge through a lightweight
4761
+ * graph that lazy-loads capabilities on-demand.
4762
+ *
4763
+ * @module agent/knowledge-map
4764
+ */
4765
+
4766
+
4767
+
4768
+ /**
4769
+ * Lightweight knowledge map (passed as agent property)
4770
+ *
4771
+ * Contains metadata about available knowledge nodes without loading
4772
+ * the full content upfront. Total size: ~300-500 tokens.
4773
+ *
4774
+ * Multi-tenancy is enforced via:
4775
+ * - File-scoped maps (organizations/{org-name}/knowledge/)
4776
+ * - ExecutionContext.organizationId passed to node.load()
4777
+ */
4778
+ interface KnowledgeMap {
4779
+ /** Available knowledge nodes indexed by ID */
4780
+ nodes: Record<string, KnowledgeNode>
4781
+ }
4782
+
4783
+ /**
4784
+ * Single knowledge source
4785
+ *
4786
+ * Represents a domain knowledge area (CRM, brand guidelines, Excel tools)
4787
+ * that can be lazy-loaded to provide instructions and tools to agents.
4788
+ */
4789
+ interface KnowledgeNode {
4790
+ /** Unique identifier for this node (e.g., "crm", "brand-guidelines") */
4791
+ id: string
4792
+
4793
+ /**
4794
+ * Description of when to use this knowledge
4795
+ * Used for semantic matching against user intent
4796
+ */
4797
+ description: string
4798
+
4799
+ /**
4800
+ * Load knowledge content on-demand
4801
+ *
4802
+ * @param context - Execution context with organizationId for multi-tenancy
4803
+ * @returns Promise resolving to knowledge content (prompt + optional tools)
4804
+ */
4805
+ load(context: ExecutionContext): Promise<KnowledgeContent>
4806
+
4807
+ /**
4808
+ * Loaded state flag
4809
+ * Set to true after load() is called
4810
+ */
4811
+ loaded?: boolean
4812
+
4813
+ /**
4814
+ * Cached prompt (for system prompt serialization)
4815
+ * Only the prompt is cached - tools go to toolRegistry, children flattened to nodes
4816
+ */
4817
+ prompt?: string
4818
+ }
4819
+
4820
+ /**
4821
+ * Content returned by knowledge node
4822
+ *
4823
+ * Separates instructions (prompt) from capabilities (tools).
4824
+ * Tools are optional - some nodes only provide context.
4825
+ *
4826
+ * Supports recursive navigation - nodes can contain child nodes
4827
+ * that are discovered when the parent node is loaded.
4828
+ */
4829
+ interface KnowledgeContent {
4830
+ /** Instructions and context (markdown format) */
4831
+ prompt: string
4832
+
4833
+ /** Tool implementations (optional) */
4834
+ tools?: Tool[]
4835
+
4836
+ /**
4837
+ * Child knowledge nodes (optional, recursive)
4838
+ *
4839
+ * Enables hierarchical navigation: base → specialized → deep expertise.
4840
+ * Child nodes are flattened into the main knowledge map when parent loads,
4841
+ * making them available for subsequent navigate-knowledge actions.
4842
+ *
4843
+ * Example: CRM base node returns crm-customers and crm-deals as children
4844
+ */
4845
+ nodes?: Record<string, KnowledgeNode>
4846
+ }
4847
+
4848
+ /**
4849
+ * Execution interface configuration
4850
+ * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
4851
+ * Applies to both agents and workflows
4852
+ */
4853
+ interface ExecutionInterface {
4854
+ /** Form configuration for execution inputs */
4855
+ form: ExecutionFormSchema
4856
+
4857
+ /** Optional: Schedule configuration */
4858
+ schedule?: ScheduleConfig
4859
+
4860
+ /** Optional: Webhook trigger configuration */
4861
+ webhook?: WebhookConfig
4862
+ }
4863
+
4864
+ /**
4865
+ * Execution form schema
4866
+ * Extends FormSchema with execution-specific fields
4867
+ */
4868
+ interface ExecutionFormSchema extends FormSchema {
4869
+ /**
4870
+ * Field mappings to resource input schema
4871
+ * Maps form field names to contract input paths
4872
+ * If omitted, field names must match contract input keys exactly
4873
+ */
4874
+ fieldMappings?: Record<string, string>
4875
+
4876
+ /**
4877
+ * Submit button configuration
4878
+ * Default: { label: 'Run', loadingLabel: 'Running...' }
4879
+ */
4880
+ submitButton?: {
4881
+ label?: string
4882
+ loadingLabel?: string
4883
+ confirmMessage?: string // Optional confirmation dialog
4884
+ }
4885
+ }
4886
+
4887
+ /**
4888
+ * Schedule configuration for automated execution
4889
+ */
4890
+ interface ScheduleConfig {
4891
+ /** Whether scheduling is enabled for this resource */
4892
+ enabled: boolean
4893
+ /** Default schedule (cron expression) */
4894
+ defaultSchedule?: string
4895
+ /** Allowed schedule patterns (if restricted) */
4896
+ allowedPatterns?: string[]
4897
+ }
4898
+
4899
+ /**
4900
+ * Webhook configuration for external triggers
4901
+ */
4902
+ interface WebhookConfig {
4903
+ /** Whether webhook trigger is enabled */
4904
+ enabled: boolean
4905
+ /** Expected payload schema (for documentation) */
4906
+ payloadSchema?: unknown
4907
+ }
4908
+
4909
+ /**
4910
+ * Agent-specific type definitions
4911
+ * Types for autonomous agents with tools, memory, and constraints
4912
+ */
4913
+
4914
+
4915
+
4916
+ /**
4917
+ * Factory function for creating LLM adapters.
4918
+ * Injected into the Agent class to decouple the engine from server-only provider SDKs.
4919
+ * - API process: provides createLLMAdapter (real SDKs + process.env API keys)
4920
+ * - SDK worker: provides PostMessageLLMAdapter (proxies via platform.call)
4921
+ *
4922
+ * Uses `any` for optional params so both the real createLLMAdapter (with typed
4923
+ * AIUsageCollector/AICallContext) and the worker proxy (which ignores them) satisfy the type.
4924
+ */
4925
+ type LLMAdapterFactory = (
4926
+ config: ModelConfig,
4927
+ ...args: any[]
4928
+ ) => LLMAdapter
4929
+
4930
+ // Agent configuration
4931
+ interface AgentConfig extends ResourceDefinition {
4932
+ type: 'agent'
4933
+
4934
+ // Agent behavior
4935
+ systemPrompt: string // System prompt defining agent behavior
4936
+
4937
+ // Execution constraints (simplified for v1)
4938
+ constraints?: AgentConstraints
4939
+
4940
+ /**
4941
+ * Session capability declaration (opt-in)
4942
+ * If true, agent is designed for multi-turn session interactions
4943
+ * Controls whether agent can use message action and appears in Sessions UI
4944
+ *
4945
+ * Use for:
4946
+ * - Conversational agents with multi-turn interactions
4947
+ * - Agents requiring persistent context across turns
4948
+ * - Agents that need human-in-the-loop communication
4949
+ */
4950
+ sessionCapable?: boolean
4951
+
4952
+ /**
4953
+ * Security level for system prompt hardening (auto-derived if omitted)
4954
+ *
4955
+ * - 'standard': Lightweight defense (3 rules) - default for non-session agents
4956
+ * - 'hardened': Comprehensive defense (6 rules) - default for session-capable agents
4957
+ * - 'none': No security prompt - for pure internal agents with no external input
4958
+ *
4959
+ * If omitted, derived from sessionCapable:
4960
+ * sessionCapable: true -> 'hardened'
4961
+ * sessionCapable: false -> 'standard'
4962
+ */
4963
+ securityLevel?: 'standard' | 'hardened' | 'none'
4964
+
4965
+ /**
4966
+ * Memory management preferences (opt-in)
4967
+ * If provided, agent can use memoryOps to manage session memory
4968
+ * If omitted, agent has no memory management capabilities
4969
+ *
4970
+ * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
4971
+ * This guidance is injected into the system prompt when memory management is enabled.
4972
+ *
4973
+ * Use for:
4974
+ * - Conversational agents needing cross-turn context
4975
+ * - Agents managing complex user preferences
4976
+ * - Agents tracking decisions over multiple iterations
4977
+ */
4978
+ memoryPreferences?: string
4979
+
4980
+ // Lifecycle callbacks for observability (optional) - DEFERRED
4981
+ }
4982
+
4983
+ // Execution constraints to prevent runaway agents
4984
+ interface AgentConstraints {
4985
+ // Agent execution control
4986
+ maxIterations?: number // Prevent infinite loops
4987
+ timeout?: number // Execution time limit (ms)
4988
+
4989
+ // Memory constraints
4990
+ maxSessionMemoryKeys?: number // Max session memory keys (default: 10)
4991
+ maxMemoryTokens?: number // Total token budget for all memory (default: 14000)
4992
+ }
4993
+
4994
+ // Agent definition - pure configuration without instance state
4995
+ // Used by registry to define agents that can be instantiated with fresh memory
4996
+ interface AgentDefinition {
4997
+ config: AgentConfig
4998
+ contract: Contract
4999
+ tools: Tool[]
5000
+
5001
+ /**
5002
+ * Model configuration for LLM execution
5003
+ * Specifies provider, API key, and model-specific options
5004
+ */
5005
+ modelConfig: ModelConfig
5006
+
5007
+ /**
5008
+ * Optional knowledge map for lazy-loading capabilities
5009
+ * Enables agents to navigate organizational knowledge on-demand
5010
+ */
5011
+ knowledgeMap?: KnowledgeMap
5012
+
5013
+ /**
5014
+ * Preload memory before execution starts
5015
+ * Handles BOTH context loading AND session restoration
5016
+ *
5017
+ * @param context - Execution context (includes sessionId if session turn)
5018
+ * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
5019
+ */
5020
+ preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory
5021
+
5022
+ /**
5023
+ * Metrics configuration for ROI calculations
5024
+ * Optional: Only needed if tracking automation savings
5025
+ */
5026
+ metricsConfig?: ResourceMetricsConfig
5027
+
5028
+ /**
5029
+ * Execution interface configuration (optional)
5030
+ * If provided, agent appears in Execution Runner UI
5031
+ */
5032
+ interface?: ExecutionInterface
5033
+ }
5034
+
5035
+ /**
5036
+ * Agent execution context
5037
+ * Groups all state needed for agent execution phases
5038
+ */
5039
+ interface IterationContext {
5040
+ config: AgentConfig
5041
+ contract: Contract
5042
+ toolRegistry: Map<string, Tool>
5043
+ memoryManager: MemoryManager
5044
+ executionContext: ExecutionContext
5045
+ iteration: number
5046
+ logger: AgentScopedLogger
5047
+ modelConfig: ModelConfig
5048
+ adapterFactory: LLMAdapterFactory
5049
+ knowledgeMap?: KnowledgeMap
5050
+ }
5051
+
5052
+ /**
5053
+ * Tool definitions
5054
+ *
5055
+ * Tool interface used by agents and workflows.
5056
+ * Provides a universal interface for AI systems to interact with tools.
5057
+ */
5058
+
5059
+
5060
+
5061
+ /**
5062
+ * Options for tool execution
5063
+ * Provides named parameters for better API clarity and extensibility
5064
+ */
5065
+ interface ToolExecutionOptions {
5066
+ /** Tool input (validated against inputSchema before execution) */
5067
+ input: unknown
5068
+
5069
+ /** Execution context with multi-tenant isolation and observability (optional for simple tools, required for platform/integration tools) */
5070
+ executionContext?: ExecutionContext
5071
+
5072
+ /** Full iteration context for advanced tools (provides access to memoryManager, toolRegistry, logger, etc.) */
5073
+ iterationContext?: IterationContext
5074
+
5075
+ /** Abort signal for timeout/cancellation -- forward to fetch() calls for clean cancellation */
5076
+ signal?: AbortSignal
5077
+ }
5078
+
5079
+ /**
5080
+ * Tool interface for AI systems
5081
+ *
5082
+ * Used by:
5083
+ * - Agents: For agentic tool use (reasoning loop selects and executes tools)
5084
+ * - Workflows: For workflow step tool invocation (future)
5085
+ * - Platform tools: createApprovalTool(), createSchedulerTool()
5086
+ * - Integration tools: External API calls (Gmail, Slack, etc.)
5087
+ */
5088
+ interface Tool {
5089
+ // Required fields
5090
+ name: string // Unique identifier (e.g., 'web_search', 'calculator')
5091
+ description: string // What the tool does (used by LLM for selection)
5092
+
5093
+ // I/O validation (both required for complete type safety)
5094
+ inputSchema: z.ZodSchema // Input validation schema
5095
+ outputSchema: z.ZodSchema // Output validation schema
5096
+
5097
+ // Execution
5098
+ execute: (options: ToolExecutionOptions) => Promise<unknown>
5099
+
5100
+ // Timeout (optional) -- per-tool override in ms, defaults to DEFAULT_TOOL_TIMEOUT (300_000 / 5min) in executor
5101
+ timeout?: number
5102
+ }
5103
+
5104
+ /**
5105
+ * Action configuration for HITL tasks
5106
+ * Defines available user actions and their behavior
5107
+ */
5108
+ interface ActionConfig {
5109
+ /** Unique action identifier (e.g., 'approve', 'retry', 'escalate') */
5110
+ id: string
5111
+
5112
+ /** Display label for UI button */
5113
+ label: string
5114
+
5115
+ /** Button variant/style */
5116
+ type: 'primary' | 'secondary' | 'danger' | 'outline'
5117
+
5118
+ /** Tabler icon name (e.g., 'IconCheck', 'IconRefresh') */
5119
+ icon?: string
5120
+
5121
+ /** Button color (Mantine theme colors) */
5122
+ color?: string
5123
+
5124
+ /** Button variant (Mantine button variant, e.g., 'light', 'filled', 'outline') */
5125
+ variant?: string
5126
+
5127
+ /** Execution target (agent/workflow to invoke) */
5128
+ target?: {
5129
+ resourceType: 'agent' | 'workflow'
5130
+ resourceId: string
5131
+ /**
5132
+ * Optional session ID for agent continuation.
5133
+ * If provided, invokes a new turn on the existing session instead of standalone execution.
5134
+ * Only valid when resourceType is 'agent'.
5135
+ */
5136
+ sessionId?: string
5137
+ }
5138
+
5139
+ /** Form schema for collecting action-specific data */
5140
+ form?: FormSchema
5141
+
5142
+ /** Payload template for pre-filling forms */
5143
+ payloadTemplate?: unknown
5144
+
5145
+ /** Requires confirmation dialog */
5146
+ requiresConfirmation?: boolean
5147
+
5148
+ /** Confirmation message */
5149
+ confirmationMessage?: string
5150
+
5151
+ /** Help text / tooltip */
5152
+ description?: string
5153
+ }
5154
+
5155
+ /**
5156
+ * Origin resource type - where an execution/task originated from.
5157
+ * Used for audit trails and tracking execution lineage.
5158
+ */
5159
+ type OriginResourceType = 'agent' | 'workflow' | 'scheduler' | 'api'
5160
+
5161
+ /**
5162
+ * Origin tracking metadata - who/what created this execution/task.
5163
+ * Used by both TaskScheduler and CommandQueue for complete audit trails.
5164
+ */
5165
+ interface OriginTracking {
5166
+ originExecutionId: string
5167
+ originResourceType: OriginResourceType
5168
+ originResourceId: string
5169
+ }
5170
+
5171
+ /**
5172
+ * Command queue task with flexible action system
5173
+ */
5174
+ interface Task extends OriginTracking {
5175
+ id: string
5176
+ organizationId: string
5177
+
5178
+ // NEW: Flexible action system
5179
+ actions: ActionConfig[]
5180
+ context: unknown
5181
+ selectedAction?: string
5182
+ actionPayload?: unknown
5183
+
5184
+ // Task metadata
5185
+ description?: string
5186
+ priority: number
5187
+
5188
+ /** Optional checkpoint identifier for grouping related human approval tasks */
5189
+ humanCheckpoint?: string
5190
+
5191
+ // Status (updated to include 'completed')
5192
+ status: TaskStatus
5193
+
5194
+ /**
5195
+ * Target resource tracking — mirrors origin columns.
5196
+ * Set when task is created; patchable to redirect execution to a different resource.
5197
+ */
5198
+ targetResourceId?: string
5199
+ targetResourceType?: 'agent' | 'workflow'
5200
+
5201
+ /**
5202
+ * Execution ID for the action that runs AFTER user approval.
5203
+ * NULL until execution starts.
5204
+ *
5205
+ * Naming distinction:
5206
+ * - originExecutionId = Parent execution that CREATED the HITL task
5207
+ * - targetExecutionId = Child execution that RUNS AFTER user approval
5208
+ */
5209
+ targetExecutionId?: string
5210
+
5211
+ createdAt: Date
5212
+ completedAt?: Date
5213
+ completedBy?: string
5214
+ expiresAt?: Date
5215
+ idempotencyKey?: string | null
5216
+ }
5217
+
5218
+ /**
5219
+ * Task status values
5220
+ * - pending: awaiting action
5221
+ * - processing: execution in progress after user approval
5222
+ * - completed: action was taken and execution succeeded
5223
+ * - failed: execution failed, task can be retried
5224
+ * - expired: timed out before action
5225
+ */
5226
+ type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'expired'
5227
+
5228
+ /**
5229
+ * Parameters for patching mutable metadata on a task
5230
+ */
5231
+ interface PatchTaskParams {
5232
+ humanCheckpoint?: string | null
5233
+ description?: string
5234
+ priority?: number
5235
+ context?: Record<string, unknown>
5236
+ actions?: unknown[]
5237
+ targetResourceId?: string | null
5238
+ targetResourceType?: 'agent' | 'workflow' | null
5239
+ targetExecutionId?: string
5240
+ status?: 'pending' | 'failed' | 'completed'
5241
+ }
5242
+
5243
+ /**
5244
+ * Checkpoint list item for sidebar grouping
5245
+ * The id field contains the resourceId of the human checkpoint
5246
+ */
5247
+ interface CheckpointListItem {
5248
+ /** Human checkpoint resourceId (or 'ungrouped' for tasks without checkpoint) */
5249
+ id: string
5250
+ /** Display name (same as id, or "Ungrouped" for null) */
5251
+ name: string
5252
+ /** Task count for this checkpoint */
5253
+ count: number
5254
+ }
5255
+
5256
+ /**
5257
+ * Status counts for pie chart display
5258
+ */
5259
+ interface StatusCounts {
3562
5260
  pending: number
3563
5261
  completed: number
3564
5262
  expired: number
3565
5263
  }
3566
5264
 
3567
5265
  /**
3568
- * Priority counts for donut chart display
5266
+ * Priority counts for donut chart display
5267
+ */
5268
+ interface PriorityCounts {
5269
+ critical: number
5270
+ high: number
5271
+ medium: number
5272
+ low: number
5273
+ }
5274
+
5275
+ /**
5276
+ * Response from GET /command-queue/checkpoints endpoint
5277
+ */
5278
+ interface CheckpointListResponse {
5279
+ checkpoints: CheckpointListItem[]
5280
+ /** Total tasks across all checkpoints */
5281
+ total: number
5282
+ /** Breakdown by status for donut chart */
5283
+ statusCounts: StatusCounts
5284
+ /** Breakdown by priority for donut chart */
5285
+ priorityCounts: PriorityCounts
5286
+ }
5287
+
5288
+ interface RecurringScheduleConfig {
5289
+ type: 'recurring'
5290
+ cron?: string
5291
+ interval?: 'daily' | 'weekly' | 'monthly'
5292
+ time?: string
5293
+ timezone: string
5294
+ payload: Record<string, unknown>
5295
+ endAt?: string | null
5296
+ overduePolicy?: 'skip' | 'execute' // Default: 'skip'
5297
+ }
5298
+
5299
+ interface RelativeScheduleConfig {
5300
+ type: 'relative'
5301
+ anchorAt: string
5302
+ anchorLabel?: string
5303
+ items: RelativeScheduleItem[]
5304
+ overduePolicy?: 'skip' | 'execute' // Default: 'skip'
5305
+ }
5306
+
5307
+ interface RelativeScheduleItem {
5308
+ offset: string // '-7d', '+3d', '-2h', '+1h'
5309
+ payload: Record<string, unknown>
5310
+ label?: string
5311
+ }
5312
+
5313
+ interface AbsoluteScheduleConfig {
5314
+ type: 'absolute'
5315
+ items: AbsoluteScheduleItem[]
5316
+ overduePolicy?: 'skip' | 'execute' // Default: 'skip'
5317
+ }
5318
+
5319
+ interface AbsoluteScheduleItem {
5320
+ runAt: string
5321
+ payload: Record<string, unknown>
5322
+ label?: string
5323
+ }
5324
+
5325
+ /**
5326
+ * Wire-format DTO for notification API responses.
5327
+ * Dates are ISO 8601 strings (not Date objects like the domain Notification type).
5328
+ * Used by frontend hooks that consume /api/notifications.
5329
+ */
5330
+ interface NotificationDTO {
5331
+ id: string
5332
+ userId: string
5333
+ organizationId: string
5334
+ category: string
5335
+ title: string
5336
+ message: string
5337
+ actionUrl: string | null
5338
+ read: boolean
5339
+ readAt: string | null
5340
+ createdAt: string
5341
+ }
5342
+
5343
+ // Workflow configuration
5344
+ interface WorkflowConfig extends ResourceDefinition {
5345
+ type: 'workflow'
5346
+ }
5347
+
5348
+ // Workflow step definition
5349
+ interface WorkflowStepDefinition {
5350
+ id: string
5351
+ name: string
5352
+ description: string
5353
+ }
5354
+
5355
+ // Step handler function type
5356
+ type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>
5357
+
5358
+ // Next step configuration types
5359
+ interface LinearNext {
5360
+ type: 'linear'
5361
+ target: string
5362
+ }
5363
+
5364
+ interface ConditionalNext {
5365
+ type: 'conditional'
5366
+ routes: Array<{
5367
+ condition: (data: unknown) => boolean
5368
+ target: string
5369
+ }>
5370
+ default: string // Required to avoid ambiguity
5371
+ }
5372
+
5373
+ type NextConfig =
5374
+ | LinearNext // Go to specific step
5375
+ | ConditionalNext // Conditional routing
5376
+ | null // Explicitly end workflow
5377
+
5378
+ // Workflow step with graph-based flow
5379
+ interface WorkflowStep extends WorkflowStepDefinition {
5380
+ handler: StepHandler
5381
+
5382
+ // I/O validation (BOTH REQUIRED for complete type safety)
5383
+ inputSchema: z.ZodSchema // Validates input from previous step or workflow
5384
+ outputSchema: z.ZodSchema // Validates output before next step
5385
+
5386
+ next: NextConfig // Required - explicit flow decision for every step
5387
+ }
5388
+
5389
+ // Workflow definition - pure configuration without instance state
5390
+ // Used by registry to define workflows that can be instantiated
5391
+ interface WorkflowDefinition {
5392
+ config: WorkflowConfig
5393
+ contract: Contract
5394
+ steps: Record<string, WorkflowStep>
5395
+ entryPoint: string
5396
+
5397
+ /**
5398
+ * Metrics configuration for ROI calculations
5399
+ * Optional: Only needed if tracking automation savings
5400
+ */
5401
+ metricsConfig?: ResourceMetricsConfig
5402
+
5403
+ /**
5404
+ * Execution interface configuration (optional)
5405
+ * If provided, workflow appears in Execution Runner UI
5406
+ */
5407
+ interface?: ExecutionInterface
5408
+ }
5409
+
5410
+ /**
5411
+ * Standard Domain Definitions
5412
+ * Centralized domain constants and definitions for all organization resources.
5413
+ */
5414
+
5415
+
5416
+
5417
+ // ============================================================================
5418
+ // Standard Domain IDs
5419
+ // ============================================================================
5420
+
5421
+ declare const DOMAINS = {
5422
+ // Business domains
5423
+ INBOUND_PIPELINE: 'inbound-pipeline',
5424
+ LEAD_GEN_PIPELINE: 'lead-gen-pipeline',
5425
+ SUPPORT: 'support',
5426
+ CLIENT_SUPPORT: 'client-support',
5427
+ DELIVERY: 'delivery',
5428
+ OPERATIONS: 'operations',
5429
+ FINANCE: 'finance',
5430
+ EXECUTIVE: 'executive',
5431
+ INSTANTLY: 'instantly',
5432
+
5433
+ // Technical domains
5434
+ TESTING: 'testing',
5435
+ INTERNAL: 'internal',
5436
+ INTEGRATION: 'integration',
5437
+ UTILITY: 'utility',
5438
+ DIAGNOSTIC: 'diagnostic'
5439
+ } as const
5440
+
5441
+ /**
5442
+ * ResourceDomain - Strongly typed domain identifier
5443
+ * Use this type for all domain references to ensure compile-time validation.
5444
+ */
5445
+ type ResourceDomain = (typeof DOMAINS)[keyof typeof DOMAINS]
5446
+
5447
+ /**
5448
+ * Supported integration types
5449
+ *
5450
+ * These represent the available integration adapters that can be used with tools.
5451
+ * Each integration type corresponds to an adapter implementation.
5452
+ *
5453
+ * Note: Concrete adapter implementations are deferred until needed.
5454
+ * This type provides compile-time safety and auto-completion for tool definitions.
5455
+ */
5456
+ type IntegrationType =
5457
+ | 'gmail' // Google Gmail API
5458
+ | 'google-sheets' // Google Sheets API
5459
+ | 'slack' // Slack API
5460
+ | 'github' // GitHub API
5461
+ | 'linear' // Linear API
5462
+ | 'attio' // Attio CRM API
5463
+ | 'airtable' // Airtable API
5464
+ | 'salesforce' // Salesforce API
5465
+ | 'hubspot' // HubSpot API
5466
+ | 'stripe' // Stripe API
5467
+ | 'twilio' // Twilio API
5468
+ | 'sendgrid' // SendGrid API
5469
+ | 'mailgun' // Mailgun API
5470
+ | 'zapier' // Zapier Webhooks
5471
+ | 'webhook' // Generic webhook
5472
+ | 'apify' // Apify actor automation
5473
+ | 'instantly' // Instantly.ai email automation
5474
+ | 'resend' // Resend transactional email API
5475
+ | 'signature-api' // SignatureAPI eSignature service
5476
+ | 'dropbox' // Dropbox file storage API
5477
+ | 'anymailfinder' // Anymailfinder email finder API
5478
+ | 'tomba' // Tomba email discovery API
5479
+ | 'millionverifier'
5480
+
5481
+ /**
5482
+ * Resource Registry type definitions
5483
+ */
5484
+
5485
+
5486
+
5487
+ // ============================================================================
5488
+ // Core Resource Type Definitions
5489
+ // ============================================================================
5490
+
5491
+ /**
5492
+ * Environment/deployment status for resources
5493
+ */
5494
+ type ResourceStatus = 'dev' | 'prod'
5495
+
5496
+ /**
5497
+ * All resource types in the platform
5498
+ * Used as the discriminator field in ResourceDefinition
5499
+ */
5500
+ type ResourceType = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human'
5501
+
5502
+ // ============================================================================
5503
+ // Base Resource Interface
5504
+ // ============================================================================
5505
+
5506
+ /**
5507
+ * Base interface for ALL platform resources
5508
+ * Shared by both executable (agents, workflows) and non-executable (triggers, integrations, etc.) resources
5509
+ */
5510
+ interface ResourceDefinition {
5511
+ /** Unique resource identifier */
5512
+ resourceId: string
5513
+
5514
+ /** Display name */
5515
+ name: string
5516
+
5517
+ /** Purpose and functionality description */
5518
+ description: string
5519
+
5520
+ /** Version for change tracking and evolution */
5521
+ version: string
5522
+
5523
+ /** Resource type discriminator */
5524
+ type: ResourceType
5525
+
5526
+ /** Environment/deployment status */
5527
+ status: ResourceStatus
5528
+
5529
+ /** Domain tags for filtering and organization */
5530
+ domains?: ResourceDomain[]
5531
+
5532
+ /** Whether the agent supports multi-turn sessions (agents only) */
5533
+ sessionCapable?: boolean
5534
+
5535
+ /** Whether the resource is local (monorepo) or remote (externally deployed) */
5536
+ origin?: 'local' | 'remote'
5537
+
5538
+ /** Whether this resource is archived and should be excluded from registration and deployment */
5539
+ archived?: boolean
5540
+ }
5541
+
5542
+ // ============================================================================
5543
+ // Domain Definition Types
5544
+ // ============================================================================
5545
+
5546
+ /**
5547
+ * Domain definition for Command View filtering
5548
+ *
5549
+ * Domains are organizational metadata for UI filtering/grouping.
5550
+ * No execution impact - purely for visualization.
5551
+ *
5552
+ * @example
5553
+ * {
5554
+ * id: 'support',
5555
+ * name: 'Customer Support',
5556
+ * description: 'Ticket triage, knowledge base, escalations',
5557
+ * color: 'green',
5558
+ * icon: 'IconHeadset'
5559
+ * }
5560
+ */
5561
+ interface DomainDefinition {
5562
+ /** Unique identifier (e.g., 'support') */
5563
+ id: string
5564
+ /** Display name (e.g., 'Customer Support') */
5565
+ name: string
5566
+ /** Purpose description */
5567
+ description: string
5568
+ /** Optional Mantine color for UI (e.g., 'blue', 'green', 'orange') */
5569
+ color?: string
5570
+ /** Optional Tabler icon name (e.g., 'IconHeadset') */
5571
+ icon?: string
5572
+ }
5573
+
5574
+ // ============================================================================
5575
+ // Resource Manifest Types
5576
+ // ============================================================================
5577
+
5578
+ // ============================================================================
5579
+ // Trigger Configuration Types
5580
+ // ============================================================================
5581
+
5582
+ /** Webhook provider identifiers */
5583
+ type WebhookProviderType = 'cal-com' | 'stripe' | 'signature-api' | 'instantly' | 'apify'
5584
+
5585
+ /** Webhook trigger configuration */
5586
+ interface WebhookTriggerConfig {
5587
+ /** Provider identifier */
5588
+ provider: WebhookProviderType
5589
+ /** Event type for documentation (not used for matching - workflow handles routing) */
5590
+ event?: string
5591
+ /** Optional filtering (e.g., specific form ID for Fillout) */
5592
+ filter?: Record<string, string>
5593
+ /** References credential in credentials table for per-org webhook secrets */
5594
+ credentialName?: string
5595
+ }
5596
+
5597
+ /** Schedule trigger configuration */
5598
+ interface ScheduleTriggerConfig {
5599
+ /** Cron expression (e.g., '0 6 * * *') */
5600
+ cron: string
5601
+ /** Optional timezone (default: UTC) */
5602
+ timezone?: string
5603
+ }
5604
+
5605
+ /** Event trigger configuration */
5606
+ interface EventTriggerConfig {
5607
+ /** Internal event type */
5608
+ eventType: string
5609
+ /** Event source */
5610
+ source?: string
5611
+ }
5612
+
5613
+ /** Union of all trigger configs */
5614
+ type TriggerConfig = WebhookTriggerConfig | ScheduleTriggerConfig | EventTriggerConfig
5615
+
5616
+ // ============================================================================
5617
+ // Trigger Definition
5618
+ // ============================================================================
5619
+
5620
+ /**
5621
+ * Trigger metadata - entry points that initiate resource execution
5622
+ *
5623
+ * Triggers represent how executions start: webhooks from external services,
5624
+ * scheduled cron jobs, platform events, or manual user actions.
5625
+ *
5626
+ * BREAKING CHANGES (2025-11-30):
5627
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
5628
+ * - Field renames: `id` -> `resourceId` (inherited), `type` -> `triggerType`
5629
+ * - Relationship rename: `invokes` -> `triggers` (unified vocabulary)
5630
+ * - New required fields: `version` (inherited), `type: 'trigger'` (inherited)
5631
+ * - triggers object now includes `externalResources` option
5632
+ *
5633
+ * @example
5634
+ * // TriggerDefinition - metadata only
5635
+ * {
5636
+ * resourceId: 'trigger-new-order',
5637
+ * type: 'trigger',
5638
+ * triggerType: 'webhook',
5639
+ * name: 'New Order',
5640
+ * description: 'Webhook from Shopify on new orders',
5641
+ * version: '1.0.0',
5642
+ * status: 'prod',
5643
+ * webhookPath: '/webhooks/shopify/orders'
5644
+ * }
5645
+ *
5646
+ * // Relationships declared in ResourceRelationships (not on TriggerDefinition):
5647
+ * // relationships: {
5648
+ * // 'trigger-new-order': { triggers: { workflows: ['order-fulfillment-workflow'] } }
5649
+ * // }
5650
+ */
5651
+ interface TriggerDefinition extends ResourceDefinition {
5652
+ /** Resource type discriminator (narrowed from base union) */
5653
+ type: 'trigger'
5654
+
5655
+ /** Trigger mechanism type (renamed from 'type' to avoid collision with base type discriminator) */
5656
+ triggerType: 'webhook' | 'schedule' | 'manual' | 'event'
5657
+
5658
+ /** Type-specific configuration */
5659
+ config?: TriggerConfig
5660
+
5661
+ // Legacy fields (deprecated, use config instead)
5662
+ /** For webhook triggers: path like '/webhooks/shopify/orders' */
5663
+ webhookPath?: string
5664
+ /** For schedule triggers: cron expression like '0 6 * * *' */
5665
+ schedule?: string
5666
+ /** For event triggers: event type like 'low-stock-alert' */
5667
+ eventType?: string
5668
+
5669
+ // NOTE: What this trigger starts is declared in ResourceRelationships, not here
5670
+ // This prevents duplication - triggers are forward-declared in relationships
5671
+ }
5672
+
5673
+ /**
5674
+ * Integration metadata - external service connections
5675
+ *
5676
+ * References credentials table for actual connection. No connection status
5677
+ * stored here (queried at runtime from credentials table).
5678
+ *
5679
+ * BREAKING CHANGES (2025-11-30):
5680
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
5681
+ * - Field renames: `id` -> `resourceId` (inherited)
5682
+ * - New required field: `status` (inherited) - organizations must add status to all integrations
5683
+ * - New required field: `version` (inherited) - organizations must add version to all integrations
5684
+ * - New required field: `type: 'integration'` (inherited) - resource type discriminator
5685
+ *
5686
+ * @example
5687
+ * {
5688
+ * resourceId: 'integration-shopify-prod',
5689
+ * type: 'integration',
5690
+ * provider: 'shopify',
5691
+ * credentialName: 'shopify-prod',
5692
+ * name: 'Shopify Production',
5693
+ * description: 'E-commerce platform',
5694
+ * version: '1.0.0',
5695
+ * status: 'prod'
5696
+ * }
5697
+ */
5698
+ interface IntegrationDefinition extends ResourceDefinition {
5699
+ /** Resource type discriminator (narrowed from base union) */
5700
+ type: 'integration'
5701
+
5702
+ /** Integration provider type */
5703
+ provider: IntegrationType
5704
+ /** References credentials table (e.g., 'shopify-prod', 'zendesk-api') */
5705
+ credentialName: string
5706
+ }
5707
+
5708
+ // ============================================================================
5709
+ // External Resource Types
5710
+ // ============================================================================
5711
+
5712
+ /**
5713
+ * External platform type
5714
+ * Supported third-party automation platforms
5715
+ */
5716
+ type ExternalPlatform = 'n8n' | 'make' | 'zapier' | 'other'
5717
+
5718
+ /**
5719
+ * External automation resource metadata
5720
+ *
5721
+ * Represents workflows/automations running on third-party platforms
5722
+ * (n8n, Make, Zapier, etc.) for visualization in Command View.
5723
+ *
5724
+ * NOTE: This is metadata ONLY for visualization. No execution logic,
5725
+ * no API integration with external platforms, no status syncing.
5726
+ *
5727
+ * BREAKING CHANGES (2025-11-30):
5728
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
5729
+ * - Field renames: `id` -> `resourceId` (inherited)
5730
+ * - New required field: `version` (inherited) - organizations must add version to all external resources
5731
+ * - New required field: `type: 'external'` (inherited) - resource type discriminator
5732
+ * - REMOVED FIELD: `triggeredBy` - per relationship-consolidation design, all relationships are forward-only declarations
5733
+ *
5734
+ * @example
5735
+ * {
5736
+ * resourceId: 'external-n8n-order-sync',
5737
+ * type: 'external',
5738
+ * version: '1.0.0',
5739
+ * platform: 'n8n',
5740
+ * name: 'Shopify Order Sync',
5741
+ * description: 'Legacy n8n workflow for syncing Shopify orders',
5742
+ * status: 'prod',
5743
+ * platformUrl: 'https://n8n.client.com/workflow/123',
5744
+ * triggers: { workflows: ['order-fulfillment-workflow'] },
5745
+ * uses: { integrations: ['integration-shopify-prod'] }
5746
+ * }
5747
+ */
5748
+ interface ExternalResourceDefinition extends ResourceDefinition {
5749
+ /** Resource type discriminator (narrowed from base union) */
5750
+ type: 'external'
5751
+
5752
+ /** Platform type */
5753
+ platform: ExternalPlatform
5754
+
5755
+ // Optional platform-specific metadata
5756
+ /** Link to external platform (e.g., n8n workflow editor URL) */
5757
+ platformUrl?: string
5758
+ /** Platform's internal ID/reference */
5759
+ externalId?: string
5760
+
5761
+ /** What this external resource triggers (external -> internal) */
5762
+ triggers?: {
5763
+ /** Elevasis workflow resourceIds this external automation triggers */
5764
+ workflows?: string[]
5765
+ /** Elevasis agent resourceIds this external automation triggers */
5766
+ agents?: string[]
5767
+ }
5768
+
5769
+ /** Integrations this external resource uses (shared credentials) */
5770
+ uses?: {
5771
+ /** Integration IDs this external automation uses */
5772
+ integrations?: string[]
5773
+ }
5774
+
5775
+ // NOTE: triggeredBy field removed - per relationship-consolidation design,
5776
+ // all relationships are forward-only declarations. Graph edges are built
5777
+ // from forward declarations only.
5778
+ }
5779
+
5780
+ /**
5781
+ * Human Checkpoint definition - human decision points in automation
5782
+ *
5783
+ * Represents where human judgment is deployed in the automation landscape.
5784
+ * Tasks with matching command_queue_group are routed to this checkpoint.
5785
+ *
5786
+ * BREAKING CHANGES (2025-11-30):
5787
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
5788
+ * - Field renames: `id` -> `resourceId` (inherited)
5789
+ * - description is now REQUIRED (was optional) - organizations must add description to all human checkpoints
5790
+ * - New required field: `version` (inherited) - organizations must add version to all human checkpoints
5791
+ * - New required field: `type: 'human'` (inherited) - resource type discriminator
5792
+ *
5793
+ * @example
5794
+ * {
5795
+ * resourceId: 'sales-approval',
5796
+ * type: 'human',
5797
+ * name: 'Sales Approval Queue',
5798
+ * description: 'High-value order approvals for sales team',
5799
+ * version: '1.0.0',
5800
+ * status: 'prod',
5801
+ * requestedBy: { agents: ['order-processor-agent'] },
5802
+ * routesTo: { agents: ['order-fulfillment-agent'] }
5803
+ * }
5804
+ */
5805
+ interface HumanCheckpointDefinition extends ResourceDefinition {
5806
+ /** Resource type discriminator (narrowed from base union) */
5807
+ type: 'human'
5808
+
5809
+ /** Resources that create tasks for this checkpoint */
5810
+ requestedBy?: {
5811
+ /** Agent resourceIds that request approval here */
5812
+ agents?: string[]
5813
+ /** Workflow resourceIds that request approval here */
5814
+ workflows?: string[]
5815
+ }
5816
+
5817
+ /** Resources that receive approved decisions */
5818
+ routesTo?: {
5819
+ /** Agent resourceIds that handle approved tasks */
5820
+ agents?: string[]
5821
+ /** Workflow resourceIds that handle approved tasks */
5822
+ workflows?: string[]
5823
+ }
5824
+ }
5825
+
5826
+ /**
5827
+ * Command View Types
5828
+ *
5829
+ * Unified type definitions for the Command View graph visualization.
5830
+ * These types are used by both backend serialization and frontend rendering.
5831
+ *
5832
+ * Command View shows the resource graph: agents, workflows, triggers, integrations,
5833
+ * external resources, and human checkpoints with their relationships.
5834
+ */
5835
+
5836
+
5837
+
5838
+ // ============================================================================
5839
+ // Node Types - Resources that appear in the graph
5840
+ // ============================================================================
5841
+
5842
+ /**
5843
+ * Extended agent metadata for Command View
5844
+ * Includes model and capability information for graph display
5845
+ */
5846
+ interface CommandViewAgent extends ResourceDefinition {
5847
+ type: 'agent'
5848
+ modelProvider: string // e.g., 'anthropic', 'openai'
5849
+ modelId: string // e.g., 'claude-sonnet-4-20250514'
5850
+ toolCount: number
5851
+ hasKnowledgeMap: boolean
5852
+ hasMemory: boolean
5853
+ sessionCapable: boolean // Explicit session capability declaration
5854
+ }
5855
+
5856
+ /**
5857
+ * Extended workflow metadata for Command View
5858
+ * Includes step information for graph display
5859
+ */
5860
+ interface CommandViewWorkflow extends ResourceDefinition {
5861
+ type: 'workflow'
5862
+ stepCount: number
5863
+ entryPoint: string
5864
+ }
5865
+
5866
+ /**
5867
+ * Node type categories for Command View
5868
+ * Simplified categorization for UI rendering and layout
5869
+ */
5870
+ type CommandViewNodeType = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human'
5871
+
5872
+ /**
5873
+ * Union type for all node types in Command View
5874
+ * Frontend can use this for type-safe node handling
5875
+ */
5876
+ type CommandViewNode =
5877
+ | CommandViewAgent
5878
+ | CommandViewWorkflow
5879
+ | TriggerDefinition
5880
+ | IntegrationDefinition
5881
+ | ExternalResourceDefinition
5882
+ | HumanCheckpointDefinition
5883
+
5884
+ // ============================================================================
5885
+ // Edge Types - Relationships between resources
5886
+ // ============================================================================
5887
+
5888
+ /**
5889
+ * Relationship types between resources
5890
+ *
5891
+ * - triggers: Resource initiates/starts another resource (orange)
5892
+ * - uses: Resource uses an integration (teal)
5893
+ * - approval: Resource requires human approval (yellow)
5894
+ */
5895
+ type RelationshipType = 'triggers' | 'uses' | 'approval'
5896
+
5897
+ /**
5898
+ * Command View edge (relationship between resources)
5899
+ */
5900
+ interface CommandViewEdge {
5901
+ id: string
5902
+ source: string // Source node ID
5903
+ target: string // Target node ID
5904
+ relationship: RelationshipType
5905
+ label?: string // Optional label for the edge
5906
+ }
5907
+
5908
+ // ============================================================================
5909
+ // Graph Data Structure
5910
+ // ============================================================================
5911
+
5912
+ /**
5913
+ * Command View data structure
5914
+ * Complete graph data for visualization
5915
+ *
5916
+ * Backend serializes this once at startup and serves it via /command-view endpoint.
5917
+ * Frontend consumes this directly for graph rendering.
5918
+ */
5919
+ interface CommandViewData {
5920
+ workflows: CommandViewWorkflow[]
5921
+ agents: CommandViewAgent[]
5922
+ triggers: TriggerDefinition[]
5923
+ integrations: IntegrationDefinition[]
5924
+ externalResources: ExternalResourceDefinition[]
5925
+ humanCheckpoints: HumanCheckpointDefinition[]
5926
+ edges: CommandViewEdge[]
5927
+ domainDefinitions?: DomainDefinition[]
5928
+ }
5929
+
5930
+ /**
5931
+ * Serialized Registry Types
5932
+ *
5933
+ * Pre-computed JSON-safe types for API responses and Command View.
5934
+ * Serialization happens once at API startup, enabling instant response times.
5935
+ */
5936
+
5937
+
5938
+
5939
+ // ============================================================================
5940
+ // Serialized Interface Types (for Execution Runner UI)
5941
+ // ============================================================================
5942
+
5943
+ /**
5944
+ * Serialized form field for API responses
5945
+ */
5946
+ interface SerializedFormField {
5947
+ name: string
5948
+ label: string
5949
+ type: FormFieldType
5950
+ defaultValue?: unknown
5951
+ required?: boolean
5952
+ placeholder?: string
5953
+ description?: string
5954
+ options?: Array<{ label: string; value: string | number }>
5955
+ min?: number
5956
+ max?: number
5957
+ }
5958
+
5959
+ /**
5960
+ * Serialized form schema for API responses
5961
+ */
5962
+ interface SerializedFormSchema {
5963
+ title?: string
5964
+ description?: string
5965
+ fields: SerializedFormField[]
5966
+ layout?: 'vertical' | 'horizontal' | 'grid'
5967
+ }
5968
+
5969
+ /**
5970
+ * Serialized execution form schema for API responses
5971
+ */
5972
+ interface SerializedExecutionFormSchema extends SerializedFormSchema {
5973
+ fieldMappings?: Record<string, string>
5974
+ submitButton?: {
5975
+ label?: string
5976
+ loadingLabel?: string
5977
+ confirmMessage?: string
5978
+ }
5979
+ }
5980
+
5981
+ /**
5982
+ * Serialized schedule config for API responses
5983
+ */
5984
+ interface SerializedScheduleConfig {
5985
+ enabled: boolean
5986
+ defaultSchedule?: string
5987
+ allowedPatterns?: string[]
5988
+ }
5989
+
5990
+ /**
5991
+ * Serialized webhook config for API responses
5992
+ */
5993
+ interface SerializedWebhookConfig {
5994
+ enabled: boolean
5995
+ payloadSchema?: unknown
5996
+ }
5997
+
5998
+ /**
5999
+ * Serialized execution interface for API responses
6000
+ */
6001
+ interface SerializedExecutionInterface {
6002
+ form: SerializedExecutionFormSchema
6003
+ schedule?: SerializedScheduleConfig
6004
+ webhook?: SerializedWebhookConfig
6005
+ }
6006
+
6007
+ // ============================================================================
6008
+ // Serialized Definition Types
6009
+ // ============================================================================
6010
+
6011
+ /**
6012
+ * Serialized agent definition (JSON-safe)
6013
+ * Result of serializeDefinition(AgentDefinition)
6014
+ */
6015
+ interface SerializedAgentDefinition {
6016
+ config: {
6017
+ resourceId: string
6018
+ name: string
6019
+ description: string
6020
+ version: string
6021
+ type: 'agent'
6022
+ status: 'dev' | 'prod'
6023
+ /** Whether this resource is archived and should be excluded from registration and deployment */
6024
+ archived?: boolean
6025
+ systemPrompt: string
6026
+ constraints?: {
6027
+ maxIterations?: number
6028
+ timeout?: number
6029
+ maxSessionMemoryKeys?: number
6030
+ maxMemoryTokens?: number
6031
+ }
6032
+ sessionCapable?: boolean
6033
+ memoryPreferences?: string
6034
+ }
6035
+ modelConfig: {
6036
+ provider: string
6037
+ model: string
6038
+ apiKey: string // Redacted: "sk-proj..."
6039
+ temperature: number
6040
+ maxOutputTokens: number
6041
+ topP?: number
6042
+ modelOptions?: Record<string, unknown>
6043
+ }
6044
+ contract: {
6045
+ inputSchema: object // JSON Schema
6046
+ outputSchema?: object // JSON Schema
6047
+ }
6048
+ tools: Array<{
6049
+ name: string
6050
+ description: string
6051
+ inputSchema?: object // JSON Schema
6052
+ outputSchema?: object // JSON Schema
6053
+ }>
6054
+ knowledgeMap?: {
6055
+ nodeCount: number
6056
+ nodes: Array<{
6057
+ id: string
6058
+ description: string
6059
+ loaded: boolean
6060
+ hasPrompt: boolean
6061
+ }>
6062
+ }
6063
+ metricsConfig?: object
6064
+ interface?: SerializedExecutionInterface
6065
+ }
6066
+
6067
+ /**
6068
+ * Serialized workflow definition (JSON-safe)
6069
+ * Result of serializeDefinition(WorkflowDefinition)
6070
+ */
6071
+ interface SerializedWorkflowDefinition {
6072
+ config: {
6073
+ resourceId: string
6074
+ name: string
6075
+ description: string
6076
+ version: string
6077
+ type: 'workflow'
6078
+ status: 'dev' | 'prod'
6079
+ /** Whether this resource is archived and should be excluded from registration and deployment */
6080
+ archived?: boolean
6081
+ }
6082
+ entryPoint: string
6083
+ steps: Array<{
6084
+ id: string
6085
+ name: string
6086
+ description: string
6087
+ inputSchema?: object // JSON Schema
6088
+ outputSchema?: object // JSON Schema
6089
+ next: {
6090
+ type: 'linear' | 'conditional'
6091
+ target?: string
6092
+ routes?: Array<{ target: string }>
6093
+ default?: string
6094
+ } | null
6095
+ }>
6096
+ contract: {
6097
+ inputSchema: object // JSON Schema
6098
+ outputSchema?: object // JSON Schema
6099
+ }
6100
+ metricsConfig?: object
6101
+ interface?: SerializedExecutionInterface
6102
+ }
6103
+
6104
+ /**
6105
+ * Base Execution Engine type definitions
6106
+ * Core types shared across all Execution Engine resources
6107
+ */
6108
+
6109
+
6110
+
6111
+ /**
6112
+ * Immutable execution metadata
6113
+ * Represents complete execution identity (who, what, when, where)
6114
+ * Shared across ExecutionContext and ExecutionLoggerContext to eliminate field duplication
6115
+ */
6116
+ interface ExecutionMetadata {
6117
+ executionId: string // Unique ID for this execution instance
6118
+ organizationId: string // Required for multi-tenant isolation and security
6119
+ organizationName: string // Required for resource lookup in registry
6120
+ resourceId: string // Required for observability and audit trails
6121
+ userId?: string // Optional: user context for audit trails (API keys, system executions may not have userId)
6122
+ sessionId?: string // Optional: only for session executions
6123
+ sessionTurnNumber?: number // Optional: only for session executions (maps to execution_logs.session_turn_number)
6124
+ }
6125
+
6126
+ /**
6127
+ * Unified message event type - covers all message types in sessions
6128
+ * Replaces separate SessionTurnMessages and AgentActivityEvent mechanisms
6129
+ */
6130
+ /**
6131
+ * Structured action metadata attached to assistant messages.
6132
+ * Frontend reads this instead of parsing text prefixes.
6133
+ */
6134
+ type AssistantAction =
6135
+ | { kind: 'navigate'; path: string; reason: string }
6136
+ | {
6137
+ kind: 'update_filters'
6138
+ timeRange: string | null
6139
+ statusFilter: string | null
6140
+ searchQuery: string | null
6141
+ }
6142
+
6143
+ type MessageEvent =
6144
+ // User/Assistant text messages
6145
+ | { type: 'user_message'; text: string }
6146
+ | { type: 'assistant_message'; text: string; _action?: AssistantAction }
6147
+
6148
+ // Agent lifecycle events
6149
+ | { type: 'agent:started' }
6150
+ | { type: 'agent:completed' }
6151
+ | { type: 'agent:error'; error: string }
6152
+
6153
+ // Agent activity events (with metadata for UI)
6154
+ | { type: 'agent:reasoning'; iteration: number; reasoning: string }
6155
+ | { type: 'agent:tool_call'; toolName: string; args: Record<string, unknown> }
6156
+ | { type: 'agent:tool_result'; toolName: string; success: boolean; result?: unknown; error?: string }
6157
+
6158
+ /**
6159
+ * Execution context for all resources
6160
+ * Unified callback replaces SessionTurnMessages (removed)
6161
+ */
6162
+ interface ExecutionContext extends ExecutionMetadata {
6163
+ // Inherited: executionId, organizationId, organizationName, resourceId, userId, sessionId, sessionTurnNumber
6164
+ logger: IExecutionLogger // Required for observability and debugging
6165
+ signal?: AbortSignal // Future: cancellation support for long-running operations
6166
+
6167
+ // Unified message event callback (immediate persistence + streaming)
6168
+ onMessageEvent?: (event: MessageEvent) => Promise<void>
6169
+
6170
+ /** Called per iteration to write heartbeat + check stall status. Non-fatal if it throws. */
6171
+ onHeartbeat?: () => Promise<void>
6172
+
6173
+ // Observability collectors (optional - injected by coordinators)
6174
+ aiUsageCollector?: AIUsageCollector // Tracks AI token usage and costs
6175
+ metricsCollector?: MetricsCollector // Tracks execution timing and ROI metrics
6176
+
6177
+ // Nested execution tracking (Wave 2c - Agent Resource Invocation)
6178
+ parentExecutionId?: string // Parent execution ID for nested invocations
6179
+ executionDepth: number // Nesting depth: 0 = top-level, 1+ = nested
6180
+
6181
+ // Integration credential tracking (for OAuth token refresh persistence)
6182
+ credentialName?: string // Credential name used for current integration call
6183
+
6184
+ // Execution-scoped storage for large data (e.g., PDF buffers) that shouldn't be logged
6185
+ // Automatically garbage collected when execution context ends
6186
+ store: Map<string, unknown>
6187
+ }
6188
+
6189
+ // Contract definition - validation schemas (Zod)
6190
+ interface Contract {
6191
+ inputSchema: z.ZodSchema // Required - use z.object({}) for no input
6192
+ outputSchema?: z.ZodSchema // Optional - if present, agent generates output
6193
+ }
6194
+
6195
+ /**
6196
+ * Agent timeline and observability types
6197
+ * Used for UI timeline visualization and backend processing
6198
+ */
6199
+
6200
+
6201
+
6202
+ /**
6203
+ * Sub-activity within an iteration
6204
+ * Represents reasoning, actions, or tool calls with timing
6205
+ */
6206
+ interface SubActivity {
6207
+ type: 'reasoning' | 'action' | 'tool-call'
6208
+ startTime: number
6209
+ endTime: number
6210
+ duration: number
6211
+ details: AgentIterationEvent | AgentToolCallEvent
6212
+ }
6213
+
6214
+ /**
6215
+ * Agent iteration state
6216
+ * Aggregates lifecycle events and sub-activities for a single iteration
6217
+ */
6218
+ interface AgentIteration {
6219
+ iterationNumber: number
6220
+ status: 'running' | 'completed' | 'failed' | 'pending'
6221
+ iterationEvents: AgentIterationEvent[]
6222
+ duration?: number
6223
+ timestamp: number
6224
+ subActivities: SubActivity[]
6225
+
6226
+ // Timeline visualization timing (Phase 2 - optional for backward compatibility)
6227
+ startTime?: number // From lifecycle 'started' event
6228
+ endTime?: number // From lifecycle 'completed'/'failed' event
6229
+ }
6230
+
6231
+ /**
6232
+ * Agent lifecycle node state
6233
+ * Represents initialization or completion phase
6234
+ */
6235
+ interface AgentLifecycleNode {
6236
+ type: 'initialization' | 'completion'
6237
+ status: 'running' | 'completed' | 'failed' | 'pending'
6238
+ duration?: number
6239
+ timestamp?: number
6240
+
6241
+ // Timeline visualization timing (Phase 2 - optional for backward compatibility)
6242
+ startTime?: number // From lifecycle 'started' event
6243
+ endTime?: number // From lifecycle 'completed'/'failed' event
6244
+ }
6245
+
6246
+ /**
6247
+ * Complete agent execution data for timeline visualization
6248
+ * Parsed from execution logs
6249
+ */
6250
+ interface AgentIterationData {
6251
+ initialization: AgentLifecycleNode
6252
+ iterations: AgentIteration[]
6253
+ completion: AgentLifecycleNode
6254
+ currentIteration: number | null
6255
+ totalIterations: number
6256
+ totalDuration?: number
6257
+ status: 'running' | 'completed' | 'failed' | 'warning'
6258
+ }
6259
+
6260
+ // Execution status type shared between API and UI
6261
+ type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'warning'
6262
+
6263
+ /**
6264
+ * Event sent when new execution starts
6265
+ */
6266
+ interface ExecutionStartedEvent {
6267
+ type: 'new-execution'
6268
+ resourceId: string
6269
+ executionId: string
6270
+ timestamp: number
6271
+ data?: undefined
6272
+ }
6273
+
6274
+ /**
6275
+ * Event sent when execution log message is emitted
6276
+ */
6277
+ interface ExecutionLogEvent {
6278
+ type: 'log'
6279
+ resourceId: string
6280
+ executionId: string
6281
+ timestamp: number
6282
+ data: {
6283
+ log: ExecutionLogMessage
6284
+ }
6285
+ }
6286
+
6287
+ /**
6288
+ * Event sent when execution completes (success or failure)
3569
6289
  */
3570
- interface PriorityCounts {
3571
- critical: number
3572
- high: number
3573
- medium: number
3574
- low: number
6290
+ interface ExecutionCompleteEvent {
6291
+ type: 'execution-complete'
6292
+ resourceId: string
6293
+ executionId: string
6294
+ timestamp: number
6295
+ data: {
6296
+ success: boolean
6297
+ status?: ExecutionStatus
6298
+ result?: unknown
6299
+ error?: string
6300
+ }
3575
6301
  }
3576
6302
 
3577
6303
  /**
3578
- * Response from GET /command-queue/checkpoints endpoint
6304
+ * Connection confirmation event
3579
6305
  */
3580
- interface CheckpointListResponse {
3581
- checkpoints: CheckpointListItem[]
3582
- /** Total tasks across all checkpoints */
3583
- total: number
3584
- /** Breakdown by status for donut chart */
3585
- statusCounts: StatusCounts
3586
- /** Breakdown by priority for donut chart */
3587
- priorityCounts: PriorityCounts
6306
+ interface ExecutionConnectedEvent {
6307
+ type: 'connected'
6308
+ resourceId: string
6309
+ executionId?: undefined
6310
+ timestamp: number
6311
+ data?: undefined
3588
6312
  }
3589
6313
 
3590
6314
  /**
3591
- * Wire-format DTO for notification API responses.
3592
- * Dates are ISO 8601 strings (not Date objects like the domain Notification type).
3593
- * Used by frontend hooks that consume /api/notifications.
6315
+ * Union of all execution SSE events
3594
6316
  */
3595
- interface NotificationDTO {
6317
+ type ExecutionSSEEvent =
6318
+ | ExecutionStartedEvent
6319
+ | ExecutionLogEvent
6320
+ | ExecutionCompleteEvent
6321
+ | ExecutionConnectedEvent
6322
+
6323
+ // API execution types
6324
+ interface APIExecutionSummary {
3596
6325
  id: string
3597
- userId: string
3598
- organizationId: string
3599
- category: string
3600
- title: string
3601
- message: string
3602
- actionUrl: string | null
3603
- read: boolean
3604
- readAt: string | null
3605
- createdAt: string
6326
+ status: ExecutionStatus
6327
+ startTime: number
6328
+ endTime?: number
6329
+ resourceStatus?: ResourceStatus // 'dev' | 'prod' - optional for backward compatibility
3606
6330
  }
3607
6331
 
3608
- // Execution status type shared between API and UI
3609
- type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'warning'
3610
-
3611
6332
  /**
3612
6333
  * Execution Runner Types
3613
6334
  *
@@ -3672,6 +6393,462 @@ declare const ExecutionHistoryResponseSchema = z.object({
3672
6393
  type ExecutionHistoryItem = z.infer<typeof ExecutionHistoryItemSchema>
3673
6394
  type ExecutionHistoryResponse = z.infer<typeof ExecutionHistoryResponseSchema>
3674
6395
 
6396
+ /**
6397
+ * Calibration Lab Type Definitions
6398
+ * Core types for AI model configuration optimization with cost/performance comparison
6399
+ */
6400
+
6401
+
6402
+
6403
+ // ============================================================================
6404
+ // Calibration Project Types
6405
+ // ============================================================================
6406
+
6407
+ /**
6408
+ * Calibration project - groups related optimization runs
6409
+ * Provides organizational structure for iterative testing
6410
+ */
6411
+ interface CalibrationProject {
6412
+ id: string
6413
+ organizationId: string
6414
+ resourceId: string
6415
+ resourceType: 'agent' | 'workflow'
6416
+ name: string
6417
+ description?: string | null
6418
+ createdAt: Date
6419
+ updatedAt: Date
6420
+ }
6421
+
6422
+ // ============================================================================
6423
+ // Configuration Variant Types
6424
+ // ============================================================================
6425
+
6426
+ /**
6427
+ * Configuration variant for testing
6428
+ * Defines what to override in the base agent/workflow definition
6429
+ */
6430
+ interface ConfigVariant {
6431
+ variantName: string
6432
+ definitionOverrides?: AgentCalibrationOverrides | WorkflowCalibrationOverrides
6433
+ }
6434
+
6435
+ /**
6436
+ * Agent definition overrides for calibration
6437
+ * Excludes identity/metadata fields that should not be modified
6438
+ */
6439
+ type AgentCalibrationOverrides = Omit<
6440
+ Partial<AgentDefinition>,
6441
+ 'config' | 'contract' | 'tools' | 'metricsConfig' | 'interface'
6442
+ >
6443
+
6444
+ /**
6445
+ * Workflow definition overrides for calibration
6446
+ * Excludes identity/metadata fields that should not be modified
6447
+ */
6448
+ type WorkflowCalibrationOverrides = Omit<
6449
+ Partial<WorkflowDefinition>,
6450
+ 'config' | 'contract' | 'steps' | 'entryPoint' | 'metricsConfig' | 'interface'
6451
+ >
6452
+
6453
+ // ============================================================================
6454
+ // Grading System Types
6455
+ // ============================================================================
6456
+
6457
+ /**
6458
+ * Grading rubric for LLM-as-judge evaluation
6459
+ * Defines criteria and passing threshold
6460
+ */
6461
+ interface GradingRubric {
6462
+ passingThreshold: number // 0-1, e.g., 0.7 means 70% to pass
6463
+ criteria: GradingCriterion[]
6464
+ }
6465
+
6466
+ /**
6467
+ * Individual grading criterion
6468
+ * Weight should be 0-1, and all weights should sum to 1
6469
+ */
6470
+ interface GradingCriterion {
6471
+ name: string
6472
+ weight: number // 0-1, weights should sum to 1
6473
+ description: string
6474
+ scoringGuide: string
6475
+ }
6476
+
6477
+ /**
6478
+ * Grading result for a single execution or session
6479
+ * Contains overall score and per-criterion breakdown
6480
+ */
6481
+ interface GradeResult {
6482
+ score: number // 0-1
6483
+ passed: boolean
6484
+ details: Record<string, { score: number; justification: string }>
6485
+ }
6486
+
6487
+ // ============================================================================
6488
+ // Result Types
6489
+ // ============================================================================
6490
+
6491
+ /**
6492
+ * Single-turn calibration result
6493
+ * One result per (variant × input) combination
6494
+ */
6495
+ interface SingleCalibrationResult {
6496
+ executionId: string // Reference to execution_logs
6497
+ variantName: string
6498
+ inputIndex: number // Which input from testInputs array (0-based)
6499
+ appliedOverrides?: AgentCalibrationOverrides | WorkflowCalibrationOverrides
6500
+ status: 'pending' | 'running' | 'completed' | 'failed'
6501
+ errorMessage?: string
6502
+ grade?: GradeResult
6503
+ gradeError?: string
6504
+ }
6505
+
6506
+ /**
6507
+ * Multi-turn session calibration result
6508
+ * Leverages existing sessions infrastructure
6509
+ */
6510
+ interface SessionCalibrationResult {
6511
+ sessionId: string // Reference to sessions table
6512
+ variantName: string
6513
+ appliedOverrides?: AgentCalibrationOverrides | WorkflowCalibrationOverrides
6514
+ status: 'pending' | 'running' | 'completed' | 'failed'
6515
+ errorMessage?: string
6516
+ turnCount: number
6517
+ grade?: GradeResult
6518
+ gradeError?: string
6519
+ }
6520
+
6521
+ // ============================================================================
6522
+ // Calibration Run Types
6523
+ // ============================================================================
6524
+
6525
+ /**
6526
+ * Calibration run - individual test execution within a project
6527
+ * Contains configuration, results, and grading information
6528
+ */
6529
+ interface CalibrationRun {
6530
+ id: string
6531
+ organizationId: string
6532
+ projectId: string
6533
+ name: string
6534
+ description?: string | null
6535
+ executionMode: 'single' | 'session'
6536
+ testInputs: unknown[]
6537
+ configVariants: ConfigVariant[]
6538
+ gradingRubric?: GradingRubric | null
6539
+ graderModel?: string | null
6540
+ results: (SingleCalibrationResult | SessionCalibrationResult)[]
6541
+ status: 'pending' | 'running' | 'completed' | 'partial' | 'failed'
6542
+ createdAt: Date
6543
+ completedAt?: Date | null
6544
+ }
6545
+
6546
+ // ============================================================================
6547
+ // Combined Response Types
6548
+ // ============================================================================
6549
+
6550
+ /**
6551
+ * Execution log subset for comparison view
6552
+ * Contains essential data without full execution context
6553
+ */
6554
+ interface ExecutionLog {
6555
+ executionId: string
6556
+ status: 'running' | 'completed' | 'failed'
6557
+ input: unknown
6558
+ output: unknown | null
6559
+ error: CalibrationExecutionError | null
6560
+ startedAt: string
6561
+ completedAt: string | null
6562
+ }
6563
+
6564
+ /**
6565
+ * Execution error information for calibration display
6566
+ * Subset of full execution error for UI display purposes
6567
+ * Named differently from ExecutionError class to avoid type conflicts
6568
+ */
6569
+ interface CalibrationExecutionError {
6570
+ message: string
6571
+ category?: string
6572
+ type?: string
6573
+ }
6574
+
6575
+ /**
6576
+ * Combined calibration run data for comparison view
6577
+ * Single API call returns run + execution logs + metrics
6578
+ */
6579
+ interface CalibrationRunWithFullData {
6580
+ run: CalibrationRun
6581
+ logs: Record<string, ExecutionLog> // keyed by executionId
6582
+ metrics: Record<string, ExecutionMetricsDetail> // keyed by executionId
6583
+ }
6584
+
6585
+ // ============================================================================
6586
+ // Calibration Project Schemas
6587
+ // ============================================================================
6588
+
6589
+ /**
6590
+ * Create calibration project schema
6591
+ * Validates request body for creating a new calibration project
6592
+ */
6593
+ declare const CreateCalibrationProjectSchema = z.object({
6594
+ resourceId: z.string().min(1),
6595
+ resourceType: z.enum(['agent', 'workflow']),
6596
+ name: z.string().min(1),
6597
+ description: z.string().optional()
6598
+ })
6599
+
6600
+ /**
6601
+ * Update calibration project schema
6602
+ * Validates request body for updating an existing calibration project
6603
+ */
6604
+ declare const UpdateCalibrationProjectSchema = z.object({
6605
+ name: z.string().min(1).optional(),
6606
+ description: z.string().optional()
6607
+ })
6608
+
6609
+ // ============================================================================
6610
+ // Calibration Run Schemas
6611
+ // ============================================================================
6612
+
6613
+ /**
6614
+ * Create calibration run schema
6615
+ * Validates request body for creating a new calibration run
6616
+ * Includes refinement for graderModel requirement when gradingRubric is provided
6617
+ */
6618
+ declare const CreateCalibrationRunSchema = z
6619
+ .object({
6620
+ projectId: z.string().uuid(),
6621
+ name: z.string().min(1),
6622
+ description: z.string().optional(),
6623
+ executionMode: z.enum(['single', 'session']).default('single'),
6624
+ testInputs: z.array(z.unknown()).min(1).max(50), // Min 1, max 50 inputs
6625
+ configVariants: z.array(ConfigVariantSchema).min(1).max(10), // Min 1, max 10 variants
6626
+ gradingRubric: GradingRubricSchema.optional(),
6627
+ graderModel: LLMModelSchema.optional()
6628
+ })
6629
+ .refine((data) => !data.gradingRubric || data.graderModel, {
6630
+ message: 'graderModel is required when gradingRubric is provided'
6631
+ })
6632
+
6633
+
6634
+ // ============================================================================
6635
+ // Inferred Types
6636
+ // ============================================================================
6637
+
6638
+ type CreateCalibrationProjectInput = z.infer<typeof CreateCalibrationProjectSchema>
6639
+ type UpdateCalibrationProjectInput = z.infer<typeof UpdateCalibrationProjectSchema>
6640
+ type CreateCalibrationRunInput = z.infer<typeof CreateCalibrationRunSchema>
6641
+
6642
+ /**
6643
+ * Calibration SSE Event Types
6644
+ *
6645
+ * Shared event type definitions for calibration real-time streaming.
6646
+ * Used by both the API broadcaster and the command-center UI.
6647
+ */
6648
+
6649
+ // Single-turn events
6650
+
6651
+ interface CalibrationExecutionStartedEvent {
6652
+ type: 'execution-started'
6653
+ variantName: string
6654
+ inputIndex: number
6655
+ timestamp: number
6656
+ }
6657
+
6658
+ interface CalibrationExecutionCompletedEvent {
6659
+ type: 'execution-completed'
6660
+ variantName: string
6661
+ inputIndex: number
6662
+ executionId: string
6663
+ timestamp: number
6664
+ }
6665
+
6666
+ interface CalibrationExecutionFailedEvent {
6667
+ type: 'execution-failed'
6668
+ variantName: string
6669
+ inputIndex?: number
6670
+ error: string
6671
+ timestamp: number
6672
+ }
6673
+
6674
+ // Session events
6675
+
6676
+ interface CalibrationSessionStartedEvent {
6677
+ type: 'session-started'
6678
+ variantName: string
6679
+ sessionId: string
6680
+ timestamp: number
6681
+ }
6682
+
6683
+ interface CalibrationTurnStartedEvent {
6684
+ type: 'turn-started'
6685
+ variantName: string
6686
+ turnNumber: number
6687
+ timestamp: number
6688
+ }
6689
+
6690
+ interface CalibrationTurnCompletedEvent {
6691
+ type: 'turn-completed'
6692
+ variantName: string
6693
+ turnNumber: number
6694
+ executionId: string
6695
+ timestamp: number
6696
+ }
6697
+
6698
+ interface CalibrationSessionCompletedEvent {
6699
+ type: 'session-completed'
6700
+ variantName: string
6701
+ sessionId: string
6702
+ turnCount: number
6703
+ timestamp: number
6704
+ }
6705
+
6706
+ // Grading events
6707
+
6708
+ interface CalibrationGradingStartedEvent {
6709
+ type: 'grading-started'
6710
+ variantName: string
6711
+ timestamp: number
6712
+ }
6713
+
6714
+ interface CalibrationGradingCompletedEvent {
6715
+ type: 'grading-completed'
6716
+ variantName: string
6717
+ score: number
6718
+ timestamp: number
6719
+ }
6720
+
6721
+ interface CalibrationGradingFailedEvent {
6722
+ type: 'grading-failed'
6723
+ variantName: string
6724
+ error: string
6725
+ timestamp: number
6726
+ }
6727
+
6728
+ // Completion events
6729
+
6730
+ interface CalibrationCompletedEvent {
6731
+ type: 'calibration-completed'
6732
+ summary: { total: number; completed: number; failed: number }
6733
+ timestamp: number
6734
+ }
6735
+
6736
+ interface CalibrationFailedEvent {
6737
+ type: 'calibration-failed'
6738
+ error: string
6739
+ timestamp: number
6740
+ }
6741
+
6742
+ // Connection event
6743
+
6744
+ interface CalibrationConnectedEvent {
6745
+ type: 'connected'
6746
+ timestamp: number
6747
+ data?: undefined
6748
+ }
6749
+
6750
+ /**
6751
+ * Union of all calibration SSE events
6752
+ */
6753
+ type CalibrationSSEEvent =
6754
+ | CalibrationExecutionStartedEvent
6755
+ | CalibrationExecutionCompletedEvent
6756
+ | CalibrationExecutionFailedEvent
6757
+ | CalibrationSessionStartedEvent
6758
+ | CalibrationTurnStartedEvent
6759
+ | CalibrationTurnCompletedEvent
6760
+ | CalibrationSessionCompletedEvent
6761
+ | CalibrationGradingStartedEvent
6762
+ | CalibrationGradingCompletedEvent
6763
+ | CalibrationGradingFailedEvent
6764
+ | CalibrationCompletedEvent
6765
+ | CalibrationFailedEvent
6766
+ | CalibrationConnectedEvent
6767
+
6768
+ /**
6769
+ * Command Queue SSE Event Types
6770
+ *
6771
+ * Type-safe definitions for command queue related SSE events
6772
+ */
6773
+
6774
+
6775
+
6776
+ /**
6777
+ * Event sent when command queue task is updated
6778
+ */
6779
+ interface CommandQueueTaskUpdatedEvent {
6780
+ type: 'task_updated'
6781
+ timestamp: number
6782
+ data: {
6783
+ task: Task
6784
+ }
6785
+ }
6786
+
6787
+ /**
6788
+ * Connection confirmation event
6789
+ */
6790
+ interface CommandQueueConnectedEvent {
6791
+ type: 'connected'
6792
+ timestamp: number
6793
+ data?: undefined
6794
+ }
6795
+
6796
+ /**
6797
+ * Event sent when action execution completes successfully
6798
+ */
6799
+ interface CommandQueueExecutionCompletedEvent {
6800
+ type: 'execution_completed'
6801
+ timestamp: number
6802
+ data: {
6803
+ taskId: string
6804
+ targetExecutionId: string
6805
+ }
6806
+ }
6807
+
6808
+ /**
6809
+ * Event sent when action execution fails
6810
+ */
6811
+ interface CommandQueueExecutionFailedEvent {
6812
+ type: 'execution_failed'
6813
+ timestamp: number
6814
+ data: {
6815
+ taskId: string
6816
+ targetExecutionId?: string
6817
+ error: string
6818
+ }
6819
+ }
6820
+
6821
+ /**
6822
+ * Union of all command queue SSE events
6823
+ */
6824
+ type CommandQueueSSEEvent =
6825
+ | CommandQueueTaskUpdatedEvent
6826
+ | CommandQueueConnectedEvent
6827
+ | CommandQueueExecutionCompletedEvent
6828
+ | CommandQueueExecutionFailedEvent
6829
+
6830
+ /**
6831
+ * Notification SSE Event Types
6832
+ *
6833
+ * Type-safe definitions for notification-related SSE events
6834
+ */
6835
+
6836
+ /**
6837
+ * Event sent when notification unread count changes
6838
+ */
6839
+ interface NotificationCountUpdatedEvent {
6840
+ type: 'unread_count_updated'
6841
+ timestamp: number
6842
+ data: {
6843
+ count: number
6844
+ }
6845
+ }
6846
+
6847
+ /**
6848
+ * Union of all notification SSE events
6849
+ */
6850
+ type NotificationSSEEvent = NotificationCountUpdatedEvent
6851
+
3675
6852
  type ActivityType =
3676
6853
  | 'workflow_execution'
3677
6854
  | 'agent_run'
@@ -3703,6 +6880,37 @@ interface Activity {
3703
6880
  createdAt: Date
3704
6881
  }
3705
6882
 
6883
+ /**
6884
+ * Activity SSE Event Types
6885
+ *
6886
+ * Type-safe definitions for activity-related SSE events
6887
+ */
6888
+
6889
+
6890
+
6891
+ /**
6892
+ * Event sent when new activity is created
6893
+ */
6894
+ interface ActivityCreatedEvent {
6895
+ type: 'activity'
6896
+ timestamp: number
6897
+ data: Activity
6898
+ }
6899
+
6900
+ /**
6901
+ * Connection confirmation event
6902
+ */
6903
+ interface ActivityConnectedEvent {
6904
+ type: 'connected'
6905
+ timestamp: number
6906
+ data?: undefined
6907
+ }
6908
+
6909
+ /**
6910
+ * Union of all activity SSE events
6911
+ */
6912
+ type ActivitySSEEvent = ActivityCreatedEvent | ActivityConnectedEvent
6913
+
3706
6914
  /**
3707
6915
  * Webhook Endpoint Domain Types
3708
6916
  *
@@ -3797,4 +7005,106 @@ declare const UpdateWebhookEndpointRequestSchema = z
3797
7005
 
3798
7006
  type UpdateWebhookEndpointRequest = z.infer<typeof UpdateWebhookEndpointRequestSchema>
3799
7007
 
3800
- export type { AIResourceDefinition, APIExecutionDetail, APIExecutionListResponse, Activity, ActivityType, ChatMessage, CheckpointListResponse, CostByModelResponse, CostSummaryResponse, CostTrendsResponse, CreateWebhookEndpointRequest, DashboardMetrics, ErrorAnalysisMetrics, ErrorDetailFull, ErrorDetailResponse, ErrorTrend, ExecutionHistoryItem, ExecutionHistoryResponse, ExecutionLogMessage, ExecutionStatus$1 as ExecutionStatus, ExecutionSummary, MembershipFeatureConfig, MembershipWithDetails, MessageEvent, NotificationDTO, OrgFeatureConfig, PatchTaskParams, ResourceDefinition, ResourceStatus, ResourceType, SessionDTO, SessionTokenUsage, SupabaseUserProfile, Task, TaskSchedule, TaskScheduleConfig, TaskStatus, TimeRange, UpdateWebhookEndpointRequest, UserConfig, WebhookEndpoint };
7008
+ /**
7009
+ * Response shape for a single webhook endpoint.
7010
+ * NOT strict — response schemas allow extra fields for forward compatibility.
7011
+ */
7012
+ declare const WebhookEndpointResponseSchema = z.object({
7013
+ id: UuidSchema,
7014
+ organizationId: UuidSchema,
7015
+ key: z.string(),
7016
+ name: z.string(),
7017
+ description: z.string().nullable(),
7018
+ resourceId: z.string().nullable(),
7019
+ status: WebhookEndpointStatusSchema,
7020
+ lastTriggeredAt: z.string().datetime().nullable(),
7021
+ requestCount: z.number().int().min(0),
7022
+ createdAt: z.string().datetime(),
7023
+ updatedAt: z.string().datetime()
7024
+ })
7025
+
7026
+ type WebhookEndpointResponse = z.infer<typeof WebhookEndpointResponseSchema>
7027
+
7028
+ /**
7029
+ * GET /api/credentials - List credentials
7030
+ */
7031
+ declare const ListCredentialsResponseSchema = z.object({
7032
+ credentials: z.array(
7033
+ z.object({
7034
+ id: UuidSchema,
7035
+ name: z.string(),
7036
+ type: z.string(),
7037
+ provider: z.string().nullable(), // OAuth provider or null for non-OAuth
7038
+ createdAt: z.string().datetime()
7039
+ })
7040
+ )
7041
+ })
7042
+
7043
+ /** API response type for a single credential list item */
7044
+ type CredentialListItem = z.infer<typeof ListCredentialsResponseSchema>['credentials'][number]
7045
+
7046
+ /**
7047
+ * @deprecated Use TimeRange from '@repo/core' directly. Kept as alias for backward compatibility.
7048
+ */
7049
+ type StatsTimeRange = TimeRange
7050
+
7051
+ /** Stats returned by /command-view/stats (counts only, no error details) */
7052
+ interface ResourceStats {
7053
+ resourceId: string
7054
+ totalRuns: number
7055
+ successCount: number
7056
+ failureCount: number // Used for badge: "X failed"
7057
+ warningCount: number // Completed with warnings (counts toward success)
7058
+ lastRunAt: string | null
7059
+ // NO recentErrors or totalErrors - fetched on-demand via /resource-errors
7060
+ }
7061
+
7062
+ /** Response from /command-view/resource-errors (on-demand) */
7063
+ interface ResourceErrorsResponse {
7064
+ resourceId: string
7065
+ errors: ErrorSummary[]
7066
+ totalErrors: number // Total count for "showing 10 of X" display
7067
+ timeRange: StatsTimeRange
7068
+ }
7069
+
7070
+ interface ErrorSummary {
7071
+ executionId: string
7072
+ errorType: string
7073
+ errorMessage: string
7074
+ occurredAt: string
7075
+ }
7076
+
7077
+ /** Single execution summary for Recent Executions list in command view */
7078
+ interface CommandViewExecution {
7079
+ executionId: string
7080
+ status: ExecutionStatus
7081
+ startedAt: string
7082
+ completedAt: string | null
7083
+ errorMessage: string | null // Only present if failed
7084
+ }
7085
+
7086
+ /** Response from /command-view/resource-executions (on-demand) */
7087
+ interface ResourceExecutionsResponse {
7088
+ resourceId: string
7089
+ executions: CommandViewExecution[]
7090
+ totalExecutions: number // Total count for "showing 10 of X" display
7091
+ timeRange: StatsTimeRange
7092
+ }
7093
+
7094
+ interface HumanCheckpointStats {
7095
+ checkpointId: string
7096
+ pendingCount: number
7097
+ completedCount: number
7098
+ expiredCount: number
7099
+ lastDecisionAt: string | null
7100
+ }
7101
+
7102
+ /** Response from /command-view/stats */
7103
+ interface CommandViewStatsResponse {
7104
+ resources: Record<string, ResourceStats>
7105
+ humanCheckpoints: Record<string, HumanCheckpointStats>
7106
+ timeRange: StatsTimeRange
7107
+ generatedAt: string
7108
+ }
7109
+
7110
+ export type { AIResourceDefinition, APIExecutionDetail, APIExecutionListResponse, APIExecutionSummary, AbsoluteScheduleConfig, AbsoluteScheduleItem, ActionConfig, Activity, ActivitySSEEvent, ActivityStatus, ActivityType, AgentIterationData, AgentMemory, ApiKeyListItem, BusinessImpactMetrics, CalibrationProject, CalibrationRun, CalibrationRunWithFullData, CalibrationSSEEvent, ChatMessage, CheckpointListResponse, CommandQueueSSEEvent, CommandViewAgent, CommandViewData, CommandViewNode, CommandViewNodeType, CommandViewStatsResponse, CommandViewWorkflow, ConfigVariant, CostBreakdownMetrics, CostByModelResponse, CostSummaryResponse, CostTrendsResponse, CreateCalibrationProjectInput, CreateCalibrationRunInput, CreateWebhookEndpointRequest, CredentialListItem, DashboardMetrics, Deployment, DeploymentStatus, DomainDefinition, ErrorAnalysisMetrics, ErrorDetailFull, ErrorDetailResponse, ErrorTrend, ExecutionHealthMetrics, ExecutionHistoryItem, ExecutionHistoryResponse, ExecutionLog, ExecutionLogMessage, ExecutionMetricsDetail, ExecutionSSEEvent, ExecutionStatus$1 as ExecutionStatus, ExecutionSummary, FailingResource, GradingRubric, HumanCheckpointDefinition, HumanCheckpointStats, ListMembershipsParams, MembershipFeatureConfig, MembershipStatus, MembershipWithDetails, MessageEvent$1 as MessageEvent, MessageType, ModelConfig, NotificationDTO, NotificationSSEEvent, OrgFeatureConfig, PatchTaskParams, RecentExecutionsByResourceResponse, RecurringScheduleConfig, RelativeScheduleConfig, RelativeScheduleItem, ResourceDefinition$1 as ResourceDefinition, ResourceDomain, ResourceErrorsResponse, ResourceExecutionSummary, ResourceExecutionsResponse, ResourceHealth, ResourceIdentifier, ResourceStats, ResourceStatus$1 as ResourceStatus, ResourceType$1 as ResourceType, ResourcesHealthResponse, SerializedAgentDefinition, SerializedExecutionInterface, SerializedWorkflowDefinition, SessionCalibrationResult, SessionDTO, SessionTokenUsage, SingleCalibrationResult, StatsTimeRange, SupabaseUserProfile, Task, TaskSchedule, TaskScheduleConfig, TaskStatus, TimeRange, WorkflowNodeVisualizerData as TimelineData, UpdateCalibrationProjectInput, UpdateWebhookEndpointRequest, UserConfig, WebhookEndpoint, WebhookEndpointResponse };