@elevasis/sdk 0.1.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.
@@ -0,0 +1,1561 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Error categories for observability grouping and classification.
5
+ * Used to categorize errors in the execution_errors table metadata.
6
+ */
7
+ type ExecutionErrorCategory = 'llm' | 'tool' | 'workflow' | 'agent' | 'validation' | 'system';
8
+ /**
9
+ * Abstract base class for all execution engine errors.
10
+ * Enforces contract for execution_errors table insertion with explicit type,
11
+ * severity, category, and context properties.
12
+ *
13
+ * All execution engine errors MUST extend this class to ensure proper error
14
+ * tracking and observability in the execution_errors table.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * export class MyExecutionError extends ExecutionError {
19
+ * readonly type = 'my_execution_error' as const
20
+ * readonly severity = 'warning' as const
21
+ * readonly category = 'workflow' as const
22
+ *
23
+ * constructor(message: string, context?: Record<string, unknown>) {
24
+ * super(message, context)
25
+ * }
26
+ * }
27
+ * ```
28
+ */
29
+ declare abstract class ExecutionError extends Error {
30
+ /**
31
+ * Error type identifier for execution_errors table.
32
+ * Should be a unique, snake_case string that identifies this specific error class.
33
+ * Used for filtering, aggregation, and error-specific handling in observability systems.
34
+ */
35
+ abstract readonly type: string;
36
+ /**
37
+ * Error severity level for execution_errors table.
38
+ * - critical: System failures, auth issues, resource exhaustion - execution cannot continue
39
+ * - warning: Transient failures, configuration errors - execution may retry or requires user correction
40
+ * - info: Validation failures, expected user errors - user/developer action needed
41
+ */
42
+ abstract readonly severity: 'critical' | 'warning' | 'info';
43
+ /**
44
+ * Error category for observability grouping.
45
+ * Used to categorize errors in dashboards and analytics.
46
+ */
47
+ abstract readonly category: ExecutionErrorCategory;
48
+ /**
49
+ * Additional context/metadata for the error.
50
+ * Stored in execution_errors.metadata JSONB column.
51
+ */
52
+ readonly context?: Record<string, unknown>;
53
+ /**
54
+ * @param message - Human-readable error message
55
+ * @param context - Additional context/metadata for observability
56
+ */
57
+ constructor(message: string, context?: Record<string, unknown>);
58
+ /**
59
+ * Indicates whether this error type is retryable.
60
+ * Default: false (safe default - only retry when explicitly safe to do so)
61
+ *
62
+ * Subclasses should override to return true for retryable scenarios:
63
+ * - Network/infrastructure errors (exponential backoff)
64
+ * - Rate limiting (linear backoff)
65
+ * - Service availability (exponential backoff)
66
+ * - Circuit breaker (circuit breaker's own delay)
67
+ *
68
+ * DO NOT retry:
69
+ * - Authentication/authorization errors
70
+ * - Validation errors
71
+ * - Configuration errors
72
+ * - Resource exhaustion errors
73
+ */
74
+ isRetryable(): boolean;
75
+ }
76
+
77
+ /**
78
+ * Workflow-specific logging types
79
+ */
80
+
81
+ interface WorkflowExecutionContext {
82
+ type: 'workflow';
83
+ contextType: 'workflow-execution';
84
+ executionId: string;
85
+ workflowId: string;
86
+ workflowName?: string;
87
+ organizationId: string;
88
+ executionPath?: string[];
89
+ }
90
+ interface WorkflowFailureContext {
91
+ type: 'workflow';
92
+ contextType: 'workflow-failure';
93
+ executionId: string;
94
+ workflowId: string;
95
+ error: string;
96
+ }
97
+ interface StepStartedContext {
98
+ type: 'workflow';
99
+ contextType: 'step-started';
100
+ stepId: string;
101
+ stepStatus: 'started';
102
+ input: unknown;
103
+ startTime: number;
104
+ }
105
+ interface StepCompletedContext {
106
+ type: 'workflow';
107
+ contextType: 'step-completed';
108
+ stepId: string;
109
+ stepStatus: 'completed';
110
+ output: unknown;
111
+ duration: number;
112
+ isTerminal: boolean;
113
+ startTime: number;
114
+ endTime: number;
115
+ }
116
+ interface StepFailedContext {
117
+ type: 'workflow';
118
+ contextType: 'step-failed';
119
+ stepId: string;
120
+ stepStatus: 'failed';
121
+ error: string;
122
+ duration: number;
123
+ startTime: number;
124
+ endTime: number;
125
+ }
126
+ interface ConditionalRouteContext {
127
+ type: 'workflow';
128
+ contextType: 'conditional-route';
129
+ stepId: string;
130
+ target: string;
131
+ error?: string;
132
+ }
133
+ interface ExecutionPathContext {
134
+ type: 'workflow';
135
+ contextType: 'execution-path';
136
+ executionPath: string[];
137
+ }
138
+ type WorkflowLogContext = WorkflowExecutionContext | WorkflowFailureContext | StepStartedContext | StepCompletedContext | StepFailedContext | ConditionalRouteContext | ExecutionPathContext;
139
+
140
+ /**
141
+ * Agent-specific logging types
142
+ * Simplified 2-event model: lifecycle, iteration
143
+ *
144
+ * Design Philosophy:
145
+ * - LIFECYCLE EVENTS: Structural checkpoints (initialization, iteration, completion)
146
+ * - ITERATION EVENTS: Execution activities (reasoning, actions during iterations)
147
+ */
148
+
149
+ /**
150
+ * Agent lifecycle stages
151
+ * Universal checkpoints that apply to all agent executions
152
+ */
153
+ type AgentLifecycle = 'initialization' | 'iteration' | 'completion';
154
+ /**
155
+ * Iteration event types
156
+ * Activities that occur during agent iterations
157
+ */
158
+ type IterationEventType = 'reasoning' | 'action' | 'tool-call';
159
+ /**
160
+ * Base fields shared by all lifecycle events
161
+ */
162
+ interface AgentLifecycleEventBase {
163
+ type: 'agent';
164
+ agentId: string;
165
+ lifecycle: AgentLifecycle;
166
+ sessionId?: string;
167
+ }
168
+ /**
169
+ * Lifecycle started event - emitted when a phase begins
170
+ * REQUIRED: startTime (phase has started, no end yet)
171
+ */
172
+ interface AgentLifecycleStartedEvent extends AgentLifecycleEventBase {
173
+ stage: 'started';
174
+ startTime: number;
175
+ iteration?: number;
176
+ }
177
+ /**
178
+ * Lifecycle completed event - emitted when a phase succeeds
179
+ * REQUIRED: startTime, endTime, duration (phase has finished successfully)
180
+ */
181
+ interface AgentLifecycleCompletedEvent extends AgentLifecycleEventBase {
182
+ stage: 'completed';
183
+ startTime: number;
184
+ endTime: number;
185
+ duration: number;
186
+ iteration?: number;
187
+ attempts?: number;
188
+ memorySize?: {
189
+ sessionMemoryKeys: number;
190
+ historyEntries: number;
191
+ };
192
+ }
193
+ /**
194
+ * Lifecycle failed event - emitted when a phase fails
195
+ * REQUIRED: startTime, endTime, duration, error (phase has finished with error)
196
+ */
197
+ interface AgentLifecycleFailedEvent extends AgentLifecycleEventBase {
198
+ stage: 'failed';
199
+ startTime: number;
200
+ endTime: number;
201
+ duration: number;
202
+ error: string;
203
+ iteration?: number;
204
+ }
205
+ /**
206
+ * Union type for all lifecycle events
207
+ * Discriminated by 'stage' field for type narrowing
208
+ */
209
+ type AgentLifecycleEvent = AgentLifecycleStartedEvent | AgentLifecycleCompletedEvent | AgentLifecycleFailedEvent;
210
+ /**
211
+ * Placeholder data for MVP
212
+ * Will be typed per actionType in future
213
+ */
214
+ interface ActionPlaceholderData {
215
+ message: string;
216
+ }
217
+ /**
218
+ * Iteration event - captures activities during agent iterations
219
+ * Consolidates reasoning (LLM thought process) and actions (tool use, memory ops, etc.)
220
+ */
221
+ interface AgentIterationEvent {
222
+ type: 'agent';
223
+ agentId: string;
224
+ lifecycle: 'iteration';
225
+ eventType: IterationEventType;
226
+ iteration: number;
227
+ sessionId?: string;
228
+ startTime: number;
229
+ endTime: number;
230
+ duration: number;
231
+ output?: string;
232
+ actionType?: string;
233
+ data?: ActionPlaceholderData;
234
+ }
235
+ /**
236
+ * Tool call event - captures individual tool executions during iterations
237
+ * Provides granular timing for each tool invocation
238
+ */
239
+ interface AgentToolCallEvent {
240
+ type: 'agent';
241
+ agentId: string;
242
+ lifecycle: 'iteration';
243
+ eventType: 'tool-call';
244
+ iteration: number;
245
+ sessionId?: string;
246
+ toolName: string;
247
+ startTime: number;
248
+ endTime: number;
249
+ duration: number;
250
+ success: boolean;
251
+ error?: string;
252
+ input?: Record<string, unknown>;
253
+ output?: unknown;
254
+ }
255
+ /**
256
+ * Union type for all agent log contexts
257
+ * 3 event types total (lifecycle, iteration, tool-call)
258
+ */
259
+ type AgentLogContext = AgentLifecycleEvent | AgentIterationEvent | AgentToolCallEvent;
260
+ /**
261
+ * Data for lifecycle 'started' events
262
+ */
263
+ interface AgentLifecycleStartedData {
264
+ startTime: number;
265
+ iteration?: number;
266
+ }
267
+ /**
268
+ * Data for lifecycle 'completed' events
269
+ */
270
+ interface AgentLifecycleCompletedData {
271
+ startTime: number;
272
+ endTime: number;
273
+ duration: number;
274
+ iteration?: number;
275
+ attempts?: number;
276
+ memorySize?: {
277
+ sessionMemoryKeys: number;
278
+ historyEntries: number;
279
+ };
280
+ }
281
+ /**
282
+ * Data for lifecycle 'failed' events
283
+ */
284
+ interface AgentLifecycleFailedData {
285
+ startTime: number;
286
+ endTime: number;
287
+ duration: number;
288
+ error: string;
289
+ iteration?: number;
290
+ }
291
+ /**
292
+ * Scoped logger for agent execution
293
+ * Captures logger and agentId to eliminate repetitive parameter passing
294
+ *
295
+ * Type-safe lifecycle logging with stage-specific required fields
296
+ */
297
+ interface AgentScopedLogger {
298
+ lifecycle(lifecycle: AgentLifecycle, stage: 'started', data: AgentLifecycleStartedData): void;
299
+ lifecycle(lifecycle: AgentLifecycle, stage: 'completed', data: AgentLifecycleCompletedData): void;
300
+ lifecycle(lifecycle: AgentLifecycle, stage: 'failed', data: AgentLifecycleFailedData): void;
301
+ reasoning(output: string, iteration: number, startTime: number, endTime: number, duration: number): void;
302
+ action(actionType: string, message: string, iteration: number, startTime: number, endTime: number, duration: number): void;
303
+ toolCall(toolName: string, iteration: number, startTime: number, endTime: number, duration: number, success: boolean, error?: string, input?: unknown, output?: unknown): void;
304
+ }
305
+
306
+ type LogContext = WorkflowLogContext | AgentLogContext;
307
+ interface IExecutionLogger {
308
+ debug(message: string, context?: LogContext): void;
309
+ info(message: string, context?: LogContext): void;
310
+ warn(message: string, context?: LogContext): void;
311
+ error(message: string, context?: LogContext): void;
312
+ }
313
+
314
+ /**
315
+ * Shared form field types for dynamic form generation
316
+ * Used by: Command Queue, Execution Runner UI, future form-based features
317
+ */
318
+ /**
319
+ * Supported form field types for action payloads
320
+ * Maps to Mantine form components
321
+ */
322
+ type FormFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'radio' | 'richtext';
323
+ /**
324
+ * Form field definition
325
+ */
326
+ interface FormField {
327
+ /** Field key in payload object */
328
+ name: string;
329
+ /** Field label for UI */
330
+ label: string;
331
+ /** Field type (determines UI component) */
332
+ type: FormFieldType;
333
+ /** Default value */
334
+ defaultValue?: unknown;
335
+ /** Required field */
336
+ required?: boolean;
337
+ /** Placeholder text */
338
+ placeholder?: string;
339
+ /** Help text */
340
+ description?: string;
341
+ /** Options for select/radio */
342
+ options?: Array<{
343
+ label: string;
344
+ value: string | number;
345
+ }>;
346
+ /** Min/max for number */
347
+ min?: number;
348
+ max?: number;
349
+ /** Path to context value for pre-filling (dot notation, e.g., 'proposal.summary') */
350
+ defaultValueFromContext?: string;
351
+ }
352
+ /**
353
+ * Form schema for action payload collection
354
+ */
355
+ interface FormSchema {
356
+ /** Form title */
357
+ title?: string;
358
+ /** Form description */
359
+ description?: string;
360
+ /** Form fields */
361
+ fields: FormField[];
362
+ /** Layout (default: 'vertical') */
363
+ layout?: 'vertical' | 'horizontal' | 'grid';
364
+ }
365
+
366
+ /**
367
+ * Model Configuration
368
+ * Centralized model information, configuration, options, constraints, and validation
369
+ * Single source of truth for all model-related definitions
370
+ * Update manually when pricing changes or new models are added
371
+ */
372
+
373
+ /**
374
+ * Supported Open AI models (direct SDK access)
375
+ */
376
+ type OpenAIModel = 'gpt-5' | 'gpt-5-mini';
377
+ /**
378
+ * Supported OpenRouter models (explicit union for type safety)
379
+ */
380
+ type OpenRouterModel = 'openrouter/anthropic/claude-sonnet-4.5' | 'openrouter/deepseek/deepseek-v3.2' | 'openrouter/x-ai/grok-4.1-fast';
381
+ /**
382
+ * Supported Google models (direct SDK access)
383
+ */
384
+ type GoogleModel = 'gemini-3-flash-preview';
385
+ /**
386
+ * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
387
+ * Using aliases for automatic updates to latest versions
388
+ */
389
+ type AnthropicModel = 'claude-opus-4-5' | 'claude-sonnet-4-5' | 'claude-haiku-4-5';
390
+ /** Supported LLM models */
391
+ type LLMModel = OpenAIModel | OpenRouterModel | GoogleModel | AnthropicModel | 'mock';
392
+ /**
393
+ * GPT-5 model options schema
394
+ */
395
+ declare const GPT5OptionsSchema: z.ZodObject<{
396
+ reasoning_effort: z.ZodOptional<z.ZodEnum<{
397
+ minimal: "minimal";
398
+ low: "low";
399
+ medium: "medium";
400
+ high: "high";
401
+ }>>;
402
+ verbosity: z.ZodOptional<z.ZodEnum<{
403
+ low: "low";
404
+ medium: "medium";
405
+ high: "high";
406
+ }>>;
407
+ }, z.core.$strip>;
408
+ /**
409
+ * OpenRouter model options schema
410
+ * OpenRouter-specific options for routing and transforms
411
+ */
412
+ declare const OpenRouterOptionsSchema: z.ZodObject<{
413
+ transforms: z.ZodOptional<z.ZodArray<z.ZodString>>;
414
+ route: z.ZodOptional<z.ZodEnum<{
415
+ fallback: "fallback";
416
+ }>>;
417
+ }, z.core.$strip>;
418
+ /**
419
+ * Google model options schema
420
+ * Gemini 3 specific options for thinking depth control
421
+ */
422
+ declare const GoogleOptionsSchema: z.ZodObject<{
423
+ thinkingLevel: z.ZodOptional<z.ZodEnum<{
424
+ minimal: "minimal";
425
+ low: "low";
426
+ medium: "medium";
427
+ high: "high";
428
+ }>>;
429
+ }, z.core.$strip>;
430
+ /**
431
+ * Anthropic model options schema
432
+ * Currently empty - future options: budget_tokens for extended thinking
433
+ */
434
+ declare const AnthropicOptionsSchema: z.ZodObject<{}, z.core.$strip>;
435
+ /**
436
+ * Infer TypeScript types from schemas
437
+ */
438
+ type GPT5Options = z.infer<typeof GPT5OptionsSchema>;
439
+ type MockOptions = Record<string, never>;
440
+ type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>;
441
+ type GoogleOptions = z.infer<typeof GoogleOptionsSchema>;
442
+ type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>;
443
+ type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | GoogleOptions | AnthropicOptions;
444
+ /**
445
+ * Model configuration for LLM execution
446
+ * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
447
+ */
448
+ interface ModelConfig {
449
+ model: LLMModel;
450
+ provider: 'openai' | 'anthropic' | 'openrouter' | 'google' | 'mock';
451
+ apiKey: string;
452
+ temperature?: number;
453
+ maxTokens?: number;
454
+ topP?: number;
455
+ /**
456
+ * Model-specific options (flat structure)
457
+ * Options are model-specific, not vendor-specific
458
+ * Available options defined in MODEL_INFO per model
459
+ * Validated at build time via validateModelOptions()
460
+ */
461
+ modelOptions?: ModelSpecificOptions;
462
+ }
463
+
464
+ /**
465
+ * Execution interface configuration
466
+ * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
467
+ * Applies to both agents and workflows
468
+ */
469
+ interface ExecutionInterface {
470
+ /** Form configuration for execution inputs */
471
+ form: ExecutionFormSchema;
472
+ /** Optional: Schedule configuration */
473
+ schedule?: ScheduleConfig;
474
+ /** Optional: Webhook trigger configuration */
475
+ webhook?: WebhookConfig;
476
+ }
477
+ /**
478
+ * Execution form schema
479
+ * Extends FormSchema with execution-specific fields
480
+ */
481
+ interface ExecutionFormSchema extends FormSchema {
482
+ /**
483
+ * Field mappings to resource input schema
484
+ * Maps form field names to contract input paths
485
+ * If omitted, field names must match contract input keys exactly
486
+ */
487
+ fieldMappings?: Record<string, string>;
488
+ /**
489
+ * Submit button configuration
490
+ * Default: { label: 'Run', loadingLabel: 'Running...' }
491
+ */
492
+ submitButton?: {
493
+ label?: string;
494
+ loadingLabel?: string;
495
+ confirmMessage?: string;
496
+ };
497
+ }
498
+ /**
499
+ * Schedule configuration for automated execution
500
+ */
501
+ interface ScheduleConfig {
502
+ /** Whether scheduling is enabled for this resource */
503
+ enabled: boolean;
504
+ /** Default schedule (cron expression) */
505
+ defaultSchedule?: string;
506
+ /** Allowed schedule patterns (if restricted) */
507
+ allowedPatterns?: string[];
508
+ }
509
+ /**
510
+ * Webhook configuration for external triggers
511
+ */
512
+ interface WebhookConfig {
513
+ /** Whether webhook trigger is enabled */
514
+ enabled: boolean;
515
+ /** Expected payload schema (for documentation) */
516
+ payloadSchema?: unknown;
517
+ }
518
+
519
+ interface WorkflowConfig extends ResourceDefinition {
520
+ type: 'workflow';
521
+ }
522
+ interface WorkflowStepDefinition {
523
+ id: string;
524
+ name: string;
525
+ description: string;
526
+ }
527
+ type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>;
528
+ declare enum StepType {
529
+ LINEAR = "linear",
530
+ CONDITIONAL = "conditional"
531
+ }
532
+ interface LinearNext {
533
+ type: StepType.LINEAR;
534
+ target: string;
535
+ }
536
+ interface ConditionalNext {
537
+ type: StepType.CONDITIONAL;
538
+ routes: Array<{
539
+ condition: (data: unknown) => boolean;
540
+ target: string;
541
+ }>;
542
+ default: string;
543
+ }
544
+ type NextConfig = LinearNext | ConditionalNext | null;
545
+ interface WorkflowStep extends WorkflowStepDefinition {
546
+ handler: StepHandler;
547
+ inputSchema: z.ZodSchema;
548
+ outputSchema: z.ZodSchema;
549
+ next: NextConfig;
550
+ }
551
+ interface WorkflowDefinition {
552
+ config: WorkflowConfig;
553
+ contract: Contract;
554
+ steps: Record<string, WorkflowStep>;
555
+ entryPoint: string;
556
+ /**
557
+ * Metrics configuration for ROI calculations
558
+ * Optional: Only needed if tracking automation savings
559
+ */
560
+ metricsConfig?: ResourceMetricsConfig;
561
+ /**
562
+ * Execution interface configuration (optional)
563
+ * If provided, workflow appears in Execution Runner UI
564
+ */
565
+ interface?: ExecutionInterface;
566
+ }
567
+
568
+ /**
569
+ * Memory type definitions
570
+ * Types for agent memory management with semantic entry types
571
+ */
572
+ /**
573
+ * Semantic memory entry types
574
+ * Use-case agnostic types that describe the purpose of each entry
575
+ * Memory types mirror action types for clarity and filtering
576
+ */
577
+ type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'delegation-result' | 'error';
578
+ /**
579
+ * Memory entry - represents a single entry in agent memory
580
+ * Stored in agent memory, translated by adapters to vendor-specific formats
581
+ */
582
+ interface MemoryEntry {
583
+ type: MemoryEntryType;
584
+ content: string;
585
+ timestamp: number;
586
+ turnNumber: number | null;
587
+ iterationNumber: number | null;
588
+ }
589
+ /**
590
+ * Agent memory - Self-orchestrated memory with session + working storage
591
+ * Agent has full control over what persists, framework handles auto-compaction
592
+ */
593
+ interface AgentMemory {
594
+ /**
595
+ * Session memory - Persists for session/conversation duration
596
+ * Never auto-trimmed by framework
597
+ * Agent-managed key-value store for critical information
598
+ * Agent provides strings, framework wraps in MemoryEntry
599
+ */
600
+ sessionMemory: Record<string, MemoryEntry>;
601
+ /**
602
+ * Working memory - Execution history
603
+ * Automatically compacted by framework when needed
604
+ * Agent doesn't control compaction
605
+ */
606
+ history: MemoryEntry[];
607
+ }
608
+ /**
609
+ * Memory status for agent awareness
610
+ */
611
+ interface MemoryStatus {
612
+ sessionMemoryKeys: number;
613
+ sessionMemoryLimit: number;
614
+ currentKeys: string[];
615
+ historyPercent: number;
616
+ historyTokens: number;
617
+ tokenBudget: number;
618
+ }
619
+ /**
620
+ * Memory constraints (optional limits)
621
+ */
622
+ interface MemoryConstraints {
623
+ maxSessionMemoryKeys?: number;
624
+ maxMemoryTokens?: number;
625
+ }
626
+
627
+ /**
628
+ * Memory Manager
629
+ * Encapsulates all memory operations with ultra-simple agent API
630
+ * Agent provides strings, framework handles wrapping and auto-compaction
631
+ */
632
+
633
+ /**
634
+ * Memory Manager - Agent memory orchestration
635
+ * Provides ultra-simple API for agents (strings only)
636
+ * Handles automatic compaction and token management
637
+ */
638
+ declare class MemoryManager {
639
+ private memory;
640
+ private constraints;
641
+ private logger?;
642
+ private cachedSnapshot?;
643
+ constructor(memory: AgentMemory, constraints?: MemoryConstraints, logger?: AgentScopedLogger | undefined);
644
+ /**
645
+ * Set session memory entry (agent provides string, framework wraps it)
646
+ * @param key - Session memory key
647
+ * @param content - String content from agent
648
+ */
649
+ set(key: string, content: string): void;
650
+ /**
651
+ * Get session memory entry content
652
+ * @param key - Session memory key
653
+ * @returns String content if exists, undefined otherwise
654
+ */
655
+ get(key: string): string | undefined;
656
+ /**
657
+ * Delete session memory entry
658
+ * @param key - Key to delete
659
+ * @returns True if key existed and was deleted
660
+ */
661
+ delete(key: string): boolean;
662
+ /**
663
+ * Add entry to history (called by framework after tool results, reasoning, etc.)
664
+ * Automatically sets timestamp to current time
665
+ * @param entry - Memory entry to add (without timestamp - auto-generated)
666
+ */
667
+ addToHistory(entry: Omit<MemoryEntry, 'timestamp'>): void;
668
+ /**
669
+ * Auto-compact history if approaching token budget
670
+ * Uses preserve-anchors strategy: keep first + recent entries
671
+ */
672
+ autoCompact(): void;
673
+ /**
674
+ * Enforce hard limits (called before LLM request)
675
+ * Emergency fallback if agent exceeds limits
676
+ */
677
+ enforceHardLimits(): void;
678
+ /**
679
+ * Get history length (for logging and introspection)
680
+ * @returns Number of entries in history
681
+ */
682
+ getHistoryLength(): number;
683
+ /**
684
+ * Get memory status for agent awareness
685
+ * @returns Memory status with token usage and key counts
686
+ */
687
+ getStatus(): MemoryStatus;
688
+ /**
689
+ * Create memory snapshot for persistence
690
+ * Caches snapshot internally for later retrieval
691
+ * @returns Deep copy of current memory state
692
+ */
693
+ toSnapshot(): AgentMemory;
694
+ /**
695
+ * Get cached memory snapshot
696
+ * Returns snapshot created by toSnapshot()
697
+ * @returns Cached snapshot (undefined if toSnapshot() not called yet)
698
+ */
699
+ getSnapshot(): AgentMemory | undefined;
700
+ /**
701
+ * Build context string for LLM
702
+ * Serializes sessionmemory + history memory with clear sections
703
+ * Shows current iteration entries FIRST (reverse chronological) for LLM attention
704
+ * @param currentIteration - Current iteration number (0 = pre-iteration)
705
+ * @param currentTurn - Current turn number (optional, for session context filtering)
706
+ * @returns Formatted memory context for LLM prompt
707
+ */
708
+ toContext(currentIteration: number, currentTurn?: number): string;
709
+ }
710
+
711
+ /**
712
+ * Knowledge Map Types
713
+ *
714
+ * Enables agents to navigate organizational knowledge through a lightweight
715
+ * graph that lazy-loads capabilities on-demand.
716
+ *
717
+ * @module agent/knowledge-map
718
+ */
719
+
720
+ /**
721
+ * Lightweight knowledge map (passed as agent property)
722
+ *
723
+ * Contains metadata about available knowledge nodes without loading
724
+ * the full content upfront. Total size: ~300-500 tokens.
725
+ *
726
+ * Multi-tenancy is enforced via:
727
+ * - File-scoped maps (organizations/{org-name}/knowledge/)
728
+ * - ExecutionContext.organizationId passed to node.load()
729
+ */
730
+ interface KnowledgeMap {
731
+ /** Available knowledge nodes indexed by ID */
732
+ nodes: Record<string, KnowledgeNode>;
733
+ }
734
+ /**
735
+ * Single knowledge source
736
+ *
737
+ * Represents a domain knowledge area (CRM, brand guidelines, Excel tools)
738
+ * that can be lazy-loaded to provide instructions and tools to agents.
739
+ */
740
+ interface KnowledgeNode {
741
+ /** Unique identifier for this node (e.g., "crm", "brand-guidelines") */
742
+ id: string;
743
+ /**
744
+ * Description of when to use this knowledge
745
+ * Used for semantic matching against user intent
746
+ */
747
+ description: string;
748
+ /**
749
+ * Load knowledge content on-demand
750
+ *
751
+ * @param context - Execution context with organizationId for multi-tenancy
752
+ * @returns Promise resolving to knowledge content (prompt + optional tools)
753
+ */
754
+ load(context: ExecutionContext): Promise<KnowledgeContent>;
755
+ /**
756
+ * Loaded state flag
757
+ * Set to true after load() is called
758
+ */
759
+ loaded?: boolean;
760
+ /**
761
+ * Cached prompt (for system prompt serialization)
762
+ * Only the prompt is cached - tools go to toolRegistry, children flattened to nodes
763
+ */
764
+ prompt?: string;
765
+ }
766
+ /**
767
+ * Content returned by knowledge node
768
+ *
769
+ * Separates instructions (prompt) from capabilities (tools).
770
+ * Tools are optional - some nodes only provide context.
771
+ *
772
+ * Supports recursive navigation - nodes can contain child nodes
773
+ * that are discovered when the parent node is loaded.
774
+ */
775
+ interface KnowledgeContent {
776
+ /** Instructions and context (markdown format) */
777
+ prompt: string;
778
+ /** Tool implementations (optional) */
779
+ tools?: Tool[];
780
+ /**
781
+ * Child knowledge nodes (optional, recursive)
782
+ *
783
+ * Enables hierarchical navigation: base → specialized → deep expertise.
784
+ * Child nodes are flattened into the main knowledge map when parent loads,
785
+ * making them available for subsequent navigate-knowledge actions.
786
+ *
787
+ * Example: CRM base node returns crm-customers and crm-deals as children
788
+ */
789
+ nodes?: Record<string, KnowledgeNode>;
790
+ }
791
+
792
+ /**
793
+ * Agent-specific type definitions
794
+ * Types for autonomous agents with tools, memory, and constraints
795
+ */
796
+
797
+ interface AgentConfig extends ResourceDefinition {
798
+ type: 'agent';
799
+ systemPrompt: string;
800
+ constraints?: AgentConstraints;
801
+ /**
802
+ * Session capability declaration (opt-in)
803
+ * If true, agent is designed for multi-turn session interactions
804
+ * Controls whether agent can use message action and appears in Sessions UI
805
+ *
806
+ * Use for:
807
+ * - Conversational agents with multi-turn interactions
808
+ * - Agents requiring persistent context across turns
809
+ * - Agents that need human-in-the-loop communication
810
+ */
811
+ sessionCapable?: boolean;
812
+ /**
813
+ * Security level for system prompt hardening (auto-derived if omitted)
814
+ *
815
+ * - 'standard': Lightweight defense (3 rules) - default for non-session agents
816
+ * - 'hardened': Comprehensive defense (6 rules) - default for session-capable agents
817
+ * - 'none': No security prompt - for pure internal agents with no external input
818
+ *
819
+ * If omitted, derived from sessionCapable:
820
+ * sessionCapable: true -> 'hardened'
821
+ * sessionCapable: false -> 'standard'
822
+ */
823
+ securityLevel?: 'standard' | 'hardened' | 'none';
824
+ /**
825
+ * Memory management preferences (opt-in)
826
+ * If provided, agent can use memoryOps to manage session memory
827
+ * If omitted, agent has no memory management capabilities
828
+ *
829
+ * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
830
+ * This guidance is injected into the system prompt when memory management is enabled.
831
+ *
832
+ * Use for:
833
+ * - Conversational agents needing cross-turn context
834
+ * - Agents managing complex user preferences
835
+ * - Agents tracking decisions over multiple iterations
836
+ */
837
+ memoryPreferences?: string;
838
+ }
839
+ interface AgentConstraints {
840
+ maxIterations?: number;
841
+ timeout?: number;
842
+ maxSessionMemoryKeys?: number;
843
+ maxMemoryTokens?: number;
844
+ }
845
+ interface AgentDefinition {
846
+ config: AgentConfig;
847
+ contract: Contract;
848
+ tools: Tool[];
849
+ /**
850
+ * Model configuration for LLM execution
851
+ * Specifies provider, API key, and model-specific options
852
+ */
853
+ modelConfig: ModelConfig;
854
+ /**
855
+ * Optional knowledge map for lazy-loading capabilities
856
+ * Enables agents to navigate organizational knowledge on-demand
857
+ */
858
+ knowledgeMap?: KnowledgeMap;
859
+ /**
860
+ * Preload memory before execution starts
861
+ * Handles BOTH context loading AND session restoration
862
+ *
863
+ * @param context - Execution context (includes sessionId if session turn)
864
+ * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
865
+ */
866
+ preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory;
867
+ /**
868
+ * Metrics configuration for ROI calculations
869
+ * Optional: Only needed if tracking automation savings
870
+ */
871
+ metricsConfig?: ResourceMetricsConfig;
872
+ /**
873
+ * Execution interface configuration (optional)
874
+ * If provided, agent appears in Execution Runner UI
875
+ */
876
+ interface?: ExecutionInterface;
877
+ }
878
+ /**
879
+ * Agent execution context
880
+ * Groups all state needed for agent execution phases
881
+ */
882
+ interface IterationContext {
883
+ config: AgentConfig;
884
+ contract: Contract;
885
+ toolRegistry: Map<string, Tool>;
886
+ memoryManager: MemoryManager;
887
+ executionContext: ExecutionContext;
888
+ iteration: number;
889
+ logger: AgentScopedLogger;
890
+ modelConfig: ModelConfig;
891
+ knowledgeMap?: KnowledgeMap;
892
+ }
893
+
894
+ /**
895
+ * ResourceRegistry - Resource discovery and lookup
896
+ * Handles resource definitions from OrganizationRegistry
897
+ *
898
+ * Features:
899
+ * - Resource discovery by organization
900
+ * - Startup validation (duplicate IDs, model configs, relationships, interface-schema alignment)
901
+ * - Pre-serialization cache for instant API responses
902
+ * - Command View data generation
903
+ */
904
+
905
+ /**
906
+ * Organization-specific resource collection
907
+ *
908
+ * Complete manifest of all automation resources for an organization.
909
+ * Used by ResourceRegistry for discovery and Command View for visualization.
910
+ */
911
+ interface OrganizationResources {
912
+ /** Workflow definitions */
913
+ workflows?: WorkflowDefinition[];
914
+ /** Agent definitions */
915
+ agents?: AgentDefinition[];
916
+ /** Trigger definitions - entry points that initiate executions */
917
+ triggers?: TriggerDefinition[];
918
+ /** Integration definitions - external service connections */
919
+ integrations?: IntegrationDefinition[];
920
+ /** Explicit relationship declarations between resources */
921
+ relationships?: ResourceRelationships;
922
+ /** External automation resources (n8n, Make, Zapier, etc.) */
923
+ externalResources?: ExternalResourceDefinition[];
924
+ /** Human checkpoint definitions - human decision points in automation */
925
+ humanCheckpoints?: HumanCheckpointDefinition[];
926
+ }
927
+
928
+ /**
929
+ * MetricsCollector
930
+ * Tracks execution timing and ROI metrics
931
+ */
932
+ declare class MetricsCollector {
933
+ private timings;
934
+ private durationMs?;
935
+ /**
936
+ * Start a timer with a label
937
+ */
938
+ startTimer(label: string): void;
939
+ /**
940
+ * End a timer and calculate duration
941
+ * If label is 'execution', stores duration for metrics summary
942
+ */
943
+ endTimer(label: string): number | null;
944
+ /**
945
+ * Build execution metrics summary with optional ROI calculation
946
+ */
947
+ buildExecutionMetrics(metricsConfig?: ResourceMetricsConfig): ExecutionMetricsSummary;
948
+ }
949
+
950
+ interface BaseAICall {
951
+ callSequence: number;
952
+ callType: 'agent-reasoning' | 'agent-completion' | 'workflow-step' | 'tool' | 'other';
953
+ model: LLMModel;
954
+ inputTokens: number;
955
+ outputTokens: number;
956
+ costUsd: number;
957
+ latencyMs: number;
958
+ context?: AICallContext;
959
+ }
960
+ type AICallContext = AgentReasoningContext | AgentCompletionContext | WorkflowStepContext | ToolCallContext | OtherCallContext;
961
+ interface AgentReasoningContext {
962
+ type: 'agent-reasoning';
963
+ iteration: number;
964
+ actionsPlanned?: string[];
965
+ sessionId?: string;
966
+ turnNumber?: number;
967
+ }
968
+ interface AgentCompletionContext {
969
+ type: 'agent-completion';
970
+ attempt: 1 | 2;
971
+ validationFailed?: boolean;
972
+ sessionId?: string;
973
+ turnNumber?: number;
974
+ }
975
+ interface WorkflowStepContext {
976
+ type: 'workflow-step';
977
+ stepId: string;
978
+ stepName?: string;
979
+ stepSequence?: number;
980
+ }
981
+ interface ToolCallContext {
982
+ type: 'tool';
983
+ toolName: string;
984
+ parentIteration?: number;
985
+ parentStepId?: string;
986
+ }
987
+ interface OtherCallContext {
988
+ type: 'other';
989
+ description?: string;
990
+ metadata?: Record<string, unknown>;
991
+ }
992
+ type AICallRecord = BaseAICall;
993
+ /**
994
+ * Raw LLM usage data returned by adapters
995
+ * Used as input to AIUsageCollector.record()
996
+ */
997
+ interface LLMUsageData {
998
+ model: LLMModel;
999
+ inputTokens: number;
1000
+ outputTokens: number;
1001
+ latencyMs: number;
1002
+ /** Actual cost from provider in USD (when available, e.g., OpenRouter) */
1003
+ cost?: number;
1004
+ }
1005
+ interface AIUsageSummary {
1006
+ model: LLMModel;
1007
+ totalInputTokens: number;
1008
+ totalOutputTokens: number;
1009
+ totalTokens: number;
1010
+ totalCostUsd: number;
1011
+ callCount: number;
1012
+ calls: AICallRecord[];
1013
+ }
1014
+ interface ExecutionMetricsSummary {
1015
+ durationMs?: number;
1016
+ automationSavingsUsd?: number;
1017
+ }
1018
+ interface ResourceMetricsConfig {
1019
+ estimatedManualMinutes: number;
1020
+ hourlyLaborRateUsd: number;
1021
+ confidenceLevel?: 'low' | 'medium' | 'high';
1022
+ notes?: string;
1023
+ }
1024
+
1025
+ /**
1026
+ * AIUsageCollector
1027
+ * Centralized token tracking that aggregates usage across all LLM calls in an execution
1028
+ */
1029
+ declare class AIUsageCollector {
1030
+ private model;
1031
+ private calls;
1032
+ private callSequence;
1033
+ /**
1034
+ * Record a single AI call with usage metrics
1035
+ *
1036
+ * @param usage - Token usage and latency data from LLM adapter
1037
+ * @param callType - Type discriminator (agent-reasoning, tool, etc.)
1038
+ * @param context - Optional typed context specific to callType
1039
+ */
1040
+ record(usage: LLMUsageData, callType?: BaseAICall['callType'], context?: AICallContext): void;
1041
+ /**
1042
+ * Get aggregated summary of all AI calls
1043
+ */
1044
+ getSummary(): AIUsageSummary;
1045
+ /**
1046
+ * Check if any usage has been recorded
1047
+ */
1048
+ hasUsage(): boolean;
1049
+ }
1050
+
1051
+ /**
1052
+ * Base Execution Engine type definitions
1053
+ * Core types shared across all Execution Engine resources
1054
+ */
1055
+
1056
+ /**
1057
+ * Immutable execution metadata
1058
+ * Represents complete execution identity (who, what, when, where)
1059
+ * Shared across ExecutionContext and ExecutionLoggerContext to eliminate field duplication
1060
+ */
1061
+ interface ExecutionMetadata {
1062
+ executionId: string;
1063
+ organizationId: string;
1064
+ organizationName: string;
1065
+ resourceId: string;
1066
+ userId?: string;
1067
+ sessionId?: string;
1068
+ sessionTurnNumber?: number;
1069
+ }
1070
+ /**
1071
+ * Unified message event type - covers all message types in sessions
1072
+ * Replaces separate SessionTurnMessages and AgentActivityEvent mechanisms
1073
+ */
1074
+ type MessageEvent = {
1075
+ type: 'user_message';
1076
+ text: string;
1077
+ } | {
1078
+ type: 'assistant_message';
1079
+ text: string;
1080
+ } | {
1081
+ type: 'agent:started';
1082
+ } | {
1083
+ type: 'agent:completed';
1084
+ } | {
1085
+ type: 'agent:error';
1086
+ error: string;
1087
+ } | {
1088
+ type: 'agent:reasoning';
1089
+ iteration: number;
1090
+ reasoning: string;
1091
+ } | {
1092
+ type: 'agent:tool_call';
1093
+ toolName: string;
1094
+ args: Record<string, unknown>;
1095
+ } | {
1096
+ type: 'agent:tool_result';
1097
+ toolName: string;
1098
+ success: boolean;
1099
+ result?: unknown;
1100
+ error?: string;
1101
+ };
1102
+ /**
1103
+ * Execution context for all resources
1104
+ * Unified callback replaces SessionTurnMessages (removed)
1105
+ */
1106
+ interface ExecutionContext extends ExecutionMetadata {
1107
+ logger: IExecutionLogger;
1108
+ signal?: AbortSignal;
1109
+ onMessageEvent?: (event: MessageEvent) => Promise<void>;
1110
+ aiUsageCollector?: AIUsageCollector;
1111
+ metricsCollector?: MetricsCollector;
1112
+ parentExecutionId?: string;
1113
+ executionDepth: number;
1114
+ credentialName?: string;
1115
+ store: Map<string, unknown>;
1116
+ }
1117
+ interface Contract {
1118
+ inputSchema: z.ZodSchema;
1119
+ outputSchema?: z.ZodSchema;
1120
+ }
1121
+
1122
+ /**
1123
+ * Tool definitions
1124
+ *
1125
+ * Tool interface used by agents and workflows.
1126
+ * Provides a universal interface for AI systems to interact with tools.
1127
+ */
1128
+
1129
+ /**
1130
+ * Options for tool execution
1131
+ * Provides named parameters for better API clarity and extensibility
1132
+ */
1133
+ interface ToolExecutionOptions {
1134
+ /** Tool input (validated against inputSchema before execution) */
1135
+ input: unknown;
1136
+ /** Execution context with multi-tenant isolation and observability (optional for simple tools, required for platform/integration tools) */
1137
+ executionContext?: ExecutionContext;
1138
+ /** Full iteration context for advanced tools (provides access to memoryManager, toolRegistry, logger, etc.) */
1139
+ iterationContext?: IterationContext;
1140
+ /** Abort signal for timeout/cancellation -- forward to fetch() calls for clean cancellation */
1141
+ signal?: AbortSignal;
1142
+ }
1143
+ /**
1144
+ * Tool interface for AI systems
1145
+ *
1146
+ * Used by:
1147
+ * - Agents: For agentic tool use (reasoning loop selects and executes tools)
1148
+ * - Workflows: For workflow step tool invocation (future)
1149
+ * - Platform tools: createApprovalTool(), createSchedulerTool()
1150
+ * - Integration tools: External API calls (Gmail, Slack, etc.)
1151
+ */
1152
+ interface Tool {
1153
+ name: string;
1154
+ description: string;
1155
+ inputSchema: z.ZodSchema;
1156
+ outputSchema: z.ZodSchema;
1157
+ execute: (options: ToolExecutionOptions) => Promise<unknown>;
1158
+ timeout?: number;
1159
+ }
1160
+ /**
1161
+ * Tooling error types
1162
+ * Used across platform tools and integration tools
1163
+ */
1164
+ type ToolingErrorType = 'service_unavailable' | 'permission_denied' | 'adapter_not_found' | 'method_not_found' | 'tool_not_found' | 'credentials_missing' | 'credentials_invalid' | 'rate_limit_exceeded' | 'server_unavailable' | 'auth_error' | 'api_error' | 'validation_error' | 'network_error' | 'timeout_error' | 'unknown_error';
1165
+ /**
1166
+ * Tooling error class
1167
+ * Provides structured error information for tool failures across all tool types
1168
+ *
1169
+ * Severity mapping:
1170
+ * - critical: credentials_missing, credentials_invalid, permission_denied, auth_error,
1171
+ * adapter_not_found, method_not_found, tool_not_found
1172
+ * - info: validation_error
1173
+ * - warning: All other types (retryable transient errors)
1174
+ *
1175
+ * Category: tool (tool execution errors)
1176
+ */
1177
+ declare class ToolingError extends ExecutionError {
1178
+ readonly errorType: ToolingErrorType;
1179
+ readonly details?: unknown | undefined;
1180
+ readonly type: "tooling_error";
1181
+ readonly category: "tool";
1182
+ constructor(errorType: ToolingErrorType, message: string, details?: unknown | undefined);
1183
+ /**
1184
+ * Derive severity based on error type
1185
+ */
1186
+ get severity(): 'critical' | 'warning' | 'info';
1187
+ /**
1188
+ * Check if error is retryable
1189
+ */
1190
+ isRetryable(): boolean;
1191
+ /**
1192
+ * Convert to JSON for logging
1193
+ */
1194
+ toJSON(): {
1195
+ name: string;
1196
+ type: ToolingErrorType;
1197
+ message: string;
1198
+ severity: "critical" | "warning" | "info";
1199
+ category: "tool";
1200
+ details: unknown;
1201
+ };
1202
+ }
1203
+
1204
+ /**
1205
+ * Supported integration types
1206
+ *
1207
+ * These represent the available integration adapters that can be used with tools.
1208
+ * Each integration type corresponds to an adapter implementation.
1209
+ *
1210
+ * Note: Concrete adapter implementations are deferred until needed.
1211
+ * This type provides compile-time safety and auto-completion for tool definitions.
1212
+ */
1213
+ type IntegrationType = 'gmail' | 'google-sheets' | 'slack' | 'github' | 'linear' | 'notion' | 'attio' | 'airtable' | 'trello' | 'salesforce' | 'hubspot' | 'stripe' | 'twilio' | 'sendgrid' | 'mailgun' | 'zapier' | 'webhook' | 'apify' | 'instantly' | 'resend' | 'signature-api' | 'dropbox' | 'mailso';
1214
+
1215
+ /**
1216
+ * Resource Registry type definitions
1217
+ */
1218
+
1219
+ /**
1220
+ * Environment/deployment status for resources
1221
+ */
1222
+ type ResourceStatus = 'dev' | 'prod';
1223
+ /**
1224
+ * All resource types in the platform
1225
+ * Used as the discriminator field in ResourceDefinition
1226
+ */
1227
+ type ResourceType = 'agent' | 'workflow' | 'pipeline' | 'trigger' | 'integration' | 'external' | 'human';
1228
+ /**
1229
+ * Base interface for ALL platform resources
1230
+ * Shared by both executable (agents, workflows) and non-executable (triggers, integrations, etc.) resources
1231
+ */
1232
+ interface ResourceDefinition {
1233
+ /** Unique resource identifier */
1234
+ resourceId: string;
1235
+ /** Display name */
1236
+ name: string;
1237
+ /** Purpose and functionality description */
1238
+ description: string;
1239
+ /** Version for change tracking and evolution */
1240
+ version: string;
1241
+ /** Resource type discriminator */
1242
+ type: ResourceType;
1243
+ /** Environment/deployment status */
1244
+ status: ResourceStatus;
1245
+ /** Domain tags for filtering and organization */
1246
+ domains?: ResourceDomain[];
1247
+ /** Whether the agent supports multi-turn sessions (agents only) */
1248
+ sessionCapable?: boolean;
1249
+ }
1250
+ /**
1251
+ * Domain definition for Command View filtering
1252
+ *
1253
+ * Domains are organizational metadata for UI filtering/grouping.
1254
+ * No execution impact - purely for visualization.
1255
+ *
1256
+ * @example
1257
+ * {
1258
+ * id: 'support',
1259
+ * name: 'Customer Support',
1260
+ * description: 'Ticket triage, knowledge base, escalations',
1261
+ * color: 'green',
1262
+ * icon: 'IconHeadset'
1263
+ * }
1264
+ */
1265
+ interface DomainDefinition {
1266
+ /** Unique identifier (e.g., 'support') */
1267
+ id: string;
1268
+ /** Display name (e.g., 'Customer Support') */
1269
+ name: string;
1270
+ /** Purpose description */
1271
+ description: string;
1272
+ /** Optional Mantine color for UI (e.g., 'blue', 'green', 'orange') */
1273
+ color?: string;
1274
+ /** Optional Tabler icon name (e.g., 'IconHeadset') */
1275
+ icon?: string;
1276
+ }
1277
+ /** Webhook provider identifiers */
1278
+ type WebhookProviderType = 'cal-com' | 'fillout' | 'stripe' | 'signature-api' | 'instantly' | 'test';
1279
+ /** Webhook trigger configuration */
1280
+ interface WebhookTriggerConfig {
1281
+ /** Provider identifier */
1282
+ provider: WebhookProviderType;
1283
+ /** Event type for documentation (not used for matching - workflow handles routing) */
1284
+ event?: string;
1285
+ /** Optional filtering (e.g., specific form ID for Fillout) */
1286
+ filter?: Record<string, string>;
1287
+ /** References credential in credentials table for per-org webhook secrets */
1288
+ credentialName?: string;
1289
+ }
1290
+ /** Schedule trigger configuration */
1291
+ interface ScheduleTriggerConfig {
1292
+ /** Cron expression (e.g., '0 6 * * *') */
1293
+ cron: string;
1294
+ /** Optional timezone (default: UTC) */
1295
+ timezone?: string;
1296
+ }
1297
+ /** Event trigger configuration */
1298
+ interface EventTriggerConfig {
1299
+ /** Internal event type */
1300
+ eventType: string;
1301
+ /** Event source */
1302
+ source?: string;
1303
+ }
1304
+ /** Union of all trigger configs */
1305
+ type TriggerConfig = WebhookTriggerConfig | ScheduleTriggerConfig | EventTriggerConfig;
1306
+ /**
1307
+ * Trigger metadata - entry points that initiate resource execution
1308
+ *
1309
+ * Triggers represent how executions start: webhooks from external services,
1310
+ * scheduled cron jobs, platform events, or manual user actions.
1311
+ *
1312
+ * BREAKING CHANGES (2025-11-30):
1313
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
1314
+ * - Field renames: `id` -> `resourceId` (inherited), `type` -> `triggerType`
1315
+ * - Relationship rename: `invokes` -> `triggers` (unified vocabulary)
1316
+ * - New required fields: `version` (inherited), `type: 'trigger'` (inherited)
1317
+ * - triggers object now includes `externalResources` option
1318
+ *
1319
+ * @example
1320
+ * // TriggerDefinition - metadata only
1321
+ * {
1322
+ * resourceId: 'trigger-new-order',
1323
+ * type: 'trigger',
1324
+ * triggerType: 'webhook',
1325
+ * name: 'New Order',
1326
+ * description: 'Webhook from Shopify on new orders',
1327
+ * version: '1.0.0',
1328
+ * status: 'prod',
1329
+ * webhookPath: '/webhooks/shopify/orders'
1330
+ * }
1331
+ *
1332
+ * // Relationships declared in ResourceRelationships (not on TriggerDefinition):
1333
+ * // relationships: {
1334
+ * // 'trigger-new-order': { triggers: { workflows: ['order-fulfillment-workflow'] } }
1335
+ * // }
1336
+ */
1337
+ interface TriggerDefinition extends ResourceDefinition {
1338
+ /** Resource type discriminator (narrowed from base union) */
1339
+ type: 'trigger';
1340
+ /** Trigger mechanism type (renamed from 'type' to avoid collision with base type discriminator) */
1341
+ triggerType: 'webhook' | 'schedule' | 'manual' | 'event';
1342
+ /** Type-specific configuration */
1343
+ config?: TriggerConfig;
1344
+ /** For webhook triggers: path like '/webhooks/shopify/orders' */
1345
+ webhookPath?: string;
1346
+ /** For schedule triggers: cron expression like '0 6 * * *' */
1347
+ schedule?: string;
1348
+ /** For event triggers: event type like 'low-stock-alert' */
1349
+ eventType?: string;
1350
+ }
1351
+ /**
1352
+ * Integration metadata - external service connections
1353
+ *
1354
+ * References credentials table for actual connection. No connection status
1355
+ * stored here (queried at runtime from credentials table).
1356
+ *
1357
+ * BREAKING CHANGES (2025-11-30):
1358
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
1359
+ * - Field renames: `id` -> `resourceId` (inherited)
1360
+ * - New required field: `status` (inherited) - organizations must add status to all integrations
1361
+ * - New required field: `version` (inherited) - organizations must add version to all integrations
1362
+ * - New required field: `type: 'integration'` (inherited) - resource type discriminator
1363
+ *
1364
+ * @example
1365
+ * {
1366
+ * resourceId: 'integration-shopify-prod',
1367
+ * type: 'integration',
1368
+ * provider: 'shopify',
1369
+ * credentialName: 'shopify-prod',
1370
+ * name: 'Shopify Production',
1371
+ * description: 'E-commerce platform',
1372
+ * version: '1.0.0',
1373
+ * status: 'prod'
1374
+ * }
1375
+ */
1376
+ interface IntegrationDefinition extends ResourceDefinition {
1377
+ /** Resource type discriminator (narrowed from base union) */
1378
+ type: 'integration';
1379
+ /** Integration provider type */
1380
+ provider: IntegrationType;
1381
+ /** References credentials table (e.g., 'shopify-prod', 'zendesk-api') */
1382
+ credentialName: string;
1383
+ }
1384
+ /**
1385
+ * Explicit resource relationship declaration
1386
+ *
1387
+ * Single-direction only - Command View derives reverse relationships.
1388
+ * Agents/workflows declare what they trigger and use.
1389
+ *
1390
+ * @example
1391
+ * {
1392
+ * triggers: { workflows: ['order-fulfillment-workflow'] },
1393
+ * uses: { integrations: ['integration-shopify-prod', 'integration-postgres'] }
1394
+ * }
1395
+ */
1396
+ interface RelationshipDeclaration {
1397
+ /** Resources this resource triggers */
1398
+ triggers?: {
1399
+ /** Agent resourceIds this resource triggers */
1400
+ agents?: string[];
1401
+ /** Workflow resourceIds this resource triggers */
1402
+ workflows?: string[];
1403
+ };
1404
+ /** Integrations this resource uses */
1405
+ uses?: {
1406
+ /** Integration IDs this resource uses */
1407
+ integrations?: string[];
1408
+ };
1409
+ }
1410
+ /**
1411
+ * Resource relationships map
1412
+ * Maps resourceId to its relationship declarations
1413
+ *
1414
+ * @example
1415
+ * {
1416
+ * 'order-processor-agent': {
1417
+ * triggers: { workflows: ['order-fulfillment-workflow'] },
1418
+ * uses: { integrations: ['integration-shopify-prod'] }
1419
+ * }
1420
+ * }
1421
+ */
1422
+ type ResourceRelationships = Record<string, RelationshipDeclaration>;
1423
+ /**
1424
+ * External platform type
1425
+ * Supported third-party automation platforms
1426
+ */
1427
+ type ExternalPlatform = 'n8n' | 'make' | 'zapier' | 'other';
1428
+ /**
1429
+ * External automation resource metadata
1430
+ *
1431
+ * Represents workflows/automations running on third-party platforms
1432
+ * (n8n, Make, Zapier, etc.) for visualization in Command View.
1433
+ *
1434
+ * NOTE: This is metadata ONLY for visualization. No execution logic,
1435
+ * no API integration with external platforms, no status syncing.
1436
+ *
1437
+ * BREAKING CHANGES (2025-11-30):
1438
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
1439
+ * - Field renames: `id` -> `resourceId` (inherited)
1440
+ * - New required field: `version` (inherited) - organizations must add version to all external resources
1441
+ * - New required field: `type: 'external'` (inherited) - resource type discriminator
1442
+ * - REMOVED FIELD: `triggeredBy` - per relationship-consolidation design, all relationships are forward-only declarations
1443
+ *
1444
+ * @example
1445
+ * {
1446
+ * resourceId: 'external-n8n-order-sync',
1447
+ * type: 'external',
1448
+ * version: '1.0.0',
1449
+ * platform: 'n8n',
1450
+ * name: 'Shopify Order Sync',
1451
+ * description: 'Legacy n8n workflow for syncing Shopify orders',
1452
+ * status: 'prod',
1453
+ * platformUrl: 'https://n8n.client.com/workflow/123',
1454
+ * triggers: { workflows: ['order-fulfillment-workflow'] },
1455
+ * uses: { integrations: ['integration-shopify-prod'] }
1456
+ * }
1457
+ */
1458
+ interface ExternalResourceDefinition extends ResourceDefinition {
1459
+ /** Resource type discriminator (narrowed from base union) */
1460
+ type: 'external';
1461
+ /** Platform type */
1462
+ platform: ExternalPlatform;
1463
+ /** Link to external platform (e.g., n8n workflow editor URL) */
1464
+ platformUrl?: string;
1465
+ /** Platform's internal ID/reference */
1466
+ externalId?: string;
1467
+ /** What this external resource triggers (external -> internal) */
1468
+ triggers?: {
1469
+ /** Elevasis workflow resourceIds this external automation triggers */
1470
+ workflows?: string[];
1471
+ /** Elevasis agent resourceIds this external automation triggers */
1472
+ agents?: string[];
1473
+ };
1474
+ /** Integrations this external resource uses (shared credentials) */
1475
+ uses?: {
1476
+ /** Integration IDs this external automation uses */
1477
+ integrations?: string[];
1478
+ };
1479
+ }
1480
+ /**
1481
+ * Human Checkpoint definition - human decision points in automation
1482
+ *
1483
+ * Represents where human judgment is deployed in the automation landscape.
1484
+ * Tasks with matching command_queue_group are routed to this checkpoint.
1485
+ *
1486
+ * BREAKING CHANGES (2025-11-30):
1487
+ * - Now extends ResourceDefinition (inherits: resourceId, name, description, version, type, status, domains)
1488
+ * - Field renames: `id` -> `resourceId` (inherited)
1489
+ * - description is now REQUIRED (was optional) - organizations must add description to all human checkpoints
1490
+ * - New required field: `version` (inherited) - organizations must add version to all human checkpoints
1491
+ * - New required field: `type: 'human'` (inherited) - resource type discriminator
1492
+ *
1493
+ * @example
1494
+ * {
1495
+ * resourceId: 'sales-approval',
1496
+ * type: 'human',
1497
+ * name: 'Sales Approval Queue',
1498
+ * description: 'High-value order approvals for sales team',
1499
+ * version: '1.0.0',
1500
+ * status: 'prod',
1501
+ * requestedBy: { agents: ['order-processor-agent'] },
1502
+ * routesTo: { agents: ['order-fulfillment-agent'] }
1503
+ * }
1504
+ */
1505
+ interface HumanCheckpointDefinition extends ResourceDefinition {
1506
+ /** Resource type discriminator (narrowed from base union) */
1507
+ type: 'human';
1508
+ /** Resources that create tasks for this checkpoint */
1509
+ requestedBy?: {
1510
+ /** Agent resourceIds that request approval here */
1511
+ agents?: string[];
1512
+ /** Workflow resourceIds that request approval here */
1513
+ workflows?: string[];
1514
+ };
1515
+ /** Resources that receive approved decisions */
1516
+ routesTo?: {
1517
+ /** Agent resourceIds that handle approved tasks */
1518
+ agents?: string[];
1519
+ /** Workflow resourceIds that handle approved tasks */
1520
+ workflows?: string[];
1521
+ };
1522
+ }
1523
+
1524
+ /**
1525
+ * Standard Domain Definitions
1526
+ * Centralized domain constants and definitions for all organization resources.
1527
+ */
1528
+
1529
+ declare const DOMAINS: {
1530
+ readonly ACQUISITION: "acquisition";
1531
+ readonly SUPPORT: "support";
1532
+ readonly DELIVERY: "delivery";
1533
+ readonly OPERATIONS: "operations";
1534
+ readonly FINANCE: "finance";
1535
+ readonly EXECUTIVE: "executive";
1536
+ readonly TESTING: "testing";
1537
+ readonly INTERNAL: "internal";
1538
+ readonly INTEGRATION: "integration";
1539
+ readonly UTILITY: "utility";
1540
+ readonly DIAGNOSTIC: "diagnostic";
1541
+ };
1542
+ /**
1543
+ * ResourceDomain - Strongly typed domain identifier
1544
+ * Use this type for all domain references to ensure compile-time validation.
1545
+ */
1546
+ type ResourceDomain = (typeof DOMAINS)[keyof typeof DOMAINS];
1547
+
1548
+ /**
1549
+ * Project configuration for an external developer project.
1550
+ * Defined in elevas.config.ts at the project root.
1551
+ */
1552
+ interface ElevasConfig {
1553
+ organization: string;
1554
+ defaultStatus?: ResourceStatus;
1555
+ dev?: {
1556
+ port?: number;
1557
+ };
1558
+ }
1559
+
1560
+ export { ExecutionError, StepType, ToolingError };
1561
+ export type { AgentConfig, AgentConstraints, AgentDefinition, ConditionalNext, Contract, DomainDefinition, ElevasConfig, EventTriggerConfig, ExecutionContext, ExecutionInterface, ExecutionMetadata, FormField, FormFieldType, FormSchema, IntegrationDefinition, LLMModel, LinearNext, ModelConfig, NextConfig, OrganizationResources, ResourceDefinition, ResourceDomain, ResourceMetricsConfig, ResourceStatus, ResourceType, ScheduleTriggerConfig, StepHandler, Tool, ToolExecutionOptions, ToolingErrorType, TriggerConfig, TriggerDefinition, WebhookProviderType, WebhookTriggerConfig, WorkflowConfig, WorkflowDefinition, WorkflowStep };