@elevasis/core 0.12.0 → 0.13.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.
@@ -1,700 +1,699 @@
1
- /**
2
- *
3
- * Tool Services Registry
4
- * Global singleton registry for tool services (command queue, task scheduler, integrations)
5
- *
6
- * Pattern: Global registry with initialization safety
7
- * - Initialized once at server startup (apps/api/src/main.ts)
8
- * - Tools import getToolServices() directly (no dependency injection)
9
- * - Fail-fast behavior if not initialized
10
- */
11
-
12
- import type { CreateTaskParams, Task } from '../../../commands/queue/types'
13
- import type { CreateScheduleInput, TaskSchedule } from '../../scheduler/types'
14
- import type { CreateNotificationParams, Notification } from '../../../operations/notifications/types'
15
- import type { ILeadService } from './lead-service-types'
16
- import type { ExecutionContext } from '../base/types'
17
- import type {
18
- ProjectRow,
19
- ProjectWithCounts,
20
- ProjectDetail,
21
- MilestoneRow,
22
- TaskRow,
23
- NoteRow
24
- } from '../../../business/projects'
25
- import type { DealListItem, DealDetail, DealStage, ListDealsQuery } from '../../../business/acquisition'
26
- import type { RecentActivityEntry } from '../../../business/sales/api-schemas'
27
- import type { Database } from '../../../supabase/database.types'
28
-
29
- /**
30
- * Service interfaces for platform tools
31
- *
32
- * IMPORTANT: These interfaces define the contract that services must implement
33
- * Actual service implementations live in apps/api/
34
- * TypeScript structural typing ensures compatibility without circular dependencies
35
- */
36
- export interface ICommandQueueService {
37
- /**
38
- * Create approval/rejection task
39
- * @see CommandQueueService.createTask (apps/api/src/command-queue/service.ts:23)
40
- */
41
- createTask(params: CreateTaskParams): Promise<Task>
42
-
43
- /**
44
- * Delete pending HITL tasks matching metadata filter
45
- * Uses JSONB containment (.contains()) for metadata-based batch deletion
46
- * @see CommandQueueService.deleteByMetadata (apps/api/src/commands/queue/service.ts)
47
- */
48
- deleteByMetadata(
49
- organizationId: string,
50
- metadata: Record<string, unknown>,
51
- status?: string
52
- ): Promise<{ deleted: number }>
53
- }
54
-
55
- export interface ITaskSchedulerService {
56
- /**
57
- * Create a unified schedule
58
- * @see TaskScheduleService.createSchedule (apps/api/src/task-scheduler/service.ts:190)
59
- */
60
- createSchedule(input: CreateScheduleInput): Promise<TaskSchedule>
61
-
62
- /**
63
- * Update anchor time for a relative schedule (used for rescheduling)
64
- * @see TaskScheduleService.updateAnchor (apps/api/src/task-scheduler/service.ts)
65
- */
66
- updateAnchor(id: string, organizationId: string, anchorAt: string): Promise<TaskSchedule>
67
-
68
- /**
69
- * Delete (cancel) a schedule
70
- * @see TaskScheduleService.deleteSchedule (apps/api/src/task-scheduler/service.ts)
71
- */
72
- deleteSchedule(id: string, organizationId: string): Promise<void>
73
-
74
- /**
75
- * Find schedule by idempotency key
76
- * @see TaskScheduleService.findByIdempotencyKey (apps/api/src/task-scheduler/service.ts)
77
- */
78
- findByIdempotencyKey(organizationId: string, idempotencyKey: string): Promise<TaskSchedule | null>
79
-
80
- /**
81
- * Delete (cancel) schedule by idempotency key
82
- * Finds schedule by key and cancels it. No-op if schedule not found.
83
- * @see TaskScheduleService.deleteScheduleByIdempotencyKey (apps/api/src/task-scheduler/service.ts)
84
- */
85
- deleteScheduleByIdempotencyKey(idempotencyKey: string, organizationId: string): Promise<void>
86
-
87
- /**
88
- * Cancel a schedule by idempotency key (soft delete)
89
- * Finds schedule by key and sets status to 'cancelled'. No-op if not found.
90
- * @see TaskScheduleService.cancelScheduleByIdempotencyKey (apps/api/src/execution/task-scheduler/service.ts)
91
- */
92
- cancelScheduleByIdempotencyKey(idempotencyKey: string, organizationId: string): Promise<{ cancelled: boolean }>
93
-
94
- /**
95
- * List schedules with optional metadata filtering
96
- * Supports JSONB containment for metadata-based queries
97
- * @see TaskScheduleService.listSchedules (apps/api/src/execution/task-scheduler/service.ts)
98
- */
99
- listSchedules(params: {
100
- organizationId: string
101
- targetResourceId?: string
102
- status?: string
103
- metadata?: Record<string, unknown>
104
- limit?: number
105
- offset?: number
106
- }): Promise<{ schedules: TaskSchedule[]; total: number }>
107
-
108
- /**
109
- * Get a single schedule by ID
110
- * @see TaskScheduleService.getSchedule (apps/api/src/execution/task-scheduler/service.ts)
111
- */
112
- getSchedule(id: string, organizationId: string): Promise<TaskSchedule | null>
113
-
114
- /**
115
- * Cancel a schedule (soft delete - sets status to 'cancelled')
116
- * @see TaskScheduleService.cancelSchedule (apps/api/src/execution/task-scheduler/service.ts)
117
- */
118
- cancelSchedule(id: string, organizationId: string): Promise<TaskSchedule>
119
-
120
- /**
121
- * Cancel all schedules matching metadata filter (batch soft delete)
122
- * Uses JSONB containment (.contains()) for metadata-based filtering
123
- * @see TaskScheduleService.cancelSchedulesByMetadata (apps/api/src/execution/task-scheduler/service.ts)
124
- */
125
- cancelSchedulesByMetadata(
126
- organizationId: string,
127
- metadata: Record<string, unknown>,
128
- status?: string
129
- ): Promise<{ cancelled: number }>
130
- }
131
-
132
- export interface INotificationsService {
133
- /**
134
- * Create platform notification for user
135
- * @see NotificationService.create (apps/api/src/notifications/service.ts:17)
136
- */
137
- create(params: CreateNotificationParams): Promise<Notification>
138
- }
139
-
140
- export interface ICrmService {
141
- getRecentActivity(organizationId: string, limit: number): Promise<RecentActivityEntry[]>
142
- listDeals(organizationId: string, filters?: Partial<ListDealsQuery>): Promise<DealListItem[]>
143
- getDeal(dealId: string, organizationId: string): Promise<DealDetail | null>
144
- getDealByEmail(email: string, organizationId: string): Promise<DealDetail | null>
145
- updateDealStage(dealId: string, organizationId: string, stage: DealStage): Promise<void>
146
- createDealNote(
147
- params: import('./lead-service-types').CreateDealNoteParams
148
- ): Promise<import('./lead-service-types').AcqDealNote>
149
- listDealNotes(
150
- params: import('./lead-service-types').ListDealNotesParams
151
- ): Promise<import('./lead-service-types').AcqDealNote[]>
152
- createDealTask(
153
- params: import('./lead-service-types').CreateDealTaskParams
154
- ): Promise<import('./lead-service-types').AcqDealTask>
155
- listDealTasks(
156
- params: import('./lead-service-types').ListDealTasksParams
157
- ): Promise<import('./lead-service-types').AcqDealTask[]>
158
- listDealTasksDue(
159
- params: import('./lead-service-types').ListDealTasksDueParams
160
- ): Promise<import('./lead-service-types').AcqDealTask[]>
161
- completeDealTask(
162
- params: import('./lead-service-types').CompleteDealTaskParams
163
- ): Promise<import('./lead-service-types').AcqDealTask>
164
- recordActivity(params: import('./lead-service-types').RecordDealActivityParams): Promise<void>
165
- deleteDeal(params: import('./lead-service-types').DeleteDealParams): Promise<void>
166
- }
167
-
168
- type ProjectInsert = Database['public']['Tables']['prj_projects']['Insert']
169
- type ProjectUpdate = Database['public']['Tables']['prj_projects']['Update']
170
- type MilestoneInsert = Database['public']['Tables']['prj_milestones']['Insert']
171
- type MilestoneUpdate = Database['public']['Tables']['prj_milestones']['Update']
172
- type TaskInsert = Database['public']['Tables']['prj_tasks']['Insert']
173
- type TaskUpdate = Database['public']['Tables']['prj_tasks']['Update']
174
- type NoteInsert = Database['public']['Tables']['prj_notes']['Insert']
175
- type NoteUpdate = Database['public']['Tables']['prj_notes']['Update']
176
- type TaskResumeContextRow = Pick<TaskRow, 'id' | 'resume_context' | 'updated_at'>
177
- type DeleteEntityResult = { id: string; project_id: string }
178
-
179
- export interface IProjectsService {
180
- listProjects(
181
- organizationId: string,
182
- filters?: {
183
- kind?: string
184
- status?: string
185
- }
186
- ): Promise<ProjectWithCounts[]>
187
- getProject(id: string, organizationId: string): Promise<ProjectDetail | null>
188
- createProject(input: Omit<ProjectInsert, 'organization_id'> & { organizationId: string }): Promise<ProjectRow>
189
- updateProject(
190
- id: string,
191
- organizationId: string,
192
- input: Omit<ProjectUpdate, 'organization_id'>
193
- ): Promise<ProjectRow | null>
194
- deleteProject(id: string, organizationId: string): Promise<boolean>
195
- listMilestones(projectId: string, organizationId: string): Promise<MilestoneRow[]>
196
- createMilestone(
197
- input: Omit<MilestoneInsert, 'organization_id' | 'project_id'> & {
198
- organizationId: string
199
- projectId: string
200
- }
201
- ): Promise<MilestoneRow>
202
- updateMilestone(
203
- id: string,
204
- organizationId: string,
205
- input: Omit<MilestoneUpdate, 'organization_id'>
206
- ): Promise<MilestoneRow | null>
207
- deleteMilestone(id: string, organizationId: string): Promise<DeleteEntityResult | null>
208
- listTasks(
209
- projectId: string,
210
- organizationId: string,
211
- filters?: {
212
- status?: string
213
- milestone_id?: string
214
- parent_task_id?: string
215
- }
216
- ): Promise<TaskRow[]>
217
- getTask(id: string, organizationId: string): Promise<TaskRow | null>
218
- createTask(input: Omit<TaskInsert, 'organization_id'> & { organizationId: string }): Promise<TaskRow>
219
- updateTask(id: string, organizationId: string, input: Omit<TaskUpdate, 'organization_id'>): Promise<TaskRow | null>
220
- deleteTask(id: string, organizationId: string): Promise<DeleteEntityResult | null>
221
- mergeTaskResumeContext(
222
- id: string,
223
- organizationId: string,
224
- incoming: Record<string, unknown>
225
- ): Promise<TaskResumeContextRow | null>
226
- listNotes(projectId: string, organizationId: string): Promise<NoteRow[]>
227
- createNote(input: Omit<NoteInsert, 'organization_id'> & { organizationId: string }): Promise<NoteRow>
228
- updateNote(id: string, organizationId: string, input: Omit<NoteUpdate, 'organization_id'>): Promise<NoteRow | null>
229
- deleteNote(id: string, organizationId: string): Promise<DeleteEntityResult | null>
230
- }
231
-
232
- // =============================================================================
233
- // Platform Email Service Types
234
- // =============================================================================
235
-
236
- /**
237
- * Parameters for sending platform emails
238
- * Supports three targeting modes: explicit userIds, role-based, or broadcast
239
- */
240
- export interface SendPlatformEmailParams {
241
- organizationId: string
242
-
243
- // Targeting (exactly one required)
244
- userIds?: string[] // Explicit: specific users
245
- targetRole?: string // Role-based: users with role
246
- targetAll?: boolean // Broadcast: all org members
247
-
248
- // Content
249
- subject: string
250
- html?: string
251
- text?: string
252
-
253
- // Optional
254
- replyTo?: string
255
- tags?: Array<{ name: string; value: string }>
256
- }
257
-
258
- /**
259
- * Result of platform email send operation
260
- * Follows partial success pattern (similar to BatchProcessResult)
261
- */
262
- export interface EmailResult {
263
- sent: number // Successfully sent
264
- failed: number // Failed to send
265
- errors?: Array<{
266
- // Only if failed > 0
267
- userId: string
268
- email: string
269
- error: string
270
- }>
271
- }
272
-
273
- /**
274
- * Platform email service interface
275
- * Sends transactional emails from notifications@elevasis.io using platform Resend credentials
276
- *
277
- * Implementation: apps/api/src/email/service.ts (EmailService class)
278
- *
279
- * Multi-tenancy: All operations require organizationId for tenant isolation.
280
- * User targeting queries filtered by organizationId via org_memberships join.
281
- */
282
- export interface IEmailService {
283
- /**
284
- * Send platform email to targeted users within an organization
285
- *
286
- * Targeting modes (exactly one required):
287
- * - userIds: Send to specific users (verified against org membership)
288
- * - targetRole: Send to users with specific role
289
- * - targetAll: Send to all org members
290
- *
291
- * @param params - Email parameters including targeting and content
292
- * @returns Result with sent/failed counts and optional errors array
293
- * @throws Error if no targeting specified or all userIds invalid
294
- * @see EmailService.send (apps/api/src/email/service.ts)
295
- */
296
- send(params: SendPlatformEmailParams): Promise<EmailResult>
297
- }
298
-
299
- /**
300
- * Credentials service interface
301
- * Provides access to organization credentials for integration tools
302
- *
303
- * Implementation: apps/api/src/multi-tenancy/credentials/service.ts (CredentialsService class)
304
- *
305
- * Note: Integration tools only need getCredential() method.
306
- * Other methods (createCredential, listCredentials, deleteCredential) exist in the implementation
307
- * but are only used by API handlers.
308
- */
309
- export interface ICredentialsService {
310
- /**
311
- * Get decrypted credential for organization and integration
312
- * @param organizationId - Organization ID from ExecutionContext
313
- * @param credentialName - Integration name (e.g., 'gmail', 'slack')
314
- * @param environment - Optional environment filter ('development' | 'production')
315
- * @returns Decrypted credential object or null if not found
316
- * @see CredentialsService.getCredential (apps/api/src/multi-tenancy/credentials/service.ts:41-57)
317
- */
318
- getCredential(
319
- organizationId: string,
320
- credentialName: string,
321
- environment?: 'development' | 'production'
322
- ): Promise<Record<string, unknown> | null>
323
- }
324
-
325
- // =============================================================================
326
- // Platform Storage Service Types
327
- // =============================================================================
328
-
329
- /**
330
- * Parameters for storage upload
331
- */
332
- export interface StorageUploadParams {
333
- organizationId: string
334
- bucket: string
335
- path: string
336
- file: Buffer | Blob
337
- contentType: string
338
- upsert?: boolean
339
- }
340
-
341
- /**
342
- * Parameters for storage download/delete
343
- */
344
- export interface StorageDownloadParams {
345
- organizationId: string
346
- bucket: string
347
- path: string
348
- }
349
-
350
- /**
351
- * Parameters for creating signed URL
352
- */
353
- export interface StorageSignedUrlParams {
354
- organizationId: string
355
- bucket: string
356
- path: string
357
- expiresIn: number // seconds
358
- }
359
-
360
- /**
361
- * Result of storage upload operation
362
- */
363
- export interface StorageUploadResult {
364
- path: string
365
- fullPath: string
366
- size: number
367
- }
368
-
369
- /**
370
- * Result of signed URL creation
371
- */
372
- export interface StorageSignedUrlResult {
373
- signedUrl: string
374
- path: string
375
- expiresAt: Date
376
- }
377
-
378
- /**
379
- * Storage service interface for platform storage tools
380
- * Provides org-scoped file storage using Supabase Storage
381
- *
382
- * Implementation: apps/api/src/storage/service.ts (StorageService class)
383
- *
384
- * Multi-tenancy: All paths prefixed with organizationId for tenant isolation.
385
- * RLS policies enforce access at storage.objects level.
386
- */
387
- export interface IStorageService {
388
- /**
389
- * Upload file to org-scoped path
390
- * Path format: {organizationId}/{path}
391
- * @see StorageService.upload (apps/api/src/storage/service.ts)
392
- */
393
- upload(params: StorageUploadParams): Promise<StorageUploadResult>
394
-
395
- /**
396
- * Download file from org-scoped path
397
- * @see StorageService.download (apps/api/src/storage/service.ts)
398
- */
399
- download(params: StorageDownloadParams): Promise<Blob>
400
-
401
- /**
402
- * Create signed URL for temporary access
403
- * @see StorageService.createSignedUrl (apps/api/src/storage/service.ts)
404
- */
405
- createSignedUrl(params: StorageSignedUrlParams): Promise<StorageSignedUrlResult>
406
-
407
- /**
408
- * Delete file from org-scoped path
409
- * @see StorageService.delete (apps/api/src/storage/service.ts)
410
- */
411
- delete(params: StorageDownloadParams): Promise<void>
412
-
413
- /**
414
- * List files in org-scoped path
415
- * @see StorageService.list (apps/api/src/storage/service.ts)
416
- */
417
- list(params: { organizationId: string; bucket: string; prefix?: string }): Promise<string[]>
418
- }
419
-
420
- /**
421
- * Integration service interface
422
- * Provides access to external API integrations (Gmail, Slack, etc.)
423
- *
424
- * Implementation: packages/core/src/execution-engine/tools/integration/service.ts
425
- *
426
- * Interface Segregation Principle: Only exposes call() method used by consumers.
427
- * Internal state (adapters, rateLimiter, retryPolicy) hidden from interface.
428
- */
429
- export interface IIntegrationService {
430
- /**
431
- * Call integration method with full orchestration
432
- *
433
- * Orchestrates: rate limiting, credential retrieval, validation, retry
434
- *
435
- * @param integration - Integration adapter type (e.g., 'gmail', 'slack')
436
- * @param method - Method name (e.g., 'sendEmail', 'postMessage')
437
- * @param params - Method parameters
438
- * @param credentialName - Credential name from credentials table
439
- * @param context - Execution context (required for multi-tenant isolation)
440
- * @returns Method result
441
- * @throws ToolingError if call fails
442
- */
443
- call(
444
- integration: string,
445
- method: string,
446
- params: unknown,
447
- credentialName: string,
448
- context?: ExecutionContext
449
- ): Promise<unknown>
450
- }
451
-
452
- // =============================================================================
453
- // PDF Service Types
454
- // =============================================================================
455
-
456
- /**
457
- * PDF document structure (schema-driven)
458
- * Full type definition lives in packages/core/src/pdf/types.ts
459
- * Using Record<string, unknown> here to avoid circular dependencies
460
- */
461
- export interface PdfRenderParams {
462
- organizationId: string
463
- /** Document structure with pages and content blocks */
464
- document: Record<string, unknown>
465
- /** Optional theme override (partial merge with default theme) */
466
- theme?: Record<string, unknown>
467
- /** Storage destination for rendered PDF */
468
- storage: {
469
- bucket: string
470
- path: string
471
- }
472
- }
473
-
474
- /**
475
- * Result of PDF render operation
476
- */
477
- export interface PdfRenderResult {
478
- success: boolean
479
- /** Signed URL for accessing the rendered PDF */
480
- pdfUrl: string
481
- /** PDF file size in bytes */
482
- size: number
483
- }
484
-
485
- /**
486
- * PDF service interface for rendering documents
487
- * Provides pdfmake-based document rendering with optional storage upload
488
- *
489
- * Implementation: packages/core/src/pdf/server/pdfmake-service.ts (PdfMakeService class)
490
- *
491
- * Multi-tenancy: organizationId used for storage path prefixing.
492
- * All PDFs stored under org-scoped paths via StorageService.
493
- */
494
- export interface IPdfService {
495
- /**
496
- * Render PDF document and upload to storage
497
- *
498
- * Flow:
499
- * 1. Parse document structure
500
- * 2. Merge theme with defaults
501
- * 3. Render via pdfmake
502
- * 4. Upload to storage via StorageService
503
- * 5. Return signed URL
504
- *
505
- * @param params - Render parameters including document, theme, and storage destination
506
- * @returns Result with signed URL and file size
507
- * @throws Error if rendering fails or storage upload fails
508
- * @see PdfMakeService.render (packages/core/src/pdf/server/pdfmake-service.ts)
509
- */
510
- render(params: PdfRenderParams): Promise<PdfRenderResult>
511
-
512
- /**
513
- * Render PDF document to buffer (no storage upload)
514
- *
515
- * Use this for testing or when you need to handle storage upload separately.
516
- *
517
- * @param params - Render parameters (organizationId, document, optional theme)
518
- * @returns Buffer containing the PDF
519
- * @throws Error if rendering fails
520
- * @see PdfMakeService.renderToBuffer (packages/core/src/pdf/server/pdfmake-service.ts)
521
- */
522
- renderToBuffer(params: Omit<PdfRenderParams, 'storage'>): Promise<Buffer>
523
- }
524
-
525
- // =============================================================================
526
- // Lead Service Types (extracted to lead-service-types.ts)
527
- // =============================================================================
528
- export {
529
- type AcqList,
530
- type AcqCompany,
531
- type AcqContact,
532
- type PaginationParams,
533
- type PaginatedResult,
534
- type CreateListParams,
535
- type UpdateListParams,
536
- type CreateCompanyParams,
537
- type UpdateCompanyParams,
538
- type UpsertCompanyParams,
539
- type CompanyFilters,
540
- type CreateContactParams,
541
- type UpdateContactParams,
542
- type UpsertContactParams,
543
- type ContactFilters,
544
- type UpsertDealParams,
545
- type AcqDeal,
546
- type DealActivityEntry,
547
- type AddContactsToListParams,
548
- type AddContactsToListResult,
549
- type BulkImportParams,
550
- type BulkImportResult,
551
- type BulkImportCompanyEntry,
552
- type BulkImportCompaniesParams,
553
- type BulkImportCompaniesResult,
554
- type DeactivateContactsByCompanyParams,
555
- type DeactivateContactsByCompanyResult,
556
- type ILeadService,
557
- type UpdateDiscoveryDataParams,
558
- type UpdateProposalDataParams,
559
- type MarkProposalSentParams,
560
- type MarkProposalReviewedParams,
561
- type UpdateCloseLostReasonParams,
562
- type UpdateFeesParams,
563
- type SyncDealStageParams,
564
- type SetContactNurtureParams,
565
- type CancelSchedulesAndHitlByEmailParams,
566
- type CancelHitlByDealIdParams,
567
- type ClearDealFieldsParams,
568
- type DeleteDealParams,
569
- type DealFilters,
570
- type DealStageSummary,
571
- type StaleDeal,
572
- type DealPipelineAnalytics,
573
- type DealAnalyticsParams,
574
- type UpsertSocialPostParams,
575
- type UpsertSocialPostsParams,
576
- type UpsertSocialPostsResult,
577
- type AcqDealNote,
578
- type CreateDealNoteParams,
579
- type ListDealNotesParams,
580
- type AcqDealTask,
581
- type AcqDealTaskKind,
582
- type CreateDealTaskParams,
583
- type ListDealTasksParams,
584
- type ListDealTasksDueParams,
585
- type CompleteDealTaskParams,
586
- type RecordDealActivityParams,
587
- type GetDealByIdParams,
588
- type GetContactByIdParams,
589
- type GetCompanyByIdParams,
590
- type UpdateListConfigParams,
591
- type UpdateCompanyStageParams,
592
- type UpdateContactStageParams,
593
- type AddCompaniesToListParams,
594
- type AddCompaniesToListResult,
595
- type RemoveCompaniesFromListParams,
596
- type RemoveCompaniesFromListResult,
597
- type RecordListExecutionParams,
598
- type ListExecutionSummary
599
- } from './lead-service-types'
600
-
601
- /**
602
- * Tool services registry
603
- * Contains all services available to tools
604
- */
605
- export interface ToolServices {
606
- commandQueueService: ICommandQueueService | null
607
- taskSchedulerService: ITaskSchedulerService | null
608
- notificationsService: INotificationsService | null
609
- projectsService?: IProjectsService | null
610
- crmService?: ICrmService | null
611
- emailService: IEmailService | null
612
- credentialsService: ICredentialsService | null
613
- integrationService: IIntegrationService | null
614
- leadService: ILeadService | null
615
- storageService: IStorageService | null
616
- /** PDF rendering service - optional for gradual adoption */
617
- pdfService?: IPdfService | null
618
- }
619
-
620
- /**
621
- * Global registry for tool services
622
- * Ensures services are initialized before use
623
- */
624
- class ToolServicesRegistry {
625
- private services: ToolServices = {
626
- commandQueueService: null,
627
- taskSchedulerService: null,
628
- notificationsService: null,
629
- projectsService: null,
630
- crmService: null,
631
- emailService: null,
632
- credentialsService: null,
633
- integrationService: null,
634
- leadService: null,
635
- storageService: null,
636
- pdfService: null
637
- }
638
- private initialized = false
639
-
640
- /**
641
- * Initialize registry with services
642
- * @throws Error if already initialized (prevents double initialization)
643
- */
644
- initialize(services: ToolServices): void {
645
- if (this.initialized) {
646
- throw new Error('ToolServices already initialized')
647
- }
648
- this.services = services
649
- this.initialized = true
650
- }
651
-
652
- /**
653
- * Get registered services
654
- * @throws Error if not initialized (fail-fast)
655
- */
656
- get(): ToolServices {
657
- if (!this.initialized) {
658
- throw new Error('ToolServices not initialized. Call toolServicesRegistry.initialize() from apps/api/src/main.ts')
659
- }
660
- return this.services
661
- }
662
-
663
- /**
664
- * Reset registry (testing only)
665
- * Allows test isolation by resetting global state
666
- */
667
- reset(): void {
668
- this.initialized = false
669
- this.services = {
670
- commandQueueService: null,
671
- taskSchedulerService: null,
672
- notificationsService: null,
673
- projectsService: null,
674
- crmService: null,
675
- emailService: null,
676
- credentialsService: null,
677
- integrationService: null,
678
- leadService: null,
679
- storageService: null,
680
- pdfService: null
681
- }
682
- }
683
- }
684
-
685
- /**
686
- * Global singleton registry
687
- * Initialized once at server startup
688
- */
689
- export const toolServicesRegistry = new ToolServicesRegistry()
690
-
691
- /**
692
- * Get tool services
693
- * Convenience function for tools to access services
694
- *
695
- * @example
696
- * const { commandQueue } = getToolServices()
697
- * if (!commandQueue) throw new Error('CommandQueueService not initialized')
698
- * await commandQueue.createTask(params)
699
- */
700
- export const getToolServices = (): ToolServices => toolServicesRegistry.get()
1
+ /**
2
+ *
3
+ * Tool Services Registry
4
+ * Global singleton registry for tool services (command queue, task scheduler, integrations)
5
+ *
6
+ * Pattern: Global registry with initialization safety
7
+ * - Initialized once at server startup (apps/api/src/main.ts)
8
+ * - Tools import getToolServices() directly (no dependency injection)
9
+ * - Fail-fast behavior if not initialized
10
+ */
11
+
12
+ import type { CreateTaskParams, Task } from '../../../commands/queue/types'
13
+ import type { CreateScheduleInput, TaskSchedule } from '../../scheduler/types'
14
+ import type { CreateNotificationParams, Notification } from '../../../operations/notifications/types'
15
+ import type { ILeadService } from './lead-service-types'
16
+ import type { ExecutionContext } from '../base/types'
17
+ import type {
18
+ ProjectRow,
19
+ ProjectWithCounts,
20
+ ProjectDetail,
21
+ MilestoneRow,
22
+ TaskRow,
23
+ NoteRow
24
+ } from '../../../business/projects'
25
+ import type { DealListItem, DealDetail, ListDealsQuery } from '../../../business/acquisition'
26
+ import type { RecentActivityEntry } from '../../../business/sales/api-schemas'
27
+ import type { Database } from '../../../supabase/database.types'
28
+
29
+ /**
30
+ * Service interfaces for platform tools
31
+ *
32
+ * IMPORTANT: These interfaces define the contract that services must implement
33
+ * Actual service implementations live in apps/api/
34
+ * TypeScript structural typing ensures compatibility without circular dependencies
35
+ */
36
+ export interface ICommandQueueService {
37
+ /**
38
+ * Create approval/rejection task
39
+ * @see CommandQueueService.createTask (apps/api/src/command-queue/service.ts:23)
40
+ */
41
+ createTask(params: CreateTaskParams): Promise<Task>
42
+
43
+ /**
44
+ * Delete pending HITL tasks matching metadata filter
45
+ * Uses JSONB containment (.contains()) for metadata-based batch deletion
46
+ * @see CommandQueueService.deleteByMetadata (apps/api/src/commands/queue/service.ts)
47
+ */
48
+ deleteByMetadata(
49
+ organizationId: string,
50
+ metadata: Record<string, unknown>,
51
+ status?: string
52
+ ): Promise<{ deleted: number }>
53
+ }
54
+
55
+ export interface ITaskSchedulerService {
56
+ /**
57
+ * Create a unified schedule
58
+ * @see TaskScheduleService.createSchedule (apps/api/src/task-scheduler/service.ts:190)
59
+ */
60
+ createSchedule(input: CreateScheduleInput): Promise<TaskSchedule>
61
+
62
+ /**
63
+ * Update anchor time for a relative schedule (used for rescheduling)
64
+ * @see TaskScheduleService.updateAnchor (apps/api/src/task-scheduler/service.ts)
65
+ */
66
+ updateAnchor(id: string, organizationId: string, anchorAt: string): Promise<TaskSchedule>
67
+
68
+ /**
69
+ * Delete (cancel) a schedule
70
+ * @see TaskScheduleService.deleteSchedule (apps/api/src/task-scheduler/service.ts)
71
+ */
72
+ deleteSchedule(id: string, organizationId: string): Promise<void>
73
+
74
+ /**
75
+ * Find schedule by idempotency key
76
+ * @see TaskScheduleService.findByIdempotencyKey (apps/api/src/task-scheduler/service.ts)
77
+ */
78
+ findByIdempotencyKey(organizationId: string, idempotencyKey: string): Promise<TaskSchedule | null>
79
+
80
+ /**
81
+ * Delete (cancel) schedule by idempotency key
82
+ * Finds schedule by key and cancels it. No-op if schedule not found.
83
+ * @see TaskScheduleService.deleteScheduleByIdempotencyKey (apps/api/src/task-scheduler/service.ts)
84
+ */
85
+ deleteScheduleByIdempotencyKey(idempotencyKey: string, organizationId: string): Promise<void>
86
+
87
+ /**
88
+ * Cancel a schedule by idempotency key (soft delete)
89
+ * Finds schedule by key and sets status to 'cancelled'. No-op if not found.
90
+ * @see TaskScheduleService.cancelScheduleByIdempotencyKey (apps/api/src/execution/task-scheduler/service.ts)
91
+ */
92
+ cancelScheduleByIdempotencyKey(idempotencyKey: string, organizationId: string): Promise<{ cancelled: boolean }>
93
+
94
+ /**
95
+ * List schedules with optional metadata filtering
96
+ * Supports JSONB containment for metadata-based queries
97
+ * @see TaskScheduleService.listSchedules (apps/api/src/execution/task-scheduler/service.ts)
98
+ */
99
+ listSchedules(params: {
100
+ organizationId: string
101
+ targetResourceId?: string
102
+ status?: string
103
+ metadata?: Record<string, unknown>
104
+ limit?: number
105
+ offset?: number
106
+ }): Promise<{ schedules: TaskSchedule[]; total: number }>
107
+
108
+ /**
109
+ * Get a single schedule by ID
110
+ * @see TaskScheduleService.getSchedule (apps/api/src/execution/task-scheduler/service.ts)
111
+ */
112
+ getSchedule(id: string, organizationId: string): Promise<TaskSchedule | null>
113
+
114
+ /**
115
+ * Cancel a schedule (soft delete - sets status to 'cancelled')
116
+ * @see TaskScheduleService.cancelSchedule (apps/api/src/execution/task-scheduler/service.ts)
117
+ */
118
+ cancelSchedule(id: string, organizationId: string): Promise<TaskSchedule>
119
+
120
+ /**
121
+ * Cancel all schedules matching metadata filter (batch soft delete)
122
+ * Uses JSONB containment (.contains()) for metadata-based filtering
123
+ * @see TaskScheduleService.cancelSchedulesByMetadata (apps/api/src/execution/task-scheduler/service.ts)
124
+ */
125
+ cancelSchedulesByMetadata(
126
+ organizationId: string,
127
+ metadata: Record<string, unknown>,
128
+ status?: string
129
+ ): Promise<{ cancelled: number }>
130
+ }
131
+
132
+ export interface INotificationsService {
133
+ /**
134
+ * Create platform notification for user
135
+ * @see NotificationService.create (apps/api/src/notifications/service.ts:17)
136
+ */
137
+ create(params: CreateNotificationParams): Promise<Notification>
138
+ }
139
+
140
+ export interface ICrmService {
141
+ getRecentActivity(organizationId: string, limit: number): Promise<RecentActivityEntry[]>
142
+ listDeals(organizationId: string, filters?: Partial<ListDealsQuery>): Promise<DealListItem[]>
143
+ getDeal(dealId: string, organizationId: string): Promise<DealDetail | null>
144
+ getDealByEmail(email: string, organizationId: string): Promise<DealDetail | null>
145
+ createDealNote(
146
+ params: import('./lead-service-types').CreateDealNoteParams
147
+ ): Promise<import('./lead-service-types').AcqDealNote>
148
+ listDealNotes(
149
+ params: import('./lead-service-types').ListDealNotesParams
150
+ ): Promise<import('./lead-service-types').AcqDealNote[]>
151
+ createDealTask(
152
+ params: import('./lead-service-types').CreateDealTaskParams
153
+ ): Promise<import('./lead-service-types').AcqDealTask>
154
+ listDealTasks(
155
+ params: import('./lead-service-types').ListDealTasksParams
156
+ ): Promise<import('./lead-service-types').AcqDealTask[]>
157
+ listDealTasksDue(
158
+ params: import('./lead-service-types').ListDealTasksDueParams
159
+ ): Promise<import('./lead-service-types').AcqDealTask[]>
160
+ completeDealTask(
161
+ params: import('./lead-service-types').CompleteDealTaskParams
162
+ ): Promise<import('./lead-service-types').AcqDealTask>
163
+ recordActivity(params: import('./lead-service-types').RecordDealActivityParams): Promise<void>
164
+ deleteDeal(params: import('./lead-service-types').DeleteDealParams): Promise<void>
165
+ }
166
+
167
+ type ProjectInsert = Database['public']['Tables']['prj_projects']['Insert']
168
+ type ProjectUpdate = Database['public']['Tables']['prj_projects']['Update']
169
+ type MilestoneInsert = Database['public']['Tables']['prj_milestones']['Insert']
170
+ type MilestoneUpdate = Database['public']['Tables']['prj_milestones']['Update']
171
+ type TaskInsert = Database['public']['Tables']['prj_tasks']['Insert']
172
+ type TaskUpdate = Database['public']['Tables']['prj_tasks']['Update']
173
+ type NoteInsert = Database['public']['Tables']['prj_notes']['Insert']
174
+ type NoteUpdate = Database['public']['Tables']['prj_notes']['Update']
175
+ type TaskResumeContextRow = Pick<TaskRow, 'id' | 'resume_context' | 'updated_at'>
176
+ type DeleteEntityResult = { id: string; project_id: string }
177
+
178
+ export interface IProjectsService {
179
+ listProjects(
180
+ organizationId: string,
181
+ filters?: {
182
+ kind?: string
183
+ status?: string
184
+ }
185
+ ): Promise<ProjectWithCounts[]>
186
+ getProject(id: string, organizationId: string): Promise<ProjectDetail | null>
187
+ createProject(input: Omit<ProjectInsert, 'organization_id'> & { organizationId: string }): Promise<ProjectRow>
188
+ updateProject(
189
+ id: string,
190
+ organizationId: string,
191
+ input: Omit<ProjectUpdate, 'organization_id'>
192
+ ): Promise<ProjectRow | null>
193
+ deleteProject(id: string, organizationId: string): Promise<boolean>
194
+ listMilestones(projectId: string, organizationId: string): Promise<MilestoneRow[]>
195
+ createMilestone(
196
+ input: Omit<MilestoneInsert, 'organization_id' | 'project_id'> & {
197
+ organizationId: string
198
+ projectId: string
199
+ }
200
+ ): Promise<MilestoneRow>
201
+ updateMilestone(
202
+ id: string,
203
+ organizationId: string,
204
+ input: Omit<MilestoneUpdate, 'organization_id'>
205
+ ): Promise<MilestoneRow | null>
206
+ deleteMilestone(id: string, organizationId: string): Promise<DeleteEntityResult | null>
207
+ listTasks(
208
+ projectId: string,
209
+ organizationId: string,
210
+ filters?: {
211
+ status?: string
212
+ milestone_id?: string
213
+ parent_task_id?: string
214
+ }
215
+ ): Promise<TaskRow[]>
216
+ getTask(id: string, organizationId: string): Promise<TaskRow | null>
217
+ createTask(input: Omit<TaskInsert, 'organization_id'> & { organizationId: string }): Promise<TaskRow>
218
+ updateTask(id: string, organizationId: string, input: Omit<TaskUpdate, 'organization_id'>): Promise<TaskRow | null>
219
+ deleteTask(id: string, organizationId: string): Promise<DeleteEntityResult | null>
220
+ mergeTaskResumeContext(
221
+ id: string,
222
+ organizationId: string,
223
+ incoming: Record<string, unknown>
224
+ ): Promise<TaskResumeContextRow | null>
225
+ listNotes(projectId: string, organizationId: string): Promise<NoteRow[]>
226
+ createNote(input: Omit<NoteInsert, 'organization_id'> & { organizationId: string }): Promise<NoteRow>
227
+ updateNote(id: string, organizationId: string, input: Omit<NoteUpdate, 'organization_id'>): Promise<NoteRow | null>
228
+ deleteNote(id: string, organizationId: string): Promise<DeleteEntityResult | null>
229
+ }
230
+
231
+ // =============================================================================
232
+ // Platform Email Service Types
233
+ // =============================================================================
234
+
235
+ /**
236
+ * Parameters for sending platform emails
237
+ * Supports three targeting modes: explicit userIds, role-based, or broadcast
238
+ */
239
+ export interface SendPlatformEmailParams {
240
+ organizationId: string
241
+
242
+ // Targeting (exactly one required)
243
+ userIds?: string[] // Explicit: specific users
244
+ targetRole?: string // Role-based: users with role
245
+ targetAll?: boolean // Broadcast: all org members
246
+
247
+ // Content
248
+ subject: string
249
+ html?: string
250
+ text?: string
251
+
252
+ // Optional
253
+ replyTo?: string
254
+ tags?: Array<{ name: string; value: string }>
255
+ }
256
+
257
+ /**
258
+ * Result of platform email send operation
259
+ * Follows partial success pattern (similar to BatchProcessResult)
260
+ */
261
+ export interface EmailResult {
262
+ sent: number // Successfully sent
263
+ failed: number // Failed to send
264
+ errors?: Array<{
265
+ // Only if failed > 0
266
+ userId: string
267
+ email: string
268
+ error: string
269
+ }>
270
+ }
271
+
272
+ /**
273
+ * Platform email service interface
274
+ * Sends transactional emails from notifications@elevasis.io using platform Resend credentials
275
+ *
276
+ * Implementation: apps/api/src/email/service.ts (EmailService class)
277
+ *
278
+ * Multi-tenancy: All operations require organizationId for tenant isolation.
279
+ * User targeting queries filtered by organizationId via org_memberships join.
280
+ */
281
+ export interface IEmailService {
282
+ /**
283
+ * Send platform email to targeted users within an organization
284
+ *
285
+ * Targeting modes (exactly one required):
286
+ * - userIds: Send to specific users (verified against org membership)
287
+ * - targetRole: Send to users with specific role
288
+ * - targetAll: Send to all org members
289
+ *
290
+ * @param params - Email parameters including targeting and content
291
+ * @returns Result with sent/failed counts and optional errors array
292
+ * @throws Error if no targeting specified or all userIds invalid
293
+ * @see EmailService.send (apps/api/src/email/service.ts)
294
+ */
295
+ send(params: SendPlatformEmailParams): Promise<EmailResult>
296
+ }
297
+
298
+ /**
299
+ * Credentials service interface
300
+ * Provides access to organization credentials for integration tools
301
+ *
302
+ * Implementation: apps/api/src/multi-tenancy/credentials/service.ts (CredentialsService class)
303
+ *
304
+ * Note: Integration tools only need getCredential() method.
305
+ * Other methods (createCredential, listCredentials, deleteCredential) exist in the implementation
306
+ * but are only used by API handlers.
307
+ */
308
+ export interface ICredentialsService {
309
+ /**
310
+ * Get decrypted credential for organization and integration
311
+ * @param organizationId - Organization ID from ExecutionContext
312
+ * @param credentialName - Integration name (e.g., 'gmail', 'slack')
313
+ * @param environment - Optional environment filter ('development' | 'production')
314
+ * @returns Decrypted credential object or null if not found
315
+ * @see CredentialsService.getCredential (apps/api/src/multi-tenancy/credentials/service.ts:41-57)
316
+ */
317
+ getCredential(
318
+ organizationId: string,
319
+ credentialName: string,
320
+ environment?: 'development' | 'production'
321
+ ): Promise<Record<string, unknown> | null>
322
+ }
323
+
324
+ // =============================================================================
325
+ // Platform Storage Service Types
326
+ // =============================================================================
327
+
328
+ /**
329
+ * Parameters for storage upload
330
+ */
331
+ export interface StorageUploadParams {
332
+ organizationId: string
333
+ bucket: string
334
+ path: string
335
+ file: Buffer | Blob
336
+ contentType: string
337
+ upsert?: boolean
338
+ }
339
+
340
+ /**
341
+ * Parameters for storage download/delete
342
+ */
343
+ export interface StorageDownloadParams {
344
+ organizationId: string
345
+ bucket: string
346
+ path: string
347
+ }
348
+
349
+ /**
350
+ * Parameters for creating signed URL
351
+ */
352
+ export interface StorageSignedUrlParams {
353
+ organizationId: string
354
+ bucket: string
355
+ path: string
356
+ expiresIn: number // seconds
357
+ }
358
+
359
+ /**
360
+ * Result of storage upload operation
361
+ */
362
+ export interface StorageUploadResult {
363
+ path: string
364
+ fullPath: string
365
+ size: number
366
+ }
367
+
368
+ /**
369
+ * Result of signed URL creation
370
+ */
371
+ export interface StorageSignedUrlResult {
372
+ signedUrl: string
373
+ path: string
374
+ expiresAt: Date
375
+ }
376
+
377
+ /**
378
+ * Storage service interface for platform storage tools
379
+ * Provides org-scoped file storage using Supabase Storage
380
+ *
381
+ * Implementation: apps/api/src/storage/service.ts (StorageService class)
382
+ *
383
+ * Multi-tenancy: All paths prefixed with organizationId for tenant isolation.
384
+ * RLS policies enforce access at storage.objects level.
385
+ */
386
+ export interface IStorageService {
387
+ /**
388
+ * Upload file to org-scoped path
389
+ * Path format: {organizationId}/{path}
390
+ * @see StorageService.upload (apps/api/src/storage/service.ts)
391
+ */
392
+ upload(params: StorageUploadParams): Promise<StorageUploadResult>
393
+
394
+ /**
395
+ * Download file from org-scoped path
396
+ * @see StorageService.download (apps/api/src/storage/service.ts)
397
+ */
398
+ download(params: StorageDownloadParams): Promise<Blob>
399
+
400
+ /**
401
+ * Create signed URL for temporary access
402
+ * @see StorageService.createSignedUrl (apps/api/src/storage/service.ts)
403
+ */
404
+ createSignedUrl(params: StorageSignedUrlParams): Promise<StorageSignedUrlResult>
405
+
406
+ /**
407
+ * Delete file from org-scoped path
408
+ * @see StorageService.delete (apps/api/src/storage/service.ts)
409
+ */
410
+ delete(params: StorageDownloadParams): Promise<void>
411
+
412
+ /**
413
+ * List files in org-scoped path
414
+ * @see StorageService.list (apps/api/src/storage/service.ts)
415
+ */
416
+ list(params: { organizationId: string; bucket: string; prefix?: string }): Promise<string[]>
417
+ }
418
+
419
+ /**
420
+ * Integration service interface
421
+ * Provides access to external API integrations (Gmail, Slack, etc.)
422
+ *
423
+ * Implementation: packages/core/src/execution-engine/tools/integration/service.ts
424
+ *
425
+ * Interface Segregation Principle: Only exposes call() method used by consumers.
426
+ * Internal state (adapters, rateLimiter, retryPolicy) hidden from interface.
427
+ */
428
+ export interface IIntegrationService {
429
+ /**
430
+ * Call integration method with full orchestration
431
+ *
432
+ * Orchestrates: rate limiting, credential retrieval, validation, retry
433
+ *
434
+ * @param integration - Integration adapter type (e.g., 'gmail', 'slack')
435
+ * @param method - Method name (e.g., 'sendEmail', 'postMessage')
436
+ * @param params - Method parameters
437
+ * @param credentialName - Credential name from credentials table
438
+ * @param context - Execution context (required for multi-tenant isolation)
439
+ * @returns Method result
440
+ * @throws ToolingError if call fails
441
+ */
442
+ call(
443
+ integration: string,
444
+ method: string,
445
+ params: unknown,
446
+ credentialName: string,
447
+ context?: ExecutionContext
448
+ ): Promise<unknown>
449
+ }
450
+
451
+ // =============================================================================
452
+ // PDF Service Types
453
+ // =============================================================================
454
+
455
+ /**
456
+ * PDF document structure (schema-driven)
457
+ * Full type definition lives in packages/core/src/pdf/types.ts
458
+ * Using Record<string, unknown> here to avoid circular dependencies
459
+ */
460
+ export interface PdfRenderParams {
461
+ organizationId: string
462
+ /** Document structure with pages and content blocks */
463
+ document: Record<string, unknown>
464
+ /** Optional theme override (partial merge with default theme) */
465
+ theme?: Record<string, unknown>
466
+ /** Storage destination for rendered PDF */
467
+ storage: {
468
+ bucket: string
469
+ path: string
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Result of PDF render operation
475
+ */
476
+ export interface PdfRenderResult {
477
+ success: boolean
478
+ /** Signed URL for accessing the rendered PDF */
479
+ pdfUrl: string
480
+ /** PDF file size in bytes */
481
+ size: number
482
+ }
483
+
484
+ /**
485
+ * PDF service interface for rendering documents
486
+ * Provides pdfmake-based document rendering with optional storage upload
487
+ *
488
+ * Implementation: packages/core/src/pdf/server/pdfmake-service.ts (PdfMakeService class)
489
+ *
490
+ * Multi-tenancy: organizationId used for storage path prefixing.
491
+ * All PDFs stored under org-scoped paths via StorageService.
492
+ */
493
+ export interface IPdfService {
494
+ /**
495
+ * Render PDF document and upload to storage
496
+ *
497
+ * Flow:
498
+ * 1. Parse document structure
499
+ * 2. Merge theme with defaults
500
+ * 3. Render via pdfmake
501
+ * 4. Upload to storage via StorageService
502
+ * 5. Return signed URL
503
+ *
504
+ * @param params - Render parameters including document, theme, and storage destination
505
+ * @returns Result with signed URL and file size
506
+ * @throws Error if rendering fails or storage upload fails
507
+ * @see PdfMakeService.render (packages/core/src/pdf/server/pdfmake-service.ts)
508
+ */
509
+ render(params: PdfRenderParams): Promise<PdfRenderResult>
510
+
511
+ /**
512
+ * Render PDF document to buffer (no storage upload)
513
+ *
514
+ * Use this for testing or when you need to handle storage upload separately.
515
+ *
516
+ * @param params - Render parameters (organizationId, document, optional theme)
517
+ * @returns Buffer containing the PDF
518
+ * @throws Error if rendering fails
519
+ * @see PdfMakeService.renderToBuffer (packages/core/src/pdf/server/pdfmake-service.ts)
520
+ */
521
+ renderToBuffer(params: Omit<PdfRenderParams, 'storage'>): Promise<Buffer>
522
+ }
523
+
524
+ // =============================================================================
525
+ // Lead Service Types (extracted to lead-service-types.ts)
526
+ // =============================================================================
527
+ export {
528
+ type AcqList,
529
+ type AcqCompany,
530
+ type AcqContact,
531
+ type PaginationParams,
532
+ type PaginatedResult,
533
+ type CreateListParams,
534
+ type UpdateListParams,
535
+ type CreateCompanyParams,
536
+ type UpdateCompanyParams,
537
+ type UpsertCompanyParams,
538
+ type CompanyFilters,
539
+ type CreateContactParams,
540
+ type UpdateContactParams,
541
+ type UpsertContactParams,
542
+ type ContactFilters,
543
+ type UpsertDealParams,
544
+ type AcqDeal,
545
+ type DealActivityEntry,
546
+ type AddContactsToListParams,
547
+ type AddContactsToListResult,
548
+ type BulkImportParams,
549
+ type BulkImportResult,
550
+ type BulkImportCompanyEntry,
551
+ type BulkImportCompaniesParams,
552
+ type BulkImportCompaniesResult,
553
+ type DeactivateContactsByCompanyParams,
554
+ type DeactivateContactsByCompanyResult,
555
+ type ILeadService,
556
+ type UpdateDiscoveryDataParams,
557
+ type UpdateProposalDataParams,
558
+ type MarkProposalSentParams,
559
+ type MarkProposalReviewedParams,
560
+ type UpdateCloseLostReasonParams,
561
+ type UpdateFeesParams,
562
+ type TransitionItemParams,
563
+ type SetContactNurtureParams,
564
+ type CancelSchedulesAndHitlByEmailParams,
565
+ type CancelHitlByDealIdParams,
566
+ type ClearDealFieldsParams,
567
+ type DeleteDealParams,
568
+ type DealFilters,
569
+ type DealStageSummary,
570
+ type StaleDeal,
571
+ type DealPipelineAnalytics,
572
+ type DealAnalyticsParams,
573
+ type UpsertSocialPostParams,
574
+ type UpsertSocialPostsParams,
575
+ type UpsertSocialPostsResult,
576
+ type AcqDealNote,
577
+ type CreateDealNoteParams,
578
+ type ListDealNotesParams,
579
+ type AcqDealTask,
580
+ type AcqDealTaskKind,
581
+ type CreateDealTaskParams,
582
+ type ListDealTasksParams,
583
+ type ListDealTasksDueParams,
584
+ type CompleteDealTaskParams,
585
+ type RecordDealActivityParams,
586
+ type GetDealByIdParams,
587
+ type GetContactByIdParams,
588
+ type GetCompanyByIdParams,
589
+ type UpdateListConfigParams,
590
+ type UpdateCompanyStageParams,
591
+ type UpdateContactStageParams,
592
+ type AddCompaniesToListParams,
593
+ type AddCompaniesToListResult,
594
+ type RemoveCompaniesFromListParams,
595
+ type RemoveCompaniesFromListResult,
596
+ type RecordListExecutionParams,
597
+ type ListExecutionSummary
598
+ } from './lead-service-types'
599
+
600
+ /**
601
+ * Tool services registry
602
+ * Contains all services available to tools
603
+ */
604
+ export interface ToolServices {
605
+ commandQueueService: ICommandQueueService | null
606
+ taskSchedulerService: ITaskSchedulerService | null
607
+ notificationsService: INotificationsService | null
608
+ projectsService?: IProjectsService | null
609
+ crmService?: ICrmService | null
610
+ emailService: IEmailService | null
611
+ credentialsService: ICredentialsService | null
612
+ integrationService: IIntegrationService | null
613
+ leadService: ILeadService | null
614
+ storageService: IStorageService | null
615
+ /** PDF rendering service - optional for gradual adoption */
616
+ pdfService?: IPdfService | null
617
+ }
618
+
619
+ /**
620
+ * Global registry for tool services
621
+ * Ensures services are initialized before use
622
+ */
623
+ class ToolServicesRegistry {
624
+ private services: ToolServices = {
625
+ commandQueueService: null,
626
+ taskSchedulerService: null,
627
+ notificationsService: null,
628
+ projectsService: null,
629
+ crmService: null,
630
+ emailService: null,
631
+ credentialsService: null,
632
+ integrationService: null,
633
+ leadService: null,
634
+ storageService: null,
635
+ pdfService: null
636
+ }
637
+ private initialized = false
638
+
639
+ /**
640
+ * Initialize registry with services
641
+ * @throws Error if already initialized (prevents double initialization)
642
+ */
643
+ initialize(services: ToolServices): void {
644
+ if (this.initialized) {
645
+ throw new Error('ToolServices already initialized')
646
+ }
647
+ this.services = services
648
+ this.initialized = true
649
+ }
650
+
651
+ /**
652
+ * Get registered services
653
+ * @throws Error if not initialized (fail-fast)
654
+ */
655
+ get(): ToolServices {
656
+ if (!this.initialized) {
657
+ throw new Error('ToolServices not initialized. Call toolServicesRegistry.initialize() from apps/api/src/main.ts')
658
+ }
659
+ return this.services
660
+ }
661
+
662
+ /**
663
+ * Reset registry (testing only)
664
+ * Allows test isolation by resetting global state
665
+ */
666
+ reset(): void {
667
+ this.initialized = false
668
+ this.services = {
669
+ commandQueueService: null,
670
+ taskSchedulerService: null,
671
+ notificationsService: null,
672
+ projectsService: null,
673
+ crmService: null,
674
+ emailService: null,
675
+ credentialsService: null,
676
+ integrationService: null,
677
+ leadService: null,
678
+ storageService: null,
679
+ pdfService: null
680
+ }
681
+ }
682
+ }
683
+
684
+ /**
685
+ * Global singleton registry
686
+ * Initialized once at server startup
687
+ */
688
+ export const toolServicesRegistry = new ToolServicesRegistry()
689
+
690
+ /**
691
+ * Get tool services
692
+ * Convenience function for tools to access services
693
+ *
694
+ * @example
695
+ * const { commandQueue } = getToolServices()
696
+ * if (!commandQueue) throw new Error('CommandQueueService not initialized')
697
+ * await commandQueue.createTask(params)
698
+ */
699
+ export const getToolServices = (): ToolServices => toolServicesRegistry.get()