@rizom/brain 0.2.0-alpha.45 → 0.2.0-alpha.47

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,523 @@
1
+ import type { z } from "zod";
2
+
3
+ export interface Logger {
4
+ debug(message: string, data?: unknown): void;
5
+ info(message: string, data?: unknown): void;
6
+ warn(message: string, data?: unknown): void;
7
+ error(message: string, data?: unknown): void;
8
+ child(context: string): Logger;
9
+ }
10
+ import type {
11
+ BaseEntity,
12
+ CreateExecutionContext,
13
+ CreateInput,
14
+ CreateInterceptionResult,
15
+ CreateInterceptor,
16
+ EntityAdapter,
17
+ EntityTypeConfig,
18
+ DataSource,
19
+ ListOptions,
20
+ SearchOptions,
21
+ SearchResult,
22
+ } from "./entities";
23
+ import type { Template, ViewTemplate, WebRenderer } from "./templates";
24
+ import type {
25
+ Daemon,
26
+ UserPermissionLevel,
27
+ ApiRouteDefinition,
28
+ WebRouteDefinition,
29
+ MessageResponse,
30
+ MessageSender,
31
+ MessageWithPayload,
32
+ MessageContext,
33
+ } from "./interfaces";
34
+ import type { BatchOperation, JobHandler, JobOptions } from "./services";
35
+
36
+ export interface ToolContext extends MessageContext {
37
+ progressToken?: string | number;
38
+ sendProgress?: (notification: {
39
+ progress?: number;
40
+ total?: number;
41
+ message?: string;
42
+ }) => Promise<void>;
43
+ }
44
+ export interface ToolResponse<T = unknown> {
45
+ success: boolean;
46
+ data?: T;
47
+ error?: string;
48
+ }
49
+ export type ToolVisibility = UserPermissionLevel;
50
+ export interface ToolConfirmation {
51
+ required: boolean;
52
+ message?: string;
53
+ }
54
+ export interface Tool<TArgs = unknown, TResult = unknown> {
55
+ name: string;
56
+ description: string;
57
+ inputSchema: z.ZodRawShape;
58
+ handler: (args: TArgs, context: ToolContext) => Promise<TResult> | TResult;
59
+ visibility?: ToolVisibility;
60
+ confirmation?: ToolConfirmation;
61
+ }
62
+ export interface Resource<TResult = unknown> {
63
+ uri: string;
64
+ name: string;
65
+ description?: string;
66
+ mimeType?: string;
67
+ handler: () => Promise<TResult> | TResult;
68
+ }
69
+ export interface ResourceTemplate<K extends string = string> {
70
+ uriTemplate: K;
71
+ name: string;
72
+ description?: string;
73
+ mimeType?: string;
74
+ }
75
+ export interface Prompt {
76
+ name: string;
77
+ description?: string;
78
+ arguments?: Array<{ name: string; description?: string; required?: boolean }>;
79
+ }
80
+ export function createTool<TArgs = unknown, TResult = unknown>(
81
+ tool: Tool<TArgs, TResult>,
82
+ ): Tool<TArgs, TResult>;
83
+ export function createResource<TResult = unknown>(
84
+ resource: Resource<TResult>,
85
+ ): Resource<TResult>;
86
+ export function toolSuccess<T = unknown>(data?: T): ToolResponse<T>;
87
+ export function toolError(error: string): ToolResponse<never>;
88
+
89
+ export interface PluginCapabilities {
90
+ tools: Tool[];
91
+ resources: Resource[];
92
+ instructions?: string;
93
+ }
94
+ export interface Plugin {
95
+ readonly id: string;
96
+ readonly version: string;
97
+ readonly type: "core" | "entity" | "service" | "interface";
98
+ readonly packageName: string;
99
+ readonly description?: string;
100
+ readonly dependencies?: string[];
101
+ ready?(): Promise<void>;
102
+ shutdown?(): Promise<void>;
103
+ requiresDaemonStartup?(): boolean;
104
+ }
105
+ export type PluginFactory = (config: PluginConfig) => Plugin | Plugin[];
106
+ export type PluginConfig = Record<string, unknown>;
107
+ export type PluginConfigInput<T extends z.ZodTypeAny> = z.input<T>;
108
+ export type InferPluginConfig<T extends z.ZodTypeAny> = z.infer<T>;
109
+ export const basePluginConfigSchema: z.ZodSchema<{
110
+ enabled: boolean;
111
+ debug: boolean;
112
+ }>;
113
+
114
+ export interface Channel<TPayload, TResponse = unknown> {
115
+ readonly name: string;
116
+ readonly schema: z.ZodType<TPayload>;
117
+ readonly _response?: TResponse;
118
+ }
119
+ export function defineChannel<TPayload, TResponse = unknown>(
120
+ name: string,
121
+ schema: z.ZodType<TPayload>,
122
+ ): Channel<TPayload, TResponse>;
123
+
124
+ export interface BaseJobTrackingInfo {
125
+ rootJobId: string;
126
+ }
127
+ export interface MessageJobTrackingInfo extends BaseJobTrackingInfo {
128
+ messageId?: string;
129
+ channelId?: string;
130
+ }
131
+
132
+ export interface BrainCharacter {
133
+ name: string;
134
+ role: string;
135
+ purpose: string;
136
+ values: string[];
137
+ }
138
+
139
+ export interface AnchorProfile {
140
+ name: string;
141
+ kind: "professional" | "team" | "collective";
142
+ organization?: string;
143
+ description?: string;
144
+ avatar?: string;
145
+ website?: string;
146
+ email?: string;
147
+ socialLinks?: Array<{
148
+ platform: "github" | "instagram" | "linkedin" | "email" | "website";
149
+ url: string;
150
+ label?: string;
151
+ }>;
152
+ }
153
+
154
+ export interface AppInfo {
155
+ model: string;
156
+ version: string;
157
+ uptime: number;
158
+ entities: number;
159
+ embeddings: number;
160
+ ai: { model: string; embeddingModel: string };
161
+ daemons: unknown[];
162
+ endpoints: Array<{
163
+ label: string;
164
+ url: string;
165
+ pluginId: string;
166
+ priority: number;
167
+ }>;
168
+ }
169
+
170
+ export interface Conversation {
171
+ id: string;
172
+ sessionId: string;
173
+ interfaceType: string;
174
+ channelId: string;
175
+ channelName: string;
176
+ metadata: string | null;
177
+ createdAt: string;
178
+ updatedAt: string;
179
+ }
180
+
181
+ export interface Message {
182
+ id: string;
183
+ conversationId: string;
184
+ role: string;
185
+ content: string;
186
+ timestamp: string;
187
+ metadata: string | null;
188
+ }
189
+
190
+ export interface GetMessagesOptions {
191
+ limit?: number;
192
+ range?: { start: number; end: number };
193
+ }
194
+
195
+ export interface IEntityService {
196
+ getEntity<T extends BaseEntity>(
197
+ entityType: string,
198
+ id: string,
199
+ ): Promise<T | null>;
200
+ listEntities<T extends BaseEntity>(
201
+ type: string,
202
+ options?: ListOptions,
203
+ ): Promise<T[]>;
204
+ search<T extends BaseEntity = BaseEntity>(
205
+ query: string,
206
+ options?: SearchOptions,
207
+ ): Promise<SearchResult<T>[]>;
208
+ getEntityTypes(): string[];
209
+ hasEntityType(type: string): boolean;
210
+ countEntities(
211
+ entityType: string,
212
+ options?: Pick<ListOptions, "publishedOnly">,
213
+ ): Promise<number>;
214
+ getEntityCounts(): Promise<Array<{ entityType: string; count: number }>>;
215
+ }
216
+
217
+ export type EvalHandler<TInput = unknown, TOutput = unknown> = (
218
+ input: TInput,
219
+ ) => Promise<TOutput>;
220
+
221
+ export type InsightHandler = (
222
+ entityService: IEntityService,
223
+ ) => Promise<Record<string, unknown>>;
224
+
225
+ export interface PendingConfirmation {
226
+ toolName: string;
227
+ description: string;
228
+ args: unknown;
229
+ }
230
+
231
+ export interface ToolResultData {
232
+ toolName: string;
233
+ args?: Record<string, unknown>;
234
+ jobId?: string;
235
+ data?: unknown;
236
+ }
237
+
238
+ export interface AgentResponse {
239
+ text: string;
240
+ toolResults?: ToolResultData[];
241
+ pendingConfirmation?: PendingConfirmation;
242
+ usage: {
243
+ promptTokens: number;
244
+ completionTokens: number;
245
+ totalTokens: number;
246
+ };
247
+ }
248
+
249
+ export interface ChatContext {
250
+ userPermissionLevel?: UserPermissionLevel;
251
+ interfaceType?: string;
252
+ channelId?: string;
253
+ channelName?: string;
254
+ }
255
+
256
+ export interface IAgentService {
257
+ chat(
258
+ message: string,
259
+ conversationId: string,
260
+ context?: ChatContext,
261
+ ): Promise<AgentResponse>;
262
+ }
263
+
264
+ export interface BasePluginContext {
265
+ readonly pluginId: string;
266
+ readonly logger: Logger;
267
+ readonly dataDir: string;
268
+ readonly domain: string | undefined;
269
+ readonly siteUrl: string | undefined;
270
+ readonly previewUrl: string | undefined;
271
+ readonly appInfo: () => Promise<AppInfo>;
272
+ readonly entityService: IEntityService;
273
+ readonly identity: {
274
+ get: () => BrainCharacter;
275
+ getProfile: () => AnchorProfile;
276
+ getAppInfo: () => Promise<AppInfo>;
277
+ };
278
+ readonly messaging: {
279
+ send: MessageSender;
280
+ subscribe: <T = unknown, R = unknown>(
281
+ channel: string | Channel<T, R>,
282
+ handler: (
283
+ message: MessageWithPayload<T> | T,
284
+ ) => Promise<MessageResponse<R>> | MessageResponse<R>,
285
+ ) => () => void;
286
+ };
287
+ readonly jobs: {
288
+ enqueue(
289
+ type: string,
290
+ data: unknown,
291
+ toolContext?: ToolContext | null,
292
+ options?: JobOptions,
293
+ ): Promise<string>;
294
+ enqueueBatch(
295
+ operations: BatchOperation[],
296
+ options?: JobOptions,
297
+ ): Promise<string>;
298
+ registerHandler(type: string, handler: JobHandler): void;
299
+ };
300
+ readonly conversations: {
301
+ get(conversationId: string): Promise<Conversation | null>;
302
+ search(query: string): Promise<Conversation[]>;
303
+ getMessages(
304
+ conversationId: string,
305
+ options?: GetMessagesOptions,
306
+ ): Promise<Message[]>;
307
+ };
308
+ readonly eval: {
309
+ registerHandler<TInput = unknown, TOutput = unknown>(
310
+ handlerId: string,
311
+ handler: EvalHandler<TInput, TOutput>,
312
+ ): void;
313
+ };
314
+ readonly insights: {
315
+ register(type: string, handler: InsightHandler): void;
316
+ };
317
+ readonly endpoints: {
318
+ register(endpoint: { label: string; url: string; priority?: number }): void;
319
+ };
320
+ }
321
+
322
+ export interface EntityPluginContext extends BasePluginContext {
323
+ readonly entityService: IEntityService;
324
+ readonly entities: {
325
+ register<T extends BaseEntity>(
326
+ entityType: string,
327
+ schema: z.ZodSchema<T>,
328
+ adapter: EntityAdapter<T>,
329
+ config?: EntityTypeConfig,
330
+ ): void;
331
+ getAdapter<T extends BaseEntity>(
332
+ entityType: string,
333
+ ): EntityAdapter<T> | undefined;
334
+ extendFrontmatterSchema(
335
+ type: string,
336
+ extension: z.ZodObject<z.ZodRawShape>,
337
+ ): void;
338
+ getEffectiveFrontmatterSchema(
339
+ type: string,
340
+ ): z.ZodObject<z.ZodRawShape> | undefined;
341
+ update<T extends BaseEntity>(
342
+ entity: T,
343
+ ): Promise<{ entityId: string; jobId: string }>;
344
+ registerDataSource(dataSource: DataSource): void;
345
+ registerCreateInterceptor(
346
+ entityType: string,
347
+ interceptor: CreateInterceptor,
348
+ ): void;
349
+ };
350
+ readonly ai: {
351
+ query(prompt: string, context?: ChatContext): Promise<AgentResponse>;
352
+ generate<T = unknown>(config: Record<string, unknown>): Promise<T>;
353
+ generateObject<T>(
354
+ prompt: string,
355
+ schema: z.ZodType<T>,
356
+ ): Promise<{ object: T }>;
357
+ generateImage(
358
+ prompt: string,
359
+ options?: Record<string, unknown>,
360
+ ): Promise<{ url?: string; data?: Uint8Array; mimeType?: string }>;
361
+ canGenerateImages(): boolean;
362
+ };
363
+ readonly prompts: {
364
+ resolve(target: string, fallback: string): Promise<string>;
365
+ };
366
+ }
367
+ export interface ServicePluginContext extends BasePluginContext {
368
+ readonly entityService: IEntityService;
369
+ readonly entities: EntityPluginContext["entities"];
370
+ readonly templates: {
371
+ register(templates: Record<string, Template>, namespace?: string): void;
372
+ format<T = unknown>(templateName: string, data: T): string;
373
+ parse<T = unknown>(templateName: string, content: string): T;
374
+ resolve<T = unknown>(
375
+ templateName: string,
376
+ options?: Record<string, unknown>,
377
+ ): Promise<T | null>;
378
+ };
379
+ readonly views: {
380
+ get(name: string): ViewTemplate | undefined;
381
+ list(): ViewTemplate[];
382
+ hasRenderer(templateName: string): boolean;
383
+ getRenderer(templateName: string): WebRenderer | undefined;
384
+ validate(templateName: string, content: unknown): boolean;
385
+ };
386
+ readonly prompts: EntityPluginContext["prompts"];
387
+ registerInstructions(instructions: string): void;
388
+ }
389
+ export interface InterfacePluginContext extends BasePluginContext {
390
+ readonly mcpTransport: unknown;
391
+ readonly agentService: IAgentService;
392
+ readonly permissions: {
393
+ getUserLevel(interfaceType: string, userId: string): UserPermissionLevel;
394
+ };
395
+ readonly daemons: { register(name: string, daemon: Daemon): void };
396
+ readonly conversations: BasePluginContext["conversations"] & {
397
+ start(
398
+ conversationId: string,
399
+ interfaceType: string,
400
+ channelId: string,
401
+ metadata: Record<string, unknown>,
402
+ ): Promise<string>;
403
+ addMessage(
404
+ conversationId: string,
405
+ role: string,
406
+ content: string,
407
+ metadata?: Record<string, unknown>,
408
+ ): Promise<void>;
409
+ };
410
+ readonly tools: {
411
+ listForPermissionLevel(level: UserPermissionLevel): unknown[];
412
+ };
413
+ readonly apiRoutes: { getRoutes(): unknown[]; getMessageBus(): unknown };
414
+ readonly webRoutes: { getRoutes(): unknown[] };
415
+ readonly plugins: { has(pluginId: string): boolean };
416
+ }
417
+
418
+ export type DeriveEvent = "created" | "updated" | "deleted" | "extract";
419
+ export abstract class EntityPlugin<
420
+ TEntity extends BaseEntity = BaseEntity,
421
+ TConfig = Record<string, never>,
422
+ > implements Plugin {
423
+ readonly type: "entity";
424
+ readonly id: string;
425
+ readonly version: string;
426
+ readonly packageName: string;
427
+ readonly description?: string;
428
+ abstract readonly entityType: string;
429
+ abstract readonly schema: z.ZodSchema<TEntity>;
430
+ abstract readonly adapter: EntityAdapter<TEntity>;
431
+ protected constructor(
432
+ id: string,
433
+ packageJson: { name: string; version: string; description?: string },
434
+ config?: Partial<TConfig>,
435
+ configSchema?: z.ZodTypeAny,
436
+ );
437
+ protected onRegister(context: EntityPluginContext): Promise<void>;
438
+ protected onReady(context: EntityPluginContext): Promise<void>;
439
+ protected onShutdown(): Promise<void>;
440
+ protected interceptCreate(
441
+ input: CreateInput,
442
+ executionContext: CreateExecutionContext,
443
+ context: EntityPluginContext,
444
+ ): Promise<CreateInterceptionResult>;
445
+ protected createGenerationHandler(
446
+ context: EntityPluginContext,
447
+ ): JobHandler | null;
448
+ protected getTemplates(): Record<string, Template> | null;
449
+ protected getDataSources(): DataSource[];
450
+ protected getEntityTypeConfig(): EntityTypeConfig | undefined;
451
+ protected derive(
452
+ source: BaseEntity,
453
+ event: DeriveEvent,
454
+ context: EntityPluginContext,
455
+ ): Promise<void>;
456
+ protected deriveAll(context: EntityPluginContext): Promise<void>;
457
+ protected rebuildAll(context: EntityPluginContext): Promise<void>;
458
+ ready?(): Promise<void>;
459
+ shutdown?(): Promise<void>;
460
+ }
461
+ export abstract class ServicePlugin<TConfig = unknown> implements Plugin {
462
+ readonly type: "service";
463
+ readonly id: string;
464
+ readonly version: string;
465
+ readonly packageName: string;
466
+ readonly description?: string;
467
+ protected constructor(
468
+ id: string,
469
+ packageJson: { name: string; version: string; description?: string },
470
+ config?: Partial<TConfig>,
471
+ configSchema?: z.ZodTypeAny,
472
+ );
473
+ protected onRegister(context: ServicePluginContext): Promise<void>;
474
+ protected onReady(context: ServicePluginContext): Promise<void>;
475
+ protected onShutdown(): Promise<void>;
476
+ protected getTools(): Promise<Tool[]>;
477
+ protected getResources(): Promise<Resource[]>;
478
+ protected getInstructions(): Promise<string | undefined>;
479
+ getApiRoutes(): ApiRouteDefinition[];
480
+ getWebRoutes(): WebRouteDefinition[];
481
+ ready?(): Promise<void>;
482
+ shutdown?(): Promise<void>;
483
+ }
484
+ export abstract class InterfacePlugin<
485
+ TConfig = unknown,
486
+ TTrackingInfo extends BaseJobTrackingInfo = BaseJobTrackingInfo,
487
+ > implements Plugin {
488
+ readonly type: "interface";
489
+ readonly id: string;
490
+ readonly version: string;
491
+ readonly packageName: string;
492
+ readonly description?: string;
493
+ protected readonly jobTrackingEntries: Map<string, TTrackingInfo>;
494
+ protected constructor(
495
+ id: string,
496
+ packageJson: { name: string; version: string; description?: string },
497
+ config?: Partial<TConfig>,
498
+ configSchema?: z.ZodTypeAny,
499
+ );
500
+ protected onRegister(context: InterfacePluginContext): Promise<void>;
501
+ protected onReady(context: InterfacePluginContext): Promise<void>;
502
+ protected onShutdown(): Promise<void>;
503
+ protected createDaemon(): Daemon | undefined;
504
+ requiresDaemonStartup(): boolean;
505
+ getWebRoutes(): WebRouteDefinition[];
506
+ ready?(): Promise<void>;
507
+ shutdown?(): Promise<void>;
508
+ }
509
+ export abstract class MessageInterfacePlugin<
510
+ TConfig = unknown,
511
+ TTrackingInfo extends MessageJobTrackingInfo = MessageJobTrackingInfo,
512
+ > extends InterfacePlugin<TConfig, TTrackingInfo> {
513
+ protected isUploadableTextFile(filename: string, mimetype?: string): boolean;
514
+ protected isFileSizeAllowed(size: number): boolean;
515
+ protected formatFileUploadMessage(filename: string, content: string): string;
516
+ }
517
+
518
+ export const urlCaptureConfigSchema: z.ZodSchema<{
519
+ captureUrls: boolean;
520
+ blockedUrlDomains: string[];
521
+ }>;
522
+ export function parseConfirmationResponse(input: string): boolean | undefined;
523
+ export function formatConfirmationPrompt(action: string): string;