@elevasis/ui 2.21.0 → 2.22.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 (81) hide show
  1. package/dist/app/index.js +2 -2
  2. package/dist/{chunk-DMYELNGA.js → chunk-3HEUGBOT.js} +1 -1
  3. package/dist/{chunk-KVW56ERD.js → chunk-AXXTN44Z.js} +5 -3
  4. package/dist/{chunk-7GG6OSD7.js → chunk-B4FHWKEF.js} +3354 -2918
  5. package/dist/{chunk-XLZZOFGM.js → chunk-BSZRKBAW.js} +275 -76
  6. package/dist/{chunk-CZK67OHH.js → chunk-COG4ABRI.js} +3 -3
  7. package/dist/{chunk-S7RL77QS.js → chunk-DDZOHLHB.js} +1 -1
  8. package/dist/{chunk-I5WRKH25.js → chunk-GJ7EIABJ.js} +1 -1
  9. package/dist/{chunk-LQU62KHD.js → chunk-IBUYJXA3.js} +1209 -705
  10. package/dist/{chunk-EDX6WIN3.js → chunk-IOTLB6ND.js} +3 -3
  11. package/dist/{chunk-GBMNCNHX.js → chunk-KVJ3LFH2.js} +3 -1
  12. package/dist/{chunk-VQESMHQV.js → chunk-LJWV4TWV.js} +1 -2
  13. package/dist/{chunk-EGKNRM6P.js → chunk-LKVBEE63.js} +2 -2
  14. package/dist/{chunk-BJWIKEQG.js → chunk-LVJGPE6H.js} +6 -14
  15. package/dist/{chunk-TIIPYB2Z.js → chunk-QZJM3RYI.js} +1 -1
  16. package/dist/{chunk-7YQKVWSD.js → chunk-SQ5JGELM.js} +25 -5
  17. package/dist/{chunk-RX4UWZZR.js → chunk-TKAYX2SP.js} +8 -3
  18. package/dist/{chunk-ATEHYDL3.js → chunk-WWJ6S2HQ.js} +6 -2
  19. package/dist/{chunk-Q5HC6ENG.js → chunk-XOTJNW4Q.js} +1 -1
  20. package/dist/{chunk-ULZ2B3NC.js → chunk-ZBCTB5CA.js} +1 -1
  21. package/dist/components/index.css +85 -85
  22. package/dist/components/index.d.ts +1646 -1381
  23. package/dist/components/index.js +236 -30
  24. package/dist/components/navigation/index.css +589 -0
  25. package/dist/components/navigation/index.js +3 -3
  26. package/dist/features/auth/index.css +2 -2
  27. package/dist/features/auth/index.d.ts +184 -3
  28. package/dist/features/crm/index.css +2 -2
  29. package/dist/features/crm/index.d.ts +189 -3
  30. package/dist/features/crm/index.js +10 -10
  31. package/dist/features/dashboard/index.css +2 -2
  32. package/dist/features/dashboard/index.js +9 -9
  33. package/dist/features/delivery/index.css +85 -85
  34. package/dist/features/delivery/index.d.ts +189 -3
  35. package/dist/features/delivery/index.js +10 -10
  36. package/dist/features/lead-gen/index.css +2 -2
  37. package/dist/features/lead-gen/index.d.ts +5 -0
  38. package/dist/features/lead-gen/index.js +10 -10
  39. package/dist/features/monitoring/index.css +85 -85
  40. package/dist/features/monitoring/index.d.ts +6 -1
  41. package/dist/features/monitoring/index.js +11 -11
  42. package/dist/features/monitoring/requests/index.css +2 -2
  43. package/dist/features/monitoring/requests/index.d.ts +5 -0
  44. package/dist/features/monitoring/requests/index.js +9 -9
  45. package/dist/features/operations/index.css +2 -2
  46. package/dist/features/operations/index.d.ts +7 -4
  47. package/dist/features/operations/index.js +12 -12
  48. package/dist/features/seo/index.d.ts +5 -0
  49. package/dist/features/settings/index.css +2 -2
  50. package/dist/features/settings/index.d.ts +210 -9
  51. package/dist/features/settings/index.js +11 -11
  52. package/dist/graph/index.css +2 -2
  53. package/dist/hooks/delivery/index.css +2 -2
  54. package/dist/hooks/delivery/index.d.ts +184 -3
  55. package/dist/hooks/index.css +85 -85
  56. package/dist/hooks/index.d.ts +1815 -1515
  57. package/dist/hooks/index.js +8 -8
  58. package/dist/hooks/published.css +85 -85
  59. package/dist/hooks/published.d.ts +1815 -1515
  60. package/dist/hooks/published.js +8 -8
  61. package/dist/index.css +12 -12
  62. package/dist/index.d.ts +322 -16
  63. package/dist/index.js +9 -9
  64. package/dist/initialization/index.d.ts +184 -3
  65. package/dist/layout/index.js +2 -2
  66. package/dist/organization/index.css +589 -0
  67. package/dist/organization/index.js +1 -1
  68. package/dist/profile/index.d.ts +184 -3
  69. package/dist/provider/index.css +384 -0
  70. package/dist/provider/index.d.ts +6 -0
  71. package/dist/provider/index.js +7 -7
  72. package/dist/provider/published.css +463 -0
  73. package/dist/provider/published.d.ts +6 -0
  74. package/dist/provider/published.js +4 -4
  75. package/dist/supabase/index.d.ts +359 -6
  76. package/dist/test-utils/index.d.ts +46 -2
  77. package/dist/test-utils/index.js +102 -1
  78. package/dist/theme/index.js +2 -2
  79. package/dist/types/index.d.ts +195 -6
  80. package/package.json +2 -2
  81. /package/dist/{chunk-6GUW5GGF.js → chunk-6Z3G4U2R.js} +0 -0
@@ -7,17 +7,10 @@ import * as zustand from 'zustand';
7
7
  import { Edge } from '@xyflow/react';
8
8
 
9
9
  /**
10
- * Query key factory for executions TanStack Query hooks.
11
- * Uses organization UUID (not name) for cache isolation.
10
+ * Error categories for observability grouping and classification.
11
+ * Used to categorize errors in the execution_errors table metadata.
12
12
  */
13
- declare const executionsKeys: {
14
- all: readonly ["executions"];
15
- resources: (orgId: string | null) => readonly ["executions", "resources", string | null];
16
- resourceDefinition: (orgId: string | null, resourceId: string) => readonly ["executions", "definition", string | null, string];
17
- executionsListBase: (orgId: string | null, resourceId: string) => readonly ["executions", "list", string | null, string];
18
- executions: (orgId: string | null, resourceId: string, resourceStatus?: string, limit?: number, offset?: number) => readonly ["executions", "list", string | null, string, string, number | null, number];
19
- execution: (orgId: string | null, resourceId: string, executionId: string) => readonly ["executions", "execution", string | null, string, string];
20
- };
13
+ type ExecutionErrorCategory = 'llm' | 'tool' | 'workflow' | 'agent' | 'validation' | 'system';
21
14
 
22
15
  /**
23
16
  * Workflow-specific logging types and utilities
@@ -267,10 +260,170 @@ interface FormSchema {
267
260
  }
268
261
 
269
262
  /**
270
- * Error categories for observability grouping and classification.
271
- * Used to categorize errors in the execution_errors table metadata.
263
+ * Serialized Registry Types
264
+ *
265
+ * Pre-computed JSON-safe types for API responses and Command View.
266
+ * Serialization happens once at API startup, enabling instant response times.
272
267
  */
273
- type ExecutionErrorCategory = 'llm' | 'tool' | 'workflow' | 'agent' | 'validation' | 'system';
268
+
269
+ /**
270
+ * Serialized form field for API responses
271
+ */
272
+ interface SerializedFormField {
273
+ name: string;
274
+ label: string;
275
+ type: FormFieldType;
276
+ defaultValue?: unknown;
277
+ required?: boolean;
278
+ placeholder?: string;
279
+ description?: string;
280
+ options?: Array<{
281
+ label: string;
282
+ value: string | number;
283
+ }>;
284
+ min?: number;
285
+ max?: number;
286
+ }
287
+ /**
288
+ * Serialized form schema for API responses
289
+ */
290
+ interface SerializedFormSchema {
291
+ title?: string;
292
+ description?: string;
293
+ fields: SerializedFormField[];
294
+ layout?: 'vertical' | 'horizontal' | 'grid';
295
+ }
296
+ /**
297
+ * Serialized execution form schema for API responses
298
+ */
299
+ interface SerializedExecutionFormSchema extends SerializedFormSchema {
300
+ fieldMappings?: Record<string, string>;
301
+ submitButton?: {
302
+ label?: string;
303
+ loadingLabel?: string;
304
+ confirmMessage?: string;
305
+ };
306
+ }
307
+ /**
308
+ * Serialized schedule config for API responses
309
+ */
310
+ interface SerializedScheduleConfig {
311
+ enabled: boolean;
312
+ defaultSchedule?: string;
313
+ allowedPatterns?: string[];
314
+ }
315
+ /**
316
+ * Serialized webhook config for API responses
317
+ */
318
+ interface SerializedWebhookConfig {
319
+ enabled: boolean;
320
+ payloadSchema?: unknown;
321
+ }
322
+ /**
323
+ * Serialized execution interface for API responses
324
+ */
325
+ interface SerializedExecutionInterface {
326
+ form: SerializedExecutionFormSchema;
327
+ schedule?: SerializedScheduleConfig;
328
+ webhook?: SerializedWebhookConfig;
329
+ }
330
+ /**
331
+ * Serialized agent definition (JSON-safe)
332
+ * Result of serializeDefinition(AgentDefinition)
333
+ */
334
+ interface SerializedAgentDefinition {
335
+ config: {
336
+ resourceId: string;
337
+ name: string;
338
+ description: string;
339
+ version: string;
340
+ type: 'agent';
341
+ status: 'dev' | 'prod';
342
+ links?: ResourceLink[];
343
+ category?: ResourceCategory;
344
+ /** Whether this resource is archived and should be excluded from registration and deployment */
345
+ archived?: boolean;
346
+ systemPrompt: string;
347
+ constraints?: {
348
+ maxIterations?: number;
349
+ timeout?: number;
350
+ maxSessionMemoryKeys?: number;
351
+ maxMemoryTokens?: number;
352
+ };
353
+ sessionCapable?: boolean;
354
+ memoryPreferences?: string;
355
+ };
356
+ modelConfig: {
357
+ provider: string;
358
+ model: string;
359
+ apiKey: string;
360
+ temperature: number;
361
+ maxOutputTokens: number;
362
+ topP?: number;
363
+ modelOptions?: Record<string, unknown>;
364
+ };
365
+ contract: {
366
+ inputSchema: object;
367
+ outputSchema?: object;
368
+ };
369
+ tools: Array<{
370
+ name: string;
371
+ description: string;
372
+ inputSchema?: object;
373
+ outputSchema?: object;
374
+ }>;
375
+ knowledgeMap?: {
376
+ nodeCount: number;
377
+ nodes: Array<{
378
+ id: string;
379
+ description: string;
380
+ loaded: boolean;
381
+ hasPrompt: boolean;
382
+ }>;
383
+ };
384
+ metricsConfig?: object;
385
+ interface?: SerializedExecutionInterface;
386
+ }
387
+ /**
388
+ * Serialized workflow definition (JSON-safe)
389
+ * Result of serializeDefinition(WorkflowDefinition)
390
+ */
391
+ interface SerializedWorkflowDefinition {
392
+ config: {
393
+ resourceId: string;
394
+ name: string;
395
+ description: string;
396
+ version: string;
397
+ type: 'workflow';
398
+ status: 'dev' | 'prod';
399
+ links?: ResourceLink[];
400
+ category?: ResourceCategory;
401
+ /** Whether this resource is archived and should be excluded from registration and deployment */
402
+ archived?: boolean;
403
+ };
404
+ entryPoint: string;
405
+ steps: Array<{
406
+ id: string;
407
+ name: string;
408
+ description: string;
409
+ inputSchema?: object;
410
+ outputSchema?: object;
411
+ next: {
412
+ type: 'linear' | 'conditional';
413
+ target?: string;
414
+ routes?: Array<{
415
+ target: string;
416
+ }>;
417
+ default?: string;
418
+ } | null;
419
+ }>;
420
+ contract: {
421
+ inputSchema: object;
422
+ outputSchema?: object;
423
+ };
424
+ metricsConfig?: object;
425
+ interface?: SerializedExecutionInterface;
426
+ }
274
427
 
275
428
  /**
276
429
  * Memory type definitions
@@ -1984,6 +2137,7 @@ type Database = {
1984
2137
  Row: {
1985
2138
  config: Json;
1986
2139
  created_at: string | null;
2140
+ effective_permissions: string[];
1987
2141
  id: string;
1988
2142
  membership_status: string | null;
1989
2143
  organization_id: string;
@@ -1995,6 +2149,7 @@ type Database = {
1995
2149
  Insert: {
1996
2150
  config?: Json;
1997
2151
  created_at?: string | null;
2152
+ effective_permissions?: string[];
1998
2153
  id?: string;
1999
2154
  membership_status?: string | null;
2000
2155
  organization_id: string;
@@ -2006,6 +2161,7 @@ type Database = {
2006
2161
  Update: {
2007
2162
  config?: Json;
2008
2163
  created_at?: string | null;
2164
+ effective_permissions?: string[];
2009
2165
  id?: string;
2010
2166
  membership_status?: string | null;
2011
2167
  organization_id?: string;
@@ -2031,92 +2187,233 @@ type Database = {
2031
2187
  }
2032
2188
  ];
2033
2189
  };
2034
- organizations: {
2190
+ org_rol_assignments: {
2035
2191
  Row: {
2036
- config: Json;
2037
- created_at: string;
2038
- id: string;
2039
- is_test: boolean;
2040
- metadata: Json;
2041
- name: string;
2042
- status: string;
2043
- updated_at: string;
2044
- workos_org_id: string;
2192
+ granted_at: string;
2193
+ granted_by: string | null;
2194
+ membership_id: string;
2195
+ role_id: string;
2045
2196
  };
2046
2197
  Insert: {
2047
- config?: Json;
2048
- created_at?: string;
2049
- id?: string;
2050
- is_test?: boolean;
2051
- metadata?: Json;
2052
- name: string;
2053
- status?: string;
2054
- updated_at?: string;
2055
- workos_org_id: string;
2198
+ granted_at?: string;
2199
+ granted_by?: string | null;
2200
+ membership_id: string;
2201
+ role_id: string;
2056
2202
  };
2057
2203
  Update: {
2058
- config?: Json;
2059
- created_at?: string;
2060
- id?: string;
2061
- is_test?: boolean;
2062
- metadata?: Json;
2063
- name?: string;
2064
- status?: string;
2065
- updated_at?: string;
2066
- workos_org_id?: string;
2204
+ granted_at?: string;
2205
+ granted_by?: string | null;
2206
+ membership_id?: string;
2207
+ role_id?: string;
2067
2208
  };
2068
- Relationships: [];
2209
+ Relationships: [
2210
+ {
2211
+ foreignKeyName: "org_rol_assignments_granted_by_fkey";
2212
+ columns: ["granted_by"];
2213
+ isOneToOne: false;
2214
+ referencedRelation: "users";
2215
+ referencedColumns: ["id"];
2216
+ },
2217
+ {
2218
+ foreignKeyName: "org_rol_assignments_membership_id_fkey";
2219
+ columns: ["membership_id"];
2220
+ isOneToOne: false;
2221
+ referencedRelation: "org_memberships";
2222
+ referencedColumns: ["id"];
2223
+ },
2224
+ {
2225
+ foreignKeyName: "org_rol_assignments_role_id_fkey";
2226
+ columns: ["role_id"];
2227
+ isOneToOne: false;
2228
+ referencedRelation: "org_rol_definitions";
2229
+ referencedColumns: ["id"];
2230
+ }
2231
+ ];
2069
2232
  };
2070
- prj_milestones: {
2233
+ org_rol_definitions: {
2071
2234
  Row: {
2072
- checklist: Json | null;
2073
- completed_at: string | null;
2074
2235
  created_at: string;
2075
2236
  description: string | null;
2076
- due_date: string | null;
2077
2237
  id: string;
2078
- metadata: Json | null;
2238
+ is_system: boolean;
2079
2239
  name: string;
2080
- organization_id: string;
2081
- project_id: string;
2082
- sequence: number;
2083
- status: string;
2240
+ organization_id: string | null;
2241
+ slug: string;
2084
2242
  updated_at: string;
2085
2243
  };
2086
2244
  Insert: {
2087
- checklist?: Json | null;
2088
- completed_at?: string | null;
2089
2245
  created_at?: string;
2090
2246
  description?: string | null;
2091
- due_date?: string | null;
2092
2247
  id?: string;
2093
- metadata?: Json | null;
2248
+ is_system?: boolean;
2094
2249
  name: string;
2095
- organization_id: string;
2096
- project_id: string;
2097
- sequence?: number;
2098
- status?: string;
2250
+ organization_id?: string | null;
2251
+ slug: string;
2099
2252
  updated_at?: string;
2100
2253
  };
2101
2254
  Update: {
2102
- checklist?: Json | null;
2103
- completed_at?: string | null;
2104
2255
  created_at?: string;
2105
2256
  description?: string | null;
2106
- due_date?: string | null;
2107
2257
  id?: string;
2108
- metadata?: Json | null;
2258
+ is_system?: boolean;
2109
2259
  name?: string;
2110
- organization_id?: string;
2111
- project_id?: string;
2112
- sequence?: number;
2113
- status?: string;
2260
+ organization_id?: string | null;
2261
+ slug?: string;
2114
2262
  updated_at?: string;
2115
2263
  };
2116
2264
  Relationships: [
2117
2265
  {
2118
- foreignKeyName: "fk_milestones_project";
2119
- columns: ["project_id"];
2266
+ foreignKeyName: "org_rol_definitions_organization_id_fkey";
2267
+ columns: ["organization_id"];
2268
+ isOneToOne: false;
2269
+ referencedRelation: "organizations";
2270
+ referencedColumns: ["id"];
2271
+ }
2272
+ ];
2273
+ };
2274
+ org_rol_grants: {
2275
+ Row: {
2276
+ granted_at: string;
2277
+ permission_key: string;
2278
+ role_id: string;
2279
+ };
2280
+ Insert: {
2281
+ granted_at?: string;
2282
+ permission_key: string;
2283
+ role_id: string;
2284
+ };
2285
+ Update: {
2286
+ granted_at?: string;
2287
+ permission_key?: string;
2288
+ role_id?: string;
2289
+ };
2290
+ Relationships: [
2291
+ {
2292
+ foreignKeyName: "org_rol_grants_permission_key_fkey";
2293
+ columns: ["permission_key"];
2294
+ isOneToOne: false;
2295
+ referencedRelation: "org_rol_permissions";
2296
+ referencedColumns: ["key"];
2297
+ },
2298
+ {
2299
+ foreignKeyName: "org_rol_grants_role_id_fkey";
2300
+ columns: ["role_id"];
2301
+ isOneToOne: false;
2302
+ referencedRelation: "org_rol_definitions";
2303
+ referencedColumns: ["id"];
2304
+ }
2305
+ ];
2306
+ };
2307
+ org_rol_permissions: {
2308
+ Row: {
2309
+ created_at: string;
2310
+ description: string;
2311
+ is_org_grantable: boolean;
2312
+ key: string;
2313
+ updated_at: string;
2314
+ };
2315
+ Insert: {
2316
+ created_at?: string;
2317
+ description: string;
2318
+ is_org_grantable?: boolean;
2319
+ key: string;
2320
+ updated_at?: string;
2321
+ };
2322
+ Update: {
2323
+ created_at?: string;
2324
+ description?: string;
2325
+ is_org_grantable?: boolean;
2326
+ key?: string;
2327
+ updated_at?: string;
2328
+ };
2329
+ Relationships: [];
2330
+ };
2331
+ organizations: {
2332
+ Row: {
2333
+ config: Json;
2334
+ created_at: string;
2335
+ id: string;
2336
+ is_test: boolean;
2337
+ metadata: Json;
2338
+ name: string;
2339
+ status: string;
2340
+ updated_at: string;
2341
+ workos_org_id: string;
2342
+ };
2343
+ Insert: {
2344
+ config?: Json;
2345
+ created_at?: string;
2346
+ id?: string;
2347
+ is_test?: boolean;
2348
+ metadata?: Json;
2349
+ name: string;
2350
+ status?: string;
2351
+ updated_at?: string;
2352
+ workos_org_id: string;
2353
+ };
2354
+ Update: {
2355
+ config?: Json;
2356
+ created_at?: string;
2357
+ id?: string;
2358
+ is_test?: boolean;
2359
+ metadata?: Json;
2360
+ name?: string;
2361
+ status?: string;
2362
+ updated_at?: string;
2363
+ workos_org_id?: string;
2364
+ };
2365
+ Relationships: [];
2366
+ };
2367
+ prj_milestones: {
2368
+ Row: {
2369
+ checklist: Json | null;
2370
+ completed_at: string | null;
2371
+ created_at: string;
2372
+ description: string | null;
2373
+ due_date: string | null;
2374
+ id: string;
2375
+ metadata: Json | null;
2376
+ name: string;
2377
+ organization_id: string;
2378
+ project_id: string;
2379
+ sequence: number;
2380
+ status: string;
2381
+ updated_at: string;
2382
+ };
2383
+ Insert: {
2384
+ checklist?: Json | null;
2385
+ completed_at?: string | null;
2386
+ created_at?: string;
2387
+ description?: string | null;
2388
+ due_date?: string | null;
2389
+ id?: string;
2390
+ metadata?: Json | null;
2391
+ name: string;
2392
+ organization_id: string;
2393
+ project_id: string;
2394
+ sequence?: number;
2395
+ status?: string;
2396
+ updated_at?: string;
2397
+ };
2398
+ Update: {
2399
+ checklist?: Json | null;
2400
+ completed_at?: string | null;
2401
+ created_at?: string;
2402
+ description?: string | null;
2403
+ due_date?: string | null;
2404
+ id?: string;
2405
+ metadata?: Json | null;
2406
+ name?: string;
2407
+ organization_id?: string;
2408
+ project_id?: string;
2409
+ sequence?: number;
2410
+ status?: string;
2411
+ updated_at?: string;
2412
+ };
2413
+ Relationships: [
2414
+ {
2415
+ foreignKeyName: "fk_milestones_project";
2416
+ columns: ["project_id"];
2120
2417
  isOneToOne: false;
2121
2418
  referencedRelation: "prj_projects";
2122
2419
  referencedColumns: ["id"];
@@ -2788,7 +3085,8 @@ type Database = {
2788
3085
  created_at: string;
2789
3086
  description: string | null;
2790
3087
  id: string;
2791
- key: string;
3088
+ key_hash: string;
3089
+ key_prefix: string | null;
2792
3090
  last_triggered_at: string | null;
2793
3091
  name: string;
2794
3092
  organization_id: string;
@@ -2801,7 +3099,8 @@ type Database = {
2801
3099
  created_at?: string;
2802
3100
  description?: string | null;
2803
3101
  id?: string;
2804
- key: string;
3102
+ key_hash: string;
3103
+ key_prefix?: string | null;
2805
3104
  last_triggered_at?: string | null;
2806
3105
  name: string;
2807
3106
  organization_id: string;
@@ -2814,7 +3113,8 @@ type Database = {
2814
3113
  created_at?: string;
2815
3114
  description?: string | null;
2816
3115
  id?: string;
2817
- key?: string;
3116
+ key_hash?: string;
3117
+ key_prefix?: string | null;
2818
3118
  last_triggered_at?: string | null;
2819
3119
  name?: string;
2820
3120
  organization_id?: string;
@@ -2860,6 +3160,13 @@ type Database = {
2860
3160
  Args: never;
2861
3161
  Returns: string;
2862
3162
  };
3163
+ can_assign_role_in_org: {
3164
+ Args: {
3165
+ p_role_id: string;
3166
+ p_target_membership_id: string;
3167
+ };
3168
+ Returns: boolean;
3169
+ };
2863
3170
  current_user_is_platform_admin: {
2864
3171
  Args: never;
2865
3172
  Returns: boolean;
@@ -2889,6 +3196,10 @@ type Database = {
2889
3196
  user_id: string;
2890
3197
  }[];
2891
3198
  };
3199
+ get_platform_credential_kek: {
3200
+ Args: never;
3201
+ Returns: string;
3202
+ };
2892
3203
  get_storage_org_id: {
2893
3204
  Args: {
2894
3205
  file_path: string;
@@ -2899,6 +3210,13 @@ type Database = {
2899
3210
  Args: never;
2900
3211
  Returns: string;
2901
3212
  };
3213
+ has_org_permission: {
3214
+ Args: {
3215
+ org_id: string;
3216
+ perm_key: string;
3217
+ };
3218
+ Returns: boolean;
3219
+ };
2902
3220
  is_org_admin: {
2903
3221
  Args: {
2904
3222
  org_id: string;
@@ -2931,6 +3249,22 @@ type Database = {
2931
3249
  Args: never;
2932
3250
  Returns: Json;
2933
3251
  };
3252
+ recompute_all_memberships: {
3253
+ Args: never;
3254
+ Returns: undefined;
3255
+ };
3256
+ sync_all_memberships_with_role: {
3257
+ Args: {
3258
+ p_role_id: string;
3259
+ };
3260
+ Returns: undefined;
3261
+ };
3262
+ sync_one_membership: {
3263
+ Args: {
3264
+ p_membership_id: string;
3265
+ };
3266
+ Returns: undefined;
3267
+ };
2934
3268
  upsert_user_profile: {
2935
3269
  Args: never;
2936
3270
  Returns: {
@@ -2963,790 +3297,960 @@ type Tables<DefaultSchemaTableNameOrOptions extends keyof (DefaultSchema["Tables
2963
3297
  Row: infer R;
2964
3298
  } ? R : never : never;
2965
3299
 
2966
- /**
2967
- * Time range selector for dashboard metrics
2968
- */
2969
- type TimeRange = '1h' | '24h' | '7d' | '30d';
2970
- /**
2971
- * Execution health metrics response
2972
- * Success rate, P95 duration, execution counts, and trend data
2973
- * trendData includes executionCount for throughput visualization (eliminates separate API call)
2974
- */
2975
- interface ExecutionHealthMetrics {
2976
- successRate: number;
2977
- p95Duration: number;
2978
- totalExecutions: number;
2979
- trendData: Array<{
2980
- time: string;
2981
- rate: number;
2982
- successCount: number;
2983
- errorCount: number;
2984
- warningCount: number;
2985
- executionCount: number;
2986
- }>;
2987
- statusCounts: {
2988
- success: number;
2989
- failed: number;
2990
- pending: number;
2991
- warning: number;
2992
- };
2993
- peakPeriod: string;
2994
- granularity: 'hour' | 'day';
2995
- }
2996
- /**
2997
- * Error analysis metrics response
2998
- * Error categories and top failing resources
2999
- */
3000
- interface ErrorAnalysisMetrics {
3001
- totalErrors: number;
3002
- errorsByCategory: Array<{
3003
- category: string;
3004
- count: number;
3005
- percentage: number;
3006
- }>;
3007
- topFailingResources: Array<{
3008
- resourceId: string;
3300
+ type SupabaseUserProfile = Tables<'users'>;
3301
+ type SupabaseApiKey = Tables<'api_keys'>;
3302
+ /** API response type for API key list items (omits sensitive key_hash) */
3303
+ type ApiKeyListItem = Omit<SupabaseApiKey, 'key_hash'>;
3304
+
3305
+ /** Raw database row type for acq_deals table */
3306
+ type AcqDealRow = Database['public']['Tables']['acq_deals']['Row'];
3307
+ type DealStage = 'interested' | 'proposal' | 'closing' | 'closed_won' | 'closed_lost' | 'nurturing';
3308
+ interface DealContact {
3309
+ id: string;
3310
+ first_name: string | null;
3311
+ last_name: string | null;
3312
+ email: string;
3313
+ title: string | null;
3314
+ headline: string | null;
3315
+ linkedin_url: string | null;
3316
+ pipeline_status: Record<string, unknown> | null;
3317
+ enrichment_data: Record<string, unknown> | null;
3318
+ company: {
3319
+ id: string;
3009
3320
  name: string;
3010
- errorCount: number;
3011
- failureRate: number;
3012
- }>;
3321
+ domain: string | null;
3322
+ website: string | null;
3323
+ linkedin_url: string | null;
3324
+ segment: string | null;
3325
+ category: string | null;
3326
+ num_employees: number | null;
3327
+ } | null;
3013
3328
  }
3014
- /**
3015
- * Business impact metrics response
3016
- * ROI, labor savings, and cost analysis
3017
- */
3018
- interface BusinessImpactMetrics$1 {
3019
- totalSavingsUsd: number;
3020
- totalCostUsd: number;
3021
- netSavingsUsd: number;
3022
- roi: number;
3329
+ interface DealFilters {
3330
+ stage?: DealStage;
3331
+ search?: string;
3332
+ limit?: number;
3333
+ offset?: number;
3334
+ }
3335
+ /** Deal list item with joined contact and company data */
3336
+ interface DealListItem extends AcqDealRow {
3337
+ contact: DealContact | null;
3023
3338
  }
3339
+ type DealDetail = DealListItem;
3340
+ /** Task kind options for a deal task (human follow-up action type) */
3341
+ type AcqDealTaskKind = 'call' | 'email' | 'meeting' | 'other';
3024
3342
  /**
3025
- * Cost breakdown metrics response
3026
- * Per-resource cost analysis
3343
+ * A CRM to-do item attached to a deal representing a human follow-up action.
3344
+ * Transformed from AcqDealTaskRow with camelCase properties.
3027
3345
  */
3028
- interface CostBreakdownMetrics {
3029
- resources: Array<{
3030
- resourceId: string;
3031
- totalCostUsd: number;
3032
- executionCount: number;
3033
- avgCostUsd: number;
3034
- }>;
3346
+ interface AcqDealTask {
3347
+ id: string;
3348
+ organizationId: string;
3349
+ dealId: string;
3350
+ title: string;
3351
+ description: string | null;
3352
+ kind: AcqDealTaskKind;
3353
+ dueAt: string | null;
3354
+ assigneeUserId: string | null;
3355
+ completedAt: string | null;
3356
+ completedByUserId: string | null;
3357
+ createdAt: string;
3358
+ updatedAt: string;
3359
+ createdByUserId: string | null;
3035
3360
  }
3036
3361
  /**
3037
- * Dashboard metrics response
3038
- * Aggregates core observability metrics in a single response
3039
- * Note: Throughput data is now included in executionHealth.trendData.executionCount
3362
+ * Live-scan aggregate telemetry for a single list, computed on demand from
3363
+ * the list junction tables and current contact deliverability state.
3040
3364
  */
3041
- interface DashboardMetrics {
3042
- executionHealth: ExecutionHealthMetrics;
3043
- costBreakdown: CostBreakdownMetrics;
3044
- businessImpact: BusinessImpactMetrics$1;
3045
- /** ISO timestamp of the currently active deployment, or null if none */
3046
- activeDeploymentDate: string | null;
3047
- /** Deployment version of the active deployment, or null if none */
3048
- activeDeploymentVersion: string | null;
3365
+ interface ListTelemetry {
3366
+ listId: string;
3367
+ totalCompanies: number;
3368
+ totalContacts: number;
3369
+ stageCounts: {
3370
+ populated: number;
3371
+ extracted: number;
3372
+ qualified: number;
3373
+ discovered: number;
3374
+ verified: number;
3375
+ personalized: number;
3376
+ uploaded: number;
3377
+ };
3378
+ deliverability: {
3379
+ valid: number;
3380
+ risky: number;
3381
+ invalid: number;
3382
+ unknown: number;
3383
+ bounced: number;
3384
+ };
3385
+ /** Reserved -- active workflow IDs associated with this list. */
3386
+ activeWorkflows?: string[];
3049
3387
  }
3388
+
3050
3389
  /**
3051
- * Error record for list view (ErrorBreakdownTable)
3390
+ * Lead Service Types
3391
+ * CRUD operation types for the acquisition platform (lists, companies, contacts, deals)
3392
+ *
3393
+ * Implementation: apps/api/src/acquisition/lead-service.ts (LeadService class)
3052
3394
  */
3053
- interface ErrorRecord {
3395
+
3396
+ interface AcqDealNote {
3054
3397
  id: string;
3055
- timestamp: string;
3056
- errorType: string;
3057
- message: string;
3058
- executionId: string;
3059
- resourceId: string;
3060
- resourceName: string;
3061
- severity: 'critical' | 'warning' | 'info';
3062
- category: ExecutionErrorCategory;
3063
- resolved: boolean;
3064
- resolvedAt: string | null;
3065
- resolvedBy: string | null;
3398
+ dealId: string;
3399
+ organizationId: string;
3400
+ authorUserId: string | null;
3401
+ body: string;
3402
+ createdAt: string;
3403
+ updatedAt: string;
3066
3404
  }
3405
+
3067
3406
  /**
3068
- * Full error detail for modal view (ErrorDetailsModal)
3407
+ * Action configuration for HITL tasks
3408
+ * Defines available user actions and their behavior
3069
3409
  */
3070
- interface ErrorDetailFull extends ErrorRecord {
3071
- stackTrace?: string;
3072
- retryAttempt?: number;
3073
- stepName?: string;
3074
- stepSequence?: number;
3075
- errorContext?: Record<string, unknown>;
3076
- executionContext?: Record<string, unknown>;
3410
+ interface ActionConfig {
3411
+ /** Unique action identifier (e.g., 'approve', 'retry', 'escalate') */
3412
+ id: string;
3413
+ /** Display label for UI button */
3414
+ label: string;
3415
+ /** Button variant/style */
3416
+ type: 'primary' | 'secondary' | 'danger' | 'outline';
3417
+ /** Tabler icon name (e.g., 'IconCheck', 'IconRefresh') */
3418
+ icon?: string;
3419
+ /** Button color (Mantine theme colors) */
3420
+ color?: string;
3421
+ /** Button variant (Mantine button variant, e.g., 'light', 'filled', 'outline') */
3422
+ variant?: string;
3423
+ /** Execution target (agent/workflow to invoke) */
3424
+ target?: {
3425
+ resourceType: 'agent' | 'workflow';
3426
+ resourceId: string;
3427
+ /**
3428
+ * Optional session ID for agent continuation.
3429
+ * If provided, invokes a new turn on the existing session instead of standalone execution.
3430
+ * Only valid when resourceType is 'agent'.
3431
+ */
3432
+ sessionId?: string;
3433
+ };
3434
+ /** Form schema for collecting action-specific data */
3435
+ form?: FormSchema;
3436
+ /** Payload template for pre-filling forms */
3437
+ payloadTemplate?: unknown;
3438
+ /** Requires confirmation dialog */
3439
+ requiresConfirmation?: boolean;
3440
+ /** Confirmation message */
3441
+ confirmationMessage?: string;
3442
+ /** Help text / tooltip */
3443
+ description?: string;
3077
3444
  }
3445
+
3078
3446
  /**
3079
- * Error details API response (paginated)
3447
+ * Origin resource type - where an execution/task originated from.
3448
+ * Used for audit trails and tracking execution lineage.
3080
3449
  */
3081
- interface ErrorDetailResponse {
3082
- errors: ErrorRecord[];
3083
- total: number;
3084
- page: number;
3085
- limit: number;
3086
- }
3450
+ type OriginResourceType = 'agent' | 'workflow' | 'scheduler' | 'api';
3087
3451
  /**
3088
- * Error trend data for time-series charts
3452
+ * Origin tracking metadata - who/what created this execution/task.
3453
+ * Used by both TaskScheduler and CommandQueue for complete audit trails.
3089
3454
  */
3090
- interface ErrorTrend {
3091
- time: string;
3092
- errorCount: number;
3093
- criticalCount: number;
3094
- warningCount: number;
3095
- infoCount: number;
3455
+ interface OriginTracking {
3456
+ originExecutionId: string;
3457
+ originResourceType: OriginResourceType;
3458
+ originResourceId: string;
3096
3459
  }
3460
+
3097
3461
  /**
3098
- * Summary of executions for a single resource
3099
- * Used by RecentExecutionsByResource dashboard component
3462
+ * Command queue task with flexible action system
3100
3463
  */
3101
- interface ResourceExecutionSummary {
3102
- resourceId: string;
3103
- resourceType: string;
3104
- resourceName: string | null;
3105
- lastExecution: string;
3106
- totalExecutions: number;
3107
- successCount: number;
3108
- failureCount: number;
3109
- warningCount: number;
3110
- successRate: number;
3464
+ interface Task extends OriginTracking {
3465
+ id: string;
3466
+ organizationId: string;
3467
+ actions: ActionConfig[];
3468
+ context: unknown;
3469
+ selectedAction?: string;
3470
+ actionPayload?: unknown;
3471
+ description?: string;
3472
+ priority: number;
3473
+ /** Optional checkpoint identifier for grouping related human approval tasks */
3474
+ humanCheckpoint?: string;
3475
+ status: QueueTaskStatus;
3476
+ /**
3477
+ * Target resource tracking — mirrors origin columns.
3478
+ * Set when task is created; patchable to redirect execution to a different resource.
3479
+ */
3480
+ targetResourceId?: string;
3481
+ targetResourceType?: 'agent' | 'workflow';
3482
+ /**
3483
+ * Execution ID for the action that runs AFTER user approval.
3484
+ * NULL until execution starts.
3485
+ *
3486
+ * Naming distinction:
3487
+ * - originExecutionId = Parent execution that CREATED the HITL task
3488
+ * - targetExecutionId = Child execution that RUNS AFTER user approval
3489
+ */
3490
+ targetExecutionId?: string;
3491
+ createdAt: Date;
3492
+ completedAt?: Date;
3493
+ completedBy?: string;
3494
+ expiresAt?: Date;
3495
+ idempotencyKey?: string | null;
3111
3496
  }
3112
3497
  /**
3113
- * Response from getRecentExecutionsByResource endpoint
3498
+ * Task status values
3499
+ * - pending: awaiting action
3500
+ * - processing: execution in progress after user approval
3501
+ * - completed: action was taken and execution succeeded
3502
+ * - failed: execution failed, task can be retried
3503
+ * - expired: timed out before action
3114
3504
  */
3115
- interface RecentExecutionsByResourceResponse {
3116
- resources: ResourceExecutionSummary[];
3117
- }
3118
- /** Resource identifier for health queries */
3119
- interface ResourceIdentifier {
3120
- entityType: string;
3121
- entityId: string;
3122
- }
3123
- /** Time-bucketed health data point */
3124
- interface ResourceHealthDataPoint {
3125
- time: string;
3126
- success: number;
3127
- failure: number;
3128
- warning: number;
3129
- rate: number;
3130
- }
3131
- /** Health data for a single resource */
3132
- interface ResourceHealth {
3133
- entityType: string;
3134
- entityId: string;
3135
- entityName: string | null;
3136
- trendData: ResourceHealthDataPoint[];
3137
- summary: {
3138
- total: number;
3139
- successRate: number;
3140
- };
3505
+ type QueueTaskStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'expired';
3506
+ /**
3507
+ * Parameters for patching mutable metadata on a task
3508
+ */
3509
+ interface PatchTaskParams {
3510
+ humanCheckpoint?: string | null;
3511
+ description?: string;
3512
+ priority?: number;
3513
+ context?: Record<string, unknown>;
3514
+ actions?: unknown[];
3515
+ targetResourceId?: string | null;
3516
+ targetResourceType?: 'agent' | 'workflow' | null;
3517
+ targetExecutionId?: string;
3518
+ status?: 'pending' | 'failed' | 'completed';
3141
3519
  }
3142
- /** Batch response with all requested resources */
3143
- interface ResourcesHealthResponse {
3144
- resources: ResourceHealth[];
3520
+ interface CommandQueueListResponse {
3521
+ tasks: Task[];
3522
+ total: number;
3145
3523
  }
3524
+
3146
3525
  /**
3147
- * Cost trend data point for time-series charts
3148
- * Represents a single time bucket (hour or day)
3526
+ * Checkpoint list item for sidebar grouping
3527
+ * The id field contains the resourceId of the human checkpoint
3149
3528
  */
3150
- interface CostTrendDataPoint {
3151
- time: string;
3152
- totalCostUsd: number;
3153
- executionCount: number;
3154
- avgCostPerExecution: number;
3529
+ interface CheckpointListItem {
3530
+ /** Human checkpoint resourceId (or 'ungrouped' for tasks without checkpoint) */
3531
+ id: string;
3532
+ /** Display name (same as id, or "Ungrouped" for null) */
3533
+ name: string;
3534
+ /** Task count for this checkpoint */
3535
+ count: number;
3155
3536
  }
3156
3537
  /**
3157
- * Cost trends response (time-series data)
3538
+ * Status counts for pie chart display
3158
3539
  */
3159
- interface CostTrendsResponse {
3160
- trendData: CostTrendDataPoint[];
3161
- granularity: 'hour' | 'day';
3162
- totalCostUsd: number;
3163
- totalExecutions: number;
3540
+ interface StatusCounts {
3541
+ pending: number;
3542
+ completed: number;
3543
+ expired: number;
3164
3544
  }
3165
3545
  /**
3166
- * Cost summary response with MTD and projections
3546
+ * Priority counts for donut chart display
3167
3547
  */
3168
- interface CostSummaryResponse {
3169
- current: {
3170
- totalCostUsd: number;
3171
- executionCount: number;
3172
- };
3173
- previous: {
3174
- totalCostUsd: number;
3175
- executionCount: number;
3176
- };
3177
- mtd: {
3178
- totalCostUsd: number;
3179
- daysElapsed: number;
3180
- };
3181
- projection: {
3182
- monthlyCostUsd: number;
3183
- confidence: 'low' | 'medium' | 'high';
3184
- };
3185
- trend: {
3186
- changePercent: number;
3187
- direction: 'up' | 'down' | 'flat';
3188
- };
3548
+ interface PriorityCounts {
3549
+ critical: number;
3550
+ high: number;
3551
+ medium: number;
3552
+ low: number;
3189
3553
  }
3190
3554
  /**
3191
- * Cost by model data for model-level breakdown
3555
+ * Response from GET /command-queue/checkpoints endpoint
3192
3556
  */
3193
- interface CostByModelData {
3194
- model: string;
3195
- totalCostUsd: number;
3196
- callCount: number;
3197
- totalInputTokens: number;
3198
- totalOutputTokens: number;
3199
- avgCostPerCall: number;
3557
+ interface CheckpointListResponse {
3558
+ checkpoints: CheckpointListItem[];
3559
+ /** Total tasks across all checkpoints */
3560
+ total: number;
3561
+ /** Breakdown by status for donut chart */
3562
+ statusCounts: StatusCounts;
3563
+ /** Breakdown by priority for donut chart */
3564
+ priorityCounts: PriorityCounts;
3200
3565
  }
3566
+
3201
3567
  /**
3202
- * Cost by model response
3568
+ * Target for schedule execution - identifies what resource to execute.
3569
+ * Unlike ExecutionTarget, payload is NOT included here because schedules
3570
+ * store payload in the scheduleConfig (varies per step/item).
3203
3571
  */
3204
- interface CostByModelResponse {
3205
- models: CostByModelData[];
3206
- totalCostUsd: number;
3207
- totalCallCount: number;
3572
+ interface ScheduleTarget {
3573
+ resourceType: 'agent' | 'workflow';
3574
+ resourceId: string;
3208
3575
  }
3209
-
3210
3576
  /**
3211
- * Supported integration types
3212
- *
3213
- * These represent the available integration adapters that can be used with tools.
3214
- * Each integration type corresponds to an adapter implementation.
3215
- *
3216
- * Note: Concrete adapter implementations are deferred until needed.
3217
- * This type provides compile-time safety and auto-completion for tool definitions.
3577
+ * Optional origin tracking for schedules.
3578
+ * Unlike OriginTracking (which is required), these fields are all optional
3579
+ * for schedules created directly via API (not triggered by another resource).
3218
3580
  */
3219
- type IntegrationType = 'gmail' | 'google-sheets' | 'slack' | 'github' | 'linear' | 'attio' | 'airtable' | 'salesforce' | 'hubspot' | 'stripe' | 'twilio' | 'sendgrid' | 'mailgun' | 'zapier' | 'webhook' | 'apify' | 'instantly' | 'resend' | 'signature-api' | 'dropbox' | 'anymailfinder' | 'tomba' | 'millionverifier';
3220
-
3221
- declare const LinkSchema: z.ZodObject<{
3222
- nodeId: z.ZodString;
3223
- kind: z.ZodEnum<{
3224
- contains: "contains";
3225
- references: "references";
3226
- exposes: "exposes";
3227
- maps_to: "maps_to";
3228
- "operates-on": "operates-on";
3229
- uses: "uses";
3230
- }>;
3231
- }, z.core.$strip>;
3232
- type Link = z.infer<typeof LinkSchema>;
3233
-
3234
- declare const ResourceCategorySchema: z.ZodEnum<{
3235
- production: "production";
3236
- diagnostic: "diagnostic";
3237
- internal: "internal";
3238
- testing: "testing";
3239
- }>;
3240
- type ResourceCategory = z.infer<typeof ResourceCategorySchema>;
3241
- type ResourceLink = Link;
3581
+ interface ScheduleOriginTracking {
3582
+ originExecutionId?: string;
3583
+ originResourceType?: OriginResourceType;
3584
+ originResourceId?: string;
3585
+ }
3586
+ type TaskScheduleConfig = RecurringScheduleConfig | RelativeScheduleConfig | AbsoluteScheduleConfig;
3587
+ interface RecurringScheduleConfig {
3588
+ type: 'recurring';
3589
+ cron?: string;
3590
+ interval?: 'daily' | 'weekly' | 'monthly';
3591
+ time?: string;
3592
+ timezone: string;
3593
+ payload: Record<string, unknown>;
3594
+ endAt?: string | null;
3595
+ overduePolicy?: 'skip' | 'execute';
3596
+ }
3597
+ interface RelativeScheduleConfig {
3598
+ type: 'relative';
3599
+ anchorAt: string;
3600
+ anchorLabel?: string;
3601
+ items: RelativeScheduleItem[];
3602
+ overduePolicy?: 'skip' | 'execute';
3603
+ }
3604
+ interface RelativeScheduleItem {
3605
+ offset: string;
3606
+ payload: Record<string, unknown>;
3607
+ label?: string;
3608
+ }
3609
+ interface AbsoluteScheduleConfig {
3610
+ type: 'absolute';
3611
+ items: AbsoluteScheduleItem[];
3612
+ overduePolicy?: 'skip' | 'execute';
3613
+ }
3614
+ interface AbsoluteScheduleItem {
3615
+ runAt: string;
3616
+ payload: Record<string, unknown>;
3617
+ label?: string;
3618
+ }
3619
+ interface TaskSchedule extends ScheduleOriginTracking {
3620
+ id: string;
3621
+ organizationId: string;
3622
+ name: string;
3623
+ description?: string;
3624
+ target: ScheduleTarget;
3625
+ scheduleConfig: TaskScheduleConfig;
3626
+ nextRunAt?: Date;
3627
+ currentStep: number;
3628
+ status: 'active' | 'paused' | 'completed' | 'cancelled';
3629
+ lastRunAt?: Date;
3630
+ lastExecutionId?: string;
3631
+ maxRetries: number;
3632
+ idempotencyKey?: string;
3633
+ createdAt: Date;
3634
+ updatedAt: Date;
3635
+ }
3242
3636
 
3243
3637
  /**
3244
- * Resource Registry type definitions
3638
+ * Wire-format DTO for notification API responses.
3639
+ * Dates are ISO 8601 strings (not Date objects like the domain Notification type).
3640
+ * Used by frontend hooks that consume /api/notifications.
3245
3641
  */
3642
+ interface NotificationDTO {
3643
+ id: string;
3644
+ userId: string;
3645
+ organizationId: string;
3646
+ category: string;
3647
+ title: string;
3648
+ message: string;
3649
+ actionUrl: string | null;
3650
+ read: boolean;
3651
+ readAt: string | null;
3652
+ createdAt: string;
3653
+ }
3246
3654
 
3247
- /**
3248
- * Environment/deployment status for resources
3249
- */
3250
- type ResourceStatus = 'dev' | 'prod';
3251
- /**
3252
- * All resource types in the platform
3253
- * Used as the discriminator field in ResourceDefinition
3254
- */
3255
- type ResourceType = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human';
3256
- /**
3257
- * Base interface for ALL platform resources
3258
- * Shared by both executable (agents, workflows) and non-executable (triggers, integrations, etc.) resources
3259
- */
3260
- interface ResourceDefinition {
3261
- /** Unique resource identifier */
3262
- resourceId: string;
3263
- /** Display name */
3264
- name: string;
3265
- /** Purpose and functionality description */
3266
- description: string;
3267
- /** Version for change tracking and evolution */
3268
- version: string;
3269
- /** Resource type discriminator */
3270
- type: ResourceType;
3271
- /** Environment/deployment status */
3272
- status: ResourceStatus;
3273
- /** Graph links to Organization Model nodes */
3274
- links?: ResourceLink[];
3275
- /** Infrastructure category for filtering */
3276
- category?: ResourceCategory;
3277
- /** Whether the agent supports multi-turn sessions (agents only) */
3278
- sessionCapable?: boolean;
3279
- /** Whether the resource is local (monorepo) or remote (externally deployed) */
3280
- origin?: 'local' | 'remote';
3281
- /** Whether this resource is archived and should be excluded from registration and deployment */
3282
- archived?: boolean;
3655
+ type ProjectRow = Database['public']['Tables']['prj_projects']['Row'];
3656
+ type ProjectUpdate = Database['public']['Tables']['prj_projects']['Update'];
3657
+ type MilestoneRow = Database['public']['Tables']['prj_milestones']['Row'];
3658
+ type MilestoneUpdate = Database['public']['Tables']['prj_milestones']['Update'];
3659
+ type TaskRow = Database['public']['Tables']['prj_tasks']['Row'];
3660
+ type TaskUpdate = Database['public']['Tables']['prj_tasks']['Update'];
3661
+ type ProjectStatus = 'active' | 'on_track' | 'at_risk' | 'blocked' | 'completed' | 'paused';
3662
+ type ProjectKind = 'client_engagement' | 'internal' | 'research' | 'other';
3663
+ type MilestoneStatus = 'upcoming' | 'in_progress' | 'completed' | 'overdue' | 'blocked';
3664
+ type TaskStatus = 'planned' | 'in_progress' | 'blocked' | 'completed' | 'cancelled' | 'submitted' | 'approved' | 'rejected' | 'revision_requested';
3665
+ type TaskType = 'documentation' | 'code' | 'report' | 'design' | 'other';
3666
+ type NoteType = 'call_note' | 'status_update' | 'issue' | 'blocker' | 'agent_learning';
3667
+ interface ProjectFilters {
3668
+ status?: ProjectStatus;
3669
+ kind?: ProjectKind;
3670
+ companyId?: string;
3671
+ search?: string;
3283
3672
  }
3284
- /** Webhook provider identifiers */
3285
- type WebhookProviderType = 'cal-com' | 'stripe' | 'signature-api' | 'instantly' | 'apify' | 'test';
3286
- /** Webhook trigger configuration */
3287
- interface WebhookTriggerConfig {
3288
- /** Provider identifier */
3289
- provider: WebhookProviderType;
3290
- /** Event type for documentation (not used for matching - workflow handles routing) */
3291
- event?: string;
3292
- /** Optional filtering (e.g., specific form ID for Fillout) */
3293
- filter?: Record<string, string>;
3294
- /** References credential in credentials table for per-org webhook secrets */
3295
- credentialName?: string;
3673
+ interface MilestoneFilters {
3674
+ status?: MilestoneStatus;
3675
+ projectId?: string;
3296
3676
  }
3297
- /** Schedule trigger configuration */
3298
- interface ScheduleTriggerConfig {
3299
- /** Cron expression (e.g., '0 6 * * *') */
3300
- cron: string;
3301
- /** Optional timezone (default: UTC) */
3302
- timezone?: string;
3677
+ interface TaskFilters {
3678
+ status?: TaskStatus;
3679
+ type?: TaskType;
3680
+ milestoneId?: string;
3681
+ projectId?: string;
3303
3682
  }
3304
- /** Event trigger configuration */
3305
- interface EventTriggerConfig {
3306
- /** Internal event type */
3307
- eventType: string;
3308
- /** Event source */
3309
- source?: string;
3683
+ interface NoteFilters {
3684
+ type?: NoteType;
3685
+ projectId?: string;
3310
3686
  }
3311
- /** Union of all trigger configs */
3312
- type TriggerConfig = WebhookTriggerConfig | ScheduleTriggerConfig | EventTriggerConfig;
3687
+ interface ProjectWithCounts extends ProjectRow {
3688
+ milestoneCount: number;
3689
+ taskCount: number;
3690
+ completedMilestones?: number;
3691
+ completedTasks?: number;
3692
+ }
3693
+ interface ProjectDetail extends ProjectRow {
3694
+ milestones: MilestoneRow[];
3695
+ tasks: TaskRow[];
3696
+ company: {
3697
+ id: string;
3698
+ name: string;
3699
+ domain: string | null;
3700
+ } | null;
3701
+ }
3702
+
3703
+ declare const ListCompaniesQuerySchema: z.ZodObject<{
3704
+ search: z.ZodOptional<z.ZodString>;
3705
+ listId: z.ZodOptional<z.ZodString>;
3706
+ domain: z.ZodOptional<z.ZodString>;
3707
+ website: z.ZodOptional<z.ZodString>;
3708
+ segment: z.ZodOptional<z.ZodString>;
3709
+ category: z.ZodOptional<z.ZodString>;
3710
+ batchId: z.ZodOptional<z.ZodString>;
3711
+ status: z.ZodOptional<z.ZodEnum<{
3712
+ active: "active";
3713
+ invalid: "invalid";
3714
+ }>>;
3715
+ includeAll: z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>;
3716
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
3717
+ offset: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
3718
+ }, z.core.$strict>;
3719
+ declare const ListContactsQuerySchema: z.ZodObject<{
3720
+ search: z.ZodOptional<z.ZodString>;
3721
+ listId: z.ZodOptional<z.ZodString>;
3722
+ openingLineIsNull: z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>;
3723
+ batchId: z.ZodOptional<z.ZodString>;
3724
+ contactStatus: z.ZodOptional<z.ZodEnum<{
3725
+ active: "active";
3726
+ invalid: "invalid";
3727
+ }>>;
3728
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
3729
+ offset: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
3730
+ }, z.core.$strict>;
3731
+ declare const AcqCompanyResponseSchema: z.ZodObject<{
3732
+ id: z.ZodString;
3733
+ organizationId: z.ZodString;
3734
+ name: z.ZodString;
3735
+ domain: z.ZodNullable<z.ZodString>;
3736
+ linkedinUrl: z.ZodNullable<z.ZodString>;
3737
+ website: z.ZodNullable<z.ZodString>;
3738
+ numEmployees: z.ZodNullable<z.ZodNumber>;
3739
+ foundedYear: z.ZodNullable<z.ZodNumber>;
3740
+ locationCity: z.ZodNullable<z.ZodString>;
3741
+ locationState: z.ZodNullable<z.ZodString>;
3742
+ category: z.ZodNullable<z.ZodString>;
3743
+ categoryPain: z.ZodNullable<z.ZodString>;
3744
+ segment: z.ZodNullable<z.ZodString>;
3745
+ pipelineStatus: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3746
+ enrichmentData: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3747
+ source: z.ZodNullable<z.ZodString>;
3748
+ batchId: z.ZodNullable<z.ZodString>;
3749
+ status: z.ZodEnum<{
3750
+ active: "active";
3751
+ invalid: "invalid";
3752
+ }>;
3753
+ contactCount: z.ZodNumber;
3754
+ verticalResearch: z.ZodNullable<z.ZodString>;
3755
+ createdAt: z.ZodString;
3756
+ updatedAt: z.ZodString;
3757
+ }, z.core.$strip>;
3758
+ declare const AcqContactResponseSchema: z.ZodObject<{
3759
+ id: z.ZodString;
3760
+ organizationId: z.ZodString;
3761
+ companyId: z.ZodNullable<z.ZodString>;
3762
+ email: z.ZodString;
3763
+ emailValid: z.ZodNullable<z.ZodEnum<{
3764
+ VALID: "VALID";
3765
+ INVALID: "INVALID";
3766
+ RISKY: "RISKY";
3767
+ UNKNOWN: "UNKNOWN";
3768
+ }>>;
3769
+ firstName: z.ZodNullable<z.ZodString>;
3770
+ lastName: z.ZodNullable<z.ZodString>;
3771
+ linkedinUrl: z.ZodNullable<z.ZodString>;
3772
+ title: z.ZodNullable<z.ZodString>;
3773
+ headline: z.ZodNullable<z.ZodString>;
3774
+ filterReason: z.ZodNullable<z.ZodString>;
3775
+ openingLine: z.ZodNullable<z.ZodString>;
3776
+ source: z.ZodNullable<z.ZodString>;
3777
+ sourceId: z.ZodNullable<z.ZodString>;
3778
+ pipelineStatus: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3779
+ enrichmentData: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3780
+ attioPersonId: z.ZodNullable<z.ZodString>;
3781
+ batchId: z.ZodNullable<z.ZodString>;
3782
+ status: z.ZodEnum<{
3783
+ active: "active";
3784
+ invalid: "invalid";
3785
+ }>;
3786
+ company: z.ZodOptional<z.ZodNullable<z.ZodObject<{
3787
+ id: z.ZodString;
3788
+ name: z.ZodString;
3789
+ domain: z.ZodNullable<z.ZodString>;
3790
+ website: z.ZodNullable<z.ZodString>;
3791
+ linkedinUrl: z.ZodNullable<z.ZodString>;
3792
+ segment: z.ZodNullable<z.ZodString>;
3793
+ category: z.ZodNullable<z.ZodString>;
3794
+ status: z.ZodEnum<{
3795
+ active: "active";
3796
+ invalid: "invalid";
3797
+ }>;
3798
+ }, z.core.$strip>>>;
3799
+ createdAt: z.ZodString;
3800
+ updatedAt: z.ZodString;
3801
+ }, z.core.$strip>;
3802
+ type ListCompaniesQuery = z.infer<typeof ListCompaniesQuerySchema>;
3803
+ type ListContactsQuery = z.infer<typeof ListContactsQuerySchema>;
3804
+ type AcqCompanyResponse = z.infer<typeof AcqCompanyResponseSchema>;
3805
+ type AcqContactResponse = z.infer<typeof AcqContactResponseSchema>;
3806
+
3807
+ type MessageType = MessageEvent['type'];
3313
3808
  /**
3314
- * Trigger metadata - entry points that initiate resource execution
3315
- *
3316
- * Triggers represent how executions start: webhooks from external services,
3317
- * scheduled cron jobs, platform events, or manual user actions.
3318
- *
3319
- * BREAKING CHANGES (2025-11-30):
3320
- * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
3321
- * - Field renames: `id` -> `resourceId` (inherited), `type` -> `triggerType`
3322
- * - Relationship rename: `invokes` -> `triggers` (unified vocabulary)
3323
- * - New required fields: `version` (inherited), `type: 'trigger'` (inherited)
3324
- * - triggers object now includes `externalResources` option
3325
- *
3326
- * @example
3327
- * // TriggerDefinition - metadata only
3328
- * {
3329
- * resourceId: 'trigger-new-order',
3330
- * type: 'trigger',
3331
- * triggerType: 'webhook',
3332
- * name: 'New Order',
3333
- * description: 'Webhook from Shopify on new orders',
3334
- * version: '1.0.0',
3335
- * status: 'prod',
3336
- * webhookPath: '/webhooks/shopify/orders'
3337
- * }
3338
- *
3339
- * // Relationships declared in ResourceRelationships (not on TriggerDefinition):
3340
- * // relationships: {
3341
- * // 'trigger-new-order': { triggers: { workflows: ['order-fulfillment-workflow'] } }
3342
- * // }
3809
+ * Session Data Transfer Object (DTO)
3810
+ * Transform type for API responses (snake_case DB → camelCase frontend)
3811
+ * Used by frontend apps to display session data
3343
3812
  */
3344
- interface TriggerDefinition extends ResourceDefinition {
3345
- /** Resource type discriminator (narrowed from base union) */
3346
- type: 'trigger';
3347
- /** Trigger mechanism type (renamed from 'type' to avoid collision with base type discriminator) */
3348
- triggerType: 'webhook' | 'schedule' | 'manual' | 'event';
3349
- /** Type-specific configuration */
3350
- config?: TriggerConfig;
3351
- /** For webhook triggers: path like '/webhooks/shopify/orders' */
3352
- webhookPath?: string;
3353
- /** For schedule triggers: cron expression like '0 6 * * *' */
3354
- schedule?: string;
3355
- /** For event triggers: event type like 'low-stock-alert' */
3356
- eventType?: string;
3813
+ interface SessionDTO {
3814
+ sessionId: string;
3815
+ resourceId: string;
3816
+ organizationId: string;
3817
+ userId?: string | null;
3818
+ turnCount: number;
3819
+ isEnded: boolean;
3820
+ title?: string | null;
3821
+ memorySnapshot?: AgentMemory;
3822
+ metadata?: Record<string, unknown> | null;
3823
+ createdAt: Date;
3824
+ updatedAt: Date;
3825
+ endedAt?: Date | null;
3826
+ }
3827
+ interface ChatMessage {
3828
+ id: string;
3829
+ role: 'user' | 'assistant';
3830
+ messageType: MessageType;
3831
+ text: string;
3832
+ metadata?: MessageEvent;
3833
+ turnNumber: number;
3834
+ messageIndex?: number;
3835
+ createdAt: Date;
3836
+ }
3837
+ /** Token usage data sent with turn:complete WebSocket events */
3838
+ interface SessionTokenUsage {
3839
+ /** Tokens consumed by this turn's input */
3840
+ turnInputTokens: number;
3841
+ /** Tokens generated by this turn's output */
3842
+ turnOutputTokens: number;
3843
+ /** Total tokens for this turn (turnInputTokens + turnOutputTokens) */
3844
+ turnTotalTokens: number;
3845
+ /** Cumulative input tokens across all turns in this session */
3846
+ cumulativeInputTokens: number;
3847
+ /** Cumulative output tokens across all turns in this session */
3848
+ cumulativeOutputTokens: number;
3849
+ /** The model's context window size for this session (e.g., 200K) */
3850
+ contextWindowSize: number;
3357
3851
  }
3852
+
3358
3853
  /**
3359
- * Integration metadata - external service connections
3360
- *
3361
- * References credentials table for actual connection. No connection status
3362
- * stored here (queried at runtime from credentials table).
3363
- *
3364
- * BREAKING CHANGES (2025-11-30):
3365
- * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
3366
- * - Field renames: `id` -> `resourceId` (inherited)
3367
- * - New required field: `status` (inherited) - organizations must add status to all integrations
3368
- * - New required field: `version` (inherited) - organizations must add version to all integrations
3369
- * - New required field: `type: 'integration'` (inherited) - resource type discriminator
3854
+ * Multi-tenancy configuration types
3370
3855
  *
3371
- * @example
3372
- * {
3373
- * resourceId: 'integration-shopify-prod',
3374
- * type: 'integration',
3375
- * provider: 'shopify',
3376
- * credentialName: 'shopify-prod',
3377
- * name: 'Shopify Production',
3378
- * description: 'E-commerce platform',
3379
- * version: '1.0.0',
3380
- * status: 'prod'
3381
- * }
3856
+ * Config is stored in dedicated `config` columns (NOT nested in metadata):
3857
+ * - organizations.config: Org-level config (no feature toggles -- all features available by default)
3858
+ * - org_memberships.config: Per-user-per-org feature overrides
3859
+ * - users.config: User-global config
3382
3860
  */
3383
- interface IntegrationDefinition extends ResourceDefinition {
3384
- /** Resource type discriminator (narrowed from base union) */
3385
- type: 'integration';
3386
- /** Integration provider type */
3387
- provider: IntegrationType;
3388
- /** References credentials table (e.g., 'shopify-prod', 'zendesk-api') */
3389
- credentialName: string;
3390
- }
3391
- /**
3392
- * External platform type
3393
- * Supported third-party automation platforms
3394
- */
3395
- type ExternalPlatform = 'n8n' | 'make' | 'zapier' | 'other';
3396
3861
  /**
3397
- * External automation resource metadata
3398
- *
3399
- * Represents workflows/automations running on third-party platforms
3400
- * (n8n, Make, Zapier, etc.) for visualization in Command View.
3401
- *
3402
- * NOTE: This is metadata ONLY for visualization. No execution logic,
3403
- * no API integration with external platforms, no status syncing.
3404
- *
3405
- * BREAKING CHANGES (2025-11-30):
3406
- * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
3407
- * - Field renames: `id` -> `resourceId` (inherited)
3408
- * - New required field: `version` (inherited) - organizations must add version to all external resources
3409
- * - New required field: `type: 'external'` (inherited) - resource type discriminator
3410
- * - REMOVED FIELD: `triggeredBy` - per relationship-consolidation design, all relationships are forward-only declarations
3411
- *
3412
- * @example
3413
- * {
3414
- * resourceId: 'external-n8n-order-sync',
3415
- * type: 'external',
3416
- * version: '1.0.0',
3417
- * platform: 'n8n',
3418
- * name: 'Shopify Order Sync',
3419
- * description: 'Legacy n8n workflow for syncing Shopify orders',
3420
- * status: 'prod',
3421
- * platformUrl: 'https://n8n.client.com/workflow/123',
3422
- * triggers: { workflows: ['order-fulfillment-workflow'] },
3423
- * uses: { integrations: ['integration-shopify-prod'] }
3424
- * }
3862
+ * Per-user-per-org config (stored in org_memberships.config)
3863
+ * Controls which features a specific member can access within their org.
3864
+ * Keys are feature IDs from the organization model (e.g. crm, lead-gen, projects, seo).
3425
3865
  */
3426
- interface ExternalResourceDefinition extends ResourceDefinition {
3427
- /** Resource type discriminator (narrowed from base union) */
3428
- type: 'external';
3429
- /** Platform type */
3430
- platform: ExternalPlatform;
3431
- /** Link to external platform (e.g., n8n workflow editor URL) */
3432
- platformUrl?: string;
3433
- /** Platform's internal ID/reference */
3434
- externalId?: string;
3435
- /** What this external resource triggers (external -> internal) */
3436
- triggers?: {
3437
- /** Elevasis workflow resourceIds this external automation triggers */
3438
- workflows?: string[];
3439
- /** Elevasis agent resourceIds this external automation triggers */
3440
- agents?: string[];
3441
- };
3442
- /** Integrations this external resource uses (shared credentials) */
3443
- uses?: {
3444
- /** Integration IDs this external automation uses */
3445
- integrations?: string[];
3446
- };
3866
+ interface MembershipFeatureConfig {
3867
+ features?: Record<string, boolean>;
3447
3868
  }
3448
3869
  /**
3449
- * Human Checkpoint definition - human decision points in automation
3450
- *
3451
- * Represents where human judgment is deployed in the automation landscape.
3452
- * Tasks with matching command_queue_group are routed to this checkpoint.
3453
- *
3454
- * BREAKING CHANGES (2025-11-30):
3455
- * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
3456
- * - Field renames: `id` -> `resourceId` (inherited)
3457
- * - description is now REQUIRED (was optional) - organizations must add description to all human checkpoints
3458
- * - New required field: `version` (inherited) - organizations must add version to all human checkpoints
3459
- * - New required field: `type: 'human'` (inherited) - resource type discriminator
3460
- *
3461
- * @example
3462
- * {
3463
- * resourceId: 'sales-approval',
3464
- * type: 'human',
3465
- * name: 'Sales Approval Queue',
3466
- * description: 'High-value order approvals for sales team',
3467
- * version: '1.0.0',
3468
- * status: 'prod',
3469
- * requestedBy: { agents: ['order-processor-agent'] },
3470
- * routesTo: { agents: ['order-fulfillment-agent'] }
3471
- * }
3870
+ * User-global config (stored in users.config)
3871
+ * Theme and onboarding are user-specific, NOT org-specific
3472
3872
  */
3473
- interface HumanCheckpointDefinition extends ResourceDefinition {
3474
- /** Resource type discriminator (narrowed from base union) */
3475
- type: 'human';
3476
- /** Resources that create tasks for this checkpoint */
3477
- requestedBy?: {
3478
- /** Agent resourceIds that request approval here */
3479
- agents?: string[];
3480
- /** Workflow resourceIds that request approval here */
3481
- workflows?: string[];
3873
+ interface UserConfig {
3874
+ theme?: {
3875
+ preset?: 'default' | 'tactical' | 'regal' | 'cyber-volt' | 'aurora' | 'rose-gold' | 'midnight' | 'titanium' | 'obsidian' | 'honey' | 'abyss' | 'canopy' | 'slate' | 'cyber-strike' | 'cyber-chrome' | 'cyber-void' | 'nirvana' | 'wave' | 'synapse' | 'cortex' | 'helios' | 'graphite' | 'quarry' | 'canyon' | 'nord' | 'catppuccin' | 'tokyo-night' | 'gruvbox';
3876
+ colorScheme?: 'light' | 'dark' | 'auto';
3482
3877
  };
3483
- /** Resources that receive approved decisions */
3484
- routesTo?: {
3485
- /** Agent resourceIds that handle approved tasks */
3486
- agents?: string[];
3487
- /** Workflow resourceIds that handle approved tasks */
3488
- workflows?: string[];
3878
+ onboarding?: {
3879
+ completed?: boolean;
3880
+ completedAt?: string;
3881
+ role?: string;
3882
+ primaryUseCase?: string[];
3883
+ experienceLevel?: string;
3884
+ /** Onboarding guide system state (set by checklist/tour system) */
3885
+ guides?: {
3886
+ completedIds?: string[];
3887
+ dismissed?: boolean;
3888
+ completedAt?: string;
3889
+ };
3489
3890
  };
3490
3891
  }
3491
3892
 
3492
3893
  /**
3493
- * Command View Types
3894
+ * Memberships Domain - Zod Validation Schemas
3494
3895
  *
3495
- * Unified type definitions for the Command View graph visualization.
3496
- * These types are used by both backend serialization and frontend rendering.
3896
+ * Validation schemas for membership management endpoints.
3897
+ * Includes request bodies, query params, and path params.
3497
3898
  *
3498
- * Command View shows the resource graph: agents, workflows, triggers, integrations,
3499
- * external resources, and human checkpoints with their relationships.
3899
+ * Security:
3900
+ * - All schemas use .strict() to prevent mass assignment attacks
3901
+ * - UUID validation prevents invalid references
3902
+ * - Role enum validation prevents privilege escalation
3903
+ * - organizationId never accepted in body (from JWT when needed)
3500
3904
  */
3501
3905
 
3502
3906
  /**
3503
- * Extended agent metadata for Command View
3504
- * Includes model and capability information for graph display
3907
+ * Membership status validation
3908
+ * Note: Database constraint only allows 'active' | 'inactive'
3505
3909
  */
3506
- interface CommandViewAgent extends ResourceDefinition {
3507
- type: 'agent';
3508
- modelProvider: string;
3509
- modelId: string;
3510
- toolCount: number;
3511
- hasKnowledgeMap: boolean;
3512
- hasMemory: boolean;
3513
- sessionCapable: boolean;
3514
- }
3910
+ declare const MembershipStatusSchema: z.ZodEnum<{
3911
+ active: "active";
3912
+ inactive: "inactive";
3913
+ }>;
3914
+ type MembershipStatus = z.infer<typeof MembershipStatusSchema>;
3915
+
3515
3916
  /**
3516
- * Extended workflow metadata for Command View
3517
- * Includes step information for graph display
3917
+ * Organization Membership types based on WorkOS API
3518
3918
  */
3519
- interface CommandViewWorkflow extends ResourceDefinition {
3520
- type: 'workflow';
3521
- stepCount: number;
3522
- entryPoint: string;
3919
+ interface OrganizationMembership {
3920
+ object: 'organization_membership';
3921
+ id: string;
3922
+ userId: string;
3923
+ organizationId: string;
3924
+ role: {
3925
+ slug: string;
3926
+ };
3927
+ status: 'active' | 'inactive';
3928
+ createdAt: string;
3929
+ updatedAt: string;
3523
3930
  }
3524
3931
  /**
3525
- * Relationship types between resources
3526
- *
3527
- * - triggers: Resource initiates/starts another resource (orange)
3528
- * - uses: Resource uses an integration (teal)
3529
- * - approval: Resource requires human approval (yellow)
3932
+ * Request interfaces for membership operations
3530
3933
  */
3531
- type RelationshipType$1 = 'triggers' | 'uses' | 'approval';
3934
+ interface CreateMembershipRequest {
3935
+ userId: string;
3936
+ organizationId: string;
3937
+ roleSlug?: string;
3938
+ }
3939
+ interface UpdateMembershipRequest {
3940
+ roleSlug: string;
3941
+ }
3942
+ interface ListMembershipsParams {
3943
+ userId?: string;
3944
+ organizationId?: string;
3945
+ statuses?: MembershipStatus[];
3946
+ limit?: number;
3947
+ before?: string;
3948
+ after?: string;
3949
+ order?: 'asc' | 'desc';
3950
+ }
3532
3951
  /**
3533
- * Command View edge (relationship between resources)
3952
+ * Response interfaces
3534
3953
  */
3535
- interface CommandViewEdge$1 {
3536
- id: string;
3537
- source: string;
3538
- target: string;
3539
- relationship: RelationshipType$1;
3540
- label?: string;
3954
+ interface ListMembershipsResponse {
3955
+ data: OrganizationMembership[];
3956
+ listMetadata?: {
3957
+ before?: string | null;
3958
+ after?: string | null;
3959
+ };
3541
3960
  }
3542
3961
  /**
3543
- * Command View data structure
3544
- * Complete graph data for visualization
3545
- *
3546
- * Backend serializes this once at startup and serves it via /command-view endpoint.
3547
- * Frontend consumes this directly for graph rendering.
3962
+ * Extended membership with user and organization details for UI
3548
3963
  */
3549
- interface CommandViewData {
3550
- workflows: CommandViewWorkflow[];
3551
- agents: CommandViewAgent[];
3552
- triggers: TriggerDefinition[];
3553
- integrations: IntegrationDefinition[];
3554
- externalResources: ExternalResourceDefinition[];
3555
- humanCheckpoints: HumanCheckpointDefinition[];
3556
- edges: CommandViewEdge$1[];
3964
+ interface MembershipWithDetails extends OrganizationMembership {
3965
+ user?: {
3966
+ id: string;
3967
+ email: string;
3968
+ firstName?: string;
3969
+ lastName?: string;
3970
+ profilePictureUrl?: string;
3971
+ };
3972
+ organization?: {
3973
+ id: string;
3974
+ name: string;
3975
+ workos_org_id: string;
3976
+ primaryDomain?: string;
3977
+ is_test?: boolean;
3978
+ status?: string;
3979
+ metadata?: Record<string, unknown>;
3980
+ config?: Record<string, unknown>;
3981
+ };
3982
+ config?: MembershipFeatureConfig;
3557
3983
  }
3558
3984
 
3559
3985
  /**
3560
- * Serialized Registry Types
3561
- *
3562
- * Pre-computed JSON-safe types for API responses and Command View.
3563
- * Serialization happens once at API startup, enabling instant response times.
3986
+ * Time range selector for dashboard metrics
3564
3987
  */
3565
-
3988
+ type TimeRange = '1h' | '24h' | '7d' | '30d';
3566
3989
  /**
3567
- * Serialized form field for API responses
3990
+ * Execution health metrics response
3991
+ * Success rate, P95 duration, execution counts, and trend data
3992
+ * trendData includes executionCount for throughput visualization (eliminates separate API call)
3568
3993
  */
3569
- interface SerializedFormField {
3570
- name: string;
3571
- label: string;
3572
- type: FormFieldType;
3573
- defaultValue?: unknown;
3574
- required?: boolean;
3575
- placeholder?: string;
3576
- description?: string;
3577
- options?: Array<{
3578
- label: string;
3579
- value: string | number;
3994
+ interface ExecutionHealthMetrics {
3995
+ successRate: number;
3996
+ p95Duration: number;
3997
+ totalExecutions: number;
3998
+ trendData: Array<{
3999
+ time: string;
4000
+ rate: number;
4001
+ successCount: number;
4002
+ errorCount: number;
4003
+ warningCount: number;
4004
+ executionCount: number;
3580
4005
  }>;
3581
- min?: number;
3582
- max?: number;
4006
+ statusCounts: {
4007
+ success: number;
4008
+ failed: number;
4009
+ pending: number;
4010
+ warning: number;
4011
+ };
4012
+ peakPeriod: string;
4013
+ granularity: 'hour' | 'day';
3583
4014
  }
3584
4015
  /**
3585
- * Serialized form schema for API responses
4016
+ * Error analysis metrics response
4017
+ * Error categories and top failing resources
3586
4018
  */
3587
- interface SerializedFormSchema {
3588
- title?: string;
3589
- description?: string;
3590
- fields: SerializedFormField[];
3591
- layout?: 'vertical' | 'horizontal' | 'grid';
4019
+ interface ErrorAnalysisMetrics {
4020
+ totalErrors: number;
4021
+ errorsByCategory: Array<{
4022
+ category: string;
4023
+ count: number;
4024
+ percentage: number;
4025
+ }>;
4026
+ topFailingResources: Array<{
4027
+ resourceId: string;
4028
+ name: string;
4029
+ errorCount: number;
4030
+ failureRate: number;
4031
+ }>;
3592
4032
  }
3593
4033
  /**
3594
- * Serialized execution form schema for API responses
4034
+ * Business impact metrics response
4035
+ * ROI, labor savings, and cost analysis
3595
4036
  */
3596
- interface SerializedExecutionFormSchema extends SerializedFormSchema {
3597
- fieldMappings?: Record<string, string>;
3598
- submitButton?: {
3599
- label?: string;
3600
- loadingLabel?: string;
3601
- confirmMessage?: string;
3602
- };
4037
+ interface BusinessImpactMetrics$1 {
4038
+ totalSavingsUsd: number;
4039
+ totalCostUsd: number;
4040
+ netSavingsUsd: number;
4041
+ roi: number;
3603
4042
  }
3604
4043
  /**
3605
- * Serialized schedule config for API responses
4044
+ * Cost breakdown metrics response
4045
+ * Per-resource cost analysis
3606
4046
  */
3607
- interface SerializedScheduleConfig {
3608
- enabled: boolean;
3609
- defaultSchedule?: string;
3610
- allowedPatterns?: string[];
4047
+ interface CostBreakdownMetrics {
4048
+ resources: Array<{
4049
+ resourceId: string;
4050
+ totalCostUsd: number;
4051
+ executionCount: number;
4052
+ avgCostUsd: number;
4053
+ }>;
3611
4054
  }
3612
4055
  /**
3613
- * Serialized webhook config for API responses
4056
+ * Dashboard metrics response
4057
+ * Aggregates core observability metrics in a single response
4058
+ * Note: Throughput data is now included in executionHealth.trendData.executionCount
3614
4059
  */
3615
- interface SerializedWebhookConfig {
3616
- enabled: boolean;
3617
- payloadSchema?: unknown;
4060
+ interface DashboardMetrics {
4061
+ executionHealth: ExecutionHealthMetrics;
4062
+ costBreakdown: CostBreakdownMetrics;
4063
+ businessImpact: BusinessImpactMetrics$1;
4064
+ /** ISO timestamp of the currently active deployment, or null if none */
4065
+ activeDeploymentDate: string | null;
4066
+ /** Deployment version of the active deployment, or null if none */
4067
+ activeDeploymentVersion: string | null;
3618
4068
  }
3619
4069
  /**
3620
- * Serialized execution interface for API responses
4070
+ * Error record for list view (ErrorBreakdownTable)
3621
4071
  */
3622
- interface SerializedExecutionInterface {
3623
- form: SerializedExecutionFormSchema;
3624
- schedule?: SerializedScheduleConfig;
3625
- webhook?: SerializedWebhookConfig;
4072
+ interface ErrorRecord {
4073
+ id: string;
4074
+ timestamp: string;
4075
+ errorType: string;
4076
+ message: string;
4077
+ executionId: string;
4078
+ resourceId: string;
4079
+ resourceName: string;
4080
+ severity: 'critical' | 'warning' | 'info';
4081
+ category: ExecutionErrorCategory;
4082
+ resolved: boolean;
4083
+ resolvedAt: string | null;
4084
+ resolvedBy: string | null;
3626
4085
  }
3627
4086
  /**
3628
- * Serialized agent definition (JSON-safe)
3629
- * Result of serializeDefinition(AgentDefinition)
4087
+ * Full error detail for modal view (ErrorDetailsModal)
3630
4088
  */
3631
- interface SerializedAgentDefinition {
3632
- config: {
3633
- resourceId: string;
3634
- name: string;
3635
- description: string;
3636
- version: string;
3637
- type: 'agent';
3638
- status: 'dev' | 'prod';
3639
- links?: ResourceLink[];
3640
- category?: ResourceCategory;
3641
- /** Whether this resource is archived and should be excluded from registration and deployment */
3642
- archived?: boolean;
3643
- systemPrompt: string;
3644
- constraints?: {
3645
- maxIterations?: number;
3646
- timeout?: number;
3647
- maxSessionMemoryKeys?: number;
3648
- maxMemoryTokens?: number;
3649
- };
3650
- sessionCapable?: boolean;
3651
- memoryPreferences?: string;
3652
- };
3653
- modelConfig: {
3654
- provider: string;
3655
- model: string;
3656
- apiKey: string;
3657
- temperature: number;
3658
- maxOutputTokens: number;
3659
- topP?: number;
3660
- modelOptions?: Record<string, unknown>;
3661
- };
3662
- contract: {
3663
- inputSchema: object;
3664
- outputSchema?: object;
3665
- };
3666
- tools: Array<{
3667
- name: string;
3668
- description: string;
3669
- inputSchema?: object;
3670
- outputSchema?: object;
3671
- }>;
3672
- knowledgeMap?: {
3673
- nodeCount: number;
3674
- nodes: Array<{
3675
- id: string;
3676
- description: string;
3677
- loaded: boolean;
3678
- hasPrompt: boolean;
3679
- }>;
3680
- };
3681
- metricsConfig?: object;
3682
- interface?: SerializedExecutionInterface;
4089
+ interface ErrorDetailFull extends ErrorRecord {
4090
+ stackTrace?: string;
4091
+ retryAttempt?: number;
4092
+ stepName?: string;
4093
+ stepSequence?: number;
4094
+ errorContext?: Record<string, unknown>;
4095
+ executionContext?: Record<string, unknown>;
3683
4096
  }
3684
4097
  /**
3685
- * Serialized workflow definition (JSON-safe)
3686
- * Result of serializeDefinition(WorkflowDefinition)
4098
+ * Error details API response (paginated)
3687
4099
  */
3688
- interface SerializedWorkflowDefinition {
3689
- config: {
3690
- resourceId: string;
3691
- name: string;
3692
- description: string;
3693
- version: string;
3694
- type: 'workflow';
3695
- status: 'dev' | 'prod';
3696
- links?: ResourceLink[];
3697
- category?: ResourceCategory;
3698
- /** Whether this resource is archived and should be excluded from registration and deployment */
3699
- archived?: boolean;
3700
- };
3701
- entryPoint: string;
3702
- steps: Array<{
3703
- id: string;
3704
- name: string;
3705
- description: string;
3706
- inputSchema?: object;
3707
- outputSchema?: object;
3708
- next: {
3709
- type: 'linear' | 'conditional';
3710
- target?: string;
3711
- routes?: Array<{
3712
- target: string;
3713
- }>;
3714
- default?: string;
3715
- } | null;
3716
- }>;
3717
- contract: {
3718
- inputSchema: object;
3719
- outputSchema?: object;
3720
- };
3721
- metricsConfig?: object;
3722
- interface?: SerializedExecutionInterface;
4100
+ interface ErrorDetailResponse {
4101
+ errors: ErrorRecord[];
4102
+ total: number;
4103
+ page: number;
4104
+ limit: number;
3723
4105
  }
3724
-
3725
4106
  /**
3726
- * Base Execution Engine type definitions
3727
- * Core types shared across all Execution Engine resources
4107
+ * Error trend data for time-series charts
3728
4108
  */
3729
-
4109
+ interface ErrorTrend {
4110
+ time: string;
4111
+ errorCount: number;
4112
+ criticalCount: number;
4113
+ warningCount: number;
4114
+ infoCount: number;
4115
+ }
3730
4116
  /**
3731
- * Unified message event type - covers all message types in sessions
3732
- * Replaces separate SessionTurnMessages and AgentActivityEvent mechanisms
4117
+ * Summary of executions for a single resource
4118
+ * Used by RecentExecutionsByResource dashboard component
3733
4119
  */
4120
+ interface ResourceExecutionSummary {
4121
+ resourceId: string;
4122
+ resourceType: string;
4123
+ resourceName: string | null;
4124
+ lastExecution: string;
4125
+ totalExecutions: number;
4126
+ successCount: number;
4127
+ failureCount: number;
4128
+ warningCount: number;
4129
+ successRate: number;
4130
+ }
3734
4131
  /**
3735
- * Structured action metadata attached to assistant messages.
3736
- * Frontend reads this instead of parsing text prefixes.
4132
+ * Response from getRecentExecutionsByResource endpoint
3737
4133
  */
3738
- type AssistantAction = {
3739
- kind: 'navigate';
3740
- path: string;
3741
- reason: string;
3742
- } | {
3743
- kind: 'update_filters';
3744
- timeRange: string | null;
3745
- statusFilter: string | null;
3746
- searchQuery: string | null;
3747
- };
3748
- type MessageEvent = {
3749
- type: 'user_message';
4134
+ interface RecentExecutionsByResourceResponse {
4135
+ resources: ResourceExecutionSummary[];
4136
+ }
4137
+ /** Resource identifier for health queries */
4138
+ interface ResourceIdentifier {
4139
+ entityType: string;
4140
+ entityId: string;
4141
+ }
4142
+ /** Time-bucketed health data point */
4143
+ interface ResourceHealthDataPoint {
4144
+ time: string;
4145
+ success: number;
4146
+ failure: number;
4147
+ warning: number;
4148
+ rate: number;
4149
+ }
4150
+ /** Health data for a single resource */
4151
+ interface ResourceHealth {
4152
+ entityType: string;
4153
+ entityId: string;
4154
+ entityName: string | null;
4155
+ trendData: ResourceHealthDataPoint[];
4156
+ summary: {
4157
+ total: number;
4158
+ successRate: number;
4159
+ };
4160
+ }
4161
+ /** Batch response with all requested resources */
4162
+ interface ResourcesHealthResponse {
4163
+ resources: ResourceHealth[];
4164
+ }
4165
+ /**
4166
+ * Cost trend data point for time-series charts
4167
+ * Represents a single time bucket (hour or day)
4168
+ */
4169
+ interface CostTrendDataPoint {
4170
+ time: string;
4171
+ totalCostUsd: number;
4172
+ executionCount: number;
4173
+ avgCostPerExecution: number;
4174
+ }
4175
+ /**
4176
+ * Cost trends response (time-series data)
4177
+ */
4178
+ interface CostTrendsResponse {
4179
+ trendData: CostTrendDataPoint[];
4180
+ granularity: 'hour' | 'day';
4181
+ totalCostUsd: number;
4182
+ totalExecutions: number;
4183
+ }
4184
+ /**
4185
+ * Cost summary response with MTD and projections
4186
+ */
4187
+ interface CostSummaryResponse {
4188
+ current: {
4189
+ totalCostUsd: number;
4190
+ executionCount: number;
4191
+ };
4192
+ previous: {
4193
+ totalCostUsd: number;
4194
+ executionCount: number;
4195
+ };
4196
+ mtd: {
4197
+ totalCostUsd: number;
4198
+ daysElapsed: number;
4199
+ };
4200
+ projection: {
4201
+ monthlyCostUsd: number;
4202
+ confidence: 'low' | 'medium' | 'high';
4203
+ };
4204
+ trend: {
4205
+ changePercent: number;
4206
+ direction: 'up' | 'down' | 'flat';
4207
+ };
4208
+ }
4209
+ /**
4210
+ * Cost by model data for model-level breakdown
4211
+ */
4212
+ interface CostByModelData {
4213
+ model: string;
4214
+ totalCostUsd: number;
4215
+ callCount: number;
4216
+ totalInputTokens: number;
4217
+ totalOutputTokens: number;
4218
+ avgCostPerCall: number;
4219
+ }
4220
+ /**
4221
+ * Cost by model response
4222
+ */
4223
+ interface CostByModelResponse {
4224
+ models: CostByModelData[];
4225
+ totalCostUsd: number;
4226
+ totalCallCount: number;
4227
+ }
4228
+
4229
+ /**
4230
+ * Base Execution Engine type definitions
4231
+ * Core types shared across all Execution Engine resources
4232
+ */
4233
+
4234
+ /**
4235
+ * Unified message event type - covers all message types in sessions
4236
+ * Replaces separate SessionTurnMessages and AgentActivityEvent mechanisms
4237
+ */
4238
+ /**
4239
+ * Structured action metadata attached to assistant messages.
4240
+ * Frontend reads this instead of parsing text prefixes.
4241
+ */
4242
+ type AssistantAction = {
4243
+ kind: 'navigate';
4244
+ path: string;
4245
+ reason: string;
4246
+ } | {
4247
+ kind: 'update_filters';
4248
+ timeRange: string | null;
4249
+ statusFilter: string | null;
4250
+ searchQuery: string | null;
4251
+ };
4252
+ type MessageEvent = {
4253
+ type: 'user_message';
3750
4254
  text: string;
3751
4255
  } | {
3752
4256
  type: 'assistant_message';
@@ -3784,717 +4288,502 @@ type MessageEvent = {
3784
4288
  */
3785
4289
  type AIResourceDefinition = SerializedWorkflowDefinition | SerializedAgentDefinition;
3786
4290
 
3787
- type SupabaseUserProfile = Tables<'users'>;
3788
- type SupabaseApiKey = Tables<'api_keys'>;
3789
- /** API response type for API key list items (omits sensitive key_hash) */
3790
- type ApiKeyListItem = Omit<SupabaseApiKey, 'key_hash'>;
3791
-
3792
- /** Raw database row type for acq_deals table */
3793
- type AcqDealRow = Database['public']['Tables']['acq_deals']['Row'];
3794
- type DealStage = 'interested' | 'proposal' | 'closing' | 'closed_won' | 'closed_lost' | 'nurturing';
3795
- interface DealContact {
3796
- id: string;
3797
- first_name: string | null;
3798
- last_name: string | null;
3799
- email: string;
3800
- title: string | null;
3801
- headline: string | null;
3802
- linkedin_url: string | null;
3803
- pipeline_status: Record<string, unknown> | null;
3804
- enrichment_data: Record<string, unknown> | null;
3805
- company: {
3806
- id: string;
3807
- name: string;
3808
- domain: string | null;
3809
- website: string | null;
3810
- linkedin_url: string | null;
3811
- segment: string | null;
3812
- category: string | null;
3813
- num_employees: number | null;
3814
- } | null;
3815
- }
3816
- interface DealFilters {
3817
- stage?: DealStage;
3818
- search?: string;
3819
- limit?: number;
3820
- offset?: number;
3821
- }
3822
- /** Deal list item with joined contact and company data */
3823
- interface DealListItem extends AcqDealRow {
3824
- contact: DealContact | null;
3825
- }
3826
- type DealDetail = DealListItem;
3827
- /** Task kind options for a deal task (human follow-up action type) */
3828
- type AcqDealTaskKind = 'call' | 'email' | 'meeting' | 'other';
3829
4291
  /**
3830
- * A CRM to-do item attached to a deal representing a human follow-up action.
3831
- * Transformed from AcqDealTaskRow with camelCase properties.
4292
+ * Supported integration types
4293
+ *
4294
+ * These represent the available integration adapters that can be used with tools.
4295
+ * Each integration type corresponds to an adapter implementation.
4296
+ *
4297
+ * Note: Concrete adapter implementations are deferred until needed.
4298
+ * This type provides compile-time safety and auto-completion for tool definitions.
3832
4299
  */
3833
- interface AcqDealTask {
3834
- id: string;
3835
- organizationId: string;
3836
- dealId: string;
3837
- title: string;
3838
- description: string | null;
3839
- kind: AcqDealTaskKind;
3840
- dueAt: string | null;
3841
- assigneeUserId: string | null;
3842
- completedAt: string | null;
3843
- completedByUserId: string | null;
3844
- createdAt: string;
3845
- updatedAt: string;
3846
- createdByUserId: string | null;
3847
- }
4300
+ type IntegrationType = 'gmail' | 'google-sheets' | 'slack' | 'github' | 'linear' | 'attio' | 'airtable' | 'salesforce' | 'hubspot' | 'stripe' | 'twilio' | 'sendgrid' | 'mailgun' | 'zapier' | 'webhook' | 'apify' | 'instantly' | 'resend' | 'signature-api' | 'dropbox' | 'anymailfinder' | 'tomba' | 'millionverifier';
4301
+
3848
4302
  /**
3849
- * Live-scan aggregate telemetry for a single list, computed on demand from
3850
- * the list junction tables and current contact deliverability state.
4303
+ * Resource Registry type definitions
3851
4304
  */
3852
- interface ListTelemetry {
3853
- listId: string;
3854
- totalCompanies: number;
3855
- totalContacts: number;
3856
- stageCounts: {
3857
- populated: number;
3858
- extracted: number;
3859
- qualified: number;
3860
- discovered: number;
3861
- verified: number;
3862
- personalized: number;
3863
- uploaded: number;
3864
- };
3865
- deliverability: {
3866
- valid: number;
3867
- risky: number;
3868
- invalid: number;
3869
- unknown: number;
3870
- bounced: number;
3871
- };
3872
- /** Reserved -- active workflow IDs associated with this list. */
3873
- activeWorkflows?: string[];
3874
- }
3875
4305
 
3876
4306
  /**
3877
- * Lead Service Types
3878
- * CRUD operation types for the acquisition platform (lists, companies, contacts, deals)
3879
- *
3880
- * Implementation: apps/api/src/acquisition/lead-service.ts (LeadService class)
4307
+ * Environment/deployment status for resources
3881
4308
  */
3882
-
3883
- interface AcqDealNote {
3884
- id: string;
3885
- dealId: string;
3886
- organizationId: string;
3887
- authorUserId: string | null;
3888
- body: string;
3889
- createdAt: string;
3890
- updatedAt: string;
3891
- }
3892
-
4309
+ type ResourceStatus = 'dev' | 'prod';
3893
4310
  /**
3894
- * Action configuration for HITL tasks
3895
- * Defines available user actions and their behavior
4311
+ * All resource types in the platform
4312
+ * Used as the discriminator field in ResourceDefinition
3896
4313
  */
3897
- interface ActionConfig {
3898
- /** Unique action identifier (e.g., 'approve', 'retry', 'escalate') */
3899
- id: string;
3900
- /** Display label for UI button */
3901
- label: string;
3902
- /** Button variant/style */
3903
- type: 'primary' | 'secondary' | 'danger' | 'outline';
3904
- /** Tabler icon name (e.g., 'IconCheck', 'IconRefresh') */
3905
- icon?: string;
3906
- /** Button color (Mantine theme colors) */
3907
- color?: string;
3908
- /** Button variant (Mantine button variant, e.g., 'light', 'filled', 'outline') */
3909
- variant?: string;
3910
- /** Execution target (agent/workflow to invoke) */
3911
- target?: {
3912
- resourceType: 'agent' | 'workflow';
3913
- resourceId: string;
3914
- /**
3915
- * Optional session ID for agent continuation.
3916
- * If provided, invokes a new turn on the existing session instead of standalone execution.
3917
- * Only valid when resourceType is 'agent'.
3918
- */
3919
- sessionId?: string;
3920
- };
3921
- /** Form schema for collecting action-specific data */
3922
- form?: FormSchema;
3923
- /** Payload template for pre-filling forms */
3924
- payloadTemplate?: unknown;
3925
- /** Requires confirmation dialog */
3926
- requiresConfirmation?: boolean;
3927
- /** Confirmation message */
3928
- confirmationMessage?: string;
3929
- /** Help text / tooltip */
3930
- description?: string;
3931
- }
3932
-
3933
- /**
3934
- * Origin resource type - where an execution/task originated from.
3935
- * Used for audit trails and tracking execution lineage.
3936
- */
3937
- type OriginResourceType = 'agent' | 'workflow' | 'scheduler' | 'api';
3938
- /**
3939
- * Origin tracking metadata - who/what created this execution/task.
3940
- * Used by both TaskScheduler and CommandQueue for complete audit trails.
3941
- */
3942
- interface OriginTracking {
3943
- originExecutionId: string;
3944
- originResourceType: OriginResourceType;
3945
- originResourceId: string;
3946
- }
3947
-
4314
+ type ResourceType = 'agent' | 'workflow' | 'trigger' | 'integration' | 'external' | 'human';
3948
4315
  /**
3949
- * Command queue task with flexible action system
4316
+ * Base interface for ALL platform resources
4317
+ * Shared by both executable (agents, workflows) and non-executable (triggers, integrations, etc.) resources
3950
4318
  */
3951
- interface Task extends OriginTracking {
3952
- id: string;
3953
- organizationId: string;
3954
- actions: ActionConfig[];
3955
- context: unknown;
3956
- selectedAction?: string;
3957
- actionPayload?: unknown;
3958
- description?: string;
3959
- priority: number;
3960
- /** Optional checkpoint identifier for grouping related human approval tasks */
3961
- humanCheckpoint?: string;
3962
- status: QueueTaskStatus;
3963
- /**
3964
- * Target resource tracking mirrors origin columns.
3965
- * Set when task is created; patchable to redirect execution to a different resource.
3966
- */
3967
- targetResourceId?: string;
3968
- targetResourceType?: 'agent' | 'workflow';
3969
- /**
3970
- * Execution ID for the action that runs AFTER user approval.
3971
- * NULL until execution starts.
3972
- *
3973
- * Naming distinction:
3974
- * - originExecutionId = Parent execution that CREATED the HITL task
3975
- * - targetExecutionId = Child execution that RUNS AFTER user approval
3976
- */
3977
- targetExecutionId?: string;
3978
- createdAt: Date;
3979
- completedAt?: Date;
3980
- completedBy?: string;
3981
- expiresAt?: Date;
3982
- idempotencyKey?: string | null;
4319
+ interface ResourceDefinition {
4320
+ /** Unique resource identifier */
4321
+ resourceId: string;
4322
+ /** Display name */
4323
+ name: string;
4324
+ /** Purpose and functionality description */
4325
+ description: string;
4326
+ /** Version for change tracking and evolution */
4327
+ version: string;
4328
+ /** Resource type discriminator */
4329
+ type: ResourceType;
4330
+ /** Environment/deployment status */
4331
+ status: ResourceStatus;
4332
+ /** Graph links to Organization Model nodes */
4333
+ links?: ResourceLink[];
4334
+ /** Infrastructure category for filtering */
4335
+ category?: ResourceCategory;
4336
+ /** Whether the agent supports multi-turn sessions (agents only) */
4337
+ sessionCapable?: boolean;
4338
+ /** Whether the resource is local (monorepo) or remote (externally deployed) */
4339
+ origin?: 'local' | 'remote';
4340
+ /** Whether this resource is archived and should be excluded from registration and deployment */
4341
+ archived?: boolean;
3983
4342
  }
3984
- /**
3985
- * Task status values
3986
- * - pending: awaiting action
3987
- * - processing: execution in progress after user approval
3988
- * - completed: action was taken and execution succeeded
3989
- * - failed: execution failed, task can be retried
3990
- * - expired: timed out before action
3991
- */
3992
- type QueueTaskStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'expired';
3993
- /**
3994
- * Parameters for patching mutable metadata on a task
3995
- */
3996
- interface PatchTaskParams {
3997
- humanCheckpoint?: string | null;
3998
- description?: string;
3999
- priority?: number;
4000
- context?: Record<string, unknown>;
4001
- actions?: unknown[];
4002
- targetResourceId?: string | null;
4003
- targetResourceType?: 'agent' | 'workflow' | null;
4004
- targetExecutionId?: string;
4005
- status?: 'pending' | 'failed' | 'completed';
4343
+ /** Webhook provider identifiers */
4344
+ type WebhookProviderType = 'cal-com' | 'stripe' | 'signature-api' | 'instantly' | 'apify' | 'test';
4345
+ /** Webhook trigger configuration */
4346
+ interface WebhookTriggerConfig {
4347
+ /** Provider identifier */
4348
+ provider: WebhookProviderType;
4349
+ /** Event type for documentation (not used for matching - workflow handles routing) */
4350
+ event?: string;
4351
+ /** Optional filtering (e.g., specific form ID for Fillout) */
4352
+ filter?: Record<string, string>;
4353
+ /** References credential in credentials table for per-org webhook secrets */
4354
+ credentialName?: string;
4006
4355
  }
4007
- interface CommandQueueListResponse {
4008
- tasks: Task[];
4009
- total: number;
4356
+ /** Schedule trigger configuration */
4357
+ interface ScheduleTriggerConfig {
4358
+ /** Cron expression (e.g., '0 6 * * *') */
4359
+ cron: string;
4360
+ /** Optional timezone (default: UTC) */
4361
+ timezone?: string;
4010
4362
  }
4011
-
4012
- /**
4013
- * Checkpoint list item for sidebar grouping
4014
- * The id field contains the resourceId of the human checkpoint
4015
- */
4016
- interface CheckpointListItem {
4017
- /** Human checkpoint resourceId (or 'ungrouped' for tasks without checkpoint) */
4018
- id: string;
4019
- /** Display name (same as id, or "Ungrouped" for null) */
4020
- name: string;
4021
- /** Task count for this checkpoint */
4022
- count: number;
4363
+ /** Event trigger configuration */
4364
+ interface EventTriggerConfig {
4365
+ /** Internal event type */
4366
+ eventType: string;
4367
+ /** Event source */
4368
+ source?: string;
4023
4369
  }
4370
+ /** Union of all trigger configs */
4371
+ type TriggerConfig = WebhookTriggerConfig | ScheduleTriggerConfig | EventTriggerConfig;
4024
4372
  /**
4025
- * Status counts for pie chart display
4373
+ * Trigger metadata - entry points that initiate resource execution
4374
+ *
4375
+ * Triggers represent how executions start: webhooks from external services,
4376
+ * scheduled cron jobs, platform events, or manual user actions.
4377
+ *
4378
+ * BREAKING CHANGES (2025-11-30):
4379
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
4380
+ * - Field renames: `id` -> `resourceId` (inherited), `type` -> `triggerType`
4381
+ * - Relationship rename: `invokes` -> `triggers` (unified vocabulary)
4382
+ * - New required fields: `version` (inherited), `type: 'trigger'` (inherited)
4383
+ * - triggers object now includes `externalResources` option
4384
+ *
4385
+ * @example
4386
+ * // TriggerDefinition - metadata only
4387
+ * {
4388
+ * resourceId: 'trigger-new-order',
4389
+ * type: 'trigger',
4390
+ * triggerType: 'webhook',
4391
+ * name: 'New Order',
4392
+ * description: 'Webhook from Shopify on new orders',
4393
+ * version: '1.0.0',
4394
+ * status: 'prod',
4395
+ * webhookPath: '/webhooks/shopify/orders'
4396
+ * }
4397
+ *
4398
+ * // Relationships declared in ResourceRelationships (not on TriggerDefinition):
4399
+ * // relationships: {
4400
+ * // 'trigger-new-order': { triggers: { workflows: ['order-fulfillment-workflow'] } }
4401
+ * // }
4026
4402
  */
4027
- interface StatusCounts {
4028
- pending: number;
4029
- completed: number;
4030
- expired: number;
4403
+ interface TriggerDefinition extends ResourceDefinition {
4404
+ /** Resource type discriminator (narrowed from base union) */
4405
+ type: 'trigger';
4406
+ /** Trigger mechanism type (renamed from 'type' to avoid collision with base type discriminator) */
4407
+ triggerType: 'webhook' | 'schedule' | 'manual' | 'event';
4408
+ /** Type-specific configuration */
4409
+ config?: TriggerConfig;
4410
+ /** For webhook triggers: path like '/webhooks/shopify/orders' */
4411
+ webhookPath?: string;
4412
+ /** For schedule triggers: cron expression like '0 6 * * *' */
4413
+ schedule?: string;
4414
+ /** For event triggers: event type like 'low-stock-alert' */
4415
+ eventType?: string;
4031
4416
  }
4032
4417
  /**
4033
- * Priority counts for donut chart display
4418
+ * Integration metadata - external service connections
4419
+ *
4420
+ * References credentials table for actual connection. No connection status
4421
+ * stored here (queried at runtime from credentials table).
4422
+ *
4423
+ * BREAKING CHANGES (2025-11-30):
4424
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
4425
+ * - Field renames: `id` -> `resourceId` (inherited)
4426
+ * - New required field: `status` (inherited) - organizations must add status to all integrations
4427
+ * - New required field: `version` (inherited) - organizations must add version to all integrations
4428
+ * - New required field: `type: 'integration'` (inherited) - resource type discriminator
4429
+ *
4430
+ * @example
4431
+ * {
4432
+ * resourceId: 'integration-shopify-prod',
4433
+ * type: 'integration',
4434
+ * provider: 'shopify',
4435
+ * credentialName: 'shopify-prod',
4436
+ * name: 'Shopify Production',
4437
+ * description: 'E-commerce platform',
4438
+ * version: '1.0.0',
4439
+ * status: 'prod'
4440
+ * }
4034
4441
  */
4035
- interface PriorityCounts {
4036
- critical: number;
4037
- high: number;
4038
- medium: number;
4039
- low: number;
4442
+ interface IntegrationDefinition extends ResourceDefinition {
4443
+ /** Resource type discriminator (narrowed from base union) */
4444
+ type: 'integration';
4445
+ /** Integration provider type */
4446
+ provider: IntegrationType;
4447
+ /** References credentials table (e.g., 'shopify-prod', 'zendesk-api') */
4448
+ credentialName: string;
4040
4449
  }
4041
4450
  /**
4042
- * Response from GET /command-queue/checkpoints endpoint
4451
+ * External platform type
4452
+ * Supported third-party automation platforms
4043
4453
  */
4044
- interface CheckpointListResponse {
4045
- checkpoints: CheckpointListItem[];
4046
- /** Total tasks across all checkpoints */
4047
- total: number;
4048
- /** Breakdown by status for donut chart */
4049
- statusCounts: StatusCounts;
4050
- /** Breakdown by priority for donut chart */
4051
- priorityCounts: PriorityCounts;
4052
- }
4053
-
4454
+ type ExternalPlatform = 'n8n' | 'make' | 'zapier' | 'other';
4054
4455
  /**
4055
- * Target for schedule execution - identifies what resource to execute.
4056
- * Unlike ExecutionTarget, payload is NOT included here because schedules
4057
- * store payload in the scheduleConfig (varies per step/item).
4058
- */
4059
- interface ScheduleTarget {
4060
- resourceType: 'agent' | 'workflow';
4061
- resourceId: string;
4062
- }
4063
- /**
4064
- * Optional origin tracking for schedules.
4065
- * Unlike OriginTracking (which is required), these fields are all optional
4066
- * for schedules created directly via API (not triggered by another resource).
4067
- */
4068
- interface ScheduleOriginTracking {
4069
- originExecutionId?: string;
4070
- originResourceType?: OriginResourceType;
4071
- originResourceId?: string;
4072
- }
4073
- type TaskScheduleConfig = RecurringScheduleConfig | RelativeScheduleConfig | AbsoluteScheduleConfig;
4074
- interface RecurringScheduleConfig {
4075
- type: 'recurring';
4076
- cron?: string;
4077
- interval?: 'daily' | 'weekly' | 'monthly';
4078
- time?: string;
4079
- timezone: string;
4080
- payload: Record<string, unknown>;
4081
- endAt?: string | null;
4082
- overduePolicy?: 'skip' | 'execute';
4083
- }
4084
- interface RelativeScheduleConfig {
4085
- type: 'relative';
4086
- anchorAt: string;
4087
- anchorLabel?: string;
4088
- items: RelativeScheduleItem[];
4089
- overduePolicy?: 'skip' | 'execute';
4090
- }
4091
- interface RelativeScheduleItem {
4092
- offset: string;
4093
- payload: Record<string, unknown>;
4094
- label?: string;
4095
- }
4096
- interface AbsoluteScheduleConfig {
4097
- type: 'absolute';
4098
- items: AbsoluteScheduleItem[];
4099
- overduePolicy?: 'skip' | 'execute';
4100
- }
4101
- interface AbsoluteScheduleItem {
4102
- runAt: string;
4103
- payload: Record<string, unknown>;
4104
- label?: string;
4105
- }
4106
- interface TaskSchedule extends ScheduleOriginTracking {
4107
- id: string;
4108
- organizationId: string;
4109
- name: string;
4110
- description?: string;
4111
- target: ScheduleTarget;
4112
- scheduleConfig: TaskScheduleConfig;
4113
- nextRunAt?: Date;
4114
- currentStep: number;
4115
- status: 'active' | 'paused' | 'completed' | 'cancelled';
4116
- lastRunAt?: Date;
4117
- lastExecutionId?: string;
4118
- maxRetries: number;
4119
- idempotencyKey?: string;
4120
- createdAt: Date;
4121
- updatedAt: Date;
4122
- }
4123
-
4124
- /**
4125
- * Wire-format DTO for notification API responses.
4126
- * Dates are ISO 8601 strings (not Date objects like the domain Notification type).
4127
- * Used by frontend hooks that consume /api/notifications.
4456
+ * External automation resource metadata
4457
+ *
4458
+ * Represents workflows/automations running on third-party platforms
4459
+ * (n8n, Make, Zapier, etc.) for visualization in Command View.
4460
+ *
4461
+ * NOTE: This is metadata ONLY for visualization. No execution logic,
4462
+ * no API integration with external platforms, no status syncing.
4463
+ *
4464
+ * BREAKING CHANGES (2025-11-30):
4465
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
4466
+ * - Field renames: `id` -> `resourceId` (inherited)
4467
+ * - New required field: `version` (inherited) - organizations must add version to all external resources
4468
+ * - New required field: `type: 'external'` (inherited) - resource type discriminator
4469
+ * - REMOVED FIELD: `triggeredBy` - per relationship-consolidation design, all relationships are forward-only declarations
4470
+ *
4471
+ * @example
4472
+ * {
4473
+ * resourceId: 'external-n8n-order-sync',
4474
+ * type: 'external',
4475
+ * version: '1.0.0',
4476
+ * platform: 'n8n',
4477
+ * name: 'Shopify Order Sync',
4478
+ * description: 'Legacy n8n workflow for syncing Shopify orders',
4479
+ * status: 'prod',
4480
+ * platformUrl: 'https://n8n.client.com/workflow/123',
4481
+ * triggers: { workflows: ['order-fulfillment-workflow'] },
4482
+ * uses: { integrations: ['integration-shopify-prod'] }
4483
+ * }
4128
4484
  */
4129
- interface NotificationDTO {
4130
- id: string;
4131
- userId: string;
4132
- organizationId: string;
4133
- category: string;
4134
- title: string;
4135
- message: string;
4136
- actionUrl: string | null;
4137
- read: boolean;
4138
- readAt: string | null;
4139
- createdAt: string;
4140
- }
4141
-
4142
- type ProjectRow = Database['public']['Tables']['prj_projects']['Row'];
4143
- type ProjectUpdate = Database['public']['Tables']['prj_projects']['Update'];
4144
- type MilestoneRow = Database['public']['Tables']['prj_milestones']['Row'];
4145
- type MilestoneUpdate = Database['public']['Tables']['prj_milestones']['Update'];
4146
- type TaskRow = Database['public']['Tables']['prj_tasks']['Row'];
4147
- type TaskUpdate = Database['public']['Tables']['prj_tasks']['Update'];
4148
- type ProjectStatus = 'active' | 'on_track' | 'at_risk' | 'blocked' | 'completed' | 'paused';
4149
- type ProjectKind = 'client_engagement' | 'internal' | 'research' | 'other';
4150
- type MilestoneStatus = 'upcoming' | 'in_progress' | 'completed' | 'overdue' | 'blocked';
4151
- type TaskStatus = 'planned' | 'in_progress' | 'blocked' | 'completed' | 'cancelled' | 'submitted' | 'approved' | 'rejected' | 'revision_requested';
4152
- type TaskType = 'documentation' | 'code' | 'report' | 'design' | 'other';
4153
- type NoteType = 'call_note' | 'status_update' | 'issue' | 'blocker' | 'agent_learning';
4154
- interface ProjectFilters {
4155
- status?: ProjectStatus;
4156
- kind?: ProjectKind;
4157
- companyId?: string;
4158
- search?: string;
4159
- }
4160
- interface MilestoneFilters {
4161
- status?: MilestoneStatus;
4162
- projectId?: string;
4163
- }
4164
- interface TaskFilters {
4165
- status?: TaskStatus;
4166
- type?: TaskType;
4167
- milestoneId?: string;
4168
- projectId?: string;
4169
- }
4170
- interface NoteFilters {
4171
- type?: NoteType;
4172
- projectId?: string;
4173
- }
4174
- interface ProjectWithCounts extends ProjectRow {
4175
- milestoneCount: number;
4176
- taskCount: number;
4177
- completedMilestones?: number;
4178
- completedTasks?: number;
4179
- }
4180
- interface ProjectDetail extends ProjectRow {
4181
- milestones: MilestoneRow[];
4182
- tasks: TaskRow[];
4183
- company: {
4184
- id: string;
4185
- name: string;
4186
- domain: string | null;
4187
- } | null;
4485
+ interface ExternalResourceDefinition extends ResourceDefinition {
4486
+ /** Resource type discriminator (narrowed from base union) */
4487
+ type: 'external';
4488
+ /** Platform type */
4489
+ platform: ExternalPlatform;
4490
+ /** Link to external platform (e.g., n8n workflow editor URL) */
4491
+ platformUrl?: string;
4492
+ /** Platform's internal ID/reference */
4493
+ externalId?: string;
4494
+ /** What this external resource triggers (external -> internal) */
4495
+ triggers?: {
4496
+ /** Elevasis workflow resourceIds this external automation triggers */
4497
+ workflows?: string[];
4498
+ /** Elevasis agent resourceIds this external automation triggers */
4499
+ agents?: string[];
4500
+ };
4501
+ /** Integrations this external resource uses (shared credentials) */
4502
+ uses?: {
4503
+ /** Integration IDs this external automation uses */
4504
+ integrations?: string[];
4505
+ };
4188
4506
  }
4189
-
4190
- declare const ListCompaniesQuerySchema: z.ZodObject<{
4191
- search: z.ZodOptional<z.ZodString>;
4192
- listId: z.ZodOptional<z.ZodString>;
4193
- domain: z.ZodOptional<z.ZodString>;
4194
- website: z.ZodOptional<z.ZodString>;
4195
- segment: z.ZodOptional<z.ZodString>;
4196
- category: z.ZodOptional<z.ZodString>;
4197
- batchId: z.ZodOptional<z.ZodString>;
4198
- status: z.ZodOptional<z.ZodEnum<{
4199
- active: "active";
4200
- invalid: "invalid";
4201
- }>>;
4202
- includeAll: z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>;
4203
- limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
4204
- offset: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
4205
- }, z.core.$strict>;
4206
- declare const ListContactsQuerySchema: z.ZodObject<{
4207
- search: z.ZodOptional<z.ZodString>;
4208
- listId: z.ZodOptional<z.ZodString>;
4209
- openingLineIsNull: z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>;
4210
- batchId: z.ZodOptional<z.ZodString>;
4211
- contactStatus: z.ZodOptional<z.ZodEnum<{
4212
- active: "active";
4213
- invalid: "invalid";
4214
- }>>;
4215
- limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
4216
- offset: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
4217
- }, z.core.$strict>;
4218
- declare const AcqCompanyResponseSchema: z.ZodObject<{
4219
- id: z.ZodString;
4220
- organizationId: z.ZodString;
4221
- name: z.ZodString;
4222
- domain: z.ZodNullable<z.ZodString>;
4223
- linkedinUrl: z.ZodNullable<z.ZodString>;
4224
- website: z.ZodNullable<z.ZodString>;
4225
- numEmployees: z.ZodNullable<z.ZodNumber>;
4226
- foundedYear: z.ZodNullable<z.ZodNumber>;
4227
- locationCity: z.ZodNullable<z.ZodString>;
4228
- locationState: z.ZodNullable<z.ZodString>;
4229
- category: z.ZodNullable<z.ZodString>;
4230
- categoryPain: z.ZodNullable<z.ZodString>;
4231
- segment: z.ZodNullable<z.ZodString>;
4232
- pipelineStatus: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
4233
- enrichmentData: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
4234
- source: z.ZodNullable<z.ZodString>;
4235
- batchId: z.ZodNullable<z.ZodString>;
4236
- status: z.ZodEnum<{
4237
- active: "active";
4238
- invalid: "invalid";
4239
- }>;
4240
- contactCount: z.ZodNumber;
4241
- verticalResearch: z.ZodNullable<z.ZodString>;
4242
- createdAt: z.ZodString;
4243
- updatedAt: z.ZodString;
4244
- }, z.core.$strip>;
4245
- declare const AcqContactResponseSchema: z.ZodObject<{
4246
- id: z.ZodString;
4247
- organizationId: z.ZodString;
4248
- companyId: z.ZodNullable<z.ZodString>;
4249
- email: z.ZodString;
4250
- emailValid: z.ZodNullable<z.ZodEnum<{
4251
- VALID: "VALID";
4252
- INVALID: "INVALID";
4253
- RISKY: "RISKY";
4254
- UNKNOWN: "UNKNOWN";
4255
- }>>;
4256
- firstName: z.ZodNullable<z.ZodString>;
4257
- lastName: z.ZodNullable<z.ZodString>;
4258
- linkedinUrl: z.ZodNullable<z.ZodString>;
4259
- title: z.ZodNullable<z.ZodString>;
4260
- headline: z.ZodNullable<z.ZodString>;
4261
- filterReason: z.ZodNullable<z.ZodString>;
4262
- openingLine: z.ZodNullable<z.ZodString>;
4263
- source: z.ZodNullable<z.ZodString>;
4264
- sourceId: z.ZodNullable<z.ZodString>;
4265
- pipelineStatus: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
4266
- enrichmentData: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
4267
- attioPersonId: z.ZodNullable<z.ZodString>;
4268
- batchId: z.ZodNullable<z.ZodString>;
4269
- status: z.ZodEnum<{
4270
- active: "active";
4271
- invalid: "invalid";
4272
- }>;
4273
- company: z.ZodOptional<z.ZodNullable<z.ZodObject<{
4274
- id: z.ZodString;
4275
- name: z.ZodString;
4276
- domain: z.ZodNullable<z.ZodString>;
4277
- website: z.ZodNullable<z.ZodString>;
4278
- linkedinUrl: z.ZodNullable<z.ZodString>;
4279
- segment: z.ZodNullable<z.ZodString>;
4280
- category: z.ZodNullable<z.ZodString>;
4281
- status: z.ZodEnum<{
4282
- active: "active";
4283
- invalid: "invalid";
4284
- }>;
4285
- }, z.core.$strip>>>;
4286
- createdAt: z.ZodString;
4287
- updatedAt: z.ZodString;
4288
- }, z.core.$strip>;
4289
- type ListCompaniesQuery = z.infer<typeof ListCompaniesQuerySchema>;
4290
- type ListContactsQuery = z.infer<typeof ListContactsQuerySchema>;
4291
- type AcqCompanyResponse = z.infer<typeof AcqCompanyResponseSchema>;
4292
- type AcqContactResponse = z.infer<typeof AcqContactResponseSchema>;
4293
-
4294
- type MessageType = MessageEvent['type'];
4295
4507
  /**
4296
- * Session Data Transfer Object (DTO)
4297
- * Transform type for API responses (snake_case DB → camelCase frontend)
4298
- * Used by frontend apps to display session data
4508
+ * Human Checkpoint definition - human decision points in automation
4509
+ *
4510
+ * Represents where human judgment is deployed in the automation landscape.
4511
+ * Tasks with matching command_queue_group are routed to this checkpoint.
4512
+ *
4513
+ * BREAKING CHANGES (2025-11-30):
4514
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, links, category)
4515
+ * - Field renames: `id` -> `resourceId` (inherited)
4516
+ * - description is now REQUIRED (was optional) - organizations must add description to all human checkpoints
4517
+ * - New required field: `version` (inherited) - organizations must add version to all human checkpoints
4518
+ * - New required field: `type: 'human'` (inherited) - resource type discriminator
4519
+ *
4520
+ * @example
4521
+ * {
4522
+ * resourceId: 'sales-approval',
4523
+ * type: 'human',
4524
+ * name: 'Sales Approval Queue',
4525
+ * description: 'High-value order approvals for sales team',
4526
+ * version: '1.0.0',
4527
+ * status: 'prod',
4528
+ * requestedBy: { agents: ['order-processor-agent'] },
4529
+ * routesTo: { agents: ['order-fulfillment-agent'] }
4530
+ * }
4299
4531
  */
4300
- interface SessionDTO {
4301
- sessionId: string;
4302
- resourceId: string;
4303
- organizationId: string;
4304
- userId?: string | null;
4305
- turnCount: number;
4306
- isEnded: boolean;
4307
- title?: string | null;
4308
- memorySnapshot?: AgentMemory;
4309
- metadata?: Record<string, unknown> | null;
4310
- createdAt: Date;
4311
- updatedAt: Date;
4312
- endedAt?: Date | null;
4313
- }
4314
- interface ChatMessage {
4315
- id: string;
4316
- role: 'user' | 'assistant';
4317
- messageType: MessageType;
4318
- text: string;
4319
- metadata?: MessageEvent;
4320
- turnNumber: number;
4321
- messageIndex?: number;
4322
- createdAt: Date;
4323
- }
4324
- /** Token usage data sent with turn:complete WebSocket events */
4325
- interface SessionTokenUsage {
4326
- /** Tokens consumed by this turn's input */
4327
- turnInputTokens: number;
4328
- /** Tokens generated by this turn's output */
4329
- turnOutputTokens: number;
4330
- /** Total tokens for this turn (turnInputTokens + turnOutputTokens) */
4331
- turnTotalTokens: number;
4332
- /** Cumulative input tokens across all turns in this session */
4333
- cumulativeInputTokens: number;
4334
- /** Cumulative output tokens across all turns in this session */
4335
- cumulativeOutputTokens: number;
4336
- /** The model's context window size for this session (e.g., 200K) */
4337
- contextWindowSize: number;
4532
+ interface HumanCheckpointDefinition extends ResourceDefinition {
4533
+ /** Resource type discriminator (narrowed from base union) */
4534
+ type: 'human';
4535
+ /** Resources that create tasks for this checkpoint */
4536
+ requestedBy?: {
4537
+ /** Agent resourceIds that request approval here */
4538
+ agents?: string[];
4539
+ /** Workflow resourceIds that request approval here */
4540
+ workflows?: string[];
4541
+ };
4542
+ /** Resources that receive approved decisions */
4543
+ routesTo?: {
4544
+ /** Agent resourceIds that handle approved tasks */
4545
+ agents?: string[];
4546
+ /** Workflow resourceIds that handle approved tasks */
4547
+ workflows?: string[];
4548
+ };
4338
4549
  }
4339
4550
 
4340
4551
  /**
4341
- * Multi-tenancy configuration types
4552
+ * Command View Types
4342
4553
  *
4343
- * Config is stored in dedicated `config` columns (NOT nested in metadata):
4344
- * - organizations.config: Org-level config (no feature toggles -- all features available by default)
4345
- * - org_memberships.config: Per-user-per-org feature overrides
4346
- * - users.config: User-global config
4554
+ * Unified type definitions for the Command View graph visualization.
4555
+ * These types are used by both backend serialization and frontend rendering.
4556
+ *
4557
+ * Command View shows the resource graph: agents, workflows, triggers, integrations,
4558
+ * external resources, and human checkpoints with their relationships.
4347
4559
  */
4560
+
4348
4561
  /**
4349
- * Per-user-per-org config (stored in org_memberships.config)
4350
- * Controls which features a specific member can access within their org.
4351
- * Keys are feature IDs from the organization model (e.g. crm, lead-gen, projects, seo).
4562
+ * Extended agent metadata for Command View
4563
+ * Includes model and capability information for graph display
4352
4564
  */
4353
- interface MembershipFeatureConfig {
4354
- features?: Record<string, boolean>;
4565
+ interface CommandViewAgent extends ResourceDefinition {
4566
+ type: 'agent';
4567
+ modelProvider: string;
4568
+ modelId: string;
4569
+ toolCount: number;
4570
+ hasKnowledgeMap: boolean;
4571
+ hasMemory: boolean;
4572
+ sessionCapable: boolean;
4355
4573
  }
4356
4574
  /**
4357
- * User-global config (stored in users.config)
4358
- * Theme and onboarding are user-specific, NOT org-specific
4575
+ * Extended workflow metadata for Command View
4576
+ * Includes step information for graph display
4359
4577
  */
4360
- interface UserConfig {
4361
- theme?: {
4362
- preset?: 'default' | 'tactical' | 'regal' | 'cyber-volt' | 'aurora' | 'rose-gold' | 'midnight' | 'titanium' | 'obsidian' | 'honey' | 'abyss' | 'canopy' | 'slate' | 'cyber-strike' | 'cyber-chrome' | 'cyber-void' | 'nirvana' | 'wave' | 'synapse' | 'cortex' | 'helios' | 'graphite' | 'quarry' | 'canyon' | 'nord' | 'catppuccin' | 'tokyo-night' | 'gruvbox';
4363
- colorScheme?: 'light' | 'dark' | 'auto';
4364
- };
4365
- onboarding?: {
4366
- completed?: boolean;
4367
- completedAt?: string;
4368
- role?: string;
4369
- primaryUseCase?: string[];
4370
- experienceLevel?: string;
4371
- /** Onboarding guide system state (set by checklist/tour system) */
4372
- guides?: {
4373
- completedIds?: string[];
4374
- dismissed?: boolean;
4375
- completedAt?: string;
4376
- };
4377
- };
4578
+ interface CommandViewWorkflow extends ResourceDefinition {
4579
+ type: 'workflow';
4580
+ stepCount: number;
4581
+ entryPoint: string;
4378
4582
  }
4379
-
4380
4583
  /**
4381
- * Memberships Domain - Zod Validation Schemas
4382
- *
4383
- * Validation schemas for membership management endpoints.
4384
- * Includes request bodies, query params, and path params.
4584
+ * Relationship types between resources
4385
4585
  *
4386
- * Security:
4387
- * - All schemas use .strict() to prevent mass assignment attacks
4388
- * - UUID validation prevents invalid references
4389
- * - Role enum validation prevents privilege escalation
4390
- * - organizationId never accepted in body (from JWT when needed)
4586
+ * - triggers: Resource initiates/starts another resource (orange)
4587
+ * - uses: Resource uses an integration (teal)
4588
+ * - approval: Resource requires human approval (yellow)
4391
4589
  */
4392
-
4590
+ type RelationshipType$1 = 'triggers' | 'uses' | 'approval';
4393
4591
  /**
4394
- * Membership status validation
4395
- * Note: Database constraint only allows 'active' | 'inactive'
4592
+ * Command View edge (relationship between resources)
4396
4593
  */
4397
- declare const MembershipStatusSchema: z.ZodEnum<{
4398
- active: "active";
4399
- inactive: "inactive";
4400
- }>;
4401
- type MembershipStatus = z.infer<typeof MembershipStatusSchema>;
4402
-
4594
+ interface CommandViewEdge$1 {
4595
+ id: string;
4596
+ source: string;
4597
+ target: string;
4598
+ relationship: RelationshipType$1;
4599
+ label?: string;
4600
+ }
4403
4601
  /**
4404
- * Organization Membership types based on WorkOS API
4602
+ * Command View data structure
4603
+ * Complete graph data for visualization
4604
+ *
4605
+ * Backend serializes this once at startup and serves it via /command-view endpoint.
4606
+ * Frontend consumes this directly for graph rendering.
4405
4607
  */
4406
- interface OrganizationMembership {
4407
- object: 'organization_membership';
4608
+ interface CommandViewData {
4609
+ workflows: CommandViewWorkflow[];
4610
+ agents: CommandViewAgent[];
4611
+ triggers: TriggerDefinition[];
4612
+ integrations: IntegrationDefinition[];
4613
+ externalResources: ExternalResourceDefinition[];
4614
+ humanCheckpoints: HumanCheckpointDefinition[];
4615
+ edges: CommandViewEdge$1[];
4616
+ }
4617
+
4618
+ declare const LinkSchema: z.ZodObject<{
4619
+ nodeId: z.ZodString;
4620
+ kind: z.ZodEnum<{
4621
+ contains: "contains";
4622
+ references: "references";
4623
+ exposes: "exposes";
4624
+ maps_to: "maps_to";
4625
+ "operates-on": "operates-on";
4626
+ uses: "uses";
4627
+ }>;
4628
+ }, z.core.$strip>;
4629
+ type Link = z.infer<typeof LinkSchema>;
4630
+
4631
+ declare const ResourceCategorySchema: z.ZodEnum<{
4632
+ production: "production";
4633
+ diagnostic: "diagnostic";
4634
+ internal: "internal";
4635
+ testing: "testing";
4636
+ }>;
4637
+ type ResourceCategory = z.infer<typeof ResourceCategorySchema>;
4638
+ type ResourceLink = Link;
4639
+
4640
+ type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'warning';
4641
+ interface APIExecutionSummary {
4408
4642
  id: string;
4409
- userId: string;
4410
- organizationId: string;
4411
- role: {
4412
- slug: string;
4413
- };
4414
- status: 'active' | 'inactive';
4415
- createdAt: string;
4416
- updatedAt: string;
4643
+ status: ExecutionStatus;
4644
+ startTime: number;
4645
+ endTime?: number;
4646
+ resourceStatus?: ResourceStatus;
4647
+ }
4648
+ interface APIExecutionDetail extends APIExecutionSummary {
4649
+ executionLogs: ExecutionLogMessage[];
4650
+ input?: unknown;
4651
+ result?: unknown;
4652
+ error?: string;
4653
+ resourceStatus: ResourceStatus;
4654
+ apiVersion?: string | null;
4655
+ resourceVersion?: string | null;
4656
+ sdkVersion?: string | null;
4657
+ isArchived?: boolean;
4658
+ archivedLogCount?: number;
4659
+ }
4660
+ interface APIExecutionListResponse {
4661
+ executions: APIExecutionSummary[];
4662
+ total?: number;
4663
+ limit?: number;
4664
+ offset?: number;
4665
+ hasMore?: boolean;
4417
4666
  }
4667
+
4418
4668
  /**
4419
- * Request interfaces for membership operations
4669
+ * @deprecated Use TimeRange from '@repo/core' directly. Kept as alias for backward compatibility.
4420
4670
  */
4421
- interface CreateMembershipRequest {
4422
- userId: string;
4423
- organizationId: string;
4424
- roleSlug?: string;
4671
+ type StatsTimeRange = TimeRange;
4672
+ /** Stats returned by /command-view/stats (counts only, no error details) */
4673
+ interface ResourceStats {
4674
+ resourceId: string;
4675
+ totalRuns: number;
4676
+ successCount: number;
4677
+ failureCount: number;
4678
+ warningCount: number;
4679
+ lastRunAt: string | null;
4425
4680
  }
4426
- interface UpdateMembershipRequest {
4427
- roleSlug: string;
4681
+ /** Response from /command-view/resource-errors (on-demand) */
4682
+ interface ResourceErrorsResponse {
4683
+ resourceId: string;
4684
+ errors: ErrorSummary[];
4685
+ totalErrors: number;
4686
+ timeRange: StatsTimeRange;
4428
4687
  }
4429
- interface ListMembershipsParams {
4430
- userId?: string;
4431
- organizationId?: string;
4432
- statuses?: MembershipStatus[];
4433
- limit?: number;
4434
- before?: string;
4435
- after?: string;
4436
- order?: 'asc' | 'desc';
4688
+ interface ErrorSummary {
4689
+ executionId: string;
4690
+ errorType: string;
4691
+ errorMessage: string;
4692
+ occurredAt: string;
4693
+ }
4694
+ /** Single execution summary for Recent Executions list in command view */
4695
+ interface CommandViewExecution {
4696
+ executionId: string;
4697
+ status: ExecutionStatus;
4698
+ startedAt: string;
4699
+ completedAt: string | null;
4700
+ errorMessage: string | null;
4701
+ }
4702
+ /** Response from /command-view/resource-executions (on-demand) */
4703
+ interface ResourceExecutionsResponse {
4704
+ resourceId: string;
4705
+ executions: CommandViewExecution[];
4706
+ totalExecutions: number;
4707
+ timeRange: StatsTimeRange;
4708
+ page: number;
4709
+ limit: number;
4710
+ }
4711
+ interface HumanCheckpointStats {
4712
+ checkpointId: string;
4713
+ pendingCount: number;
4714
+ completedCount: number;
4715
+ expiredCount: number;
4716
+ lastDecisionAt: string | null;
4717
+ }
4718
+ /** Response from /command-view/stats */
4719
+ interface CommandViewStatsResponse {
4720
+ resources: Record<string, ResourceStats>;
4721
+ humanCheckpoints: Record<string, HumanCheckpointStats>;
4722
+ timeRange: StatsTimeRange;
4723
+ generatedAt: string;
4724
+ }
4725
+
4726
+ type ActivityType = 'workflow_execution' | 'agent_run' | 'hitl_action' | 'webhook_received' | 'webhook_executed' | 'webhook_failed' | 'credential_change' | 'credential_read' | 'api_key_change' | 'deployment_change' | 'membership_change';
4727
+ type ActivityStatus = 'success' | 'failure' | 'pending' | 'approved' | 'rejected' | 'completed';
4728
+ interface Activity {
4729
+ id: string;
4730
+ organizationId: string;
4731
+ activityType: ActivityType;
4732
+ status: ActivityStatus;
4733
+ title: string;
4734
+ description: string | null;
4735
+ entityType: string;
4736
+ entityId: string;
4737
+ entityName: string | null;
4738
+ metadata: Record<string, unknown> | null;
4739
+ actorId: string | null;
4740
+ actorType: string | null;
4741
+ occurredAt: Date;
4742
+ createdAt: Date;
4437
4743
  }
4744
+
4438
4745
  /**
4439
- * Response interfaces
4746
+ * Canonical permission catalog.
4747
+ *
4748
+ * Source of truth for the permission keys used by:
4749
+ * - RLS policies in Supabase (via has_org_permission(org_id, key))
4750
+ * - API middleware (via requireOrganizationPermission(key))
4751
+ * - UI hooks (via useOrganizationPermissions().hasPermission(key))
4752
+ *
4753
+ * The DB table `org_rol_permissions` mirrors this constant. Reconciliation
4754
+ * runs at API boot (insert-or-update only — never auto-delete; see the
4755
+ * deletion runbook in the auth-role-system-redesign doc).
4756
+ *
4757
+ * Adding a permission:
4758
+ * 1. Add an entry below.
4759
+ * 2. Add a row to the migration / via reconcilePermissionCatalog at boot.
4760
+ * 3. Reference it in RLS / middleware as needed.
4761
+ * 4. Optionally grant it to one or more system roles in org_rol_grants.
4762
+ *
4763
+ * Removing a permission: follow the deletion runbook — never just delete
4764
+ * the entry. Existing role grants and policy references must be cleared first.
4440
4765
  */
4441
- interface ListMembershipsResponse {
4442
- data: OrganizationMembership[];
4443
- listMetadata?: {
4444
- before?: string | null;
4445
- after?: string | null;
4446
- };
4447
- }
4766
+ declare const PERMISSIONS: {
4767
+ readonly ORG_READ: "org.read";
4768
+ readonly ORG_MANAGE: "org.manage";
4769
+ readonly ORG_DELETE: "org.delete";
4770
+ readonly MEMBERS_MANAGE: "members.manage";
4771
+ readonly ROLES_MANAGE: "roles.manage";
4772
+ readonly SECRETS_MANAGE: "secrets.manage";
4773
+ readonly OPERATIONS_READ: "operations.read";
4774
+ readonly OPERATIONS_MANAGE: "operations.manage";
4775
+ readonly WORK_MANAGE: "work.manage";
4776
+ };
4777
+ type PermissionKey = (typeof PERMISSIONS)[keyof typeof PERMISSIONS];
4448
4778
  /**
4449
- * Extended membership with user and organization details for UI
4779
+ * Static metadata for each permission. Mirrored into org_rol_permissions on
4780
+ * boot reconciliation. is_org_grantable=false means the permission is reserved
4781
+ * to system roles only — custom roles cannot include it (privilege-escalation guard).
4450
4782
  */
4451
- interface MembershipWithDetails extends OrganizationMembership {
4452
- user?: {
4453
- id: string;
4454
- email: string;
4455
- firstName?: string;
4456
- lastName?: string;
4457
- profilePictureUrl?: string;
4458
- };
4459
- organization?: {
4460
- id: string;
4461
- name: string;
4462
- workos_org_id: string;
4463
- primaryDomain?: string;
4464
- is_test?: boolean;
4465
- status?: string;
4466
- metadata?: Record<string, unknown>;
4467
- config?: Record<string, unknown>;
4468
- };
4469
- config?: MembershipFeatureConfig;
4470
- }
4471
-
4472
- type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'warning';
4473
- interface APIExecutionSummary {
4474
- id: string;
4475
- status: ExecutionStatus;
4476
- startTime: number;
4477
- endTime?: number;
4478
- resourceStatus?: ResourceStatus;
4479
- }
4480
- interface APIExecutionDetail extends APIExecutionSummary {
4481
- executionLogs: ExecutionLogMessage[];
4482
- input?: unknown;
4483
- result?: unknown;
4484
- error?: string;
4485
- resourceStatus: ResourceStatus;
4486
- apiVersion?: string | null;
4487
- resourceVersion?: string | null;
4488
- sdkVersion?: string | null;
4489
- isArchived?: boolean;
4490
- archivedLogCount?: number;
4491
- }
4492
- interface APIExecutionListResponse {
4493
- executions: APIExecutionSummary[];
4494
- total?: number;
4495
- limit?: number;
4496
- offset?: number;
4497
- hasMore?: boolean;
4783
+ interface PermissionDescriptor {
4784
+ key: PermissionKey;
4785
+ description: string;
4786
+ isOrgGrantable: boolean;
4498
4787
  }
4499
4788
 
4500
4789
  /**
@@ -4541,6 +4830,63 @@ declare const ExecutionHistoryResponseSchema: z.ZodObject<{
4541
4830
  type ExecutionHistoryItem = z.infer<typeof ExecutionHistoryItemSchema>;
4542
4831
  type ExecutionHistoryResponse = z.infer<typeof ExecutionHistoryResponseSchema>;
4543
4832
 
4833
+ /**
4834
+ * Deployment types — browser-safe
4835
+ *
4836
+ * Canonical API response types for the deployment resource.
4837
+ * The API's transformRow converts snake_case DB columns to these camelCase fields.
4838
+ */
4839
+ type DeploymentStatus = 'deploying' | 'active' | 'failed' | 'rolled_back' | 'stopped';
4840
+ interface Deployment {
4841
+ id: string;
4842
+ organizationId: string;
4843
+ status: DeploymentStatus;
4844
+ sdkVersion: string;
4845
+ deploymentVersion: string | null;
4846
+ port: number | null;
4847
+ pid: number | null;
4848
+ tarballPath: string | null;
4849
+ errorMessage: string | null;
4850
+ createdAt: string;
4851
+ updatedAt: string;
4852
+ }
4853
+
4854
+ /**
4855
+ * GET /api/credentials - List credentials
4856
+ */
4857
+ declare const ListCredentialsResponseSchema: z.ZodObject<{
4858
+ credentials: z.ZodArray<z.ZodObject<{
4859
+ id: z.ZodString;
4860
+ name: z.ZodString;
4861
+ type: z.ZodString;
4862
+ provider: z.ZodNullable<z.ZodString>;
4863
+ createdAt: z.ZodString;
4864
+ }, z.core.$strip>>;
4865
+ }, z.core.$strip>;
4866
+ /** API response type for a single credential list item */
4867
+ type CredentialListItem = z.infer<typeof ListCredentialsResponseSchema>['credentials'][number];
4868
+
4869
+ declare function useOrganizationPermissions(): {
4870
+ hasPermission: (key: PermissionKey | string) => boolean;
4871
+ permissions: string[];
4872
+ isPlatformAdmin: boolean;
4873
+ isReady: boolean;
4874
+ };
4875
+ declare function useHasPermission(key: PermissionKey | string): boolean;
4876
+
4877
+ /**
4878
+ * Query key factory for executions TanStack Query hooks.
4879
+ * Uses organization UUID (not name) for cache isolation.
4880
+ */
4881
+ declare const executionsKeys: {
4882
+ all: readonly ["executions"];
4883
+ resources: (orgId: string | null) => readonly ["executions", "resources", string | null];
4884
+ resourceDefinition: (orgId: string | null, resourceId: string) => readonly ["executions", "definition", string | null, string];
4885
+ executionsListBase: (orgId: string | null, resourceId: string) => readonly ["executions", "list", string | null, string];
4886
+ executions: (orgId: string | null, resourceId: string, resourceStatus?: string, limit?: number, offset?: number) => readonly ["executions", "list", string | null, string, string, number | null, number];
4887
+ execution: (orgId: string | null, resourceId: string, executionId: string) => readonly ["executions", "execution", string | null, string, string];
4888
+ };
4889
+
4544
4890
  /**
4545
4891
  * Fetch the execution list for a given resource.
4546
4892
  *
@@ -4644,119 +4990,6 @@ interface BulkDeleteExecutionsResult {
4644
4990
  */
4645
4991
  declare function useBulkDeleteExecutions(): _tanstack_react_query.UseMutationResult<BulkDeleteExecutionsResult, Error, BulkDeleteExecutionsParams, unknown>;
4646
4992
 
4647
- /**
4648
- * @deprecated Use TimeRange from '@repo/core' directly. Kept as alias for backward compatibility.
4649
- */
4650
- type StatsTimeRange = TimeRange;
4651
- /** Stats returned by /command-view/stats (counts only, no error details) */
4652
- interface ResourceStats {
4653
- resourceId: string;
4654
- totalRuns: number;
4655
- successCount: number;
4656
- failureCount: number;
4657
- warningCount: number;
4658
- lastRunAt: string | null;
4659
- }
4660
- /** Response from /command-view/resource-errors (on-demand) */
4661
- interface ResourceErrorsResponse {
4662
- resourceId: string;
4663
- errors: ErrorSummary[];
4664
- totalErrors: number;
4665
- timeRange: StatsTimeRange;
4666
- }
4667
- interface ErrorSummary {
4668
- executionId: string;
4669
- errorType: string;
4670
- errorMessage: string;
4671
- occurredAt: string;
4672
- }
4673
- /** Single execution summary for Recent Executions list in command view */
4674
- interface CommandViewExecution {
4675
- executionId: string;
4676
- status: ExecutionStatus;
4677
- startedAt: string;
4678
- completedAt: string | null;
4679
- errorMessage: string | null;
4680
- }
4681
- /** Response from /command-view/resource-executions (on-demand) */
4682
- interface ResourceExecutionsResponse {
4683
- resourceId: string;
4684
- executions: CommandViewExecution[];
4685
- totalExecutions: number;
4686
- timeRange: StatsTimeRange;
4687
- page: number;
4688
- limit: number;
4689
- }
4690
- interface HumanCheckpointStats {
4691
- checkpointId: string;
4692
- pendingCount: number;
4693
- completedCount: number;
4694
- expiredCount: number;
4695
- lastDecisionAt: string | null;
4696
- }
4697
- /** Response from /command-view/stats */
4698
- interface CommandViewStatsResponse {
4699
- resources: Record<string, ResourceStats>;
4700
- humanCheckpoints: Record<string, HumanCheckpointStats>;
4701
- timeRange: StatsTimeRange;
4702
- generatedAt: string;
4703
- }
4704
-
4705
- type ActivityType = 'workflow_execution' | 'agent_run' | 'hitl_action' | 'webhook_received' | 'webhook_executed' | 'webhook_failed' | 'credential_change' | 'api_key_change' | 'deployment_change' | 'membership_change';
4706
- type ActivityStatus = 'success' | 'failure' | 'pending' | 'approved' | 'rejected' | 'completed';
4707
- interface Activity {
4708
- id: string;
4709
- organizationId: string;
4710
- activityType: ActivityType;
4711
- status: ActivityStatus;
4712
- title: string;
4713
- description: string | null;
4714
- entityType: string;
4715
- entityId: string;
4716
- entityName: string | null;
4717
- metadata: Record<string, unknown> | null;
4718
- actorId: string | null;
4719
- actorType: string | null;
4720
- occurredAt: Date;
4721
- createdAt: Date;
4722
- }
4723
-
4724
- /**
4725
- * Deployment types — browser-safe
4726
- *
4727
- * Canonical API response types for the deployment resource.
4728
- * The API's transformRow converts snake_case DB columns to these camelCase fields.
4729
- */
4730
- type DeploymentStatus = 'deploying' | 'active' | 'failed' | 'rolled_back' | 'stopped';
4731
- interface Deployment {
4732
- id: string;
4733
- organizationId: string;
4734
- status: DeploymentStatus;
4735
- sdkVersion: string;
4736
- deploymentVersion: string | null;
4737
- port: number | null;
4738
- pid: number | null;
4739
- tarballPath: string | null;
4740
- errorMessage: string | null;
4741
- createdAt: string;
4742
- updatedAt: string;
4743
- }
4744
-
4745
- /**
4746
- * GET /api/credentials - List credentials
4747
- */
4748
- declare const ListCredentialsResponseSchema: z.ZodObject<{
4749
- credentials: z.ZodArray<z.ZodObject<{
4750
- id: z.ZodString;
4751
- name: z.ZodString;
4752
- type: z.ZodString;
4753
- provider: z.ZodNullable<z.ZodString>;
4754
- createdAt: z.ZodString;
4755
- }, z.core.$strip>>;
4756
- }, z.core.$strip>;
4757
- /** API response type for a single credential list item */
4758
- type CredentialListItem = z.infer<typeof ListCredentialsResponseSchema>['credentials'][number];
4759
-
4760
4993
  /**
4761
4994
  * Fetch all available Execution Engine resources (workflows, agents, pipelines).
4762
4995
  *
@@ -5707,10 +5940,6 @@ declare function createFeatureAccessHook({ useInitialization, useOrganization }:
5707
5940
  checkFeature: (featureKey: string) => FeatureAccessResult;
5708
5941
  isReady: boolean;
5709
5942
  };
5710
- /**
5711
- * @deprecated Use `createFeatureAccessHook` instead. This alias will be removed in a future release.
5712
- */
5713
- declare const createUseFeatureAccess: typeof createFeatureAccessHook;
5714
5943
 
5715
5944
  interface UseSSEConnectionOptions {
5716
5945
  manager: SSEConnectionManagerLike;
@@ -6169,6 +6398,8 @@ interface UseCommandViewStatsOptions {
6169
6398
  */
6170
6399
  declare function useCommandViewStats(timeRange?: StatsTimeRange, options?: UseCommandViewStatsOptions): _tanstack_react_query.UseQueryResult<CommandViewStatsResponse, Error>;
6171
6400
 
6401
+ type CommandViewVisualizationMode = 'cluster' | 'swimlane' | 'focus' | 'network' | 'spatial';
6402
+
6172
6403
  /**
6173
6404
  * Command View Types
6174
6405
  *
@@ -6290,15 +6521,28 @@ interface CommandViewStore {
6290
6521
  setShowIntegrations: (v: boolean) => void;
6291
6522
  fitViewOnFilter: boolean;
6292
6523
  setFitViewOnFilter: (v: boolean) => void;
6524
+ visualizationMode: CommandViewVisualizationMode;
6525
+ setVisualizationMode: (v: CommandViewVisualizationMode) => void;
6293
6526
  selectedNodeId: string | null;
6294
6527
  setSelectedNodeId: (id: string | null) => void;
6528
+ resourcesHidden: boolean;
6529
+ setResourcesHidden: (v: boolean) => void;
6530
+ diagnosticsHidden: boolean;
6531
+ setDiagnosticsHidden: (v: boolean) => void;
6532
+ diagnosticCategories: string[];
6533
+ revealedIds: Set<string>;
6534
+ setRevealedIds: (ids: Iterable<string>) => void;
6535
+ clearRevealedIds: () => void;
6536
+ hasVisibilityInteraction: boolean;
6537
+ markVisibilityInteraction: () => void;
6538
+ resetVisibilityInteraction: () => void;
6295
6539
  }
6296
6540
  /**
6297
6541
  * Shared store for Command View filter/settings state.
6298
6542
  * Allows CommandViewPage (graph) and CommandViewSidebarContent (sidebar) to share state.
6299
6543
  *
6300
- * Persisted to localStorage: showIntegrations, fitViewOnFilter
6301
- * Not persisted (reset on reload): statusFilter, selectedNodeId
6544
+ * Persisted to localStorage: showIntegrations, fitViewOnFilter, resource/diagnostic visibility preferences.
6545
+ * Not persisted (reset on reload): statusFilter, selectedNodeId, revealedIds, CTA interaction state.
6302
6546
  */
6303
6547
  declare const useCommandViewStore: zustand.UseBoundStore<Omit<zustand.StoreApi<CommandViewStore>, "setState" | "persist"> & {
6304
6548
  setState(partial: CommandViewStore | Partial<CommandViewStore> | ((state: CommandViewStore) => CommandViewStore | Partial<CommandViewStore>), replace?: false | undefined): unknown;
@@ -6307,6 +6551,9 @@ declare const useCommandViewStore: zustand.UseBoundStore<Omit<zustand.StoreApi<C
6307
6551
  setOptions: (options: Partial<zustand_middleware.PersistOptions<CommandViewStore, {
6308
6552
  showIntegrations: boolean;
6309
6553
  fitViewOnFilter: boolean;
6554
+ visualizationMode: CommandViewVisualizationMode;
6555
+ resourcesHidden: boolean;
6556
+ diagnosticsHidden: boolean;
6310
6557
  }, unknown>>) => void;
6311
6558
  clearStorage: () => void;
6312
6559
  rehydrate: () => Promise<void> | void;
@@ -6316,6 +6563,9 @@ declare const useCommandViewStore: zustand.UseBoundStore<Omit<zustand.StoreApi<C
6316
6563
  getOptions: () => Partial<zustand_middleware.PersistOptions<CommandViewStore, {
6317
6564
  showIntegrations: boolean;
6318
6565
  fitViewOnFilter: boolean;
6566
+ visualizationMode: CommandViewVisualizationMode;
6567
+ resourcesHidden: boolean;
6568
+ diagnosticsHidden: boolean;
6319
6569
  }, unknown>>;
6320
6570
  };
6321
6571
  }>;
@@ -7593,10 +7843,56 @@ declare function useReactivateMembership(): _tanstack_react_query.UseMutationRes
7593
7843
  previousData: unknown;
7594
7844
  }>;
7595
7845
 
7846
+ type OrgRolDefinitionRow = Database['public']['Tables']['org_rol_definitions']['Row'];
7847
+ type OrgRole = OrgRolDefinitionRow & {
7848
+ grants?: string[];
7849
+ memberCount?: number;
7850
+ };
7851
+ type CreateOrgRoleInput = {
7852
+ name: string;
7853
+ slug: string;
7854
+ description?: string;
7855
+ permissionKeys: string[];
7856
+ };
7857
+ type UpdateOrgRoleInput = Partial<CreateOrgRoleInput>;
7858
+ type AssignRoleInput = {
7859
+ membershipId: string;
7860
+ roleId: string;
7861
+ };
7862
+ type RevokeRoleInput = {
7863
+ membershipId: string;
7864
+ roleId: string;
7865
+ };
7866
+
7867
+ declare function useOrgRoles(orgId?: string): _tanstack_react_query.UseQueryResult<{
7868
+ roles: OrgRole[];
7869
+ }, Error>;
7870
+
7871
+ declare function usePermissionCatalog(): _tanstack_react_query.UseQueryResult<{
7872
+ permissions: PermissionDescriptor[];
7873
+ }, Error>;
7874
+
7875
+ declare function useCreateOrgRole(): _tanstack_react_query.UseMutationResult<OrgRole, Error, CreateOrgRoleInput, unknown>;
7876
+
7877
+ interface UpdateOrgRoleParams {
7878
+ roleId: string;
7879
+ input: UpdateOrgRoleInput;
7880
+ }
7881
+ declare function useUpdateOrgRole(): _tanstack_react_query.UseMutationResult<OrgRole, Error, UpdateOrgRoleParams, unknown>;
7882
+
7883
+ declare function useDeleteOrgRole(): _tanstack_react_query.UseMutationResult<void, Error, string, unknown>;
7884
+
7885
+ declare function useAssignRole(): _tanstack_react_query.UseMutationResult<void, Error, AssignRoleInput, unknown>;
7886
+ declare function useRevokeRole(): _tanstack_react_query.UseMutationResult<void, Error, RevokeRoleInput, unknown>;
7887
+
7888
+ declare function useEffectivePermissions(membershipId: string | undefined): _tanstack_react_query.UseQueryResult<{
7889
+ permissions: string[];
7890
+ }, Error>;
7891
+
7596
7892
  declare function useListWebhookEndpoints(): _tanstack_react_query.UseQueryResult<{
7597
7893
  id: string;
7598
7894
  organizationId: string;
7599
- key: string;
7895
+ keyPrefix: string | null;
7600
7896
  name: string;
7601
7897
  description: string | null;
7602
7898
  resourceId: string | null;
@@ -7605,12 +7901,13 @@ declare function useListWebhookEndpoints(): _tanstack_react_query.UseQueryResult
7605
7901
  requestCount: number;
7606
7902
  createdAt: string;
7607
7903
  updatedAt: string;
7904
+ key?: string | undefined;
7608
7905
  }[], Error>;
7609
7906
 
7610
7907
  declare function useCreateWebhookEndpoint(): _tanstack_react_query.UseMutationResult<{
7611
7908
  id: string;
7612
7909
  organizationId: string;
7613
- key: string;
7910
+ keyPrefix: string | null;
7614
7911
  name: string;
7615
7912
  description: string | null;
7616
7913
  resourceId: string | null;
@@ -7619,6 +7916,7 @@ declare function useCreateWebhookEndpoint(): _tanstack_react_query.UseMutationRe
7619
7916
  requestCount: number;
7620
7917
  createdAt: string;
7621
7918
  updatedAt: string;
7919
+ key?: string | undefined;
7622
7920
  }, Error, {
7623
7921
  name: string;
7624
7922
  resourceId?: string | undefined;
@@ -7660,7 +7958,8 @@ type UpdateWebhookEndpointRequest = z.infer<typeof UpdateWebhookEndpointRequestS
7660
7958
  declare const WebhookEndpointResponseSchema: z.ZodObject<{
7661
7959
  id: z.ZodString;
7662
7960
  organizationId: z.ZodString;
7663
- key: z.ZodString;
7961
+ key: z.ZodOptional<z.ZodString>;
7962
+ keyPrefix: z.ZodNullable<z.ZodString>;
7664
7963
  name: z.ZodString;
7665
7964
  description: z.ZodNullable<z.ZodString>;
7666
7965
  resourceId: z.ZodNullable<z.ZodString>;
@@ -7678,7 +7977,7 @@ type WebhookEndpointResponse = z.infer<typeof WebhookEndpointResponseSchema>;
7678
7977
  declare function useUpdateWebhookEndpoint(): _tanstack_react_query.UseMutationResult<{
7679
7978
  id: string;
7680
7979
  organizationId: string;
7681
- key: string;
7980
+ keyPrefix: string | null;
7682
7981
  name: string;
7683
7982
  description: string | null;
7684
7983
  resourceId: string | null;
@@ -7687,6 +7986,7 @@ declare function useUpdateWebhookEndpoint(): _tanstack_react_query.UseMutationRe
7687
7986
  requestCount: number;
7688
7987
  createdAt: string;
7689
7988
  updatedAt: string;
7989
+ key?: string | undefined;
7690
7990
  }, Error, {
7691
7991
  endpointId: string;
7692
7992
  data: UpdateWebhookEndpointRequest;
@@ -8255,5 +8555,5 @@ declare function useCreateNote(): _tanstack_react_query.UseMutationResult<{
8255
8555
  type?: string;
8256
8556
  }, "organization_id">, unknown>;
8257
8557
 
8258
- export { ApiKeyService, CredentialService, DeploymentService, OperationsService, OrganizationMembershipService, REFETCH_INTERVAL_RUNNING, WS_MAX_RETRIES_BEFORE_ERROR, WS_RECONNECT_BASE_DELAY, WS_RECONNECT_MAX_DELAY, WebhookEndpointService, acquisitionListKeys, collectResourceFilterFacets, companyKeys, contactKeys, createFeatureAccessHook, createUseFeatureAccess, dealKeys, dealNoteKeys, dealTaskKeys, executionsKeys, filterByDomainFilters, getResourceFilterFacetIds, isSessionCapable, labelResourceFilterFacet, milestoneKeys, noteKeys, observabilityKeys, operationsKeys, projectActivityKeys, projectKeys, requestsKeys, scheduleKeys, sessionsKeys, sortData, taskKeys, useActivateDeployment, useActivities, useActivitiesRealtime, useActivityFilters, useActivityTrend, useArchiveSession, useArchivedLogs, useBatchDelete, useBatchTelemetry, useBatchedResourcesHealth, useBulkDeleteExecutions, useBusinessImpact, useCancelExecution, useCancelSchedule, useCheckpointTasks, useCommandQueue, useCommandQueueTotals, useCommandViewData, useCommandViewDomainFilters, useCommandViewLayout, useCommandViewStats, useCommandViewStore, useCompanies, useCompany, useCompanyFacets, useCompleteDealTask, useContact, useContacts, useCostBreakdown, useCostByModel, useCostSummary, useCostTrends, useCreateApiKey, useCreateCompany, useCreateContact, useCreateCredential, useCreateDealNote, useCreateDealTask, useCreateProject as useCreateDeliveryProject, useCreateList, useCreateMilestone, useCreateNote, useCreateSchedule, useCreateSession, useCreateTask, useCreateWebhookEndpoint, useCredentials, useDashboardMetrics, useDeactivateDeployment, useDeactivateMembership, useDealDetail, useDealNotes, useDealTasks, useDealTasksDue, useDeals, useDealsLookup, useDealsSummary, useDeleteApiKey, useDeleteCompanies, useDeleteContacts, useDeleteCredential, useDeleteDeal, useDeleteProject as useDeleteDeliveryProject, useDeleteTask as useDeleteDeliveryTask, useDeleteDeployment, useDeleteExecution, useDeleteList, useDeleteMilestone, useDeleteRequest, useDeleteSchedule, useDeleteSession, useDeleteTask$1 as useDeleteTask, useDeleteWebhookEndpoint, useErrorAnalysis, useErrorDetail, useErrorDetails, useErrorDistribution, useErrorNotification, useErrorTrends, useExecuteAsync, useExecuteResource, useExecution, useExecutionHealth, useExecutionLogSSE, useExecutionLogs, useExecutionLogsFilters, useExecutionPanelState, useExecutions, useGetExecutionHistory, useGetSchedule, useGraphStats, useList, useListApiKeys, useListDeployments, useListExecutions, useListProgress, useListSchedules, useListWebhookEndpoints, useLists, useListsTelemetry, useMarkAllAsRead, useMarkAsRead, useMergedExecution, useMilestones, useNotificationCount as useNotificationCountSSE, useNotifications, useOrganizationMembers, usePaginationState, usePatchTask, usePauseSchedule, useProject, useProjectActivities, useProjectMilestones, useProjectNotes, useProjectRealtime, useProjectTasks, useProjects, useReactivateMembership, useRecentExecutionsByResource, useRequest, useRequestsList, useResolveAllErrors, useResolveError, useResolveErrorsByExecution, useResourceDefinition, useResourceErrors, useResourceExecutions, useResourceSearch, useResources, useResourcesDomainFilters, useResourcesHealth, useResumeSchedule, useRetryExecution, useSSEConnection, useScheduledTasks, useSession, useSessionExecution, useSessionExecutions, useSessionMessages, useSessionWebSocket, useSessions, useSortedData, useStatusFilter, useSubmitAction, useSuccessNotification, useSyncDealStage, useTableSelection, useTableSort, useTasks, useTestNotification, useTimeRangeDates, useTopFailingResources, useUnresolveError, useUnresolvedErrors, useUpdateAnchor, useUpdateApiKey, useUpdateCompany, useUpdateContact, useUpdateCredential, useUpdateProject as useUpdateDeliveryProject, useUpdateList, useUpdateListConfig, useUpdateMemberConfig, useUpdateMilestone, useUpdateRequestStatus, useUpdateSchedule, useUpdateTask, useUpdateWebhookEndpoint, useUserMemberships, useVisibleResources, useWarningNotification };
8259
- export type { AcqCompanyWithCount, AcqContactWithCompany, AcqDealNote, AcqDealTask, AcqDealTaskKind, ActivityFilters, ActivityTrendResponse, BulkDeleteExecutionsParams, BulkDeleteExecutionsResult, BusinessImpactMetrics, CancelExecutionParams, CancelExecutionResult, ChatMessage, CreateApiKeyRequest, CreateApiKeyResponse, CreateCredentialRequest, CreateCredentialResponse, CreateScheduleInput, CreateSessionResponse, CredentialListItem, DealDetail, DealLookupFilters, DealLookupItem, DealSummaryStageItem, DealsSummaryResponse, DeleteExecutionParams, Deployment, ErrorDistributionItem, ErrorDistributionParams, ErrorFilters, ErrorTrendsParams, ExecuteAsyncParams, ExecuteAsyncResult, ExecutionErrorDetails, ExecutionHistoryItem, ExecutionHistoryResponse, ExecutionLogsFilters, ExecutionLogsPageResponse, FailingResource, FeatureAccessResult, GetMessagesResponse, ListActivitiesResponse, ListApiKeysResponse, ListCredentialsResponse, ListSchedulesFilters, ListSchedulesResponse, ListWebhookEndpointsResponse, MessageEvent, MessageType, RequestRow, RequestsListFilters, ResourceFilterFacet, ResourcesResponse, RetryExecutionParams, SessionDTO, SessionExecution, SessionExecutionsResponse, SessionListItem, SessionTokenUsage, SortDirection, SortState, StaleDealSummaryItem, StatusFilter, SubmitActionRequest, SubmitActionResponse, TaskSchedule, TopFailingResourcesParams, UpdateScheduleInput, UseActivitiesParams, UseActivityTrendParams, UseBatchedResourcesHealthParams, UseExecuteResourceOptions, UseExecutionHealthParams, UseExecutionLogsParams, UseExecutionPanelStateOptions, UseExecutionPanelStateReturn, UseNotificationCountArgs, UseResourcesHealthParams, UseSSEConnectionOptions, UseScheduledTasksOptions, WebSocketState };
8558
+ export { ApiKeyService, CredentialService, DeploymentService, OperationsService, OrganizationMembershipService, REFETCH_INTERVAL_RUNNING, WS_MAX_RETRIES_BEFORE_ERROR, WS_RECONNECT_BASE_DELAY, WS_RECONNECT_MAX_DELAY, WebhookEndpointService, acquisitionListKeys, collectResourceFilterFacets, companyKeys, contactKeys, createFeatureAccessHook, dealKeys, dealNoteKeys, dealTaskKeys, executionsKeys, filterByDomainFilters, getResourceFilterFacetIds, isSessionCapable, labelResourceFilterFacet, milestoneKeys, noteKeys, observabilityKeys, operationsKeys, projectActivityKeys, projectKeys, requestsKeys, scheduleKeys, sessionsKeys, sortData, taskKeys, useActivateDeployment, useActivities, useActivitiesRealtime, useActivityFilters, useActivityTrend, useArchiveSession, useArchivedLogs, useAssignRole, useBatchDelete, useBatchTelemetry, useBatchedResourcesHealth, useBulkDeleteExecutions, useBusinessImpact, useCancelExecution, useCancelSchedule, useCheckpointTasks, useCommandQueue, useCommandQueueTotals, useCommandViewData, useCommandViewDomainFilters, useCommandViewLayout, useCommandViewStats, useCommandViewStore, useCompanies, useCompany, useCompanyFacets, useCompleteDealTask, useContact, useContacts, useCostBreakdown, useCostByModel, useCostSummary, useCostTrends, useCreateApiKey, useCreateCompany, useCreateContact, useCreateCredential, useCreateDealNote, useCreateDealTask, useCreateProject as useCreateDeliveryProject, useCreateList, useCreateMilestone, useCreateNote, useCreateOrgRole, useCreateSchedule, useCreateSession, useCreateTask, useCreateWebhookEndpoint, useCredentials, useDashboardMetrics, useDeactivateDeployment, useDeactivateMembership, useDealDetail, useDealNotes, useDealTasks, useDealTasksDue, useDeals, useDealsLookup, useDealsSummary, useDeleteApiKey, useDeleteCompanies, useDeleteContacts, useDeleteCredential, useDeleteDeal, useDeleteProject as useDeleteDeliveryProject, useDeleteTask as useDeleteDeliveryTask, useDeleteDeployment, useDeleteExecution, useDeleteList, useDeleteMilestone, useDeleteOrgRole, useDeleteRequest, useDeleteSchedule, useDeleteSession, useDeleteTask$1 as useDeleteTask, useDeleteWebhookEndpoint, useEffectivePermissions, useErrorAnalysis, useErrorDetail, useErrorDetails, useErrorDistribution, useErrorNotification, useErrorTrends, useExecuteAsync, useExecuteResource, useExecution, useExecutionHealth, useExecutionLogSSE, useExecutionLogs, useExecutionLogsFilters, useExecutionPanelState, useExecutions, useGetExecutionHistory, useGetSchedule, useGraphStats, useHasPermission, useList, useListApiKeys, useListDeployments, useListExecutions, useListProgress, useListSchedules, useListWebhookEndpoints, useLists, useListsTelemetry, useMarkAllAsRead, useMarkAsRead, useMergedExecution, useMilestones, useNotificationCount as useNotificationCountSSE, useNotifications, useOrgRoles, useOrganizationMembers, useOrganizationPermissions, usePaginationState, usePatchTask, usePauseSchedule, usePermissionCatalog, useProject, useProjectActivities, useProjectMilestones, useProjectNotes, useProjectRealtime, useProjectTasks, useProjects, useReactivateMembership, useRecentExecutionsByResource, useRequest, useRequestsList, useResolveAllErrors, useResolveError, useResolveErrorsByExecution, useResourceDefinition, useResourceErrors, useResourceExecutions, useResourceSearch, useResources, useResourcesDomainFilters, useResourcesHealth, useResumeSchedule, useRetryExecution, useRevokeRole, useSSEConnection, useScheduledTasks, useSession, useSessionExecution, useSessionExecutions, useSessionMessages, useSessionWebSocket, useSessions, useSortedData, useStatusFilter, useSubmitAction, useSuccessNotification, useSyncDealStage, useTableSelection, useTableSort, useTasks, useTestNotification, useTimeRangeDates, useTopFailingResources, useUnresolveError, useUnresolvedErrors, useUpdateAnchor, useUpdateApiKey, useUpdateCompany, useUpdateContact, useUpdateCredential, useUpdateProject as useUpdateDeliveryProject, useUpdateList, useUpdateListConfig, useUpdateMemberConfig, useUpdateMilestone, useUpdateOrgRole, useUpdateRequestStatus, useUpdateSchedule, useUpdateTask, useUpdateWebhookEndpoint, useUserMemberships, useVisibleResources, useWarningNotification };
8559
+ export type { AcqCompanyWithCount, AcqContactWithCompany, AcqDealNote, AcqDealTask, AcqDealTaskKind, ActivityFilters, ActivityTrendResponse, AssignRoleInput, BulkDeleteExecutionsParams, BulkDeleteExecutionsResult, BusinessImpactMetrics, CancelExecutionParams, CancelExecutionResult, ChatMessage, CreateApiKeyRequest, CreateApiKeyResponse, CreateCredentialRequest, CreateCredentialResponse, CreateOrgRoleInput, CreateScheduleInput, CreateSessionResponse, CredentialListItem, DealDetail, DealLookupFilters, DealLookupItem, DealSummaryStageItem, DealsSummaryResponse, DeleteExecutionParams, Deployment, ErrorDistributionItem, ErrorDistributionParams, ErrorFilters, ErrorTrendsParams, ExecuteAsyncParams, ExecuteAsyncResult, ExecutionErrorDetails, ExecutionHistoryItem, ExecutionHistoryResponse, ExecutionLogsFilters, ExecutionLogsPageResponse, FailingResource, FeatureAccessResult, GetMessagesResponse, ListActivitiesResponse, ListApiKeysResponse, ListCredentialsResponse, ListSchedulesFilters, ListSchedulesResponse, ListWebhookEndpointsResponse, MessageEvent, MessageType, OrgRole, RequestRow, RequestsListFilters, ResourceFilterFacet, ResourcesResponse, RetryExecutionParams, RevokeRoleInput, SessionDTO, SessionExecution, SessionExecutionsResponse, SessionListItem, SessionTokenUsage, SortDirection, SortState, StaleDealSummaryItem, StatusFilter, SubmitActionRequest, SubmitActionResponse, TaskSchedule, TopFailingResourcesParams, UpdateOrgRoleInput, UpdateScheduleInput, UseActivitiesParams, UseActivityTrendParams, UseBatchedResourcesHealthParams, UseExecuteResourceOptions, UseExecutionHealthParams, UseExecutionLogsParams, UseExecutionPanelStateOptions, UseExecutionPanelStateReturn, UseNotificationCountArgs, UseResourcesHealthParams, UseSSEConnectionOptions, UseScheduledTasksOptions, WebSocketState };