@rizom/brain 0.2.0-alpha.5 → 0.2.0-alpha.50

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,1120 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Options for entity mutation operations (create, update, upsert)
5
+ */
6
+ interface EntityJobOptions {
7
+ priority?: number;
8
+ maxRetries?: number;
9
+ }
10
+ /**
11
+ * Options for entity creation (extends EntityJobOptions with deduplication)
12
+ */
13
+ interface CreateEntityOptions extends EntityJobOptions {
14
+ deduplicateId?: boolean;
15
+ }
16
+ /**
17
+ * Result of an entity mutation that triggers an embedding job.
18
+ * When skipped is true, content was unchanged — no DB write, no event, no embedding job.
19
+ */
20
+ interface EntityMutationResult {
21
+ entityId: string;
22
+ jobId: string;
23
+ skipped: boolean;
24
+ }
25
+ /**
26
+ * Input for adapter-validated direct creation from finalized markdown.
27
+ */
28
+ interface CreateEntityFromMarkdownInput {
29
+ entityType: string;
30
+ id: string;
31
+ markdown: string;
32
+ }
33
+ /**
34
+ * Data for storing an embedding for an entity
35
+ */
36
+ interface StoreEmbeddingData {
37
+ entityId: string;
38
+ entityType: string;
39
+ embedding: Float32Array;
40
+ contentHash: string;
41
+ }
42
+ /**
43
+ * Base entity type - generic to support typed metadata
44
+ * TMetadata defaults to Record<string, unknown> for backward compatibility
45
+ */
46
+ interface BaseEntity<TMetadata = Record<string, unknown>> {
47
+ id: string;
48
+ entityType: string;
49
+ content: string;
50
+ created: string;
51
+ updated: string;
52
+ metadata: TMetadata;
53
+ /** SHA256 hash of content for change detection */
54
+ contentHash: string;
55
+ }
56
+ /**
57
+ * Entity input type for creation - allows partial entities with optional system fields
58
+ * contentHash is excluded because it's computed automatically by the entity service
59
+ */
60
+ type EntityInput<T extends BaseEntity> = Omit<T, "id" | "created" | "updated" | "contentHash"> & {
61
+ id?: string;
62
+ created?: string;
63
+ updated?: string;
64
+ };
65
+ /**
66
+ * Search result type
67
+ */
68
+ interface SearchResult<T extends BaseEntity = BaseEntity> {
69
+ entity: T;
70
+ score: number;
71
+ excerpt: string;
72
+ }
73
+ /**
74
+ * Normalized system_create input shape used by plugin create interceptors.
75
+ */
76
+ interface CreateInput {
77
+ entityType: string;
78
+ prompt?: string;
79
+ title?: string;
80
+ content?: string;
81
+ url?: string;
82
+ targetEntityType?: string;
83
+ targetEntityId?: string;
84
+ }
85
+ /**
86
+ * Minimal caller context forwarded to plugin create interceptors.
87
+ */
88
+ interface CreateExecutionContext {
89
+ interfaceType: string;
90
+ userId: string;
91
+ channelId?: string;
92
+ channelName?: string;
93
+ }
94
+ /**
95
+ * Result returned to system_create when a plugin fully handles creation.
96
+ */
97
+ type CreateResult = {
98
+ success: true;
99
+ data: {
100
+ entityId?: string;
101
+ jobId?: string;
102
+ status: string;
103
+ };
104
+ } | {
105
+ success: false;
106
+ error: string;
107
+ };
108
+ /**
109
+ * Plugin create interceptors can either fully handle creation,
110
+ * or continue with a rewritten normalized input.
111
+ */
112
+ type CreateInterceptionResult = {
113
+ kind: "handled";
114
+ result: CreateResult;
115
+ } | {
116
+ kind: "continue";
117
+ input: CreateInput;
118
+ };
119
+ /**
120
+ * Interface for entity adapter - handles conversion between entities and markdown
121
+ * following the hybrid storage model
122
+ *
123
+ * @template TEntity - The full entity type
124
+ * @template TMetadata - The metadata type (defaults to Record<string, unknown>)
125
+ */
126
+ interface EntityAdapter<TEntity extends BaseEntity<TMetadata>, TMetadata = Record<string, unknown>> {
127
+ entityType: string;
128
+ schema: z.ZodSchema<TEntity>;
129
+ toMarkdown(entity: TEntity): string;
130
+ fromMarkdown(markdown: string): Partial<TEntity>;
131
+ extractMetadata(entity: TEntity): TMetadata;
132
+ parseFrontMatter<TFrontmatter>(markdown: string, schema: z.ZodSchema<TFrontmatter>): TFrontmatter;
133
+ generateFrontMatter(entity: TEntity): string;
134
+ /** Optional: Zod schema for frontmatter fields. Used by CMS config generation. */
135
+ frontmatterSchema?: z.ZodObject<z.ZodRawShape>;
136
+ /** Optional: Declares this entity type is a singleton (one file, e.g., identity/identity.md). Used by CMS to generate files collection. */
137
+ isSingleton?: boolean;
138
+ /** Optional: Whether this entity has a free-form markdown body below frontmatter. Defaults to true. When false, CMS omits the body widget. */
139
+ hasBody?: boolean;
140
+ /** Returns a markdown body template with section headings for this entity type. Empty string for free-form entities. */
141
+ getBodyTemplate(): string;
142
+ /** Optional: Declares that this entity type supports cover images via coverImageId in frontmatter */
143
+ supportsCoverImage?: boolean;
144
+ /** Optional: Extract coverImageId from entity content/frontmatter */
145
+ getCoverImageId?(entity: TEntity): string | undefined;
146
+ }
147
+ /**
148
+ * Sort field specification for multi-field sorting
149
+ */
150
+ interface SortField {
151
+ /** Field to sort by - "created", "updated", or a metadata field name */
152
+ field: string;
153
+ /** Sort direction */
154
+ direction: "asc" | "desc";
155
+ /** Sort NULL values before non-NULL values (default: false / SQLite default) */
156
+ nullsFirst?: boolean;
157
+ }
158
+ /**
159
+ * List entities options
160
+ * Generic over metadata type for type-safe filtering
161
+ */
162
+ interface ListOptions<TMetadata = Record<string, unknown>> {
163
+ limit?: number;
164
+ offset?: number;
165
+ /** Multi-field sorting - supports system fields (created, updated) and metadata fields */
166
+ sortFields?: SortField[];
167
+ filter?: {
168
+ metadata?: Partial<TMetadata>;
169
+ };
170
+ /** Filter to only entities with metadata.status = "published" */
171
+ publishedOnly?: boolean;
172
+ }
173
+ /**
174
+ * Search options
175
+ */
176
+ interface SearchOptions {
177
+ limit?: number;
178
+ offset?: number;
179
+ types?: string[];
180
+ excludeTypes?: string[];
181
+ sortBy?: "relevance" | "created" | "updated";
182
+ sortDirection?: "asc" | "desc";
183
+ /** Score multipliers per entity type - applied after initial search */
184
+ weight?: Record<string, number>;
185
+ }
186
+ /**
187
+ * Configuration for entity type registration
188
+ */
189
+ interface EntityTypeConfig {
190
+ /** Score multiplier for search results (default: 1.0) */
191
+ weight?: number;
192
+ /** Whether to generate embeddings for this entity type (default: true).
193
+ * Set to false for entity types with non-textual content (e.g., images). */
194
+ embeddable?: boolean;
195
+ }
196
+ /**
197
+ * Core entity service interface for read-only operations
198
+ * Used by core plugins that need entity access but shouldn't modify entities
199
+ */
200
+ interface ICoreEntityService {
201
+ getEntity<T extends BaseEntity>(entityType: string, id: string): Promise<T | null>;
202
+ /**
203
+ * Get entity without content resolution (raw)
204
+ * Used internally to avoid recursion when resolving image references
205
+ */
206
+ getEntityRaw<T extends BaseEntity>(entityType: string, id: string): Promise<T | null>;
207
+ listEntities<T extends BaseEntity>(type: string, options?: ListOptions): Promise<T[]>;
208
+ search<T extends BaseEntity = BaseEntity>(query: string, options?: SearchOptions): Promise<SearchResult<T>[]>;
209
+ getEntityTypes(): string[];
210
+ hasEntityType(type: string): boolean;
211
+ countEntities(entityType: string, options?: Pick<ListOptions, "publishedOnly" | "filter">): Promise<number>;
212
+ getEntityCounts(): Promise<Array<{
213
+ entityType: string;
214
+ count: number;
215
+ }>>;
216
+ /** Get weight map for all registered entity types with non-default weights */
217
+ getWeightMap(): Record<string, number>;
218
+ }
219
+ /**
220
+ * Entity service interface for managing brain entities
221
+ */
222
+ interface EntityService extends ICoreEntityService {
223
+ createEntity<T extends BaseEntity>(entity: EntityInput<T>, options?: CreateEntityOptions): Promise<EntityMutationResult>;
224
+ createEntityFromMarkdown(input: CreateEntityFromMarkdownInput, options?: CreateEntityOptions): Promise<EntityMutationResult>;
225
+ updateEntity<T extends BaseEntity>(entity: T, options?: EntityJobOptions): Promise<EntityMutationResult>;
226
+ deleteEntity(entityType: string, id: string): Promise<boolean>;
227
+ upsertEntity<T extends BaseEntity>(entity: T, options?: EntityJobOptions): Promise<EntityMutationResult & {
228
+ created: boolean;
229
+ }>;
230
+ storeEmbedding(data: StoreEmbeddingData): Promise<void>;
231
+ serializeEntity(entity: BaseEntity): string;
232
+ deserializeEntity(markdown: string, entityType: string): Partial<BaseEntity>;
233
+ countEmbeddings(): Promise<number>;
234
+ searchWithDistances(query: string): Promise<Array<{
235
+ entityId: string;
236
+ entityType: string;
237
+ distance: number;
238
+ }>>;
239
+ initialize(): Promise<void>;
240
+ getAsyncJobStatus(jobId: string): Promise<{
241
+ status: "pending" | "processing" | "completed" | "failed";
242
+ error?: string;
243
+ } | null>;
244
+ }
245
+
246
+ /**
247
+ * Context passed to all DataSource operations
248
+ * Contains internal state that should not be mixed with user query parameters
249
+ */
250
+ interface BaseDataSourceContext {
251
+ /**
252
+ * Whether to filter to only published/complete content
253
+ * Set by site-builder: true for production, false for preview
254
+ */
255
+ publishedOnly?: boolean;
256
+ /**
257
+ * Scoped entity service that auto-applies publishedOnly filter
258
+ * Datasources should use this instead of their injected entityService
259
+ * to ensure consistent filtering behavior across environments
260
+ */
261
+ entityService: EntityService;
262
+ }
263
+ /**
264
+ * DataSource Interface
265
+ *
266
+ * Provides data for templates through fetch, generate, or transform operations.
267
+ * DataSources are registered in the DataSourceRegistry and referenced by templates
268
+ * via their dataSourceId property.
269
+ */
270
+ interface DataSource {
271
+ /**
272
+ * Unique identifier for this data source
273
+ */
274
+ id: string;
275
+ /**
276
+ * Human-readable name for this data source
277
+ */
278
+ name: string;
279
+ /**
280
+ * Optional description of what this data source provides
281
+ */
282
+ description?: string;
283
+ /**
284
+ * Optional: Fetch existing data
285
+ * Used by data sources that aggregate or retrieve data (e.g., dashboard stats, API data)
286
+ * DataSources validate output using the provided schema
287
+ * @param query - Query parameters for fetching data
288
+ * @param outputSchema - Schema for validating output data
289
+ * @param context - Context with environment
290
+ */
291
+ fetch?: <T>(query: unknown, outputSchema: z.ZodSchema<T>, context: BaseDataSourceContext) => Promise<T>;
292
+ /**
293
+ * Optional: Generate new content
294
+ * Used by data sources that create content (e.g., AI-generated content, reports)
295
+ */
296
+ generate?: <T>(request: unknown, schema: z.ZodSchema<T>) => Promise<T>;
297
+ /**
298
+ * Optional: Transform content between formats
299
+ * Used by data sources that convert content (e.g., markdown to HTML, data formatting)
300
+ */
301
+ transform?: <T>(content: unknown, format: string, schema: z.ZodSchema<T>) => Promise<T>;
302
+ }
303
+
304
+ declare const ChatContextSchema: z.ZodObject<{
305
+ userPermissionLevel: z.ZodOptional<z.ZodEnum<["public", "trusted", "anchor"]>>;
306
+ interfaceType: z.ZodOptional<z.ZodString>;
307
+ channelId: z.ZodOptional<z.ZodString>;
308
+ channelName: z.ZodOptional<z.ZodString>;
309
+ }, "strip", z.ZodTypeAny, {
310
+ userPermissionLevel?: "public" | "trusted" | "anchor" | undefined;
311
+ interfaceType?: string | undefined;
312
+ channelId?: string | undefined;
313
+ channelName?: string | undefined;
314
+ }, {
315
+ userPermissionLevel?: "public" | "trusted" | "anchor" | undefined;
316
+ interfaceType?: string | undefined;
317
+ channelId?: string | undefined;
318
+ channelName?: string | undefined;
319
+ }>;
320
+ type ChatContext = z.infer<typeof ChatContextSchema>;
321
+ declare const PendingConfirmationSchema: z.ZodObject<{
322
+ toolName: z.ZodString;
323
+ description: z.ZodString;
324
+ args: z.ZodUnknown;
325
+ }, "strip", z.ZodTypeAny, {
326
+ toolName: string;
327
+ description: string;
328
+ args?: unknown;
329
+ }, {
330
+ toolName: string;
331
+ description: string;
332
+ args?: unknown;
333
+ }>;
334
+ type PendingConfirmation = z.infer<typeof PendingConfirmationSchema>;
335
+ declare const ToolResultDataSchema: z.ZodObject<{
336
+ toolName: z.ZodString;
337
+ args: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
338
+ jobId: z.ZodOptional<z.ZodString>;
339
+ data: z.ZodOptional<z.ZodUnknown>;
340
+ }, "strip", z.ZodTypeAny, {
341
+ toolName: string;
342
+ args?: Record<string, unknown> | undefined;
343
+ jobId?: string | undefined;
344
+ data?: unknown;
345
+ }, {
346
+ toolName: string;
347
+ args?: Record<string, unknown> | undefined;
348
+ jobId?: string | undefined;
349
+ data?: unknown;
350
+ }>;
351
+ type ToolResultData = z.infer<typeof ToolResultDataSchema>;
352
+ declare const AgentResponseSchema: z.ZodObject<{
353
+ text: z.ZodString;
354
+ toolResults: z.ZodOptional<z.ZodArray<z.ZodObject<{
355
+ toolName: z.ZodString;
356
+ args: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
357
+ jobId: z.ZodOptional<z.ZodString>;
358
+ data: z.ZodOptional<z.ZodUnknown>;
359
+ }, "strip", z.ZodTypeAny, {
360
+ toolName: string;
361
+ args?: Record<string, unknown> | undefined;
362
+ jobId?: string | undefined;
363
+ data?: unknown;
364
+ }, {
365
+ toolName: string;
366
+ args?: Record<string, unknown> | undefined;
367
+ jobId?: string | undefined;
368
+ data?: unknown;
369
+ }>, "many">>;
370
+ pendingConfirmation: z.ZodOptional<z.ZodObject<{
371
+ toolName: z.ZodString;
372
+ description: z.ZodString;
373
+ args: z.ZodUnknown;
374
+ }, "strip", z.ZodTypeAny, {
375
+ toolName: string;
376
+ description: string;
377
+ args?: unknown;
378
+ }, {
379
+ toolName: string;
380
+ description: string;
381
+ args?: unknown;
382
+ }>>;
383
+ usage: z.ZodObject<{
384
+ promptTokens: z.ZodNumber;
385
+ completionTokens: z.ZodNumber;
386
+ totalTokens: z.ZodNumber;
387
+ }, "strip", z.ZodTypeAny, {
388
+ promptTokens: number;
389
+ completionTokens: number;
390
+ totalTokens: number;
391
+ }, {
392
+ promptTokens: number;
393
+ completionTokens: number;
394
+ totalTokens: number;
395
+ }>;
396
+ }, "strip", z.ZodTypeAny, {
397
+ text: string;
398
+ usage: {
399
+ promptTokens: number;
400
+ completionTokens: number;
401
+ totalTokens: number;
402
+ };
403
+ toolResults?: {
404
+ toolName: string;
405
+ args?: Record<string, unknown> | undefined;
406
+ jobId?: string | undefined;
407
+ data?: unknown;
408
+ }[] | undefined;
409
+ pendingConfirmation?: {
410
+ toolName: string;
411
+ description: string;
412
+ args?: unknown;
413
+ } | undefined;
414
+ }, {
415
+ text: string;
416
+ usage: {
417
+ promptTokens: number;
418
+ completionTokens: number;
419
+ totalTokens: number;
420
+ };
421
+ toolResults?: {
422
+ toolName: string;
423
+ args?: Record<string, unknown> | undefined;
424
+ jobId?: string | undefined;
425
+ data?: unknown;
426
+ }[] | undefined;
427
+ pendingConfirmation?: {
428
+ toolName: string;
429
+ description: string;
430
+ args?: unknown;
431
+ } | undefined;
432
+ }>;
433
+ type AgentResponse = z.infer<typeof AgentResponseSchema>;
434
+ interface AgentNamespace {
435
+ chat(message: string, conversationId: string, context?: ChatContext): Promise<AgentResponse>;
436
+ confirmPendingAction(conversationId: string, confirmed: boolean): Promise<AgentResponse>;
437
+ invalidate(): void;
438
+ }
439
+
440
+ declare const AppInfoSchema: z.ZodObject<{
441
+ model: z.ZodString;
442
+ version: z.ZodString;
443
+ uptime: z.ZodNumber;
444
+ entities: z.ZodNumber;
445
+ embeddings: z.ZodNumber;
446
+ ai: z.ZodObject<{
447
+ model: z.ZodString;
448
+ embeddingModel: z.ZodString;
449
+ }, "strip", z.ZodTypeAny, {
450
+ model: string;
451
+ embeddingModel: string;
452
+ }, {
453
+ model: string;
454
+ embeddingModel: string;
455
+ }>;
456
+ daemons: z.ZodArray<z.ZodObject<{
457
+ name: z.ZodString;
458
+ pluginId: z.ZodString;
459
+ status: z.ZodString;
460
+ health: z.ZodOptional<z.ZodObject<{
461
+ status: z.ZodEnum<["healthy", "warning", "error", "unknown"]>;
462
+ message: z.ZodOptional<z.ZodString>;
463
+ lastCheck: z.ZodOptional<z.ZodString>;
464
+ details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
465
+ }, "strip", z.ZodTypeAny, {
466
+ status: "unknown" | "healthy" | "warning" | "error";
467
+ message?: string | undefined;
468
+ lastCheck?: string | undefined;
469
+ details?: Record<string, unknown> | undefined;
470
+ }, {
471
+ status: "unknown" | "healthy" | "warning" | "error";
472
+ message?: string | undefined;
473
+ lastCheck?: string | undefined;
474
+ details?: Record<string, unknown> | undefined;
475
+ }>>;
476
+ }, "strip", z.ZodTypeAny, {
477
+ status: string;
478
+ name: string;
479
+ pluginId: string;
480
+ health?: {
481
+ status: "unknown" | "healthy" | "warning" | "error";
482
+ message?: string | undefined;
483
+ lastCheck?: string | undefined;
484
+ details?: Record<string, unknown> | undefined;
485
+ } | undefined;
486
+ }, {
487
+ status: string;
488
+ name: string;
489
+ pluginId: string;
490
+ health?: {
491
+ status: "unknown" | "healthy" | "warning" | "error";
492
+ message?: string | undefined;
493
+ lastCheck?: string | undefined;
494
+ details?: Record<string, unknown> | undefined;
495
+ } | undefined;
496
+ }>, "many">;
497
+ endpoints: z.ZodArray<z.ZodObject<{
498
+ label: z.ZodString;
499
+ url: z.ZodString;
500
+ pluginId: z.ZodString;
501
+ priority: z.ZodNumber;
502
+ }, "strip", z.ZodTypeAny, {
503
+ pluginId: string;
504
+ label: string;
505
+ url: string;
506
+ priority: number;
507
+ }, {
508
+ pluginId: string;
509
+ label: string;
510
+ url: string;
511
+ priority: number;
512
+ }>, "many">;
513
+ }, "strip", z.ZodTypeAny, {
514
+ model: string;
515
+ version: string;
516
+ uptime: number;
517
+ entities: number;
518
+ embeddings: number;
519
+ ai: {
520
+ model: string;
521
+ embeddingModel: string;
522
+ };
523
+ daemons: {
524
+ status: string;
525
+ name: string;
526
+ pluginId: string;
527
+ health?: {
528
+ status: "unknown" | "healthy" | "warning" | "error";
529
+ message?: string | undefined;
530
+ lastCheck?: string | undefined;
531
+ details?: Record<string, unknown> | undefined;
532
+ } | undefined;
533
+ }[];
534
+ endpoints: {
535
+ pluginId: string;
536
+ label: string;
537
+ url: string;
538
+ priority: number;
539
+ }[];
540
+ }, {
541
+ model: string;
542
+ version: string;
543
+ uptime: number;
544
+ entities: number;
545
+ embeddings: number;
546
+ ai: {
547
+ model: string;
548
+ embeddingModel: string;
549
+ };
550
+ daemons: {
551
+ status: string;
552
+ name: string;
553
+ pluginId: string;
554
+ health?: {
555
+ status: "unknown" | "healthy" | "warning" | "error";
556
+ message?: string | undefined;
557
+ lastCheck?: string | undefined;
558
+ details?: Record<string, unknown> | undefined;
559
+ } | undefined;
560
+ }[];
561
+ endpoints: {
562
+ pluginId: string;
563
+ label: string;
564
+ url: string;
565
+ priority: number;
566
+ }[];
567
+ }>;
568
+ type AppInfo = z.infer<typeof AppInfoSchema>;
569
+
570
+ declare const ConversationSchema: z.ZodObject<{
571
+ id: z.ZodString;
572
+ sessionId: z.ZodString;
573
+ interfaceType: z.ZodString;
574
+ channelId: z.ZodString;
575
+ channelName: z.ZodOptional<z.ZodString>;
576
+ startedAt: z.ZodString;
577
+ lastActiveAt: z.ZodString;
578
+ createdAt: z.ZodString;
579
+ updatedAt: z.ZodString;
580
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
581
+ }, "strip", z.ZodTypeAny, {
582
+ interfaceType: string;
583
+ channelId: string;
584
+ id: string;
585
+ sessionId: string;
586
+ startedAt: string;
587
+ lastActiveAt: string;
588
+ createdAt: string;
589
+ updatedAt: string;
590
+ metadata: Record<string, unknown>;
591
+ channelName?: string | undefined;
592
+ }, {
593
+ interfaceType: string;
594
+ channelId: string;
595
+ id: string;
596
+ sessionId: string;
597
+ startedAt: string;
598
+ lastActiveAt: string;
599
+ createdAt: string;
600
+ updatedAt: string;
601
+ metadata: Record<string, unknown>;
602
+ channelName?: string | undefined;
603
+ }>;
604
+ type Conversation = z.infer<typeof ConversationSchema>;
605
+ declare const messageRoleSchema: z.ZodEnum<["user", "assistant", "system"]>;
606
+ type MessageRole = z.infer<typeof messageRoleSchema>;
607
+ declare const MessageSchema: z.ZodObject<{
608
+ id: z.ZodString;
609
+ conversationId: z.ZodString;
610
+ role: z.ZodEnum<["user", "assistant", "system"]>;
611
+ content: z.ZodString;
612
+ timestamp: z.ZodString;
613
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
614
+ }, "strip", z.ZodTypeAny, {
615
+ id: string;
616
+ metadata: Record<string, unknown>;
617
+ conversationId: string;
618
+ role: "user" | "assistant" | "system";
619
+ content: string;
620
+ timestamp: string;
621
+ }, {
622
+ id: string;
623
+ metadata: Record<string, unknown>;
624
+ conversationId: string;
625
+ role: "user" | "assistant" | "system";
626
+ content: string;
627
+ timestamp: string;
628
+ }>;
629
+ type Message = z.infer<typeof MessageSchema>;
630
+
631
+ declare const BrainCharacterSchema: z.ZodObject<{
632
+ name: z.ZodString;
633
+ role: z.ZodString;
634
+ purpose: z.ZodString;
635
+ values: z.ZodArray<z.ZodString, "many">;
636
+ }, "strip", z.ZodTypeAny, {
637
+ values: string[];
638
+ name: string;
639
+ role: string;
640
+ purpose: string;
641
+ }, {
642
+ values: string[];
643
+ name: string;
644
+ role: string;
645
+ purpose: string;
646
+ }>;
647
+ type BrainCharacter = z.infer<typeof BrainCharacterSchema>;
648
+ declare const AnchorProfileSchema: z.ZodObject<{
649
+ name: z.ZodString;
650
+ kind: z.ZodEnum<["professional", "team", "collective"]>;
651
+ organization: z.ZodOptional<z.ZodString>;
652
+ description: z.ZodOptional<z.ZodString>;
653
+ avatar: z.ZodOptional<z.ZodString>;
654
+ website: z.ZodOptional<z.ZodString>;
655
+ email: z.ZodOptional<z.ZodString>;
656
+ socialLinks: z.ZodOptional<z.ZodArray<z.ZodObject<{
657
+ platform: z.ZodEnum<["github", "instagram", "linkedin", "email", "website"]>;
658
+ url: z.ZodString;
659
+ label: z.ZodOptional<z.ZodString>;
660
+ }, "strip", z.ZodTypeAny, {
661
+ url: string;
662
+ platform: "website" | "email" | "github" | "instagram" | "linkedin";
663
+ label?: string | undefined;
664
+ }, {
665
+ url: string;
666
+ platform: "website" | "email" | "github" | "instagram" | "linkedin";
667
+ label?: string | undefined;
668
+ }>, "many">>;
669
+ }, "strip", z.ZodTypeAny, {
670
+ name: string;
671
+ kind: "professional" | "team" | "collective";
672
+ description?: string | undefined;
673
+ organization?: string | undefined;
674
+ avatar?: string | undefined;
675
+ website?: string | undefined;
676
+ email?: string | undefined;
677
+ socialLinks?: {
678
+ url: string;
679
+ platform: "website" | "email" | "github" | "instagram" | "linkedin";
680
+ label?: string | undefined;
681
+ }[] | undefined;
682
+ }, {
683
+ name: string;
684
+ kind: "professional" | "team" | "collective";
685
+ description?: string | undefined;
686
+ organization?: string | undefined;
687
+ avatar?: string | undefined;
688
+ website?: string | undefined;
689
+ email?: string | undefined;
690
+ socialLinks?: {
691
+ url: string;
692
+ platform: "website" | "email" | "github" | "instagram" | "linkedin";
693
+ label?: string | undefined;
694
+ }[] | undefined;
695
+ }>;
696
+ type AnchorProfile = z.infer<typeof AnchorProfileSchema>;
697
+
698
+ declare const MessageResponseSchema: z.ZodUnion<[z.ZodObject<{
699
+ success: z.ZodBoolean;
700
+ data: z.ZodOptional<z.ZodUnknown>;
701
+ error: z.ZodOptional<z.ZodString>;
702
+ }, "strip", z.ZodTypeAny, {
703
+ success: boolean;
704
+ data?: unknown;
705
+ error?: string | undefined;
706
+ }, {
707
+ success: boolean;
708
+ data?: unknown;
709
+ error?: string | undefined;
710
+ }>, z.ZodObject<{
711
+ noop: z.ZodLiteral<true>;
712
+ }, "strip", z.ZodTypeAny, {
713
+ noop: true;
714
+ }, {
715
+ noop: true;
716
+ }>]>;
717
+ type MessageResponse<T = unknown> = ({
718
+ success: boolean;
719
+ error?: string | undefined;
720
+ } & {
721
+ data?: T | undefined;
722
+ }) | {
723
+ noop: true;
724
+ };
725
+ declare const BaseMessageSchema: z.ZodObject<{
726
+ id: z.ZodString;
727
+ timestamp: z.ZodString;
728
+ type: z.ZodString;
729
+ source: z.ZodString;
730
+ target: z.ZodOptional<z.ZodString>;
731
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
732
+ }, "strip", z.ZodTypeAny, {
733
+ type: string;
734
+ id: string;
735
+ timestamp: string;
736
+ source: string;
737
+ metadata?: Record<string, unknown> | undefined;
738
+ target?: string | undefined;
739
+ }, {
740
+ type: string;
741
+ id: string;
742
+ timestamp: string;
743
+ source: string;
744
+ metadata?: Record<string, unknown> | undefined;
745
+ target?: string | undefined;
746
+ }>;
747
+ type BaseMessage = z.infer<typeof BaseMessageSchema>;
748
+ type MessageWithPayload<T = unknown> = BaseMessage & {
749
+ payload: T;
750
+ };
751
+ interface MessageSendOptions {
752
+ broadcast?: boolean;
753
+ }
754
+ type MessageSender<T = unknown, R = unknown> = (type: string, payload: T, options?: MessageSendOptions) => Promise<MessageResponse<R>>;
755
+ interface MessageContext {
756
+ userId?: string;
757
+ channelId?: string;
758
+ messageId?: string;
759
+ timestamp?: string;
760
+ interfaceType?: string;
761
+ userPermissionLevel?: "public" | "trusted" | "anchor";
762
+ threadId?: string;
763
+ }
764
+
765
+ type PluginConfig = Record<string, unknown>;
766
+ type PluginConfigInput<T extends z.ZodTypeAny> = z.input<T>;
767
+ interface Plugin {
768
+ readonly id: string;
769
+ readonly version: string;
770
+ readonly type: "core" | "entity" | "service" | "interface";
771
+ readonly packageName: string;
772
+ readonly description?: string;
773
+ readonly dependencies?: string[];
774
+ ready?(): Promise<void>;
775
+ shutdown?(): Promise<void>;
776
+ requiresDaemonStartup?(): boolean;
777
+ }
778
+ type PluginFactory = (config: PluginConfig) => Plugin | Plugin[];
779
+ interface Logger {
780
+ debug(message: string, data?: unknown): void;
781
+ info(message: string, data?: unknown): void;
782
+ warn(message: string, data?: unknown): void;
783
+ error(message: string, data?: unknown): void;
784
+ child(context: string): Logger;
785
+ }
786
+ interface ToolContext {
787
+ progressToken?: string | number;
788
+ sendProgress?: (notification: {
789
+ progress?: number;
790
+ total?: number;
791
+ message?: string;
792
+ }) => Promise<void>;
793
+ interfaceType?: string;
794
+ userId?: string;
795
+ channelId?: string;
796
+ channelName?: string;
797
+ }
798
+ interface ToolResponse<T = unknown> {
799
+ success: boolean;
800
+ data?: T;
801
+ error?: string;
802
+ }
803
+ type ToolVisibility = "public" | "trusted" | "anchor";
804
+ interface ToolConfirmation {
805
+ required: boolean;
806
+ message?: string;
807
+ }
808
+ interface Tool<TArgs = unknown, TResult = unknown> {
809
+ name: string;
810
+ description: string;
811
+ inputSchema: z.ZodRawShape;
812
+ handler: (args: TArgs, context: ToolContext) => Promise<TResult> | TResult;
813
+ visibility?: ToolVisibility;
814
+ confirmation?: ToolConfirmation;
815
+ }
816
+ interface Resource<TResult = unknown> {
817
+ uri: string;
818
+ name: string;
819
+ description?: string;
820
+ mimeType?: string;
821
+ handler: () => Promise<TResult> | TResult;
822
+ }
823
+ interface ResourceTemplate<K extends string = string> {
824
+ uriTemplate: K;
825
+ name: string;
826
+ description?: string;
827
+ mimeType?: string;
828
+ }
829
+ interface Prompt {
830
+ name: string;
831
+ description?: string;
832
+ arguments?: Array<{
833
+ name: string;
834
+ description?: string;
835
+ required?: boolean;
836
+ }>;
837
+ }
838
+ declare function createTool<TArgs = unknown, TResult = unknown>(tool: Tool<TArgs, TResult>): Tool<TArgs, TResult>;
839
+ declare function createResource<TResult = unknown>(resource: Resource<TResult>): Resource<TResult>;
840
+ declare function toolSuccess<T = unknown>(data?: T): ToolResponse<T>;
841
+ declare function toolError(error: string): ToolResponse<never>;
842
+ interface BaseJobTrackingInfo {
843
+ rootJobId: string;
844
+ }
845
+ interface MessageJobTrackingInfo extends BaseJobTrackingInfo {
846
+ messageId?: string;
847
+ channelId?: string;
848
+ }
849
+ type JobProgressStatus = "pending" | "processing" | "completed" | "failed";
850
+ interface JobProgressContext {
851
+ rootJobId: string;
852
+ operationType: "file_operations" | "content_operations" | "data_processing" | "batch_processing";
853
+ pluginId?: string | undefined;
854
+ progressToken?: string | number | undefined;
855
+ operationTarget?: string | undefined;
856
+ interfaceType?: string | undefined;
857
+ channelId?: string | undefined;
858
+ }
859
+ interface JobProgressEvent {
860
+ id: string;
861
+ type: "job" | "batch";
862
+ status: JobProgressStatus;
863
+ message?: string | undefined;
864
+ progress?: {
865
+ current: number;
866
+ total: number;
867
+ percentage: number;
868
+ } | undefined;
869
+ aggregationKey?: string | undefined;
870
+ batchDetails?: {
871
+ totalOperations: number;
872
+ completedOperations: number;
873
+ failedOperations: number;
874
+ currentOperation?: string | undefined;
875
+ errors?: string[] | undefined;
876
+ } | undefined;
877
+ jobDetails?: {
878
+ jobType: string;
879
+ priority: number;
880
+ retryCount: number;
881
+ } | undefined;
882
+ metadata: JobProgressContext;
883
+ }
884
+ declare const urlCaptureConfigSchema: z.ZodObject<{
885
+ captureUrls: z.ZodDefault<z.ZodBoolean>;
886
+ blockedUrlDomains: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
887
+ }, "strip", z.ZodTypeAny, {
888
+ captureUrls: boolean;
889
+ blockedUrlDomains: string[];
890
+ }, {
891
+ captureUrls?: boolean | undefined;
892
+ blockedUrlDomains?: string[] | undefined;
893
+ }>;
894
+ interface Channel<TPayload, TResponse = unknown> {
895
+ readonly name: string;
896
+ readonly schema: z.ZodType<TPayload>;
897
+ readonly _response?: TResponse;
898
+ }
899
+ declare function defineChannel<TPayload, TResponse = unknown>(name: string, schema: z.ZodType<TPayload>): Channel<TPayload, TResponse>;
900
+ interface IEntityService {
901
+ getEntity<T = unknown>(entityType: string, id: string): Promise<T | null>;
902
+ listEntities<T = unknown>(type: string, options?: unknown): Promise<T[]>;
903
+ search<T = unknown>(query: string, options?: unknown): Promise<T[]>;
904
+ getEntityTypes(): string[];
905
+ hasEntityType(type: string): boolean;
906
+ countEntities(entityType: string, options?: unknown): Promise<number>;
907
+ getEntityCounts(): Promise<Array<{
908
+ entityType: string;
909
+ count: number;
910
+ }>>;
911
+ }
912
+ interface IIdentityNamespace {
913
+ get: () => BrainCharacter;
914
+ getProfile: () => AnchorProfile;
915
+ getAppInfo: () => Promise<AppInfo>;
916
+ }
917
+ interface IConversationsNamespace {
918
+ get(conversationId: string): Promise<Conversation | null>;
919
+ search(query: string): Promise<Conversation[]>;
920
+ list(options?: {
921
+ limit?: number;
922
+ updatedAfter?: string;
923
+ }): Promise<Conversation[]>;
924
+ getMessages(conversationId: string, options?: {
925
+ limit?: number;
926
+ range?: {
927
+ start: number;
928
+ end: number;
929
+ };
930
+ }): Promise<Message[]>;
931
+ }
932
+ interface IMessagingNamespace {
933
+ send: MessageSender;
934
+ subscribe<T = unknown, R = unknown>(channel: string | Channel<T, R>, handler: (message: MessageWithPayload<T>) => Promise<MessageResponse<R>>): () => void;
935
+ }
936
+ type EvalHandler<TInput = unknown, TOutput = unknown> = (input: TInput) => Promise<TOutput>;
937
+ type InsightHandler = (entityService: IEntityService) => Promise<Record<string, unknown>>;
938
+ interface IEvalNamespace {
939
+ registerHandler<TInput = unknown, TOutput = unknown>(handlerId: string, handler: EvalHandler<TInput, TOutput>): void;
940
+ }
941
+ interface IInsightsNamespace {
942
+ register(type: string, handler: InsightHandler): void;
943
+ }
944
+ interface BasePluginContext {
945
+ readonly pluginId: string;
946
+ readonly logger: Logger;
947
+ readonly dataDir: string;
948
+ readonly domain: string | undefined;
949
+ readonly siteUrl: string | undefined;
950
+ readonly previewUrl: string | undefined;
951
+ readonly appInfo: () => Promise<AppInfo>;
952
+ readonly entityService: IEntityService;
953
+ readonly identity: IIdentityNamespace;
954
+ readonly messaging: IMessagingNamespace;
955
+ readonly conversations: IConversationsNamespace;
956
+ readonly eval: IEvalNamespace;
957
+ readonly insights: IInsightsNamespace;
958
+ }
959
+ interface IEntitiesNamespace {
960
+ register<TEntity extends BaseEntity>(entityType: string, schema: z.ZodSchema<TEntity>, adapter: EntityAdapter<TEntity>, config?: EntityTypeConfig): void;
961
+ getAdapter<TEntity extends BaseEntity>(entityType: string): EntityAdapter<TEntity> | undefined;
962
+ update<TEntity extends BaseEntity>(entity: TEntity): Promise<{
963
+ entityId: string;
964
+ jobId: string;
965
+ }>;
966
+ registerDataSource(dataSource: DataSource): void;
967
+ registerCreateInterceptor(entityType: string, interceptor: (input: CreateInput, executionContext: CreateExecutionContext) => Promise<CreateInterceptionResult>): void;
968
+ }
969
+ interface IPromptsNamespace {
970
+ resolve(target: string, fallback: string): Promise<string>;
971
+ }
972
+ interface IServiceTemplatesNamespace {
973
+ register(templates: unknown): void;
974
+ }
975
+ interface IViewsNamespace {
976
+ register(views: unknown): void;
977
+ }
978
+ interface ServicePluginContext extends BasePluginContext {
979
+ readonly entities: IEntitiesNamespace;
980
+ readonly templates: IServiceTemplatesNamespace;
981
+ readonly views: IViewsNamespace;
982
+ readonly prompts: IPromptsNamespace;
983
+ registerInstructions(instructions: string): void;
984
+ }
985
+ interface EntityPluginContext extends BasePluginContext {
986
+ readonly entities: IEntitiesNamespace;
987
+ readonly prompts: IPromptsNamespace;
988
+ }
989
+ interface InterfacePluginContext extends BasePluginContext {
990
+ readonly agent: AgentNamespace;
991
+ }
992
+
993
+ declare abstract class EntityPlugin<TEntity extends BaseEntity = BaseEntity, TConfig = unknown> implements Plugin {
994
+ readonly type: "entity";
995
+ readonly id: string;
996
+ readonly version: string;
997
+ readonly packageName: string;
998
+ readonly description?: string;
999
+ abstract readonly entityType: string;
1000
+ abstract readonly schema: z.ZodSchema<TEntity>;
1001
+ abstract readonly adapter: EntityAdapter<TEntity>;
1002
+ private readonly delegate;
1003
+ protected constructor(id: string, packageJson: {
1004
+ name: string;
1005
+ version: string;
1006
+ description?: string;
1007
+ }, config: Partial<TConfig>, configSchema: z.ZodTypeAny);
1008
+ protected onRegister(_context: EntityPluginContext): Promise<void>;
1009
+ protected onReady(_context: EntityPluginContext): Promise<void>;
1010
+ protected onShutdown(): Promise<void>;
1011
+ protected getInstructions(): Promise<string | undefined>;
1012
+ protected getEntityTypeConfig(): EntityTypeConfig | undefined;
1013
+ protected getDataSources(): DataSource[];
1014
+ protected interceptCreate(input: CreateInput, _executionContext: CreateExecutionContext, _context: EntityPluginContext): Promise<CreateInterceptionResult>;
1015
+ ready(): Promise<void>;
1016
+ shutdown(): Promise<void>;
1017
+ }
1018
+
1019
+ declare const WebRouteMethods: readonly ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
1020
+ type WebRouteMethod = (typeof WebRouteMethods)[number];
1021
+ type WebRouteHandler = (request: Request) => Response | Promise<Response>;
1022
+ interface WebRouteDefinition {
1023
+ /** Absolute mounted path (e.g. "/cms" or "/cms-config") */
1024
+ path: string;
1025
+ /** HTTP method */
1026
+ method?: WebRouteMethod;
1027
+ /** Allow unauthenticated access */
1028
+ public?: boolean;
1029
+ /** Request handler */
1030
+ handler: WebRouteHandler;
1031
+ }
1032
+
1033
+ declare abstract class InterfacePlugin<TConfig = unknown, TTrackingInfo extends BaseJobTrackingInfo = BaseJobTrackingInfo> implements Plugin {
1034
+ readonly type: "interface";
1035
+ readonly id: string;
1036
+ readonly version: string;
1037
+ readonly packageName: string;
1038
+ readonly description?: string;
1039
+ private readonly delegate;
1040
+ protected constructor(id: string, packageJson: {
1041
+ name: string;
1042
+ version: string;
1043
+ description?: string;
1044
+ }, config: Partial<TConfig>, configSchema: z.ZodTypeAny);
1045
+ protected onRegister(_context: InterfacePluginContext): Promise<void>;
1046
+ protected onReady(_context: InterfacePluginContext): Promise<void>;
1047
+ protected onShutdown(): Promise<void>;
1048
+ protected getTools(): Promise<Tool[]>;
1049
+ protected getResources(): Promise<Resource[]>;
1050
+ protected getInstructions(): Promise<string | undefined>;
1051
+ getWebRoutes(): WebRouteDefinition[];
1052
+ requiresDaemonStartup(): boolean;
1053
+ ready(): Promise<void>;
1054
+ shutdown(): Promise<void>;
1055
+ }
1056
+
1057
+ declare abstract class MessageInterfacePlugin<TConfig = unknown, TTrackingInfo extends MessageJobTrackingInfo = MessageJobTrackingInfo> extends InterfacePlugin<TConfig, TTrackingInfo> {
1058
+ private readonly messageDelegate;
1059
+ protected constructor(id: string, packageJson: {
1060
+ name: string;
1061
+ version: string;
1062
+ description?: string;
1063
+ }, config: Partial<TConfig>, configSchema: z.ZodTypeAny);
1064
+ protected abstract sendMessageToChannel(channelId: string | null, message: string): void;
1065
+ protected onRegister(_context: InterfacePluginContext): Promise<void>;
1066
+ protected onReady(_context: InterfacePluginContext): Promise<void>;
1067
+ protected onShutdown(): Promise<void>;
1068
+ protected getTools(): Promise<Tool[]>;
1069
+ protected getResources(): Promise<Resource[]>;
1070
+ protected getInstructions(): Promise<string | undefined>;
1071
+ protected sendMessageWithId(_channelId: string | null, _message: string): Promise<string | undefined>;
1072
+ protected editMessage(_channelId: string, _messageId: string, _newMessage: string): Promise<boolean>;
1073
+ protected supportsMessageEditing(): boolean;
1074
+ protected onProgressUpdate(_event: JobProgressEvent): Promise<void>;
1075
+ protected trackAgentResponseForJob(jobId: string, messageId: string, channelId: string): void;
1076
+ registerProgressCallback(callback: (events: JobProgressEvent[]) => void): void;
1077
+ unregisterProgressCallback(): void;
1078
+ getProgressEvents(): JobProgressEvent[];
1079
+ getActiveProgressEvents(): JobProgressEvent[];
1080
+ startProcessingInput(channelId?: string | null): void;
1081
+ endProcessingInput(): void;
1082
+ protected getCurrentChannelId(): string | null;
1083
+ ready(): Promise<void>;
1084
+ shutdown(): Promise<void>;
1085
+ }
1086
+
1087
+ declare abstract class ServicePlugin<TConfig = unknown> implements Plugin {
1088
+ readonly type: "service";
1089
+ readonly id: string;
1090
+ readonly version: string;
1091
+ readonly packageName: string;
1092
+ readonly description?: string;
1093
+ private readonly delegate;
1094
+ protected constructor(id: string, packageJson: {
1095
+ name: string;
1096
+ version: string;
1097
+ description?: string;
1098
+ }, config: Partial<TConfig>, configSchema: z.ZodTypeAny);
1099
+ protected onRegister(_context: ServicePluginContext): Promise<void>;
1100
+ protected onReady(_context: ServicePluginContext): Promise<void>;
1101
+ protected onShutdown(): Promise<void>;
1102
+ protected getTools(): Promise<Tool[]>;
1103
+ protected getResources(): Promise<Resource[]>;
1104
+ protected getInstructions(): Promise<string | undefined>;
1105
+ ready(): Promise<void>;
1106
+ shutdown(): Promise<void>;
1107
+ }
1108
+
1109
+ /**
1110
+ * Best-effort extension metadata carried across public DTO boundaries.
1111
+ *
1112
+ * Individual keys are not stable public API. When a metadata value becomes a
1113
+ * documented contract, hoist it to a typed top-level field on the owning DTO
1114
+ * schema and keep this bag only as optional extension data.
1115
+ */
1116
+ declare const ExtensionMetadataSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
1117
+ type ExtensionMetadata = z.infer<typeof ExtensionMetadataSchema>;
1118
+
1119
+ export { AgentResponseSchema, AnchorProfileSchema, AppInfoSchema, BaseMessageSchema, BrainCharacterSchema, ChatContextSchema, ConversationSchema, EntityPlugin, ExtensionMetadataSchema, InterfacePlugin, MessageInterfacePlugin, MessageResponseSchema, MessageSchema, PendingConfirmationSchema, ServicePlugin, ToolResultDataSchema, createResource, createTool, defineChannel, toolError, toolSuccess, urlCaptureConfigSchema };
1120
+ export type { AgentNamespace, AgentResponse, AnchorProfile, AppInfo, BaseJobTrackingInfo, BaseMessage, BasePluginContext, BrainCharacter, Channel, ChatContext, Conversation, EntityPluginContext, ExtensionMetadata, IConversationsNamespace, IEntitiesNamespace, IEvalNamespace, IIdentityNamespace, IInsightsNamespace, IMessagingNamespace, IPromptsNamespace, IServiceTemplatesNamespace, IViewsNamespace, InterfacePluginContext, JobProgressContext, JobProgressEvent, JobProgressStatus, Message, MessageContext, MessageJobTrackingInfo, MessageResponse, MessageRole, MessageSendOptions, MessageSender, MessageWithPayload, PendingConfirmation, Plugin, PluginConfig, PluginConfigInput, PluginFactory, Prompt, Resource, ResourceTemplate, ServicePluginContext, Tool, ToolConfirmation, ToolContext, ToolResponse, ToolResultData, ToolVisibility };