@rizom/site-rizom-ai 0.2.0-alpha.258 → 0.2.0-alpha.260

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/index.d.ts +4350 -110
  2. package/dist/index.js +4489 -7892
  3. package/dist/index.js.map +43 -27
  4. package/package.json +1 -1
  5. package/src/brain.tsx +165 -311
  6. package/src/favicon.svg +1 -0
  7. package/src/foundation.tsx +120 -95
  8. package/src/index.ts +0 -1
  9. package/src/layout.tsx +87 -265
  10. package/src/living-memory.tsx +86 -291
  11. package/src/opening-datasource.ts +82 -0
  12. package/src/opening.tsx +218 -0
  13. package/src/rizom/create-site.ts +17 -2
  14. package/src/rizom/runtime/boot/boot.boot.js +1 -82
  15. package/src/rizom/runtime/plugin.ts +20 -10
  16. package/src/routes.ts +14 -53
  17. package/src/shared.ts +14 -0
  18. package/src/site.ts +15 -13
  19. package/src/story/brain-organism.tsx +153 -0
  20. package/src/story/emphasis.tsx +11 -0
  21. package/src/story/foundation-organism.tsx +150 -0
  22. package/src/story/living-organism.tsx +213 -0
  23. package/src/story/network.ts +81 -0
  24. package/src/story/organism.tsx +223 -0
  25. package/src/story/runtime.ts +116 -0
  26. package/src/story/story-page.tsx +72 -0
  27. package/src/story/work-organism.tsx +159 -0
  28. package/src/story.css +1231 -0
  29. package/src/work.tsx +105 -292
  30. package/src/writing-datasource.ts +71 -0
  31. package/src/writing.css +201 -0
  32. package/src/writing.tsx +199 -0
  33. package/src/assets/brain/README.md +0 -11
  34. package/src/assets/brain/chat-desktop-dark.svg +0 -1
  35. package/src/assets/brain/chat-desktop-light.svg +0 -1
  36. package/src/assets/brain/chat-mobile-dark.svg +0 -1
  37. package/src/assets/brain/chat-mobile-light.svg +0 -1
  38. package/src/brain-assets.ts +0 -12
  39. package/src/brain-network.tsx +0 -113
  40. package/src/brain-screens.tsx +0 -474
  41. package/src/brain.css +0 -1453
  42. package/src/growth-diagram.tsx +0 -343
  43. package/src/home.tsx +0 -218
  44. package/src/living-memory-art.tsx +0 -394
  45. package/src/living-memory-maps.css +0 -326
  46. package/src/living-memory.css +0 -1771
  47. package/src/shared.tsx +0 -276
package/dist/index.d.ts CHANGED
@@ -1,22 +1,25 @@
1
- import { JSX, ReactNode } from "react";
2
- import { z } from "zod/v4";
1
+ import { JSX, ReactElement, ReactNode } from "react";
2
+ import { ZodRawShape, ZodType, z, z as z$1 } from "zod/v4";
3
+ import { LibSQLDatabase } from "drizzle-orm/libsql";
4
+ import { SQLiteColumn, SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
5
+ import { McpServer, ToolAnnotations } from "@modelcontextprotocol/server";
3
6
  //#region ../../packages/site/src/index.d.ts
4
7
  /** Permission levels for editable site content templates. */
5
- type UserPermissionLevel = "admin" | "trusted" | "public";
6
- type JsonPrimitive = null | boolean | number | string;
7
- type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;
8
+ type UserPermissionLevel$1 = "admin" | "trusted" | "public";
9
+ type JsonPrimitive$1 = null | boolean | number | string;
10
+ type JsonValue$1 = JsonPrimitive$1 | JsonValue$1[] | JsonObject$1;
8
11
  /** A JSON document with an object at its root. */
9
- interface JsonObject {
10
- [key: string]: JsonValue;
12
+ interface JsonObject$1 {
13
+ [key: string]: JsonValue$1;
11
14
  }
12
15
  /** Runtime script declaration attached to a content section/template. */
13
- interface RuntimeScript {
16
+ interface RuntimeScript$1 {
14
17
  src: string;
15
18
  defer?: boolean;
16
19
  module?: boolean;
17
20
  }
18
21
  /** Bivariant component type for author-supplied layout components. */
19
- type ComponentType<P = unknown> = {
22
+ type ComponentType$1<P = unknown> = {
20
23
  bivarianceHack(props: P): JSX.Element;
21
24
  }["bivarianceHack"];
22
25
  /** Navigation slot types exposed to authored routes and generated entity routes. */
@@ -89,11 +92,11 @@ type SiteContentFieldDefinition = SiteContentStringFieldDefinition | SiteContent
89
92
  interface SiteContentSectionDefinition {
90
93
  description: string;
91
94
  title: string;
92
- layout: ComponentType<unknown>;
95
+ layout: ComponentType$1<unknown>;
93
96
  fields: Record<string, SiteContentFieldDefinition>;
94
- requiredPermission?: UserPermissionLevel;
97
+ requiredPermission?: UserPermissionLevel$1;
95
98
  fullscreen?: boolean;
96
- runtimeScripts?: RuntimeScript[];
99
+ runtimeScripts?: RuntimeScript$1[];
97
100
  }
98
101
  interface SiteContentDefinition {
99
102
  namespace: string;
@@ -103,16 +106,16 @@ interface SiteContentDefinition {
103
106
  interface SectionMeta {
104
107
  title: string;
105
108
  description: string;
106
- requiredPermission?: UserPermissionLevel | undefined;
109
+ requiredPermission?: UserPermissionLevel$1 | undefined;
107
110
  fullscreen?: boolean | undefined;
108
111
  }
109
112
  /**
110
113
  * A schema-first content section. Its component props are inferred from the
111
114
  * same schema used by runtime validation, markdown formatting, and editing.
112
115
  */
113
- interface SiteSectionDefinition<S extends z.ZodType = z.ZodType<JsonObject>> extends SectionMeta {
116
+ interface SiteSectionDefinition<S extends z$1.ZodType = z$1.ZodType<JsonObject$1>> extends SectionMeta {
114
117
  schema: S;
115
- component: ComponentType<z.output<S>>;
118
+ component: ComponentType$1<z$1.output<S>>;
116
119
  }
117
120
  interface SiteSectionGroup {
118
121
  namespace: string;
@@ -165,12 +168,12 @@ interface SiteLayoutProps {
165
168
  }
166
169
  /** Initial section content keyed by section-group namespace and section id. */
167
170
  interface SiteContent {
168
- [namespace: string]: Record<string, JsonObject>;
171
+ [namespace: string]: Record<string, JsonObject$1>;
169
172
  }
170
173
  /** Declarative site-package shape authored by public site packages. */
171
174
  interface SiteDefinition {
172
175
  /** Layout components keyed by name — a `default` layout is required. */
173
- layouts: Record<string, ComponentType<SiteLayoutProps>>;
176
+ layouts: Record<string, ComponentType$1<SiteLayoutProps>>;
174
177
  /** Hand-written route definitions (home, about, etc.). */
175
178
  routes: RouteDefinitionInput[];
176
179
  /** Optional initial content validated by the corresponding section schema. */
@@ -187,28 +190,28 @@ interface SiteDefinition {
187
190
  staticAssets?: Record<string, string> | undefined;
188
191
  }
189
192
  type SiteDefinitionOverrides = { [K in keyof SiteDefinition]?: SiteDefinition[K] | undefined; };
190
- type Strict<Shape extends z.ZodRawShape> = z.ZodObject<Shape, z.core.$strict>;
193
+ type Strict$2<Shape extends z$1.ZodRawShape> = z$1.ZodObject<Shape, z$1.core.$strict>;
191
194
  /**
192
195
  * Display and behavior metadata for an entity type, as a site declares it.
193
196
  * The one definition: the site-builder takes it as it is.
194
197
  */
195
- declare const entityDisplaySchema: Strict<{
196
- label: z.ZodString;
197
- pluralName: z.ZodOptional<z.ZodString>;
198
- layout: z.ZodOptional<z.ZodString>;
199
- paginate: z.ZodOptional<z.ZodBoolean>;
200
- pageSize: z.ZodOptional<z.ZodNumber>;
201
- citable: z.ZodOptional<z.ZodBoolean>;
202
- navigation: z.ZodOptional<Strict<{
203
- show: z.ZodOptional<z.ZodBoolean>;
204
- slot: z.ZodOptional<z.ZodEnum<{
198
+ declare const entityDisplaySchema: Strict$2<{
199
+ label: z$1.ZodString;
200
+ pluralName: z$1.ZodOptional<z$1.ZodString>;
201
+ layout: z$1.ZodOptional<z$1.ZodString>;
202
+ paginate: z$1.ZodOptional<z$1.ZodBoolean>;
203
+ pageSize: z$1.ZodOptional<z$1.ZodNumber>;
204
+ citable: z$1.ZodOptional<z$1.ZodBoolean>;
205
+ navigation: z$1.ZodOptional<Strict$2<{
206
+ show: z$1.ZodOptional<z$1.ZodBoolean>;
207
+ slot: z$1.ZodOptional<z$1.ZodEnum<{
205
208
  primary: "primary";
206
209
  secondary: "secondary";
207
210
  }>>;
208
- priority: z.ZodOptional<z.ZodNumber>;
211
+ priority: z$1.ZodOptional<z$1.ZodNumber>;
209
212
  }>>;
210
213
  }>;
211
- type EntityDisplayEntry = z.output<typeof entityDisplaySchema>;
214
+ type EntityDisplayEntry = z$1.output<typeof entityDisplaySchema>;
212
215
  //#endregion
213
216
  //#region src/rizom/contracts.d.ts
214
217
  interface RizomLink {
@@ -245,14 +248,14 @@ interface RizomMessageBus {
245
248
  interface RizomLogger {
246
249
  info(message: string): void;
247
250
  }
248
- interface DataSourceRegistry {
251
+ interface DataSourceRegistry$1 {
249
252
  register(dataSource: unknown): void;
250
253
  }
251
254
  interface RizomSiteShell {
252
255
  getMessageBus(): RizomMessageBus;
253
256
  getLogger(): RizomLogger;
254
257
  registerTemplates(templates: Record<string, unknown>, namespace?: string): void;
255
- getDataSourceRegistry(): DataSourceRegistry;
258
+ getDataSourceRegistry(): DataSourceRegistry$1;
256
259
  }
257
260
  interface SiteCompositionPlugin {
258
261
  readonly id: string;
@@ -349,108 +352,4345 @@ interface DividerProps {
349
352
  }
350
353
  declare const Divider: ({ className }: DividerProps) => JSX.Element;
351
354
  //#endregion
352
- //#region ../../shared/ui-library/src/highlighted-text.d.ts
355
+ //#region ../../shell/entity-service/src/entity-type-classification.d.ts
356
+ /** Plugin-owned semantic classification, independent of access and projection policy. */
357
+ declare const entityTypeClassificationSchema: z.ZodDefault<z.ZodEnum<{
358
+ content: "content";
359
+ system: "system";
360
+ }>>;
361
+ type EntityTypeClassification = z.output<typeof entityTypeClassificationSchema>;
362
+ //#endregion
363
+ //#region ../../shell/entity-service/src/visibility.d.ts
364
+ declare const canonicalContentVisibilitySchema: z.ZodEnum<{
365
+ public: "public";
366
+ shared: "shared";
367
+ restricted: "restricted";
368
+ }>;
369
+ type ContentVisibility = z.infer<typeof canonicalContentVisibilitySchema>;
370
+ type RawContentVisibility = ContentVisibility | "private";
371
+ //#endregion
372
+ //#region ../../shell/entity-service/src/entity-grouping.d.ts
373
+ declare const entityGroupingSchema: z.ZodObject<{
374
+ key: z.ZodString;
375
+ label: z.ZodString;
376
+ field: z.ZodString;
377
+ types: z.ZodArray<z.ZodString>;
378
+ }>;
379
+ type EntityGrouping = z.infer<typeof entityGroupingSchema>;
380
+ /** One ordering vocabulary, shared by the queries, the routes and the UI. */
381
+ declare const groupingSortSchema: z.ZodEnum<{
382
+ "updated-desc": "updated-desc";
383
+ "updated-asc": "updated-asc";
384
+ "created-desc": "created-desc";
385
+ "created-asc": "created-asc";
386
+ }>;
387
+ declare const queryGroupingCatalogSchema: z.ZodObject<{
388
+ grouping: z.ZodString;
389
+ entityTypes: z.ZodArray<z.ZodString>;
390
+ visibilityScope: z.ZodOptional<typeof canonicalContentVisibilitySchema>;
391
+ limit: z.ZodDefault<z.ZodNumber>;
392
+ offset: z.ZodDefault<z.ZodNumber>;
393
+ signal: z.ZodOptional<z.ZodCustom<AbortSignal, AbortSignal>>;
394
+ }>;
395
+ declare const queryGroupingMembersSchema: z.ZodObject<{
396
+ grouping: z.ZodString;
397
+ entityTypes: z.ZodArray<z.ZodString>;
398
+ visibilityScope: z.ZodOptional<typeof canonicalContentVisibilitySchema>;
399
+ limit: z.ZodDefault<z.ZodNumber>;
400
+ offset: z.ZodDefault<z.ZodNumber>;
401
+ signal: z.ZodOptional<z.ZodCustom<AbortSignal, AbortSignal>>;
402
+ value: z.ZodString;
403
+ q: z.ZodOptional<z.ZodString>;
404
+ sort: z.ZodDefault<typeof groupingSortSchema>;
405
+ }>;
406
+ /** Usage is a distinct entry total plus counts for a bounded set of exact values. */
407
+ declare const queryGroupingUsageSchema: z.ZodObject<{
408
+ grouping: z.ZodString;
409
+ entityTypes: z.ZodArray<z.ZodString>;
410
+ visibilityScope: z.ZodOptional<typeof canonicalContentVisibilitySchema>;
411
+ signal: z.ZodOptional<z.ZodCustom<AbortSignal, AbortSignal>>;
412
+ values: z.ZodDefault<z.ZodArray<z.ZodString>>;
413
+ }>;
414
+ type QueryGroupingUsageRequest = z.input<typeof queryGroupingUsageSchema>;
415
+ interface EntityGroupingUsage {
416
+ /** Entries with at least one text membership, including values outside a list. */
417
+ entries: number;
418
+ /** Request order and literals preserved; unused values have a zero count. */
419
+ values: Array<{
420
+ value: string;
421
+ count: number;
422
+ }>;
423
+ }
424
+ type QueryGroupingCatalogRequest = z.input<typeof queryGroupingCatalogSchema>;
425
+ type QueryGroupingMembersRequest = z.input<typeof queryGroupingMembersSchema>;
426
+ interface EntityGroupingCatalog {
427
+ values: Array<{
428
+ value: string;
429
+ count: number;
430
+ }>;
431
+ total: number;
432
+ }
433
+ //#endregion
434
+ //#region ../../shell/entity-service/src/grouping-projection-state.d.ts
435
+ interface GroupingProjectionTarget {
436
+ entityType: string;
437
+ field: string;
438
+ generation: number;
439
+ }
440
+ //#endregion
441
+ //#region ../../shared/assets/src/index.d.ts
442
+ type AssetRef = `asset://sha256/${string}`;
443
+ interface AssetStat {
444
+ ref: AssetRef;
445
+ sizeBytes: number;
446
+ }
447
+ interface AssetVerification extends AssetStat {
448
+ expectedDigest: string;
449
+ actualDigest: string;
450
+ valid: boolean;
451
+ }
353
452
  /**
354
- * Render a content string with two lightweight markup conventions:
453
+ * Validated, bounded bytes ready to join an entity mutation. Preparation does
454
+ * not write durable state; only the entity transaction may commit the bytes.
455
+ */
456
+ interface PreparedAsset extends AssetRecord {
457
+ bytes: Uint8Array;
458
+ }
459
+ /** Read-only durable asset surface. There is deliberately no independent put. */
460
+ interface AssetReader {
461
+ read(ref: AssetRef): Promise<Uint8Array>;
462
+ stat(ref: AssetRef): Promise<AssetStat | null>;
463
+ verify(ref: AssetRef): Promise<AssetVerification>;
464
+ }
465
+ declare const assetRefSchema: z.ZodCustom<AssetRef, AssetRef>;
466
+ declare const assetRecordSchema: z.ZodObject<{
467
+ ref: typeof assetRefSchema;
468
+ digest: z.ZodString;
469
+ sizeBytes: z.ZodNumber;
470
+ }>;
471
+ type AssetRecord = z.output<typeof assetRecordSchema>;
472
+ //#endregion
473
+ //#region ../../shell/entity-service/src/entity-id-path.d.ts
474
+ type EntityIdPath = [string, ...string[]];
475
+ type EntityIdPathInput = readonly [string, ...string[]];
476
+ //#endregion
477
+ //#region ../../shared/contracts/src/guest-execution.d.ts
478
+ type Strict$1<Shape extends z.ZodRawShape> = z.ZodObject<Shape, z.core.$strict>;
479
+ /** Server-owned limits, not a browser's requested model settings. */
480
+ declare const guestExecutionLimitsSchema: Strict$1<{
481
+ messageCharacters: z.ZodNumber;
482
+ requestTimeoutSeconds: z.ZodNumber;
483
+ }>;
484
+ declare const guestExecutionPolicySchema: Strict$1<{
485
+ limits: typeof guestExecutionLimitsSchema;
486
+ maxCostMicroUsd: z.ZodNumber;
487
+ }>;
488
+ type GuestExecutionPolicy = z.output<typeof guestExecutionPolicySchema>;
489
+ /** What the provider reported for a guest turn, summed across its calls. */
490
+ declare const guestTurnUsageSchema: Strict$1<{
491
+ modelCalls: z.ZodNumber;
492
+ inputTokens: z.ZodNumber;
493
+ cachedInputTokens: z.ZodNumber;
494
+ outputTokens: z.ZodNumber;
495
+ reasoningTokens: z.ZodNumber;
496
+ embeddingTokens: z.ZodNumber;
497
+ }>;
498
+ /**
499
+ * A turn's cost from provider usage at a pinned pricing revision. Computed
500
+ * locally, not reconciled billing; a quote is never a known cost. Missing
501
+ * usage or pricing the revision does not cover stays unknown.
502
+ */
503
+ declare const guestTurnCostSchema: z.ZodDiscriminatedUnion<[Strict$1<{
504
+ state: z.ZodLiteral<"known">;
505
+ microUsd: z.ZodNumber;
506
+ pricing: z.ZodString;
507
+ }>, Strict$1<{
508
+ state: z.ZodLiteral<"unknown">;
509
+ reason: z.ZodEnum<{
510
+ "missing-usage": "missing-usage";
511
+ "unsupported-pricing": "unsupported-pricing";
512
+ }>;
513
+ }>], "state">;
514
+ declare const guestTurnSettlementSchema: Strict$1<{
515
+ usage: typeof guestTurnUsageSchema;
516
+ cost: typeof guestTurnCostSchema;
517
+ }>;
518
+ /**
519
+ * What a guest turn screens a visitor's question against, passed in by the
520
+ * box's host beside its execution limits: the site's public topics as its
521
+ * scope, and the refusal a screened-out visitor reads, in the site's words.
522
+ */
523
+ declare const guestScreeningSchema: Strict$1<{
524
+ topics: z.ZodArray<z.ZodString>;
525
+ refusal: z.ZodOptional<z.ZodString>;
526
+ }>;
527
+ type GuestScreening = z.output<typeof guestScreeningSchema>;
528
+ /** The categories that refuse a question. */
529
+ declare const guestRefusalCategorySchema: z.ZodEnum<{
530
+ "off-topic": "off-topic";
531
+ abusive: "abusive";
532
+ injection: "injection";
533
+ harmful: "harmful";
534
+ }>;
535
+ /**
536
+ * What screening did with a guest turn: answered after an in-scope judgment,
537
+ * refused with the category it was judged, or answered unscreened because
538
+ * the judgment failed.
539
+ */
540
+ declare const guestScreeningOutcomeSchema: z.ZodDiscriminatedUnion<[Strict$1<{
541
+ outcome: z.ZodLiteral<"answered">;
542
+ }>, Strict$1<{
543
+ outcome: z.ZodLiteral<"refused">;
544
+ category: typeof guestRefusalCategorySchema;
545
+ }>, Strict$1<{
546
+ outcome: z.ZodLiteral<"unscreened">;
547
+ }>], "outcome">;
548
+ //#endregion
549
+ //#region ../../shared/contracts/src/agent-response.d.ts
550
+ type PendingConfirmationSchema = z.ZodObject<{
551
+ id: z.ZodString;
552
+ toolCallId: z.ZodOptional<z.ZodString>;
553
+ toolName: z.ZodString;
554
+ summary: z.ZodString;
555
+ completionSummary: z.ZodOptional<z.ZodString>;
556
+ preview: z.ZodOptional<z.ZodString>;
557
+ args: z.ZodUnknown;
558
+ }>;
559
+ declare const PendingConfirmationSchema: PendingConfirmationSchema;
560
+ type ToolApprovalCardStateSchema = z.ZodEnum<{
561
+ "approval-requested": "approval-requested";
562
+ "approval-responded": "approval-responded";
563
+ "output-available": "output-available";
564
+ "output-denied": "output-denied";
565
+ "output-error": "output-error";
566
+ }>;
567
+ declare const ToolApprovalCardStateSchema: ToolApprovalCardStateSchema;
568
+ type ToolApprovalCardSchema = z.ZodObject<{
569
+ kind: z.ZodLiteral<"tool-approval">;
570
+ id: z.ZodString;
571
+ toolCallId: z.ZodOptional<z.ZodString>;
572
+ toolName: z.ZodString;
573
+ input: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
574
+ summary: z.ZodString;
575
+ completionSummary: z.ZodOptional<z.ZodString>;
576
+ preview: z.ZodOptional<z.ZodString>;
577
+ state: ToolApprovalCardStateSchema;
578
+ output: z.ZodOptional<z.ZodUnknown>;
579
+ error: z.ZodOptional<z.ZodString>;
580
+ }>;
581
+ declare const ToolApprovalCardSchema: ToolApprovalCardSchema;
582
+ type AttachmentCardSourceSchema = z.ZodObject<{
583
+ entityType: z.ZodOptional<z.ZodString>;
584
+ entityId: z.ZodOptional<z.ZodString>;
585
+ attachmentType: z.ZodOptional<z.ZodString>;
586
+ }>;
587
+ declare const AttachmentCardSourceSchema: AttachmentCardSourceSchema;
588
+ type AttachmentCardDataSchema = z.ZodObject<{
589
+ mediaType: z.ZodString;
590
+ url: z.ZodString;
591
+ downloadUrl: z.ZodOptional<z.ZodString>;
592
+ previewUrl: z.ZodOptional<z.ZodString>;
593
+ filename: z.ZodOptional<z.ZodString>;
594
+ sizeBytes: z.ZodOptional<z.ZodNumber>;
595
+ source: z.ZodOptional<AttachmentCardSourceSchema>;
596
+ }>;
597
+ declare const AttachmentCardDataSchema: AttachmentCardDataSchema;
598
+ type AttachmentCardSchema = z.ZodObject<{
599
+ kind: z.ZodLiteral<"attachment">;
600
+ id: z.ZodString;
601
+ jobId: z.ZodOptional<z.ZodString>;
602
+ title: z.ZodString;
603
+ description: z.ZodOptional<z.ZodString>;
604
+ attachment: AttachmentCardDataSchema;
605
+ }>;
606
+ declare const AttachmentCardSchema: AttachmentCardSchema;
607
+ type SourceCitationSchema = z.ZodObject<{
608
+ id: z.ZodString;
609
+ title: z.ZodOptional<z.ZodString>;
610
+ source: z.ZodString;
611
+ url: z.ZodOptional<z.ZodString>;
612
+ entityType: z.ZodOptional<z.ZodString>;
613
+ entityId: z.ZodOptional<z.ZodString>;
614
+ excerpt: z.ZodOptional<z.ZodString>;
615
+ provenance: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
616
+ }>;
617
+ declare const SourceCitationSchema: SourceCitationSchema;
618
+ type SourcesCardSchema = z.ZodObject<{
619
+ kind: z.ZodLiteral<"sources">;
620
+ id: z.ZodString;
621
+ title: z.ZodOptional<z.ZodString>;
622
+ sources: z.ZodArray<SourceCitationSchema>;
623
+ }>;
624
+ declare const SourcesCardSchema: SourcesCardSchema;
625
+ type PromptChatActionSchema = z.ZodObject<{
626
+ type: z.ZodLiteral<"prompt">;
627
+ id: z.ZodString;
628
+ label: z.ZodString;
629
+ prompt: z.ZodString;
630
+ description: z.ZodOptional<z.ZodString>;
631
+ }>;
632
+ declare const PromptChatActionSchema: PromptChatActionSchema;
633
+ type EventChatActionSchema = z.ZodObject<{
634
+ type: z.ZodLiteral<"event">;
635
+ id: z.ZodString;
636
+ label: z.ZodString;
637
+ event: z.ZodString;
638
+ fromState: z.ZodOptional<z.ZodString>;
639
+ description: z.ZodOptional<z.ZodString>;
640
+ }>;
641
+ declare const EventChatActionSchema: EventChatActionSchema;
642
+ type ChatActionSchema = z.ZodDiscriminatedUnion<[PromptChatActionSchema, EventChatActionSchema]>;
643
+ declare const ChatActionSchema: ChatActionSchema;
644
+ type ActionsCardSchema = z.ZodObject<{
645
+ kind: z.ZodLiteral<"actions">;
646
+ id: z.ZodString;
647
+ title: z.ZodOptional<z.ZodString>;
648
+ defaultOpen: z.ZodOptional<z.ZodBoolean>;
649
+ actions: z.ZodArray<ChatActionSchema>;
650
+ }>;
651
+ declare const ActionsCardSchema: ActionsCardSchema;
652
+ type StructuredChatCardSchema = z.ZodDiscriminatedUnion<[ToolApprovalCardSchema, AttachmentCardSchema, SourcesCardSchema, ActionsCardSchema]>;
653
+ declare const StructuredChatCardSchema: StructuredChatCardSchema;
654
+ type ToolResultErrorDataSchema = z.ZodObject<{
655
+ message: z.ZodString;
656
+ code: z.ZodOptional<z.ZodString>;
657
+ }>;
658
+ type ToolResultDataSchema = z.ZodObject<{
659
+ toolName: z.ZodString;
660
+ args: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
661
+ jobId: z.ZodOptional<z.ZodString>;
662
+ data: z.ZodOptional<z.ZodUnknown>;
663
+ error: z.ZodOptional<ToolResultErrorDataSchema>;
664
+ }>;
665
+ declare const ToolResultDataSchema: ToolResultDataSchema;
666
+ type AgentResponseUsageSchema = z.ZodObject<{
667
+ promptTokens: z.ZodNumber;
668
+ completionTokens: z.ZodNumber;
669
+ totalTokens: z.ZodNumber;
670
+ }>;
671
+ type AgentResponseSchema = z.ZodObject<{
672
+ text: z.ZodString;
673
+ error: z.ZodOptional<z.ZodString>;
674
+ toolResults: z.ZodOptional<z.ZodArray<ToolResultDataSchema>>;
675
+ cards: z.ZodOptional<z.ZodArray<StructuredChatCardSchema>>;
676
+ pendingConfirmations: z.ZodOptional<z.ZodArray<PendingConfirmationSchema>>;
677
+ usage: AgentResponseUsageSchema;
678
+ guestSettlement: z.ZodOptional<typeof guestTurnSettlementSchema>;
679
+ guestScreening: z.ZodOptional<typeof guestScreeningOutcomeSchema>;
680
+ }>;
681
+ declare const AgentResponseSchema: AgentResponseSchema;
682
+ type AgentResponse = z.output<typeof AgentResponseSchema>;
683
+ //#endregion
684
+ //#region ../../shared/contracts/src/actor-ref.d.ts
685
+ type ActorRefSchema = z.ZodDiscriminatedUnion<[z.ZodObject<{
686
+ kind: z.ZodLiteral<"user">;
687
+ userId: z.ZodString;
688
+ canonicalId: z.ZodOptional<z.ZodString>;
689
+ }>, z.ZodObject<{
690
+ kind: z.ZodLiteral<"external">;
691
+ externalActorId: z.ZodString;
692
+ }>, z.ZodObject<{
693
+ kind: z.ZodLiteral<"agent">;
694
+ agentId: z.ZodString;
695
+ }>, z.ZodObject<{
696
+ kind: z.ZodLiteral<"service">;
697
+ serviceId: z.ZodString;
698
+ }>]>;
699
+ declare const actorRefSchema: ActorRefSchema;
700
+ type ActorRef = z.output<typeof actorRefSchema>;
701
+ //#endregion
702
+ //#region ../../shared/contracts/src/interface-principal.d.ts
703
+ interface InterfacePrincipalGrantState {
704
+ interfaceType: string;
705
+ principalKeyHash: string;
706
+ permissionLevel: "admin" | "trusted";
707
+ }
708
+ interface InterfaceAnchorBindingState {
709
+ interfaceType: string;
710
+ principalKeyHash: string;
711
+ }
712
+ interface RuntimeInterfacePrincipalState {
713
+ grants: InterfacePrincipalGrantState[];
714
+ anchors: InterfaceAnchorBindingState[];
715
+ }
716
+ //#endregion
717
+ //#region ../../shared/contracts/src/json.d.ts
718
+ type JsonPrimitive = null | boolean | number | string;
719
+ type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;
720
+ /** A JSON document with an object at its root. */
721
+ interface JsonObject {
722
+ [key: string]: JsonValue;
723
+ }
724
+ //#endregion
725
+ //#region ../../shared/contracts/src/message-role.d.ts
726
+ type MessageRoleSchema = z.ZodEnum<{
727
+ user: "user";
728
+ assistant: "assistant";
729
+ }>;
730
+ declare const messageRoleSchema: MessageRoleSchema;
731
+ /** Canonical role of a stored conversation message. */
732
+ type MessageRole = z.output<typeof messageRoleSchema>;
733
+ //#endregion
734
+ //#region ../../shared/contracts/src/operation-provenance.d.ts
735
+ type ProvenanceEntityReferenceSchema = z.ZodObject<{
736
+ entityType: z.ZodString;
737
+ entityId: z.ZodString;
738
+ contentHash: z.ZodOptional<z.ZodString>;
739
+ }>;
740
+ declare const ProvenanceEntityReferenceSchema: ProvenanceEntityReferenceSchema;
741
+ type ProvenanceEntityReference = z.output<typeof ProvenanceEntityReferenceSchema>;
742
+ type OperationProvenanceSchema = z.ZodObject<{
743
+ rootJobId: z.ZodString;
744
+ causationId: z.ZodString;
745
+ projectionId: z.ZodOptional<z.ZodString>;
746
+ projectionLineage: z.ZodArray<z.ZodString>;
747
+ sourceEntity: z.ZodOptional<ProvenanceEntityReferenceSchema>;
748
+ derivationDepth: z.ZodNumber;
749
+ }>;
750
+ declare const OperationProvenanceSchema: OperationProvenanceSchema;
751
+ //#endregion
752
+ //#region ../../shared/contracts/src/publish-types.d.ts
753
+ type PublishMediaData = {
754
+ type: "document";
755
+ data: Buffer;
756
+ mimeType: "application/pdf";
757
+ filename: string;
758
+ } | {
759
+ type: "image";
760
+ data: Buffer;
761
+ mimeType: "image/png";
762
+ filename: string;
763
+ };
764
+ //#endregion
765
+ //#region ../../shared/contracts/src/response-types.d.ts
766
+ /**
767
+ * Query response schemas used throughout the system
768
+ */
769
+ type DefaultQuerySourceSchema = z.ZodObject<{
770
+ id: z.ZodString;
771
+ type: z.ZodString;
772
+ excerpt: z.ZodOptional<z.ZodString>;
773
+ relevance: z.ZodOptional<z.ZodNumber>;
774
+ }>;
775
+ type DefaultQueryResponseSchema = z.ZodObject<{
776
+ message: z.ZodString;
777
+ summary: z.ZodOptional<z.ZodString>;
778
+ topics: z.ZodOptional<z.ZodArray<z.ZodString>>;
779
+ sources: z.ZodOptional<z.ZodArray<DefaultQuerySourceSchema>>;
780
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
781
+ }>;
782
+ declare const defaultQueryResponseSchema: DefaultQueryResponseSchema;
783
+ type DefaultQueryResponse = z.output<typeof defaultQueryResponseSchema>;
784
+ //#endregion
785
+ //#region ../../shared/db/src/sqlite.d.ts
786
+ type SqliteDatabase = LibSQLDatabase<Record<string, unknown>>;
787
+ //#endregion
788
+ //#region ../../shared/utils/src/logger.d.ts
789
+ /**
790
+ * What a logger provides to callers.
355
791
  *
356
- * - `\n` in the string produces a `<br />` (for multi-line headlines)
357
- * - Any `*...*` run is wrapped in a `<span>` carrying `highlightClass`
792
+ * Consumers depend on this rather than on `ConsoleLogger`. The class carries
793
+ * private fields and a private constructor, so nothing else can be assignable
794
+ * to it — which is why every test double had to be asserted into place, a cast
795
+ * that also erased the check on the members the double did define.
796
+ */
797
+ interface Logger {
798
+ silly(message: string, ...args: unknown[]): void;
799
+ verbose(message: string, ...args: unknown[]): void;
800
+ debug(message: string, ...args: unknown[]): void;
801
+ info(message: string, ...args: unknown[]): void;
802
+ warn(message: string, ...args: unknown[]): void;
803
+ error(message: string, ...args: unknown[]): void;
804
+ child(context: string): Logger;
805
+ setUseStderr(useStderr: boolean): void;
806
+ }
807
+ //#endregion
808
+ //#region ../../shared/db/src/sqlite-columns.d.ts
809
+ /**
810
+ * Drizzle column annotation aliases for exported SQLite tables.
358
811
  *
359
- * Authors write the phrase as one natural string in markdown content;
360
- * the renderer does the structural split. Highlight styling is passed
361
- * per-brand (rizom.ai uses accent+midline, professional uses italic+accent)
362
- * so each consumer owns its own emphasis treatment while the parsing/
363
- * structure is shared.
812
+ * `isolatedDeclarations` requires exported table constants to carry explicit
813
+ * types, and drizzle's inferred column types are internal `SQLiteColumn`
814
+ * config objects. Before this module, every DB-owning package hand-wrote the
815
+ * same sixteen-key config literal per column kind; these aliases are that
816
+ * literal written once, with every axis the schemas actually vary on exposed
817
+ * as a parameter.
818
+ *
819
+ * Schema files keep short local aliases binding their table name (and any
820
+ * fixed axes) so the table declarations below them stay readable.
364
821
  */
365
- declare function renderHighlightedText(text: string, highlightClass: string): JSX.Element;
822
+ type SqliteTextColumn<TTableName extends string, TName extends string, TNotNull extends boolean, THasDefault extends boolean = false, TPrimaryKey extends boolean = false, THasRuntimeDefault extends boolean = false, TData = string, TEnumValues extends [string, ...string[]] = [string, ...string[]]> = SQLiteColumn<{
823
+ name: TName;
824
+ tableName: TTableName;
825
+ dataType: "string";
826
+ columnType: "SQLiteText";
827
+ data: TData;
828
+ driverParam: string;
829
+ notNull: TNotNull;
830
+ hasDefault: THasDefault;
831
+ isPrimaryKey: TPrimaryKey;
832
+ isAutoincrement: false;
833
+ hasRuntimeDefault: THasRuntimeDefault;
834
+ enumValues: TEnumValues;
835
+ baseColumn: never;
836
+ identity: undefined;
837
+ generated: undefined;
838
+ }, Record<string, never>, {
839
+ length: number | undefined;
840
+ }>;
841
+ type SqliteIntegerColumn<TTableName extends string, TName extends string, TNotNull extends boolean, THasDefault extends boolean = false, THasRuntimeDefault extends boolean = false, TPrimaryKey extends boolean = false, TAutoincrement extends boolean = false, TData = number> = SQLiteColumn<{
842
+ name: TName;
843
+ tableName: TTableName;
844
+ dataType: "number";
845
+ columnType: "SQLiteInteger";
846
+ data: TData;
847
+ driverParam: number;
848
+ notNull: TNotNull;
849
+ hasDefault: THasDefault;
850
+ isPrimaryKey: TPrimaryKey;
851
+ isAutoincrement: TAutoincrement;
852
+ hasRuntimeDefault: THasRuntimeDefault;
853
+ enumValues: undefined;
854
+ baseColumn: never;
855
+ identity: undefined;
856
+ generated: undefined;
857
+ }, Record<string, never>, Record<string, never>>;
858
+ type SqliteJsonColumn<TTableName extends string, TName extends string, TData, TNotNull extends boolean, TExtraConfig extends object = Record<string, never>, THasDefault extends boolean = false> = SQLiteColumn<{
859
+ name: TName;
860
+ tableName: TTableName;
861
+ dataType: "json";
862
+ columnType: "SQLiteTextJson";
863
+ data: TData;
864
+ driverParam: string;
865
+ notNull: TNotNull;
866
+ hasDefault: THasDefault;
867
+ isPrimaryKey: false;
868
+ isAutoincrement: false;
869
+ hasRuntimeDefault: false;
870
+ enumValues: undefined;
871
+ baseColumn: never;
872
+ identity: undefined;
873
+ generated: undefined;
874
+ }, Record<string, never>, TExtraConfig>;
366
875
  //#endregion
367
- //#region src/rizom/ui/site-info-links.d.ts
368
- declare function socialLinksToRizomLinks(siteInfo: Pick<SiteLayoutInfo, "socialLinks">, allowedPlatforms?: string[]): RizomLink[];
876
+ //#region ../../shell/entity-service/src/db/index.d.ts
877
+ type EntityDB = SqliteDatabase;
369
878
  //#endregion
370
- //#region src/rizom/ui/Wordmark.d.ts
371
- interface WordmarkProps {
372
- /** Brand name before the dot. Defaults to `"rizom"`. */
373
- name?: string;
374
- /** Suffix after the dot. Any string (e.g. `"ai"`, `"io"`, `"foundation"`). */
375
- brandSuffix: RizomBrandSuffix | string;
376
- className?: string;
377
- dotClassName?: string;
378
- suffixClassName?: string;
879
+ //#region ../../shell/entity-service/src/mutation-admission.d.ts
880
+ interface EntityMutationAdmissionTarget {
881
+ operation: "create" | "update" | "delete";
882
+ entityType: string;
883
+ entityId: string;
884
+ }
885
+ interface EntityMutationAdmission {
886
+ assertMutationAdmission(target: EntityMutationAdmissionTarget): Promise<void>;
379
887
  }
380
- declare const Wordmark: ({ name, brandSuffix, className, dotClassName, suffixClassName }: WordmarkProps) => JSX.Element;
381
888
  //#endregion
382
- //#region src/rizom/ui/Ecosystem.d.ts
383
- interface EcosystemCard {
384
- suffix: RizomBrandSuffix;
385
- title: string;
386
- body: string;
387
- linkLabel: string;
388
- linkHref: string;
889
+ //#region ../../shell/entity-service/src/projection-batch-contracts.d.ts
890
+ interface BulkMutationInput {
891
+ source: string;
892
+ operationId: string;
389
893
  }
390
- interface EcosystemContent {
391
- eyebrow: string;
392
- headline: string;
393
- cards: EcosystemCard[];
894
+ interface DurableBulkMutationRootInput extends BulkMutationInput {
895
+ rootJobId: string;
896
+ expectedChildren: number;
897
+ }
898
+ interface DurableBulkMutationChildInput extends DurableBulkMutationRootInput {
899
+ childKey: string;
900
+ jobId: string;
901
+ }
902
+ interface SettleDurableBulkMutationChildInput {
903
+ operationId: string;
904
+ childKey: string;
905
+ jobId: string;
906
+ outcome: "completed" | "failed";
907
+ }
908
+ interface ProjectionBatchOwnedJob {
909
+ jobId: string;
910
+ childKey: string;
911
+ status: "pending" | "processing" | "completed" | "failed";
912
+ terminalAt: number | null;
913
+ }
914
+ type ProjectionBatchRootReader = (rootJobId: string, operationId: string) => Promise<readonly ProjectionBatchOwnedJob[]>;
915
+ interface ProjectionBatchRecoveryResult {
916
+ fencedCallbacks: number;
917
+ releasedDurableRoots: number;
394
918
  }
395
- declare const Ecosystem: ({ eyebrow, headline, cards }: EcosystemContent) => JSX.Element;
396
919
  //#endregion
397
- //#region src/rizom/runtime/default-layout.d.ts
398
- declare const DefaultRizomLayout: ({ sections }: RizomLayoutProps) => JSX.Element;
920
+ //#region ../../shell/entity-service/src/projection-transaction-runner.d.ts
921
+ type EntityTransaction = Parameters<Parameters<EntityDB["transaction"]>[0]>[0];
399
922
  //#endregion
400
- //#region src/rizom/runtime/base-site.d.ts
401
- declare const rizomBaseSite: SiteDefinition;
923
+ //#region ../../shell/entity-service/src/projection-batch-coordinator.d.ts
924
+ interface ProjectionBatchDiagnostics {
925
+ preparing: number;
926
+ open: number;
927
+ abandoned: number;
928
+ expiredCallbackLeases: number;
929
+ oldestActiveAgeMs: number | null;
930
+ oldestProgressAgeMs: number | null;
931
+ }
402
932
  //#endregion
403
- //#region src/rizom/create-site.d.ts
404
- interface RizomRuntimeHooks {
405
- contentNamespace: string;
406
- templates?: Record<string, unknown>;
407
- dataSources?: unknown[];
933
+ //#region ../../shell/entity-service/src/projection-contracts.d.ts
934
+ type ProjectionJsonObject = JsonObject;
935
+ interface ProjectionEntityWrite<TMetadata extends ProjectionJsonObject = ProjectionJsonObject> {
936
+ id: string;
937
+ entityType: string;
938
+ content: string;
939
+ metadata: TMetadata;
940
+ visibility: ContentVisibility;
408
941
  }
409
- interface CreateRizomSiteOptions {
410
- packageName: string;
411
- layout: unknown;
412
- routes: RouteDefinitionInput[];
413
- content?: SiteContent;
942
+ type ProjectionWriteIntent<TMetadata extends ProjectionJsonObject = ProjectionJsonObject> = {
943
+ operation: "upsert";
944
+ entity: ProjectionEntityWrite<TMetadata>;
945
+ } | {
946
+ operation: "delete";
947
+ entityType: string;
948
+ id: string;
949
+ };
950
+ //#endregion
951
+ //#region ../../shell/entity-service/src/schema/projection-state.d.ts
952
+ type ProjectionTextColumn<TTable extends string, TName extends string, TNotNull extends boolean, THasDefault extends boolean = false, TPrimaryKey extends boolean = false, TData = string, TEnumValues extends [string, ...string[]] = [string, ...string[]]> = SqliteTextColumn<TTable, TName, TNotNull, THasDefault, TPrimaryKey, false, TData, TEnumValues>;
953
+ type ProjectionIntegerColumn<TTable extends string, TName extends string, TNotNull extends boolean, THasDefault extends boolean = false, TPrimaryKey extends boolean = false, TAutoincrement extends boolean = false> = SqliteIntegerColumn<TTable, TName, TNotNull, THasDefault, false, TPrimaryKey, TAutoincrement>;
954
+ type ProjectionJsonColumn<TTable extends string, TName extends string, TData, THasDefault extends boolean = false> = SqliteJsonColumn<TTable, TName, TData, true, {
955
+ $type: TData;
956
+ }, THasDefault>;
957
+ type ProjectionDirtyInputsTable = SQLiteTableWithColumns<{
958
+ name: "projection_dirty_inputs";
959
+ schema: undefined;
960
+ columns: {
961
+ generation: ProjectionIntegerColumn<"projection_dirty_inputs", "generation", true, true, true>;
962
+ sourceType: ProjectionTextColumn<"projection_dirty_inputs", "source_type", true>;
963
+ sourceId: ProjectionTextColumn<"projection_dirty_inputs", "source_id", true>;
964
+ revision: ProjectionTextColumn<"projection_dirty_inputs", "revision", true>;
965
+ operation: ProjectionTextColumn<"projection_dirty_inputs", "operation", true, false, false, "upsert" | "delete", ["upsert", "delete"]>;
966
+ markedAt: ProjectionIntegerColumn<"projection_dirty_inputs", "marked_at", true>;
967
+ };
968
+ dialect: "sqlite";
969
+ }>;
970
+ type ProjectionWavesTable = SQLiteTableWithColumns<{
971
+ name: "projection_waves";
972
+ schema: undefined;
973
+ columns: {
974
+ id: ProjectionTextColumn<"projection_waves", "id", true, false, true>;
975
+ cutoffGeneration: ProjectionIntegerColumn<"projection_waves", "cutoff_generation", true>;
976
+ graphFingerprint: ProjectionTextColumn<"projection_waves", "graph_fingerprint", true>;
977
+ admissionEpoch: ProjectionIntegerColumn<"projection_waves", "admission_epoch", true, true>;
978
+ status: ProjectionTextColumn<"projection_waves", "status", true, false, false, "running" | "completed" | "failed" | "superseded", ["running", "completed", "failed", "superseded"]>;
979
+ startedAt: ProjectionIntegerColumn<"projection_waves", "started_at", true>;
980
+ completedAt: ProjectionIntegerColumn<"projection_waves", "completed_at", false>;
981
+ };
982
+ dialect: "sqlite";
983
+ }>;
984
+ type ProjectionIncidentsTable = SQLiteTableWithColumns<{
985
+ name: "projection_incidents";
986
+ schema: undefined;
987
+ columns: {
988
+ waveId: ProjectionTextColumn<"projection_incidents", "wave_id", true, false, true>;
989
+ ruleId: ProjectionTextColumn<"projection_incidents", "rule_id", true>;
990
+ jobId: ProjectionTextColumn<"projection_incidents", "job_id", false>;
991
+ failureReason: ProjectionTextColumn<"projection_incidents", "failure_reason", true>;
992
+ recoveryGeneration: ProjectionIntegerColumn<"projection_incidents", "recovery_generation", true>;
993
+ createdAt: ProjectionIntegerColumn<"projection_incidents", "created_at", true>;
994
+ resolvedAt: ProjectionIntegerColumn<"projection_incidents", "resolved_at", false>;
995
+ };
996
+ dialect: "sqlite";
997
+ }>;
998
+ type ProjectionWaveInputsTable = SQLiteTableWithColumns<{
999
+ name: "projection_wave_inputs";
1000
+ schema: undefined;
1001
+ columns: {
1002
+ waveId: ProjectionTextColumn<"projection_wave_inputs", "wave_id", true>;
1003
+ sourceType: ProjectionTextColumn<"projection_wave_inputs", "source_type", true>;
1004
+ sourceId: ProjectionTextColumn<"projection_wave_inputs", "source_id", true>;
1005
+ revision: ProjectionTextColumn<"projection_wave_inputs", "revision", true>;
1006
+ operation: ProjectionTextColumn<"projection_wave_inputs", "operation", true, false, false, "upsert" | "delete", ["upsert", "delete"]>;
1007
+ generation: ProjectionIntegerColumn<"projection_wave_inputs", "generation", true>;
1008
+ };
1009
+ dialect: "sqlite";
1010
+ }>;
1011
+ interface ProjectionChangedTarget {
1012
+ entityType: string;
1013
+ entityId: string;
1014
+ operation: "upsert" | "delete";
1015
+ contentHash?: string | undefined;
1016
+ }
1017
+ type ProjectionWaveRulesTable = SQLiteTableWithColumns<{
1018
+ name: "projection_wave_rules";
1019
+ schema: undefined;
1020
+ columns: {
1021
+ waveId: ProjectionTextColumn<"projection_wave_rules", "wave_id", true>;
1022
+ ruleId: ProjectionTextColumn<"projection_wave_rules", "rule_id", true>;
1023
+ targetType: ProjectionTextColumn<"projection_wave_rules", "target_type", true>;
1024
+ level: ProjectionIntegerColumn<"projection_wave_rules", "level", true>;
1025
+ jobId: ProjectionTextColumn<"projection_wave_rules", "job_id", false>;
1026
+ status: ProjectionTextColumn<"projection_wave_rules", "status", true, false, false, "pending" | "queued" | "completed" | "failed", ["pending", "queued", "completed", "failed"]>;
1027
+ inputFingerprint: ProjectionTextColumn<"projection_wave_rules", "input_fingerprint", false>;
1028
+ changedTargets: ProjectionJsonColumn<"projection_wave_rules", "changed_targets", ProjectionChangedTarget[], true>;
1029
+ };
1030
+ dialect: "sqlite";
1031
+ }>;
1032
+ type ProjectionRuleMemosTable = SQLiteTableWithColumns<{
1033
+ name: "projection_rule_memos";
1034
+ schema: undefined;
1035
+ columns: {
1036
+ ruleId: ProjectionTextColumn<"projection_rule_memos", "rule_id", true>;
1037
+ ruleVersion: ProjectionTextColumn<"projection_rule_memos", "rule_version", true>;
1038
+ inputFingerprint: ProjectionTextColumn<"projection_rule_memos", "input_fingerprint", true>;
1039
+ writeIntents: ProjectionJsonColumn<"projection_rule_memos", "write_intents", ProjectionWriteIntent[]>;
1040
+ createdAt: ProjectionIntegerColumn<"projection_rule_memos", "created_at", true>;
1041
+ };
1042
+ dialect: "sqlite";
1043
+ }>;
1044
+ declare const projectionDirtyInputs: ProjectionDirtyInputsTable;
1045
+ declare const projectionWaves: ProjectionWavesTable;
1046
+ declare const projectionIncidents: ProjectionIncidentsTable;
1047
+ declare const projectionWaveInputs: ProjectionWaveInputsTable;
1048
+ declare const projectionWaveRules: ProjectionWaveRulesTable;
1049
+ declare const projectionRuleMemos: ProjectionRuleMemosTable;
1050
+ type ProjectionDirtyInput = typeof projectionDirtyInputs.$inferSelect;
1051
+ type ProjectionIncident = typeof projectionIncidents.$inferSelect;
1052
+ type ProjectionWave = typeof projectionWaves.$inferSelect;
1053
+ type ProjectionWaveInput = typeof projectionWaveInputs.$inferSelect;
1054
+ type ProjectionWaveRule = typeof projectionWaveRules.$inferSelect;
1055
+ type ProjectionRuleMemo = typeof projectionRuleMemos.$inferSelect;
1056
+ //#endregion
1057
+ //#region ../../shell/entity-service/src/projection-rule-contracts.d.ts
1058
+ interface GetProjectionRuleMemoInput {
1059
+ ruleId: string;
1060
+ ruleVersion: string;
1061
+ inputFingerprint: string;
1062
+ }
1063
+ interface ProjectionWaveRuleInput {
1064
+ ruleId: string;
1065
+ targetType: string;
1066
+ level: number;
1067
+ }
1068
+ interface ApplyProjectionRuleResultInput {
1069
+ waveId: string;
1070
+ ruleId: string;
1071
+ ruleVersion: string;
1072
+ inputFingerprint: string;
1073
+ writeIntents: readonly ProjectionWriteIntent[];
1074
+ completedAt: number;
1075
+ }
1076
+ interface ProjectionRuleMemoValue extends Omit<ProjectionRuleMemo, "writeIntents"> {
1077
+ writeIntents: ProjectionWriteIntent[];
1078
+ }
1079
+ //#endregion
1080
+ //#region ../../shell/entity-service/src/projection-wave-contracts.d.ts
1081
+ interface ProjectionIncidentDiagnostics {
1082
+ total: number;
1083
+ incidents: ProjectionIncident[];
1084
+ }
1085
+ interface ClaimProjectionWaveInput {
1086
+ waveId: string;
1087
+ graphFingerprint: string;
1088
+ startedAt: number;
1089
+ }
1090
+ interface ProjectionIncidentInput {
1091
+ waveId: string;
1092
+ ruleId: string;
1093
+ jobId: string | null;
1094
+ failureReason: string;
1095
+ failedAt: number;
1096
+ }
1097
+ //#endregion
1098
+ //#region ../../shell/entity-service/src/entity-export-types.d.ts
1099
+ interface EntityExportIntent {
1100
+ entityType: string;
1101
+ entityId: string;
1102
+ operation: "upsert" | "delete";
1103
+ revision: string;
1104
+ markedAt: number;
1105
+ }
1106
+ interface EntityExportAcknowledgement {
1107
+ entityType: string;
1108
+ entityId: string;
1109
+ revision: string;
1110
+ }
1111
+ interface AcknowledgeEntityExportsRequest {
1112
+ intents: readonly EntityExportAcknowledgement[];
1113
+ }
1114
+ //#endregion
1115
+ //#region ../../shell/entity-service/src/sqlite-asset-repository.d.ts
1116
+ type AssetTransaction = Parameters<Parameters<EntityDB["transaction"]>[0]>[0];
1117
+ /** Validated and copied before a transaction acquires SQLite's write lock. */
1118
+ interface StagedAsset extends AssetRecord {
1119
+ bytes: Buffer;
1120
+ }
1121
+ /**
1122
+ * SQLite implementation owned by the entity database. Durable insertion is
1123
+ * intentionally package-private and requires the entity transaction type.
1124
+ */
1125
+ declare class SqliteAssetRepository implements AssetReader {
1126
+ private readonly db;
1127
+ private readonly maxBytes;
1128
+ private readonly now;
1129
+ constructor(db: EntityDB, options?: {
1130
+ maxBytes?: number;
1131
+ now?: () => number;
1132
+ });
1133
+ /** Validate and copy bytes before entering an entity transaction. */
1134
+ stage(prepared: PreparedAsset): StagedAsset;
414
1135
  /**
415
- * Schema-first section groups (authored via `@rizom/site`'
416
- * `defineSection`/`sectionGroup`). Registered as content templates at brain
417
- * boot exactly like `content`, so the Studio + directory-sync + resolver treat
418
- * them identically — but the section shape is derived from one zod schema.
1136
+ * Bind asset-backed entity content to bytes in the same transaction. Legacy
1137
+ * inline content is left alone for the temporary image migration window.
419
1138
  */
420
- sections?: SiteSectionGroup | SiteSectionGroup[];
421
- themeOverride?: string;
1139
+ bindEntityContent(transaction: AssetTransaction, content: string, staged?: StagedAsset): Promise<void>;
1140
+ read(ref: AssetRef): Promise<Uint8Array>;
1141
+ stat(ref: AssetRef): Promise<AssetStat | null>;
1142
+ verify(ref: AssetRef): Promise<AssetVerification>;
1143
+ private insertOrVerify;
1144
+ private assertExists;
1145
+ private assertSize;
1146
+ }
1147
+ //#endregion
1148
+ //#region ../../shell/entity-service/src/projection-write-intent-applier.d.ts
1149
+ /** Stored row plus timestamps, including schema-normalized owner metadata. */
1150
+ interface ProjectionPersistEntity extends Omit<ProjectionEntityWrite, "metadata"> {
1151
+ metadata: Record<string, unknown>;
1152
+ contentHash: string;
1153
+ created: string;
1154
+ updated: string;
1155
+ }
1156
+ interface ProjectionEntityStoragePolicy {
1157
+ assetRepository: SqliteAssetRepository;
1158
+ isAssetBacked(entityType: string): boolean;
1159
+ isFullTextSearchable(entityType: string): boolean;
1160
+ /** Normalize source fields and check read-only persistence constraints
1161
+ * inside the admitted transaction, before any upsert effects. */
1162
+ prepareEntity?(entity: ProjectionPersistEntity, operation: "create" | "update"): Promise<ProjectionPersistEntity>;
1163
+ }
1164
+ //#endregion
1165
+ //#region ../../shell/entity-service/src/projection-store.d.ts
1166
+ interface MarkProjectionDirtyInput {
1167
+ sourceType: string;
1168
+ sourceId: string;
1169
+ revision: string;
1170
+ operation: "upsert" | "delete";
1171
+ markedAt: number;
1172
+ }
1173
+ interface ProjectionOwnedEntityInput {
1174
+ entityType: string;
1175
+ id: string;
1176
+ }
1177
+ /** Entity-database persistence boundary for scheduler coordination state. */
1178
+ declare class ProjectionStore {
1179
+ private readonly db;
1180
+ private readonly writeIntentApplier;
1181
+ private readonly transactions;
1182
+ private readonly batches;
1183
+ private readonly waves;
1184
+ private readonly rules;
1185
+ constructor(db: EntityDB, mutationAdmission?: EntityMutationAdmission, now?: () => number, storagePolicy?: ProjectionEntityStoragePolicy);
1186
+ runBulkMutation<TResult>(input: BulkMutationInput, mutation: () => Promise<TResult>): Promise<TResult>;
422
1187
  /**
423
- * Presentation config for entity-backed list/detail routes (labels, plural
424
- * names, navigation). Merged onto the base site's empty map. Sites that
425
- * surface plugin lists — e.g. `post`→"Essay", `deck`→"Talk" — set it here.
1188
+ * Force the batch coordinator's ambient scope to empty for the duration of
1189
+ * `fn`. A caller that defines a fresh unit of work (the job queue, once per
1190
+ * job) must wrap that unit in this so it never inherits another unit's
1191
+ * batch identity — see ProjectionBatchCoordinator.runFreshBatchScope.
426
1192
  */
427
- entityDisplay?: Record<string, EntityDisplayEntry>;
428
- /** Advanced runtime hooks for in-repo sites that need custom template/data-source wiring. */
429
- runtime?: RizomRuntimeHooks;
1193
+ runFreshBatchScope<T>(fn: () => T): T;
1194
+ prepareDurableBulkMutation(input: DurableBulkMutationRootInput): Promise<void>;
1195
+ finalizeDurableBulkMutationEnqueue(operationId: string): Promise<void>;
1196
+ failDurableBulkMutationEnqueue(operationId: string): Promise<void>;
1197
+ runDurableBulkMutationChild<TResult>(input: DurableBulkMutationChildInput, mutation: () => Promise<TResult>): Promise<TResult>;
1198
+ settleDurableBulkMutationChild(input: SettleDurableBulkMutationChildInput): Promise<boolean>;
1199
+ recoverProjectionBatches(readRoot: ProjectionBatchRootReader): Promise<ProjectionBatchRecoveryResult>;
1200
+ cleanupProjectionBatches(retentionMs?: number, maximumRecords?: number): Promise<number>;
1201
+ getProjectionBatchDiagnostics(): Promise<ProjectionBatchDiagnostics>;
1202
+ isProjectionOwnedEntity(input: ProjectionOwnedEntityInput): Promise<boolean>;
1203
+ releaseProjectionOwnership(input: ProjectionOwnedEntityInput): Promise<void>;
1204
+ transferEntityAuthority<TResult>(input: ProjectionOwnedEntityInput, mutation: (transaction: EntityTransaction) => Promise<TResult>): Promise<TResult>;
1205
+ markDirty(input: MarkProjectionDirtyInput): Promise<number>;
1206
+ withDirtyInput<TResult>(input: MarkProjectionDirtyInput, mutation: (transaction: EntityTransaction) => Promise<TResult>): Promise<TResult>;
1207
+ listPendingInputs(): Promise<ProjectionDirtyInput[]>;
1208
+ hasActiveProjectionBatch(): Promise<boolean>;
1209
+ claimPendingWave(input: ClaimProjectionWaveInput): Promise<ProjectionWave | null>;
1210
+ listWaveInputs(waveId: string): Promise<ProjectionWaveInput[]>;
1211
+ getWave(waveId: string): Promise<ProjectionWave | null>;
1212
+ getActiveWave(): Promise<ProjectionWave | null>;
1213
+ completeWave(waveId: string, completedAt: number): Promise<ProjectionWave>;
1214
+ supersedeWaveIfStale(waveId: string, supersededAt: number): Promise<boolean>;
1215
+ failWave(waveId: string, failedAt: number): Promise<ProjectionWave>;
1216
+ failWaveWithIncident(input: ProjectionIncidentInput): Promise<ProjectionWave>;
1217
+ getUnresolvedProjectionIncidentDiagnostics(limit?: number): Promise<ProjectionIncidentDiagnostics>;
1218
+ putWaveRules(waveId: string, rules: readonly ProjectionWaveRuleInput[]): Promise<void>;
1219
+ listWaveRules(waveId: string): Promise<ProjectionWaveRule[]>;
1220
+ queueWaveRule(waveId: string, ruleId: string, jobId: string): Promise<ProjectionWaveRule>;
1221
+ getWaveRule(waveId: string, ruleId: string): Promise<ProjectionWaveRule | null>;
1222
+ applyRuleResult(input: ApplyProjectionRuleResultInput): Promise<ProjectionWaveRule | null>;
1223
+ getRuleMemo(input: GetProjectionRuleMemoInput): Promise<ProjectionRuleMemoValue | null>;
430
1224
  }
431
- declare function createRizomSite(options: CreateRizomSiteOptions): SitePackage;
432
1225
  //#endregion
433
- //#region src/site.d.ts
434
- declare const rizomAiSite: SitePackage;
1226
+ //#region ../../shell/entity-service/src/entity-write-contracts.d.ts
1227
+ /** null means create only if absent; a token means replace that incarnation. */
1228
+ interface EntityWriteCondition {
1229
+ expectedRevision: string | null;
1230
+ }
435
1231
  //#endregion
436
- //#region src/routes.d.ts
1232
+ //#region ../../shell/entity-service/src/types.d.ts
437
1233
  /**
438
- * The consolidated Rizom site routes. The home page composes the living-memory
439
- * content namespace; the layout owns navigation (the
440
- * two-tier faces strip), so routes stay out of the entity nav.
1234
+ * Options for entity mutation operations (create, update, upsert)
441
1235
  */
442
- declare const aiRoutes: RouteDefinitionInput[];
443
- //#endregion
444
- //#region src/home.d.ts
1236
+ interface EntityMutationEventContext {
1237
+ conversationId?: string;
1238
+ channelId?: string;
1239
+ runId?: string;
1240
+ toolCallId?: string;
1241
+ actor?: ActorRef;
1242
+ interfaceType?: string;
1243
+ }
1244
+ interface EntityWriteSnapshot {
1245
+ entity: BaseEntity;
1246
+ revision: string;
1247
+ }
1248
+ type EntityPersistenceOrigin = "ordinary" | "directory-sync";
1249
+ interface EntityJobOptions {
1250
+ priority?: number;
1251
+ maxRetries?: number;
1252
+ eventContext?: EntityMutationEventContext;
1253
+ /**
1254
+ * Identifies authoritative file imports/deletes so they clear, rather than
1255
+ * create, an outbound directory-export intent.
1256
+ */
1257
+ persistenceOrigin?: EntityPersistenceOrigin;
1258
+ }
1259
+ /**
1260
+ * Options for entity creation (extends EntityJobOptions with deduplication)
1261
+ */
1262
+ interface CreateEntityOptions extends EntityJobOptions {
1263
+ /** Cancel before the atomic write boundary, not after a mutation commits. */
1264
+ signal?: AbortSignal;
1265
+ /** Runtime-only guard over the final persisted fields, immediately before writing. */
1266
+ beforeWrite?: (entity: Readonly<BaseEntity>) => Promise<void>;
1267
+ deduplicateId?: boolean;
1268
+ /** Atomic create-if-absent. Cannot deduplicate. */
1269
+ conditionalWrite?: EntityWriteCondition;
1270
+ }
1271
+ /** Options for updating an existing entity. */
1272
+ interface UpdateEntityOptions extends EntityJobOptions {
1273
+ /** Cancel before the atomic write boundary, not after a mutation commits. */
1274
+ signal?: AbortSignal;
1275
+ /** Runtime-only guard over the final persisted fields, immediately before writing. */
1276
+ beforeWrite?: (entity: Readonly<BaseEntity>) => Promise<void>;
1277
+ /** Apply only while the stored entity still has this content hash. */
1278
+ expectedContentHash?: string | undefined;
1279
+ /** Atomic full-revision replace. */
1280
+ conditionalWrite?: EntityWriteCondition;
1281
+ }
1282
+ /**
1283
+ * Result of an entity mutation that triggers an embedding job.
1284
+ * When skipped is true, no DB write, event, or embedding job was produced.
1285
+ */
1286
+ interface EntityMutationResult {
1287
+ entityId: string;
1288
+ jobId: string;
1289
+ skipped: boolean;
1290
+ skipReason?: "content-conflict" | undefined;
1291
+ }
1292
+ /**
1293
+ * Input for adapter-validated direct creation from finalized markdown.
1294
+ */
1295
+ interface CreateEntityFromMarkdownInput {
1296
+ entityType: string;
1297
+ id: string;
1298
+ markdown: string;
1299
+ /** Explicit core visibility. When omitted, markdown frontmatter or the public default applies. */
1300
+ visibility?: ContentVisibility;
1301
+ }
1302
+ /**
1303
+ * Data for storing an embedding for an entity
1304
+ */
1305
+ interface StoreEmbeddingData {
1306
+ entityId: string;
1307
+ entityType: string;
1308
+ embedding: Float32Array;
1309
+ contentHash: string;
1310
+ }
1311
+ type EntitySchema<T> = z.ZodType<T, unknown>;
1312
+ type UnknownEntitySchema = EntitySchema<unknown>;
1313
+ type FrontmatterSchema = z.ZodObject<z.ZodRawShape>;
1314
+ /**
1315
+ * Base entity type - generic to support typed metadata
1316
+ * TMetadata defaults to Record<string, unknown> for backward compatibility
1317
+ */
1318
+ interface BaseEntity<TMetadata = Record<string, unknown>> {
1319
+ id: string;
1320
+ entityType: string;
1321
+ content: string;
1322
+ created: string;
1323
+ updated: string;
1324
+ visibility: ContentVisibility;
1325
+ metadata: TMetadata;
1326
+ /** SHA256 hash of content for change detection */
1327
+ contentHash: string;
1328
+ }
1329
+ /**
1330
+ * Entity input type for creation - allows partial entities with optional system fields
1331
+ * contentHash is excluded because it's computed automatically by the entity service
1332
+ */
1333
+ type EntityInput<T extends BaseEntity> = Omit<T, "id" | "created" | "updated" | "contentHash" | "visibility"> & {
1334
+ id?: string;
1335
+ created?: string;
1336
+ updated?: string;
1337
+ visibility?: RawContentVisibility;
1338
+ };
1339
+ /**
1340
+ * Search result type
1341
+ */
1342
+ interface SearchResult<T extends BaseEntity = BaseEntity> {
1343
+ entity: T;
1344
+ score: number;
1345
+ excerpt: string;
1346
+ }
1347
+ /**
1348
+ * Normalized system_create input shape used by plugin create interceptors.
1349
+ */
1350
+ interface CreateCoverImageInput {
1351
+ generate?: boolean | undefined;
1352
+ prompt?: string | undefined;
1353
+ }
1354
+ interface CreateFromAttachmentInput {
1355
+ kind: "entity-attachment";
1356
+ sourceEntityType: string;
1357
+ sourceEntityId: string;
1358
+ attachmentType: string;
1359
+ }
1360
+ interface CreateFromUploadInput {
1361
+ kind: "upload";
1362
+ id: string;
1363
+ }
1364
+ interface CreateFromConversationMessageInput {
1365
+ kind: "conversation-message";
1366
+ messageId?: string | undefined;
1367
+ }
1368
+ type CreateFromInput = CreateFromAttachmentInput | CreateFromUploadInput | CreateFromConversationMessageInput;
1369
+ type CreateTransform = "extract-markdown" | "preserve";
1370
+ interface CreateInput {
1371
+ entityType: string;
1372
+ prompt?: string;
1373
+ title?: string;
1374
+ visibility?: ContentVisibility;
1375
+ content?: string;
1376
+ url?: string;
1377
+ from?: CreateFromInput;
1378
+ transform?: CreateTransform;
1379
+ replace?: boolean;
1380
+ sourceEntityType?: string;
1381
+ sourceEntityId?: string;
1382
+ sourceEntityIds?: string[];
1383
+ targetEntityType?: string;
1384
+ targetEntityId?: string;
1385
+ coverImage?: boolean | CreateCoverImageInput;
1386
+ }
1387
+ /**
1388
+ * Minimal caller context forwarded to plugin create interceptors.
1389
+ */
1390
+ interface CreateExecutionContext {
1391
+ interfaceType: string;
1392
+ actor: ActorRef;
1393
+ channelId?: string;
1394
+ channelName?: string;
1395
+ }
1396
+ /**
1397
+ * Result returned to system_create when a plugin fully handles creation.
1398
+ */
1399
+ declare const createResultAttachmentSchema: z.ZodObject<{
1400
+ mediaType: z.ZodString;
1401
+ url: z.ZodString;
1402
+ downloadUrl: z.ZodOptional<z.ZodString>;
1403
+ previewUrl: z.ZodOptional<z.ZodString>;
1404
+ filename: z.ZodOptional<z.ZodString>;
1405
+ sizeBytes: z.ZodOptional<z.ZodNumber>;
1406
+ source: z.ZodOptional<z.ZodObject<{
1407
+ entityType: z.ZodOptional<z.ZodString>;
1408
+ entityId: z.ZodOptional<z.ZodString>;
1409
+ attachmentType: z.ZodOptional<z.ZodString>;
1410
+ }>>;
1411
+ }>;
1412
+ type CreateResultAttachment = z.infer<typeof createResultAttachmentSchema>;
1413
+ type CreateResult = {
1414
+ success: true;
1415
+ data: {
1416
+ entityId?: string;
1417
+ jobId?: string;
1418
+ status: string;
1419
+ attachment?: CreateResultAttachment;
1420
+ };
1421
+ } | {
1422
+ success: false;
1423
+ error: string;
1424
+ };
445
1425
  /**
446
- * The umbrella home page's authored sections. The namespace ("home") matches
447
- * the route id, so each stores as site-content/home/<section>.md and resolves
448
- * as "home:<section>". Two sections live elsewhere: the hero is the live
449
- * agent proximity map (agent-discovery:proximity-map) and the proof/ask is
450
- * the knowledge map (topics:knowledge-map) — both authored via overlay
451
- * markdown merged over their live datasource payloads.
1426
+ * Plugin create interceptors can either fully handle creation,
1427
+ * or continue with a rewritten normalized input.
452
1428
  */
453
- declare const homeSections: SiteSectionGroup;
1429
+ type CreateInterceptionResult = {
1430
+ kind: "handled";
1431
+ result: CreateResult;
1432
+ } | {
1433
+ kind: "continue";
1434
+ input: CreateInput;
1435
+ };
1436
+ type CreateInterceptor = (input: CreateInput, executionContext: CreateExecutionContext) => Promise<CreateInterceptionResult>;
1437
+ interface UploadSaveInput {
1438
+ upload: CreateFromUploadInput;
1439
+ title?: string;
1440
+ visibility?: ContentVisibility;
1441
+ }
1442
+ type UploadSaveHandler = (input: UploadSaveInput, executionContext: CreateExecutionContext) => Promise<CreateResult>;
1443
+ interface UploadSaveHandlerRegistration {
1444
+ entityType: string;
1445
+ mediaTypes: string[];
1446
+ handler: UploadSaveHandler;
1447
+ }
1448
+ /**
1449
+ * Called before an entity is persisted (on create or update). Throws to reject
1450
+ * the write with an operator-facing error. Use this for cross-entity invariants
1451
+ * the per-entity Zod schema cannot express. Includes projection upserts, which
1452
+ * validate inside their transaction. Read-only lookups are allowed; mutations
1453
+ * and external effects are not.
1454
+ */
1455
+ type PersistValidator<T extends BaseEntity = BaseEntity> = (entity: T, context: {
1456
+ operation: "create" | "update";
1457
+ }) => Promise<void>;
1458
+ /**
1459
+ * Interface for entity adapter - handles conversion between entities and markdown
1460
+ * following the hybrid storage model
1461
+ *
1462
+ * @template TEntity - The full entity type
1463
+ * @template TMetadata - The metadata type (defaults to Record<string, unknown>)
1464
+ */
1465
+ interface EntityAdapter<TEntity extends BaseEntity<TMetadata>, TMetadata = Record<string, unknown>> {
1466
+ entityType: string;
1467
+ /**
1468
+ * One declarative sentence describing what this entity type is. This is the
1469
+ * data the model reads to select `entityType`, replacing hardcoded example
1470
+ * phrasings in system instructions. Required: every type must define itself.
1471
+ */
1472
+ purpose: string;
1473
+ schema: EntitySchema<TEntity>;
1474
+ toMarkdown(entity: TEntity): string;
1475
+ fromMarkdown(markdown: string): Partial<TEntity>;
1476
+ extractMetadata(entity: TEntity): TMetadata;
1477
+ parseFrontMatter<TFrontmatter>(markdown: string, schema: {
1478
+ parse(data: unknown): TFrontmatter;
1479
+ }): TFrontmatter;
1480
+ generateFrontMatter(entity: TEntity): string;
1481
+ /** Optional: Zod schema for frontmatter fields. Used by Studio config generation. */
1482
+ frontmatterSchema?: z.ZodObject<z.ZodRawShape>;
1483
+ /** Optional: Declares this entity type is a singleton (one file, e.g., identity/identity.md). Used by Studio to generate files collection. */
1484
+ isSingleton?: boolean;
1485
+ /** Optional: Whether this entity has a free-form markdown body below frontmatter. Defaults to true. When false, Studio omits the body widget. */
1486
+ hasBody?: boolean;
1487
+ /** Returns a markdown body template with section headings for this entity type. Empty string for free-form entities. */
1488
+ getBodyTemplate(): string;
1489
+ /** Optional: Declares that this entity type supports cover images via coverImageId in frontmatter */
1490
+ supportsCoverImage?: boolean;
1491
+ /**
1492
+ * Optional: the `metadata.status` values that count as published for
1493
+ * `publishedOnly` queries (production site builds). Declaring this makes the
1494
+ * list exact — entities without a status are NOT published. When absent, the
1495
+ * default lifecycle semantics apply: status `published`, `active`, or no
1496
+ * status at all.
1497
+ */
1498
+ publishedStatuses?: string[];
1499
+ /** Optional: Extract coverImageId from entity content/frontmatter */
1500
+ getCoverImageId?(entity: TEntity): string | undefined;
1501
+ /**
1502
+ * Optional: build the markdown content and metadata for a queued-generation stub.
1503
+ * When undefined, this entity type does not support prompt-based queued creation
1504
+ * via system_create; the tool will reject the call rather than silently degrade.
1505
+ * The returned metadata must satisfy this entity's metadata schema (with
1506
+ * status set to "generating"); central code only stamps id/timestamps/visibility.
1507
+ */
1508
+ buildStub?(input: {
1509
+ id: string;
1510
+ title: string;
1511
+ }): {
1512
+ content: string;
1513
+ metadata: TMetadata;
1514
+ };
1515
+ }
1516
+ /**
1517
+ * Sort field specification for multi-field sorting
1518
+ */
1519
+ interface SortField {
1520
+ /** Field to sort by - "created", "updated", or a metadata field name */
1521
+ field: string;
1522
+ /** Sort direction */
1523
+ direction: "asc" | "desc";
1524
+ /** Sort NULL values before non-NULL values (default: false / SQLite default) */
1525
+ nullsFirst?: boolean;
1526
+ }
1527
+ /**
1528
+ * List entities options
1529
+ * Generic over metadata type for type-safe filtering
1530
+ */
1531
+ interface EntityReadOptions {
1532
+ /** Cooperative boundary checks, not proof of remote SQL cancellation. */
1533
+ signal?: AbortSignal;
1534
+ }
1535
+ interface ListOptions<TMetadata = Record<string, unknown>> extends EntityReadOptions {
1536
+ limit?: number;
1537
+ offset?: number;
1538
+ /** Multi-field sorting - supports system fields (created, updated) and metadata fields */
1539
+ sortFields?: SortField[];
1540
+ filter?: {
1541
+ metadata?: Partial<TMetadata>;
1542
+ /** Literal substring search through serialized content, including frontmatter. */
1543
+ contentContains?: string | undefined;
1544
+ /** Exact visibility, intersected with visibilityScope rather than widening it. */
1545
+ visibility?: ContentVisibility | undefined;
1546
+ visibilityScope?: ContentVisibility | undefined;
1547
+ };
1548
+ /** Filter to only entities with metadata.status = "published" */
1549
+ publishedOnly?: boolean;
1550
+ }
1551
+ /**
1552
+ * Search options
1553
+ */
1554
+ interface SearchOptions extends EntityReadOptions {
1555
+ limit?: number;
1556
+ offset?: number;
1557
+ types?: string[];
1558
+ excludeTypes?: string[];
1559
+ sortBy?: "relevance" | "created" | "updated";
1560
+ sortDirection?: "asc" | "desc";
1561
+ /** Score multipliers per entity type - applied after initial search */
1562
+ weight?: Record<string, number>;
1563
+ visibilityScope?: ContentVisibility | undefined;
1564
+ /** Include queued/failed generation stubs in search results (default: false) */
1565
+ includeUngenerated?: boolean;
1566
+ /** Only entities their type counts as published, as for published-only listings (default: false) */
1567
+ publishedOnly?: boolean;
1568
+ /** Minimum relevance score to return. Omit for no score cutoff. */
1569
+ minScore?: number;
1570
+ }
1571
+ type ProjectionSourceRole = "canonical" | "primary" | "secondary" | "supporting" | "ambient" | "excluded";
1572
+ /**
1573
+ * Configuration for entity type registration
1574
+ */
1575
+ interface EntityTypeConfig {
1576
+ /** Plugin-owned semantic role, defaulting to content. System types cannot contribute to groupings. */
1577
+ classification?: EntityTypeClassification;
1578
+ /** Score multiplier for search results (default: 1.0) */
1579
+ weight?: number;
1580
+ /** Whether to generate embeddings for this entity type (default: true).
1581
+ * Set to false for entity types with non-textual content (e.g., images). */
1582
+ embeddable?: boolean;
1583
+ /** Whether to index serialized content in full-text search (default: true).
1584
+ * Set to false for binary entity types. Mutations remove stale FTS rows. */
1585
+ fullTextSearchable?: boolean;
1586
+ /** Binary storage policy. Absence means text content. */
1587
+ binaryStorage?: "data-url" | "asset";
1588
+ /** Default system_list order, applied by the entity service before pagination. */
1589
+ defaultSort?: SortField[];
1590
+ /** Accepts upload text extraction through system_create extract-markdown. */
1591
+ markdownImport?: boolean;
1592
+ /**
1593
+ * The type's own minimum action policy, from whoever registers it. It
1594
+ * tightens wildcard defaults without relaxing stricter rules, including
1595
+ * `never`, so an admin-only type stays protected without its bundle's rule.
1596
+ * An explicit per-type instance entry still overrides, action by action.
1597
+ */
1598
+ actionPolicy?: Partial<Record<"create" | "update" | "delete" | "extract" | "publish", "never" | "admin" | "trusted" | "public">>;
1599
+ /** Whether this entity type may be used as source material for derived projections (default: true).
1600
+ * Set to false for projection outputs that would create feedback loops. */
1601
+ projectionSource?: boolean;
1602
+ /** Default source authority role for derived projections. Entity types own
1603
+ * their durable/source character; consumers may map roles to local policy. */
1604
+ projectionSourceRole?: ProjectionSourceRole;
1605
+ /** Publish semantics for status-bearing entity types. Statuses listed here
1606
+ * represent publication commitment/execution states and require the
1607
+ * `publish` entity action when entered or modified. */
1608
+ publish?: {
1609
+ publishStatuses: string[];
1610
+ };
1611
+ }
1612
+ /**
1613
+ * Core entity service interface for read-only operations
1614
+ * Used by core plugins that need entity access but shouldn't modify entities
1615
+ */
1616
+ interface GetEntityRequest extends EntityReadOptions {
1617
+ entityType: string;
1618
+ id: string;
1619
+ /**
1620
+ * Optional visibility scope. Undefined fails closed to "public" — callers
1621
+ * with elevated access must opt up explicitly.
1622
+ */
1623
+ visibilityScope?: ContentVisibility | undefined;
1624
+ /** Only an entity its type counts as published, as for published-only listings. */
1625
+ publishedOnly?: boolean | undefined;
1626
+ }
1627
+ type GetEntityRawRequest = GetEntityRequest;
1628
+ interface ProjectionOwnedEntityRequest {
1629
+ entityType: string;
1630
+ id: string;
1631
+ }
1632
+ interface ListEntitiesRequest {
1633
+ entityType: string;
1634
+ options?: ListOptions | undefined;
1635
+ }
1636
+ interface QueryEntityHierarchyRequest {
1637
+ entityType: string;
1638
+ /** Null/omitted means the collection root; segments identify stored identity. */
1639
+ prefix?: EntityIdPathInput | null | undefined;
1640
+ /** Search matching entries throughout the prefix; no folder rows in this mode. */
1641
+ includeDescendants?: boolean | undefined;
1642
+ /** Omitted fails closed to public, including folder names and counts. */
1643
+ visibilityScope?: ContentVisibility | undefined;
1644
+ limit?: number | undefined;
1645
+ offset?: number | undefined;
1646
+ sortFields?: SortField[] | undefined;
1647
+ filter?: {
1648
+ metadata?: Record<string, unknown> | undefined;
1649
+ contentContains?: string | undefined;
1650
+ visibility?: ContentVisibility | undefined;
1651
+ } | undefined;
1652
+ signal?: AbortSignal | undefined;
1653
+ }
1654
+ interface EntityHierarchyPage {
1655
+ prefix: EntityIdPath | null;
1656
+ folders: Array<{
1657
+ path: EntityIdPath;
1658
+ name: string;
1659
+ descendantCount: number;
1660
+ }>;
1661
+ /** Only direct children, with derived paths kept outside durable entity data. */
1662
+ entities: Array<{
1663
+ entity: BaseEntity;
1664
+ path: EntityIdPath;
1665
+ }>;
1666
+ offset: number;
1667
+ totalEntities: number;
1668
+ }
1669
+ interface CountEntitiesRequest {
1670
+ entityType: string;
1671
+ options?: Pick<ListOptions, "publishedOnly" | "filter"> | undefined;
1672
+ }
1673
+ interface CreateEntityRequest<T extends BaseEntity> {
1674
+ entity: EntityInput<T>;
1675
+ /** Prepared bytes committed in the same transaction as their entity reference. */
1676
+ preparedAsset?: PreparedAsset | undefined;
1677
+ options?: CreateEntityOptions | undefined;
1678
+ }
1679
+ interface CreateEntityFromMarkdownRequest {
1680
+ input: CreateEntityFromMarkdownInput;
1681
+ options?: CreateEntityOptions | undefined;
1682
+ }
1683
+ interface UpdateEntityRequest<T extends BaseEntity> {
1684
+ entity: T;
1685
+ /** Prepared bytes committed in the same transaction as their entity reference. */
1686
+ preparedAsset?: PreparedAsset | undefined;
1687
+ options?: UpdateEntityOptions | undefined;
1688
+ }
1689
+ interface DeleteEntityRequest {
1690
+ entityType: string;
1691
+ id: string;
1692
+ options?: Pick<EntityJobOptions, "eventContext" | "persistenceOrigin"> | undefined;
1693
+ }
1694
+ interface UpsertEntityRequest<T extends BaseEntity> {
1695
+ entity: T;
1696
+ /** Prepared bytes committed in the same transaction as their entity reference. */
1697
+ preparedAsset?: PreparedAsset | undefined;
1698
+ /** Conditional upserts never fall through from a raced create to update. */
1699
+ options?: (EntityJobOptions & {
1700
+ conditionalWrite?: EntityWriteCondition;
1701
+ }) | undefined;
1702
+ }
1703
+ interface EntitySearchRequest {
1704
+ query: string;
1705
+ options?: SearchOptions | undefined;
1706
+ }
1707
+ interface SearchWithDistancesRequest {
1708
+ query: string;
1709
+ }
1710
+ interface SemanticEntityReference {
1711
+ entityId: string;
1712
+ entityType: string;
1713
+ }
1714
+ interface ProjectSemanticSpaceRequest {
1715
+ /** Entity types to include as projected points. Empty or omitted includes all types. */
1716
+ types?: string[];
1717
+ /** Optional entity used as the semantic origin. Missing origins fall back to the point centroid. */
1718
+ origin?: SemanticEntityReference;
1719
+ /** Include pairwise neighbors at or below this cosine distance. */
1720
+ maxNeighborDistance?: number;
1721
+ /** Undefined fails closed to public-only visibility. */
1722
+ visibilityScope?: ContentVisibility | undefined;
1723
+ }
1724
+ interface SemanticSpacePoint extends SemanticEntityReference {
1725
+ /** Coordinates on the first two principal components of the semantic space. */
1726
+ coordinates: [number, number];
1727
+ /** Cosine distance from the requested origin or the fallback centroid. */
1728
+ distanceToOrigin: number;
1729
+ }
1730
+ interface SemanticSpaceNeighbor {
1731
+ source: SemanticEntityReference;
1732
+ target: SemanticEntityReference;
1733
+ distance: number;
1734
+ }
1735
+ type SemanticSpaceOrigin = ({
1736
+ kind: "entity";
1737
+ } & SemanticEntityReference) | {
1738
+ kind: "centroid";
1739
+ };
1740
+ interface SemanticSpaceDistanceRange {
1741
+ min: number;
1742
+ max: number;
1743
+ }
1744
+ interface SemanticSpaceProjection {
1745
+ origin: SemanticSpaceOrigin;
1746
+ points: SemanticSpacePoint[];
1747
+ neighbors: SemanticSpaceNeighbor[];
1748
+ /** Observed origin-distance extent for projection-independent scaling. */
1749
+ distanceRange: SemanticSpaceDistanceRange;
1750
+ }
1751
+ /**
1752
+ * Context passed to all DataSource operations
1753
+ * Contains internal state that should not be mixed with user query parameters
1754
+ */
1755
+ interface BaseDataSourceContext {
1756
+ /**
1757
+ * Whether to filter to only published/complete content
1758
+ * Set by site-builder: true for production, false for preview
1759
+ */
1760
+ publishedOnly?: boolean;
1761
+ /**
1762
+ * Scoped entity service that auto-applies publishedOnly filter
1763
+ * Datasources should use this instead of their injected entityService
1764
+ * to ensure consistent filtering behavior across environments
1765
+ */
1766
+ entityService: EntityServiceClient;
1767
+ }
1768
+ /**
1769
+ * DataSource Interface
1770
+ *
1771
+ * Provides data for templates through fetch, generate, or transform operations.
1772
+ * DataSources are registered in the DataSourceRegistry and referenced by templates
1773
+ * via their dataSourceId property.
1774
+ */
1775
+ /** Runtime-only, read-only access for caller-bound generation. */
1776
+ interface DataSourceGenerationContext {
1777
+ readonly visibilityScope: ContentVisibility;
1778
+ readonly signal?: AbortSignal;
1779
+ getEntity(entityType: string, id: string): Promise<BaseEntity | null>;
1780
+ search(query: string, options?: Pick<SearchOptions, "limit" | "weight">): Promise<SearchResult[]>;
1781
+ }
1782
+ interface DataSource {
1783
+ /**
1784
+ * Unique identifier for this data source
1785
+ */
1786
+ id: string;
1787
+ /**
1788
+ * Human-readable name for this data source
1789
+ */
1790
+ name: string;
1791
+ /**
1792
+ * Optional description of what this data source provides
1793
+ */
1794
+ description?: string;
1795
+ /**
1796
+ * Optional: Fetch existing data
1797
+ * Used by data sources that aggregate or retrieve data (e.g., dashboard stats, API data)
1798
+ * DataSources validate output using the provided schema
1799
+ * @param query - Query parameters for fetching data
1800
+ * @param outputSchema - Schema for validating output data
1801
+ * @param context - Context with environment
1802
+ */
1803
+ fetch?: <T>(query: unknown, outputSchema: z.ZodSchema<T>, context: BaseDataSourceContext) => Promise<T>;
1804
+ /**
1805
+ * Optional: Generate new content
1806
+ * Used by data sources that create content (e.g., AI-generated content, reports)
1807
+ */
1808
+ generate?: <T>(request: unknown, schema: z.ZodSchema<T>, signal?: AbortSignal) => Promise<T>;
1809
+ /**
1810
+ * Opt-in scoped generation. All content reads must use this runtime context,
1811
+ * not ambient entity services/caches. Never fall back to generate().
1812
+ */
1813
+ generateScoped?: <T>(request: unknown, schema: z.ZodSchema<T>, context: DataSourceGenerationContext) => Promise<T>;
1814
+ /**
1815
+ * Optional: Transform content between formats
1816
+ * Used by data sources that convert content (e.g., markdown to HTML, data formatting)
1817
+ */
1818
+ transform?: <T>(content: unknown, format: string, schema: z.ZodSchema<T>) => Promise<T>;
1819
+ }
1820
+ /**
1821
+ * DataSource capabilities for discovery and validation
1822
+ */
1823
+ interface DataSourceCapabilities {
1824
+ canFetch: boolean;
1825
+ canGenerate: boolean;
1826
+ canTransform: boolean;
1827
+ }
1828
+ interface ICoreEntityService {
1829
+ getEntity(request: GetEntityRequest): Promise<BaseEntity | null>;
1830
+ getEntity<T extends BaseEntity>(request: GetEntityRequest, schema: EntitySchema<T>): Promise<T | null>;
1831
+ /**
1832
+ * Get entity without content resolution (raw)
1833
+ * Used internally to avoid recursion when resolving image references
1834
+ */
1835
+ getEntityRaw(request: GetEntityRawRequest): Promise<BaseEntity | null>;
1836
+ getEntityRaw<T extends BaseEntity>(request: GetEntityRawRequest, schema: EntitySchema<T>): Promise<T | null>;
1837
+ listEntities(request: ListEntitiesRequest): Promise<BaseEntity[]>;
1838
+ listEntities<T extends BaseEntity>(request: ListEntitiesRequest, schema: EntitySchema<T>): Promise<T[]>;
1839
+ /** Immediate folders and paginated direct children; no filesystem interpretation. */
1840
+ queryEntityHierarchy(request: QueryEntityHierarchyRequest): Promise<EntityHierarchyPage>;
1841
+ queryGroupingCatalog(request: QueryGroupingCatalogRequest): Promise<EntityGroupingCatalog>;
1842
+ queryGroupingMembers(request: QueryGroupingMembersRequest): Promise<EntityGroupingMembers>;
1843
+ queryGroupingUsage(request: QueryGroupingUsageRequest): Promise<EntityGroupingUsage>;
1844
+ search(request: EntitySearchRequest): Promise<SearchResult<BaseEntity>[]>;
1845
+ search<T extends BaseEntity>(request: EntitySearchRequest, schema: EntitySchema<T>): Promise<SearchResult<T>[]>;
1846
+ /** Return embedded entities with raw cosine distance to a query. */
1847
+ searchWithDistances(request: SearchWithDistancesRequest): Promise<Array<{
1848
+ entityId: string;
1849
+ entityType: string;
1850
+ distance: number;
1851
+ }>>;
1852
+ /** Project visible entities into a provider-independent semantic space. */
1853
+ projectSemanticSpace(request: ProjectSemanticSpaceRequest): Promise<SemanticSpaceProjection>;
1854
+ getEntityTypes(): string[];
1855
+ hasEntityType(type: string): boolean;
1856
+ countEntities(request: CountEntitiesRequest): Promise<number>;
1857
+ /**
1858
+ * Group counts by entity type. Fails closed: undefined visibilityScope
1859
+ * filters to public-only counts so aggregate insights cannot reveal
1860
+ * non-public entity existence.
1861
+ */
1862
+ getEntityCounts(visibilityScope?: ContentVisibility): Promise<Array<{
1863
+ entityType: string;
1864
+ count: number;
1865
+ }>>;
1866
+ /** Get configuration for a specific entity type */
1867
+ getEntityTypeConfig(type: string): EntityTypeConfig;
1868
+ /** Get weight map for all registered entity types with non-default weights */
1869
+ getWeightMap(): Record<string, number>;
1870
+ }
1871
+ /** One visibility-scoped, mixed-type member page. */
1872
+ interface EntityGroupingMembers {
1873
+ entities: BaseEntity[];
1874
+ total: number;
1875
+ }
1876
+ /** A single document owner refreshes in-memory grouping contracts before use. */
1877
+ interface EntityGroupingSource {
1878
+ readonly entityType: string;
1879
+ /** Read-only with respect to persistence: never mutate entities or reproject. */
1880
+ ensureCurrent(options?: {
1881
+ afterWrite?: boolean;
1882
+ }): Promise<void>;
1883
+ }
1884
+ interface EmbeddingBackfillResult {
1885
+ queued: number;
1886
+ skipped: number;
1887
+ }
1888
+ interface EmbeddingIndexStats {
1889
+ missingEmbeddings: number;
1890
+ staleEmbeddings: number;
1891
+ failedEmbeddings: number;
1892
+ /** Entities whose type generates embeddings (non-embeddable types excluded). */
1893
+ embeddableEntities: number;
1894
+ /** Embeddable entities whose embedding is present and current. */
1895
+ embeddedEntities: number;
1896
+ }
1897
+ interface IndexReadinessOptions {
1898
+ /** Stop polling after this duration. Omit for an owning runtime monitor. */
1899
+ timeoutMs?: number;
1900
+ intervalMs?: number;
1901
+ /** Cancels readiness polling when the owning runtime shuts down. */
1902
+ signal?: AbortSignal;
1903
+ }
1904
+ interface IndexReadinessStatus extends EmbeddingIndexStats {
1905
+ ready: boolean;
1906
+ degraded: boolean;
1907
+ activeEmbeddingJobs: number;
1908
+ }
1909
+ /**
1910
+ * The entity-service surface ordinary plugins receive. A real interface
1911
+ * rather than Omit<EntityService, ...>: mapped types collapse overloaded
1912
+ * methods (like the schema-taking reads) down to one signature.
1913
+ */
1914
+ interface EntityServiceClient extends ICoreEntityService {
1915
+ /** Visibility-scoped read and revision for atomic conditional writes. */
1916
+ getEntityWriteSnapshot(request: GetEntityRequest): Promise<EntityWriteSnapshot | null>;
1917
+ /** Local admission state; grouping endpoints must not serve partial bootstrap results. */
1918
+ areGroupingsReady(): boolean;
1919
+ /** Refresh definitions and start missing scans outside write transactions. */
1920
+ ensureGroupingsReady(): Promise<boolean>;
1921
+ /** Internal source-authority check used by persistence integrations. */
1922
+ isProjectionOwnedEntity(request: ProjectionOwnedEntityRequest): Promise<boolean>;
1923
+ listPendingEntityExports(): Promise<EntityExportIntent[]>;
1924
+ hasPendingEntityExports(): Promise<boolean>;
1925
+ acknowledgeEntityExports(request: AcknowledgeEntityExportsRequest): Promise<number>;
1926
+ runBulkMutation<TResult>(input: BulkMutationInput, mutation: () => Promise<TResult>): Promise<TResult>;
1927
+ createEntity<T extends BaseEntity>(request: CreateEntityRequest<T>): Promise<EntityMutationResult>;
1928
+ createEntityFromMarkdown(request: CreateEntityFromMarkdownRequest): Promise<EntityMutationResult>;
1929
+ updateEntity<T extends BaseEntity>(request: UpdateEntityRequest<T>): Promise<EntityMutationResult>;
1930
+ deleteEntity(request: DeleteEntityRequest): Promise<boolean>;
1931
+ upsertEntity<T extends BaseEntity>(request: UpsertEntityRequest<T>): Promise<EntityMutationResult & {
1932
+ created: boolean;
1933
+ }>;
1934
+ storeEmbedding(data: StoreEmbeddingData): Promise<void>;
1935
+ reconcileProjectionTargets(targets: readonly ProjectionChangedTarget[]): Promise<void>;
1936
+ backfillMissingEmbeddings(): Promise<EmbeddingBackfillResult>;
1937
+ isIndexReady(): boolean;
1938
+ awaitIndexReady(options: IndexReadinessOptions): Promise<IndexReadinessStatus>;
1939
+ serializeEntity(entity: BaseEntity): string;
1940
+ deserializeEntity(markdown: string, entityType: string): Partial<BaseEntity>;
1941
+ countEmbeddings(): Promise<number>;
1942
+ initialize(): Promise<void>;
1943
+ getAsyncJobStatus(jobId: string): Promise<{
1944
+ status: "pending" | "processing" | "completed" | "failed";
1945
+ error?: string;
1946
+ } | null>;
1947
+ }
1948
+ interface EntityService extends EntityServiceClient {
1949
+ /** Normal web/combined boot only, after initial sync; not an ordinary mutation. */
1950
+ reprojectRegisteredGroupings(): Promise<void>;
1951
+ getProjectionStore(): ProjectionStore;
1952
+ setProjectionWakeup(wakeup: () => Promise<void>): () => void;
1953
+ prepareDurableBulkMutation(input: DurableBulkMutationRootInput): Promise<void>;
1954
+ finalizeDurableBulkMutationEnqueue(operationId: string): Promise<void>;
1955
+ failDurableBulkMutationEnqueue(operationId: string): Promise<void>;
1956
+ runDurableBulkMutationChild<TResult>(input: DurableBulkMutationChildInput, mutation: () => Promise<TResult>): Promise<TResult>;
1957
+ settleDurableBulkMutationChild(input: SettleDurableBulkMutationChildInput): Promise<boolean>;
1958
+ recoverProjectionBatches(readRoot: ProjectionBatchRootReader): Promise<ProjectionBatchRecoveryResult>;
1959
+ }
1960
+ /**
1961
+ * Entity Registry interface for managing entity types and their schemas/adapters
1962
+ */
1963
+ interface EntityRegistry {
1964
+ registerEntityType<TEntity extends BaseEntity<TMetadata>, TMetadata extends Record<string, unknown> = Record<string, unknown>>(type: string, schema: UnknownEntitySchema, adapter: EntityAdapter<TEntity, TMetadata>, config?: EntityTypeConfig): void;
1965
+ /** Remove an entity type after failed plugin registration or shell teardown. */
1966
+ unregisterEntityType(type: string): void;
1967
+ getSchema(type: string): UnknownEntitySchema;
1968
+ getAdapter(type: string): EntityAdapter<BaseEntity>;
1969
+ hasEntityType(type: string): boolean;
1970
+ validateEntity(type: string, entity: unknown): BaseEntity;
1971
+ getAllEntityTypes(): string[];
1972
+ /** Get configuration for a specific entity type */
1973
+ getEntityTypeConfig(type: string): EntityTypeConfig;
1974
+ /** Get weight map for all registered entity types with non-default weights */
1975
+ getWeightMap(): Record<string, number>;
1976
+ registerCreateInterceptor(type: string, interceptor: CreateInterceptor): void;
1977
+ getCreateInterceptor(type: string): CreateInterceptor | undefined;
1978
+ registerUploadSaveHandler(registration: UploadSaveHandlerRegistration): void;
1979
+ getUploadSaveHandler(mediaType: string): UploadSaveHandlerRegistration | undefined;
1980
+ registerPersistValidator(type: string, validator: PersistValidator): void;
1981
+ getPersistValidator(type: string): PersistValidator | undefined;
1982
+ /**
1983
+ * Extend an adapter's frontmatterSchema with additional fields.
1984
+ * Used by plugins to add domain-specific fields (e.g., professional-site adds tagline to profile).
1985
+ * Extensions are merged into the effective schema returned by getEffectiveFrontmatterSchema().
1986
+ */
1987
+ extendFrontmatterSchema(type: string, extension: z.ZodObject<z.ZodRawShape>): void;
1988
+ registerGroupingSource(source: EntityGroupingSource): void;
1989
+ /** Capture preparation state; invoke the guard inside the write transaction. */
1990
+ captureGroupingWriteGuard(entityType: string): () => Promise<void>;
1991
+ getGroupingSourceType(): string | undefined;
1992
+ getPendingGroupingProjections(): GroupingProjectionTarget[];
1993
+ completeGroupingProjections(targets: readonly GroupingProjectionTarget[]): void;
1994
+ /** The source's own entity reads skip refresh to avoid recursion. */
1995
+ ensureGroupingsCurrent(entityType?: string, options?: {
1996
+ afterWrite?: boolean;
1997
+ }): Promise<void>;
1998
+ /** Preflight a complete replacement set without modifying active schemas. */
1999
+ validateGroupings(groupings: readonly EntityGrouping[]): void;
2000
+ /** Atomically replace declarations; observers may recheck retained fields. */
2001
+ replaceGroupings(groupings: readonly EntityGrouping[], options?: {
2002
+ reprojectExisting?: boolean;
2003
+ }): void;
2004
+ registerGrouping(grouping: EntityGrouping): void;
2005
+ getGrouping(key: string): EntityGrouping;
2006
+ getGroupings(): EntityGrouping[];
2007
+ projectMetadata(type: string, content: string, metadata: Record<string, unknown>): Record<string, unknown>;
2008
+ /** Bootstrap projection: an invalid stored value is omitted, never fatal. */
2009
+ projectStoredMetadata(type: string, content: string, metadata: Record<string, unknown>): Record<string, unknown>;
2010
+ groupingFields(type: string): string[];
2011
+ isGroupingContributor(type: string): boolean;
2012
+ /** Registered extension contracts, including their refinements. */
2013
+ getFrontmatterExtensions(type: string): readonly FrontmatterSchema[];
2014
+ /**
2015
+ * Get the effective frontmatter schema for an entity type,
2016
+ * with all registered extensions merged in.
2017
+ * Returns undefined if the adapter has no frontmatterSchema.
2018
+ */
2019
+ getEffectiveFrontmatterSchema(type: string): z.ZodObject<z.ZodRawShape> | undefined;
2020
+ }
2021
+ /**
2022
+ * The read-only projection of the entity service.
2023
+ *
2024
+ * What a plugin is handed when it has no business writing: insight handlers
2025
+ * compute over entities and return a summary. A projection of
2026
+ * `ICoreEntityService` rather than a hand-written parallel interface, so a
2027
+ * method that changes shape fails to compile here instead of drifting.
2028
+ *
2029
+ * `@brains/plugins` restates this as `IEntityService` on its published
2030
+ * authoring surface; `public-surface-soundness.test.ts` holds the two
2031
+ * together.
2032
+ */
2033
+ type ReadOnlyEntityService = Pick<ICoreEntityService, "getEntity" | "listEntities" | "search" | "searchWithDistances" | "getEntityTypes" | "hasEntityType" | "countEntities" | "getEntityCounts" | "getEntityTypeConfig">;
2034
+ //#endregion
2035
+ //#region ../../shell/job-queue/src/schema/types.d.ts
2036
+ /**
2037
+ * Operation type enum for structured progress tracking and aggregation
2038
+ * Using generic categories to accommodate various plugin operations
2039
+ */
2040
+ declare const OperationTypeEnum: z.ZodEnum<{
2041
+ file_operations: "file_operations";
2042
+ content_operations: "content_operations";
2043
+ data_processing: "data_processing";
2044
+ batch_processing: "batch_processing";
2045
+ }>;
2046
+ type JobContextInputSchema = z.ZodObject<{
2047
+ pluginId: z.ZodOptional<z.ZodString>;
2048
+ progressToken: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
2049
+ operationType: typeof OperationTypeEnum;
2050
+ operationTarget: z.ZodOptional<z.ZodString>;
2051
+ interfaceType: z.ZodOptional<z.ZodString>;
2052
+ conversationId: z.ZodOptional<z.ZodString>;
2053
+ channelId: z.ZodOptional<z.ZodString>;
2054
+ requestedByActor: z.ZodOptional<typeof actorRefSchema>;
2055
+ requestedByUserId: z.ZodOptional<z.ZodString>;
2056
+ requestedByInterface: z.ZodOptional<z.ZodString>;
2057
+ silent: z.ZodOptional<z.ZodBoolean>;
2058
+ provenance: z.ZodOptional<typeof OperationProvenanceSchema>;
2059
+ }, z.core.$loose>;
2060
+ /**
2061
+ * Job context input schema - what callers provide when creating jobs
2062
+ * Note: rootJobId is not included here - it's managed internally by the job queue service
2063
+ * and defaults to the job's own ID for standalone jobs, or the batch ID for batch children.
2064
+ *
2065
+ * Callers attach further keys of their own; the object is loose so parsing
2066
+ * keeps them and the type admits them.
2067
+ */
2068
+ declare const JobContextInputSchema: JobContextInputSchema;
2069
+ type JobContextInput = z.output<typeof JobContextInputSchema>;
2070
+ /**
2071
+ * Full job context schema - includes rootJobId for stored/transmitted metadata
2072
+ * This is what gets stored in the database and sent in progress events.
2073
+ */
2074
+ declare const JobContextSchema: z.ZodObject<JobContextInputSchema["shape"] & {
2075
+ rootJobId: z.ZodString;
2076
+ }, z.core.$loose>;
2077
+ /**
2078
+ * Deduplication strategy for job queue
2079
+ */
2080
+ declare const DeduplicationStrategyEnum: z.ZodEnum<{
2081
+ none: "none";
2082
+ skip: "skip";
2083
+ replace: "replace";
2084
+ coalesce: "coalesce";
2085
+ }>;
2086
+ type DeduplicationStrategy = z.output<typeof DeduplicationStrategyEnum>;
2087
+ /**
2088
+ * Job options for job creation
2089
+ */
2090
+ interface ProjectionJobContext {
2091
+ id: string;
2092
+ sourceEntity?: ProvenanceEntityReference | undefined;
2093
+ }
2094
+ interface JobOptions {
2095
+ priority?: number;
2096
+ maxRetries?: number;
2097
+ delayMs?: number;
2098
+ source: string;
2099
+ metadata: JobContextInput;
2100
+ deduplication?: DeduplicationStrategy;
2101
+ deduplicationKey?: string;
2102
+ /** Projection identity used to advance inherited causal provenance. */
2103
+ projection?: ProjectionJobContext;
2104
+ /**
2105
+ * Override rootJobId for batch child jobs
2106
+ * External callers should not use this - it's set automatically by the job queue service
2107
+ * Batch jobs use this to link child jobs to the parent batch
2108
+ */
2109
+ rootJobId?: string;
2110
+ }
2111
+ //#endregion
2112
+ //#region ../../shared/utils/src/progress.d.ts
2113
+ /**
2114
+ * Progress notification for long-running operations
2115
+ */
2116
+ interface ProgressNotification {
2117
+ progress: number;
2118
+ total?: number;
2119
+ message?: string;
2120
+ rate?: number;
2121
+ eta?: number;
2122
+ }
2123
+ /**
2124
+ * Progress callback type
2125
+ */
2126
+ type ProgressCallback = (notification: ProgressNotification) => Promise<void>;
2127
+ /**
2128
+ * A simple utility class for managing progress reporting in nested operations
2129
+ *
2130
+ * @example
2131
+ * ```typescript
2132
+ * // Create from a callback
2133
+ * const progress = ProgressReporter.from(sendProgress);
2134
+ *
2135
+ * // Report progress
2136
+ * await progress?.report({
2137
+ * message: "Building project",
2138
+ * progress: 10,
2139
+ * total: 100
2140
+ * });
2141
+ *
2142
+ * // Create sub-progress with scaled range
2143
+ * const subProgress = progress?.createSub({ scale: { start: 10, end: 90 } });
2144
+ *
2145
+ * // Use with APIs that expect a callback
2146
+ * await someApi(subProgress?.toCallback());
2147
+ * ```
2148
+ */
2149
+ /**
2150
+ * What a progress reporter provides to callers.
2151
+ *
2152
+ * Consumers depend on this rather than on `CallbackProgressReporter`. The class
2153
+ * carries a private callback and a private constructor, so nothing else can be
2154
+ * assignable to it — which is why every test double had to be asserted into
2155
+ * place, a cast that also erased the check on the members it did define.
2156
+ */
2157
+ interface ProgressReporter {
2158
+ createSub(options?: {
2159
+ scale?: {
2160
+ start: number;
2161
+ end: number;
2162
+ };
2163
+ }): ProgressReporter;
2164
+ report(notification: ProgressNotification): Promise<void>;
2165
+ startHeartbeat(message: string, intervalMs?: number): void;
2166
+ stopHeartbeat(): void;
2167
+ toCallback(): ProgressCallback;
2168
+ }
2169
+ //#endregion
2170
+ //#region ../../shell/job-queue/src/batch-schemas.d.ts
2171
+ type BatchOperationSchema = z.ZodObject<{
2172
+ type: z.ZodString;
2173
+ data: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2174
+ }>;
2175
+ /**
2176
+ * Schema for batch operation data
2177
+ */
2178
+ declare const BatchOperationSchema: BatchOperationSchema;
2179
+ type BatchOperation = z.output<typeof BatchOperationSchema>;
2180
+ type BatchJobStatusSchema = z.ZodObject<{
2181
+ batchId: z.ZodString;
2182
+ totalOperations: z.ZodNumber;
2183
+ completedOperations: z.ZodNumber;
2184
+ failedOperations: z.ZodNumber;
2185
+ currentOperation: z.ZodOptional<z.ZodString>;
2186
+ errors: z.ZodArray<z.ZodString>;
2187
+ status: z.ZodEnum<{
2188
+ pending: "pending";
2189
+ processing: "processing";
2190
+ completed: "completed";
2191
+ failed: "failed";
2192
+ }>;
2193
+ metadata: z.ZodOptional<typeof JobContextSchema>;
2194
+ }>;
2195
+ /**
2196
+ * Schema for batch job status response
2197
+ */
2198
+ declare const BatchJobStatusSchema: BatchJobStatusSchema;
2199
+ type BatchJobStatus = z.output<typeof BatchJobStatusSchema>;
2200
+ type BatchSchema = z.ZodObject<{
2201
+ batchId: z.ZodString;
2202
+ status: BatchJobStatusSchema;
2203
+ metadata: z.ZodObject<{
2204
+ operations: z.ZodArray<BatchOperationSchema>;
2205
+ source: z.ZodString;
2206
+ startedAt: z.ZodString;
2207
+ metadata: typeof JobContextSchema;
2208
+ }>;
2209
+ }>;
2210
+ /**
2211
+ * Schema for batch result with full metadata
2212
+ */
2213
+ declare const BatchSchema: BatchSchema;
2214
+ type Batch = z.output<typeof BatchSchema>;
2215
+ //#endregion
2216
+ //#region ../../shell/job-queue/src/types.d.ts
2217
+ /**
2218
+ * Request for enqueueing a job in the core job queue service.
2219
+ */
2220
+ interface JobQueueEnqueueRequest {
2221
+ /** Job type to enqueue */
2222
+ type: string;
2223
+ /** Job payload passed to the registered handler */
2224
+ data: unknown;
2225
+ /** Optional queue behavior, routing metadata, and retry settings */
2226
+ options?: JobOptions;
2227
+ }
2228
+ /** Ownership attached atomically when a worker dequeues a job. */
2229
+ interface JobClaimOptions {
2230
+ workerSlotId: string;
2231
+ workerSessionId: string;
2232
+ leaseDurationMs: number;
2233
+ }
2234
+ type JobInfoSchema = z.ZodObject<{
2235
+ id: z.ZodString;
2236
+ type: z.ZodString;
2237
+ data: z.ZodString;
2238
+ status: z.ZodEnum<{
2239
+ pending: "pending";
2240
+ processing: "processing";
2241
+ completed: "completed";
2242
+ failed: "failed";
2243
+ }>;
2244
+ source: z.ZodNullable<z.ZodString>;
2245
+ priority: z.ZodNumber;
2246
+ retryCount: z.ZodNumber;
2247
+ maxRetries: z.ZodNumber;
2248
+ lastError: z.ZodNullable<z.ZodString>;
2249
+ createdAt: z.ZodNumber;
2250
+ scheduledFor: z.ZodNumber;
2251
+ startedAt: z.ZodNullable<z.ZodNumber>;
2252
+ completedAt: z.ZodNullable<z.ZodNumber>;
2253
+ attemptId: z.ZodNullable<z.ZodString>;
2254
+ workerSlotId: z.ZodNullable<z.ZodString>;
2255
+ workerSessionId: z.ZodNullable<z.ZodString>;
2256
+ leaseExpiresAt: z.ZodNullable<z.ZodNumber>;
2257
+ attemptHeartbeatAt: z.ZodNullable<z.ZodNumber>;
2258
+ runtimeUpdatedAt: z.ZodNullable<z.ZodNumber>;
2259
+ metadata: typeof JobContextSchema;
2260
+ progress: z.ZodNullable<z.ZodCustom<ProgressNotification, ProgressNotification>>;
2261
+ result: z.ZodOptional<z.ZodNullable<z.ZodUnknown>>;
2262
+ }>;
2263
+ /**
2264
+ * Simplified job info schema for external packages
2265
+ * Avoids exposing the complex Drizzle-inferred JobQueue type
2266
+ */
2267
+ declare const JobInfoSchema: JobInfoSchema;
2268
+ type JobInfo = z.output<typeof JobInfoSchema>;
2269
+ interface JobValidator<TInput = unknown> {
2270
+ /** Validate and parse job data before durable enqueue. */
2271
+ validateAndParse(data: unknown): TInput | null;
2272
+ }
2273
+ /** Immutable declaration derived from a registered durable handler. */
2274
+ interface JobExecutionRegistration {
2275
+ readonly type: string;
2276
+ readonly pluginId: string | undefined;
2277
+ }
2278
+ /**
2279
+ * Job handler interface for processing specific job types
2280
+ *
2281
+ * @template TJobType - The job type string (can be any string for plugin extensibility)
2282
+ * @template TInput - The input data type for the job
2283
+ * @template TOutput - The output data type for the job
2284
+ */
2285
+ interface JobHandler<_TJobType extends string = string, TInput = unknown, TOutput = unknown> extends JobValidator<TInput> {
2286
+ /** Per-type execution deadline; falls back to the worker default. */
2287
+ readonly executionTimeoutMs?: number | undefined;
2288
+ /**
2289
+ * Process a job of this type
2290
+ * @param data - The job input data
2291
+ * @param jobId - Unique identifier for this job
2292
+ * @param progressReporter - Progress reporter for granular updates
2293
+ */
2294
+ process(data: TInput, jobId: string, progressReporter: ProgressReporter, signal: AbortSignal): Promise<TOutput>;
2295
+ /**
2296
+ * Handle job failure (optional)
2297
+ */
2298
+ /** Runs after successful terminal state is durably persisted. */
2299
+ onTerminalSuccess?(data: TInput, jobId: string, progressReporter: ProgressReporter, signal: AbortSignal): Promise<void>;
2300
+ onError?(error: Error, data: TInput, jobId: string, progressReporter: ProgressReporter, signal: AbortSignal): Promise<void>;
2301
+ /** Runs once after the queue exhausts retries and persists terminal failure. */
2302
+ onTerminalError?(error: Error, data: TInput, jobId: string, progressReporter: ProgressReporter, signal: AbortSignal): Promise<void>;
2303
+ }
2304
+ interface JobQueueStats {
2305
+ pending: number;
2306
+ processing: number;
2307
+ failed: number;
2308
+ completed: number;
2309
+ total: number;
2310
+ }
2311
+ interface JobRuntimeUpdateCursor {
2312
+ readonly updatedAt: number;
2313
+ readonly jobId: string;
2314
+ }
2315
+ interface JobRuntimeUpdate {
2316
+ readonly job: JobInfo;
2317
+ readonly cursor: JobRuntimeUpdateCursor;
2318
+ }
2319
+ interface JobWorkerSessionDiagnostics {
2320
+ total: number;
2321
+ active: number;
2322
+ stale: number;
2323
+ latestHeartbeatAgeMs: number | null;
2324
+ }
2325
+ interface JobQueueDiagnostics {
2326
+ totals: Omit<JobQueueStats, "total">;
2327
+ byType: Array<{
2328
+ type: string;
2329
+ status: JobInfo["status"];
2330
+ count: number;
2331
+ }>;
2332
+ oldestPendingAgeMs: number | null;
2333
+ duePending: number;
2334
+ oldestDuePendingAgeMs: number | null;
2335
+ latestClaimAgeMs: number | null;
2336
+ oldestProcessingAgeMs: number | null;
2337
+ staleLeaseCount: number;
2338
+ workerSessions: JobWorkerSessionDiagnostics;
2339
+ }
2340
+ interface JobQueueIdleOptions {
2341
+ /** How long the queue must stay empty before it counts as settled. */
2342
+ quietMs?: number;
2343
+ /** Give up after this long and report what is still outstanding. */
2344
+ timeoutMs?: number;
2345
+ pollIntervalMs?: number;
2346
+ signal?: AbortSignal;
2347
+ }
2348
+ /**
2349
+ * Job queue service interface
2350
+ */
2351
+ interface IJobQueueService {
2352
+ /** Settle database readiness work before runtime services start. */
2353
+ initialize?(): Promise<void>;
2354
+ /**
2355
+ * Register a job handler for a specific type
2356
+ */
2357
+ registerHandler(type: string, handler: JobHandler, pluginId?: string): void;
2358
+ /**
2359
+ * Unregister a job handler for a specific type
2360
+ */
2361
+ unregisterHandler(type: string): void;
2362
+ /**
2363
+ * Unregister all handlers for a specific plugin
2364
+ */
2365
+ unregisterPluginHandlers(pluginId: string): void;
2366
+ /**
2367
+ * Get a handler for a specific job type
2368
+ */
2369
+ getHandler(type: string): JobHandler | undefined;
2370
+ /**
2371
+ * Get the validator for a declared job type. Present in every registration
2372
+ * mode, including validation-only processes that hold no executable handler.
2373
+ */
2374
+ getValidator(type: string): JobValidator | undefined;
2375
+ /** Freeze handler declarations before runtime services can admit work. */
2376
+ finalizeHandlerRegistrations(): readonly JobExecutionRegistration[];
2377
+ /** Read the immutable handler declarations derived during boot. */
2378
+ getExecutionRegistrations(): readonly JobExecutionRegistration[];
2379
+ /**
2380
+ * Enqueue a job for processing
2381
+ */
2382
+ enqueue(request: JobQueueEnqueueRequest): Promise<string>;
2383
+ /** Dequeue and attach explicit attempt ownership. */
2384
+ dequeue(claim?: JobClaimOptions): Promise<JobInfo | null>;
2385
+ /** Register or supersede the live session for a stable worker slot. */
2386
+ startWorkerSession(workerSlotId: string, workerSessionId: string, workerSessionTimeoutMs?: number): Promise<void>;
2387
+ /** Persist worker liveness only while the session still owns its slot. */
2388
+ heartbeatWorkerSession(workerSlotId: string, workerSessionId: string, workerSessionTimeoutMs?: number): Promise<boolean>;
2389
+ /** Remove a normally stopped worker session. */
2390
+ endWorkerSession(workerSlotId: string, workerSessionId: string): Promise<boolean>;
2391
+ /** Renew a processing attempt's fenced lease. */
2392
+ renewAttemptLease(jobId: string, attemptId: string, leaseDurationMs: number): Promise<boolean>;
2393
+ /** Fence and persist a progress snapshot without extending the lease. */
2394
+ recordAttemptProgress(jobId: string, attemptId: string, progress: ProgressNotification): Promise<boolean>;
2395
+ /** Mark job as completed, fenced when an attempt token is supplied. */
2396
+ complete(jobId: string, result: unknown, attemptId?: string): Promise<boolean>;
2397
+ /** Mark job as failed, fenced when an attempt token is supplied. */
2398
+ fail(jobId: string, error: Error, attemptId?: string): Promise<boolean>;
2399
+ /** Update job data, fenced when an attempt token is supplied. */
2400
+ update(jobId: string, data: unknown, attemptId?: string): Promise<boolean>;
2401
+ /**
2402
+ * Get job status by job ID
2403
+ */
2404
+ getStatus(jobId: string): Promise<JobInfo | null>;
2405
+ /** Read all durable jobs belonging to one root operation. */
2406
+ getJobsByRootJobId(rootJobId: string): Promise<JobInfo[]>;
2407
+ /**
2408
+ * Get job status by entity ID (for embedding jobs)
2409
+ */
2410
+ getStatusByEntityId(entityId: string): Promise<JobInfo | null>;
2411
+ /**
2412
+ * Get queue statistics
2413
+ */
2414
+ getStats(): Promise<JobQueueStats>;
2415
+ /** Get bounded operational diagnostics without loading queue rows. */
2416
+ getDiagnostics(now?: number): Promise<JobQueueDiagnostics>;
2417
+ /** Settle once nothing is in flight and nothing new has arrived. */
2418
+ waitForIdle(options?: JobQueueIdleOptions): Promise<void>;
2419
+ /** Read durable processing and terminal updates for web-owned publication. */
2420
+ getRuntimeUpdates(cursor: JobRuntimeUpdateCursor, limit?: number): Promise<JobRuntimeUpdate[]>;
2421
+ /**
2422
+ * Clean up old completed jobs
2423
+ */
2424
+ cleanup(olderThanMs: number): Promise<number>;
2425
+ /**
2426
+ * Get active jobs (pending or processing)
2427
+ */
2428
+ getActiveJobs(types?: string[]): Promise<JobInfo[]>;
2429
+ /**
2430
+ * Get recent jobs of any status, newest first
2431
+ */
2432
+ getRecentJobs(types?: string[], limit?: number): Promise<JobInfo[]>;
2433
+ /**
2434
+ * Get failed jobs
2435
+ */
2436
+ getFailedJobs(types?: string[]): Promise<JobInfo[]>;
2437
+ /**
2438
+ * Get registered job types
2439
+ */
2440
+ getRegisteredTypes(): string[];
2441
+ /**
2442
+ * Close the underlying database connection.
2443
+ */
2444
+ close(): void;
2445
+ }
2446
+ /**
2447
+ * Unified jobs namespace interface
2448
+ * Combines job queue and batch operations for shell/context usage
2449
+ */
2450
+ interface IJobsNamespace {
2451
+ /** Get active jobs, optionally filtered by type */
2452
+ getActiveJobs(types?: string[]): Promise<JobInfo[]>;
2453
+ /** Get recent jobs of any status, newest first, optionally filtered by type */
2454
+ getRecentJobs(types?: string[], limit?: number): Promise<JobInfo[]>;
2455
+ /** Get status of a specific job */
2456
+ getStatus(jobId: string): Promise<JobInfo | null>;
2457
+ /** Enqueue multiple operations as a batch */
2458
+ enqueueBatch(operations: BatchOperation[], options: JobOptions, batchId: string, pluginId: string): Promise<string>;
2459
+ /** Get all active batches */
2460
+ getActiveBatches(): Promise<Batch[]>;
2461
+ /** Get status of a specific batch */
2462
+ getBatchStatus(batchId: string): Promise<BatchJobStatus | null>;
2463
+ }
2464
+ //#endregion
2465
+ //#region ../../shared/content-formatters/src/types.d.ts
2466
+ /**
2467
+ * Interface for content formatters (human-editable content formatting)
2468
+ *
2469
+ * ContentFormatters handle bidirectional transformation between structured data
2470
+ * and human-editable markdown templates. Unlike SchemaFormatters which are for
2471
+ * one-way API response formatting, ContentFormatters support parsing edited
2472
+ * content back into structured data.
2473
+ */
2474
+ interface ContentFormatter<T = unknown> {
2475
+ /**
2476
+ * Format structured data into human-editable markdown
2477
+ * @param data - The structured data to format
2478
+ * @returns Human-editable markdown representation
2479
+ */
2480
+ format(data: T): string;
2481
+ /**
2482
+ * Parse human-editable markdown back into structured data
2483
+ * @param content - The markdown content to parse
2484
+ * @returns Structured data parsed from the markdown
2485
+ * @throws Error if the content cannot be parsed
2486
+ */
2487
+ parse(content: string): T;
2488
+ }
2489
+ //#endregion
2490
+ //#region ../../shell/templates/src/types.d.ts
2491
+ /**
2492
+ * Component type for layouts - using React
2493
+ * Returns a React element
2494
+ */
2495
+ type ComponentType<P = unknown> = {
2496
+ bivarianceHack(props: P): ReactElement;
2497
+ }["bivarianceHack"];
2498
+ type TemplateDataSchema<T> = ZodType<T, unknown>;
2499
+ /**
2500
+ * A runtime script that a template depends on. Site-builder collects
2501
+ * these per route across all templates rendered on the page, dedupes
2502
+ * by `src`, and injects them as <script> tags.
2503
+ *
2504
+ * Use this for non-hydration runtime scripts (background canvases,
2505
+ * scroll observers, decorative animations) that should ONLY load on
2506
+ * pages where the template actually renders — unlike the plugin-level
2507
+ * head-script registration which fires on every page.
2508
+ */
2509
+ interface RuntimeScript {
2510
+ src: string;
2511
+ defer?: boolean;
2512
+ module?: boolean;
2513
+ }
2514
+ /**
2515
+ * Unified template interface that bundles content generation and view rendering
2516
+ * This is the single source of truth for what constitutes a template
2517
+ */
2518
+ interface TemplateBase extends Omit<TemplateInput, "schema" | "layout" | "formatter"> {
2519
+ formatter?: ContentFormatter<unknown>;
2520
+ /**
2521
+ * Opt-in content overlay. When set alongside a `dataSourceId`, the section's
2522
+ * saved content is parsed with this formatter and merged over the datasource
2523
+ * output (authored fields win), rather than the two being mutually exclusive.
2524
+ * Lets a live datasource-backed section carry content-authored fields — e.g.
2525
+ * a map whose data is live but whose hero copy is editable. Absent → the
2526
+ * classic datasource-or-saved precedence is unchanged.
2527
+ */
2528
+ overlayFormatter?: ContentFormatter<unknown>;
2529
+ /**
2530
+ * Whether to retrieve relevant entities from the knowledge base
2531
+ * and inject them as context before AI generation. Default: false.
2532
+ */
2533
+ useKnowledgeContext?: boolean;
2534
+ /**
2535
+ * Runtime script dependencies. Loaded only on routes where this
2536
+ * template actually renders — site-builder collects from all
2537
+ * templates on a route, dedupes by src, and injects into <head>.
2538
+ */
2539
+ runtimeScripts?: RuntimeScript[];
2540
+ /**
2541
+ * Static files this template needs served alongside the site — typically
2542
+ * the file behind a runtimeScripts src. Keyed by output-relative path;
2543
+ * site-builder writes each entry into the build output for routes that
2544
+ * actually render this template.
2545
+ */
2546
+ staticAssets?: Record<string, string>;
2547
+ }
2548
+ /** A renderer template must parse to a JSON document before it can be snapshotted. */
2549
+ interface LayoutTemplate extends TemplateBase {
2550
+ schema: TemplateDataSchema<JsonObject>;
2551
+ layout: {
2552
+ component?: ComponentType<unknown>;
2553
+ fullscreen?: boolean;
2554
+ };
2555
+ }
2556
+ /** Generation-only templates never enter the serializable site-build snapshot. */
2557
+ interface NonLayoutTemplate extends TemplateBase {
2558
+ schema: TemplateDataSchema<unknown>;
2559
+ layout?: undefined;
2560
+ }
2561
+ type Template = LayoutTemplate | NonLayoutTemplate;
2562
+ /**
2563
+ * Template schema for validation
2564
+ */
2565
+ declare const TemplateSchema: z.ZodObject<{
2566
+ name: z.ZodString;
2567
+ description: z.ZodString;
2568
+ schema: z.ZodUnknown;
2569
+ basePrompt: z.ZodOptional<z.ZodString>;
2570
+ useKnowledgeContext: z.ZodOptional<z.ZodBoolean>;
2571
+ requiredPermission: z.ZodEnum<{
2572
+ admin: "admin";
2573
+ trusted: "trusted";
2574
+ public: "public";
2575
+ }>;
2576
+ formatter: z.ZodOptional<z.ZodUnknown>;
2577
+ overlayFormatter: z.ZodOptional<z.ZodUnknown>;
2578
+ layout: z.ZodOptional<z.ZodObject<{
2579
+ component: z.ZodOptional<z.ZodUnknown>;
2580
+ fullscreen: z.ZodOptional<z.ZodBoolean>;
2581
+ }>>;
2582
+ dataSourceId: z.ZodOptional<z.ZodString>;
2583
+ }>;
2584
+ type TemplateInput = z.output<typeof TemplateSchema>;
2585
+ //#endregion
2586
+ //#region ../../shell/templates/src/permission-service.d.ts
2587
+ /**
2588
+ * User permission level schema
2589
+ */
2590
+ declare const UserPermissionLevelSchema: z.ZodEnum<{
2591
+ admin: "admin";
2592
+ trusted: "trusted";
2593
+ public: "public";
2594
+ }>;
2595
+ type UserPermissionLevel = z.output<typeof UserPermissionLevelSchema>;
2596
+ declare const EntityActionSchema: z.ZodEnum<{
2597
+ create: "create";
2598
+ update: "update";
2599
+ delete: "delete";
2600
+ extract: "extract";
2601
+ publish: "publish";
2602
+ }>;
2603
+ type EntityAction = z.output<typeof EntityActionSchema>;
2604
+ /**
2605
+ * Required level for an entity action.
2606
+ *
2607
+ * `never` forbids the action through system tools regardless of caller level.
2608
+ */
2609
+ declare const EntityActionRequiredLevelSchema: z.ZodEnum<{
2610
+ never: "never";
2611
+ admin: "admin";
2612
+ trusted: "trusted";
2613
+ public: "public";
2614
+ }>;
2615
+ type EntityActionRequiredLevel = z.output<typeof EntityActionRequiredLevelSchema>;
2616
+ declare const entityActionPolicyRuleSchema: z.ZodObject<{
2617
+ create: z.ZodOptional<typeof EntityActionRequiredLevelSchema>;
2618
+ update: z.ZodOptional<typeof EntityActionRequiredLevelSchema>;
2619
+ delete: z.ZodOptional<typeof EntityActionRequiredLevelSchema>;
2620
+ extract: z.ZodOptional<typeof EntityActionRequiredLevelSchema>;
2621
+ publish: z.ZodOptional<typeof EntityActionRequiredLevelSchema>;
2622
+ }, z.core.$strict>;
2623
+ type EntityActionPolicyRule = z.output<typeof entityActionPolicyRuleSchema>;
2624
+ declare const entityActionPolicyConfigSchema: z.ZodRecord<z.ZodString, typeof entityActionPolicyRuleSchema>;
2625
+ type EntityActionPolicyConfigInput = z.input<typeof entityActionPolicyConfigSchema>;
2626
+ /**
2627
+ * Generic interface for items with visibility
2628
+ */
2629
+ interface WithVisibility {
2630
+ visibility?: UserPermissionLevel;
2631
+ }
2632
+ /**
2633
+ * Permission rule for pattern-based permission matching
2634
+ */
2635
+ interface PermissionRule {
2636
+ pattern: string;
2637
+ level: UserPermissionLevel;
2638
+ }
2639
+ type PermissionRuleInput = PermissionRule;
2640
+ /**
2641
+ * Configuration for the permission system
2642
+ */
2643
+ interface ConfiguredPrincipalSeeds {
2644
+ admins: string[];
2645
+ anchors: string[];
2646
+ trusted: string[];
2647
+ }
2648
+ interface PermissionConfig {
2649
+ /** Callers with administrative permission. */
2650
+ admins?: string[];
2651
+ /** Caller identities that represent the brain's person anchor in chat. */
2652
+ anchors?: string[];
2653
+ trusted?: string[];
2654
+ rules?: PermissionRuleInput[];
2655
+ entityActions?: EntityActionPolicyConfigInput;
2656
+ }
2657
+ /**
2658
+ * Additional context interfaces can provide for shared-space permission checks.
2659
+ *
2660
+ * Each interface normalizes its location concept (Discord channel/thread,
2661
+ * Slack channel, Matrix room, ...) into the single canonical `channelId`
2662
+ * before calling the resolver.
2663
+ */
2664
+ interface PermissionLookupContext {
2665
+ channelId?: string;
2666
+ isBot?: boolean;
2667
+ isGuest?: boolean;
2668
+ }
2669
+ interface PermissionServiceOptions {
2670
+ /** Shared conversation space selectors, e.g. discord:123 or discord:project-* */
2671
+ spaces?: string[];
2672
+ /**
2673
+ * A type's own minimum, from whoever registered it. It tightens wildcard
2674
+ * defaults without relaxing stricter rules, including `never`, so a brain
2675
+ * assembled without the canonical bundle cannot leave an admin-only type
2676
+ * open. An explicit entry for the type still wins, action by action.
2677
+ */
2678
+ entityActionFloor?: (entityType: string) => EntityActionPolicyRule | undefined;
2679
+ }
2680
+ /**
2681
+ * Centralized permission service for determining user permission levels
2682
+ * Handles both explicit user lists and pattern-based rules
2683
+ * Replaces the previous permission handler.
2684
+ */
2685
+ declare class PermissionService {
2686
+ private admins;
2687
+ private anchors;
2688
+ private trusted;
2689
+ private readonly configuredPrincipalSeeds;
2690
+ private rules;
2691
+ private spaces;
2692
+ private entityActions?;
2693
+ private readonly entityActionFloor?;
2694
+ constructor(config: PermissionConfig, options?: PermissionServiceOptions);
2695
+ /**
2696
+ * Determine the permission level for a user in a specific interface.
2697
+ *
2698
+ * Resolution order (load-bearing — locks user-facing trust semantics):
2699
+ * 1. Explicit admin/trusted lists win — they encode operator intent.
2700
+ * 2. Pattern rules granting admin/trusted win — same intent, broader.
2701
+ * 3. Configured shared-space membership grants `trusted` — only raises
2702
+ * otherwise-public callers; never elevates to `admin`.
2703
+ * 4. Public-fallback pattern rules apply.
2704
+ * 5. Default `public`.
2705
+ */
2706
+ determineUserLevel(interfaceType: string, userId: string, context?: PermissionLookupContext): UserPermissionLevel;
2707
+ /** Whether the caller is this professional brain's Anchor identity. */
2708
+ isAnchor(interfaceType: string, userId: string): boolean;
2709
+ getConfiguredPrincipalSeeds(): ConfiguredPrincipalSeeds;
2710
+ replaceRuntimePrincipalState(state: RuntimeInterfacePrincipalState): void;
2711
+ /**
2712
+ * Return the merged entity action policy for an entity type.
2713
+ * Entity-specific entries override the "*" default one action at a time.
2714
+ */
2715
+ getResolvedEntityActionPolicy(entityType: string): EntityActionPolicyRule | undefined;
2716
+ getEntityActionRequiredLevel(entityType: string, action: EntityAction): EntityActionRequiredLevel | undefined;
2717
+ getRequiredEntityActionLevel(entityType: string, action: EntityAction): EntityActionRequiredLevel | undefined;
2718
+ canPerformEntityAction(userLevel: UserPermissionLevel | undefined, entityType: string, action: EntityAction): boolean;
2719
+ assertEntityActionAllowed(entityType: string, action: EntityAction, userLevel: UserPermissionLevel | undefined): void;
2720
+ /**
2721
+ * Check if a user has a specific permission level or higher
2722
+ * @param userLevel The user's actual permission level
2723
+ * @param requiredLevel The required permission level
2724
+ * @returns True if the user meets the permission requirement
2725
+ */
2726
+ hasPermission(userLevel: UserPermissionLevel, requiredLevel: UserPermissionLevel): boolean;
2727
+ /**
2728
+ * Filter items based on user permission level
2729
+ * Works for tools, commands, or any item with a visibility property
2730
+ * @param items Array of items with visibility levels
2731
+ * @param userLevel The user's permission level
2732
+ * @returns Filtered array of items the user can access
2733
+ */
2734
+ filterByPermission<T extends WithVisibility>(items: T[], userLevel: UserPermissionLevel): T[];
2735
+ /**
2736
+ * Static method to check if a permission level meets the required level
2737
+ * Used by Shell for interface-based permission checking (commands, templates, etc.)
2738
+ * Maintains compatibility with existing Shell.generateContent() usage
2739
+ */
2740
+ static hasPermission(grantedLevel: UserPermissionLevel, requiredLevel: UserPermissionLevel): boolean;
2741
+ private getPatternLevel;
2742
+ private matchesConfiguredSpace;
2743
+ }
2744
+ //#endregion
2745
+ //#region ../../shell/templates/src/render-types.d.ts
2746
+ /**
2747
+ * Renderer output formats supported by view templates.
2748
+ */
2749
+ declare const OutputFormatSchema: z.ZodEnum<{
2750
+ web: "web";
2751
+ image: "image";
2752
+ pdf: "pdf";
2753
+ }>;
2754
+ type OutputFormat = z.output<typeof OutputFormatSchema>;
2755
+ /**
2756
+ * Renderer types for different output formats
2757
+ */
2758
+ type WebRenderer<T = unknown> = ComponentType<T> | string;
2759
+ type ImageRenderer<T = unknown> = ComponentType<T> | string;
2760
+ type PdfRenderer<T = unknown> = ComponentType<T> | string;
2761
+ type MediaRenderer<T = unknown> = ImageRenderer<T> | PdfRenderer<T>;
2762
+ type Renderer<T = unknown> = WebRenderer<T> | MediaRenderer<T>;
2763
+ /**
2764
+ * View template with support for multiple output formats
2765
+ */
2766
+ interface ViewTemplate<T extends JsonObject = JsonObject> {
2767
+ name: string;
2768
+ schema: TemplateDataSchema<T>;
2769
+ description?: string;
2770
+ pluginId: string;
2771
+ renderers: {
2772
+ web?: WebRenderer<T>;
2773
+ image?: ImageRenderer<T>;
2774
+ pdf?: PdfRenderer<T>;
2775
+ };
2776
+ fullscreen?: boolean;
2777
+ providerId?: string;
2778
+ formatter?: ContentFormatter<T>;
2779
+ /** Runtime script dependencies (see Template.runtimeScripts). */
2780
+ runtimeScripts?: RuntimeScript[];
2781
+ /** Static files behind runtimeScripts srcs (see Template.staticAssets). */
2782
+ staticAssets?: Record<string, string>;
2783
+ }
2784
+ /**
2785
+ * View template registry interface
2786
+ */
2787
+ /**
2788
+ * The render service as consumers use it.
2789
+ *
2790
+ * `hasRenderer` and `listFormats` were missing here even though callers use
2791
+ * both: consumers took the `RenderService` class instead, which meant a test
2792
+ * double had to be asserted into a type with private state.
2793
+ */
2794
+ interface ViewTemplateRegistry {
2795
+ get(name: string): ViewTemplate | undefined;
2796
+ list(): ViewTemplate[];
2797
+ validate(templateName: string, content: unknown): boolean;
2798
+ findViewTemplate(filter: {
2799
+ name?: string;
2800
+ pluginId?: string;
2801
+ namePattern?: string;
2802
+ }): ViewTemplate | undefined;
2803
+ getRenderer(templateName: string, format: OutputFormat): Renderer | undefined;
2804
+ hasRenderer(templateName: string, format: OutputFormat): boolean;
2805
+ listFormats(templateName: string): OutputFormat[];
2806
+ }
2807
+ //#endregion
2808
+ //#region ../../shell/messaging-service/src/message-validator.d.ts
2809
+ type MessageValidationResult<T> = {
2810
+ valid: true;
2811
+ data: T;
2812
+ } | {
2813
+ valid: false;
2814
+ error: string;
2815
+ };
2816
+ type MessageValidationSchema<T> = ZodType<T, unknown>;
2817
+ //#endregion
2818
+ //#region ../../shell/messaging-service/src/base-types.d.ts
2819
+ /**
2820
+ * Simple response schema for message handlers
2821
+ */
2822
+ declare const messageResponseSchema: z.ZodObject<{
2823
+ success: z.ZodBoolean;
2824
+ data: z.ZodOptional<z.ZodUnknown>;
2825
+ error: z.ZodOptional<z.ZodString>;
2826
+ }>;
2827
+ /** A handler's reply: the parsed response with its data narrowed to T, or a no-op. */
2828
+ type MessageResponse<T = unknown> = (Omit<z.output<typeof messageResponseSchema>, "data"> & {
2829
+ data?: T | undefined;
2830
+ }) | {
2831
+ noop: true;
2832
+ };
2833
+ type BaseMessageSchema = z.ZodObject<{
2834
+ id: z.ZodString;
2835
+ timestamp: z.ZodString;
2836
+ type: z.ZodString;
2837
+ source: z.ZodString;
2838
+ target: z.ZodOptional<z.ZodString>;
2839
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2840
+ }>;
2841
+ /**
2842
+ * Base message schema - all messages must have these fields
2843
+ */
2844
+ declare const baseMessageSchema: BaseMessageSchema;
2845
+ type BaseMessage = z.output<typeof baseMessageSchema>;
2846
+ type MessageWithPayload<T = unknown> = BaseMessage & {
2847
+ payload: T;
2848
+ };
2849
+ /**
2850
+ * Message handler type
2851
+ */
2852
+ type MessageHandler<T = unknown, R = unknown> = (message: MessageWithPayload<T>) => Promise<MessageResponse<R>> | MessageResponse<R>;
2853
+ /**
2854
+ * Options for sending messages
2855
+ */
2856
+ interface MessageSendOptions {
2857
+ /** Optional target for filtered delivery */
2858
+ target?: string;
2859
+ /** Optional metadata for filtered delivery */
2860
+ metadata?: Record<string, unknown>;
2861
+ /** If true, all matching handlers are called regardless of responses */
2862
+ broadcast?: boolean;
2863
+ }
2864
+ interface MessageSendRequest<T = unknown> extends MessageSendOptions {
2865
+ type: string;
2866
+ payload: T;
2867
+ }
2868
+ interface MessageBusSendRequest<T = unknown> extends MessageSendRequest<T> {
2869
+ sender: string;
2870
+ }
2871
+ //#endregion
2872
+ //#region ../../shell/messaging-service/src/types.d.ts
2873
+ /**
2874
+ * Subscription filter for targeted message delivery
2875
+ */
2876
+ interface SubscriptionFilter {
2877
+ source?: string | RegExp;
2878
+ target?: string | RegExp;
2879
+ metadata?: Record<string, unknown>;
2880
+ predicate?: (message: MessageWithPayload) => boolean;
2881
+ }
2882
+ /**
2883
+ * Message bus interface
2884
+ */
2885
+ interface IMessageBus {
2886
+ send<T = unknown, R = unknown>(request: MessageBusSendRequest<T>): Promise<MessageResponse<R>>;
2887
+ subscribe<T = unknown, R = unknown>(type: string, handler: MessageHandler<T, R>, filter?: SubscriptionFilter): () => void;
2888
+ /** Collect one response from every matching handler, in registration order. */
2889
+ collect<T = unknown, R = unknown>(request: MessageBusSendRequest<T>): Promise<MessageResponse<R>[]>;
2890
+ validateMessage<T>(message: unknown, schema: MessageValidationSchema<T>): MessageValidationResult<T>;
2891
+ unsubscribe<T = unknown, R = unknown>(type: string, handler: MessageHandler<T, R>): void;
2892
+ hasHandlers?(type: string): boolean;
2893
+ getHandlerCount(messageType: string): number;
2894
+ getTargetedHandlerCount(messageType: string, target: string): number;
2895
+ clearHandlers(messageType: string): void;
2896
+ clearAllHandlers(): void;
2897
+ }
2898
+ //#endregion
2899
+ //#region ../../shell/mcp-service/src/types.d.ts
2900
+ /**
2901
+ * Tool visibility levels for permission control
2902
+ * Uses the same levels as UserPermissionLevel for consistency
2903
+ */
2904
+ type ToolVisibility = UserPermissionLevel;
2905
+ /**
2906
+ * Tool execution context
2907
+ * Provides progress reporting and routing metadata
2908
+ */
2909
+ interface ToolContext {
2910
+ progressToken?: string | number;
2911
+ sendProgress?: (notification: ProgressNotification) => Promise<void>;
2912
+ /** Cancellation for the active request; handlers may opt in. */
2913
+ signal?: AbortSignal;
2914
+ interfaceType: string;
2915
+ actor: ActorRef;
2916
+ displayName?: string;
2917
+ conversationId?: string;
2918
+ channelId?: string;
2919
+ channelName?: string;
2920
+ runId?: string;
2921
+ toolCallId?: string;
2922
+ /** Caller's permission level. Tools that read/write entities use this to derive
2923
+ * the content-visibility scope they are allowed to see. */
2924
+ userPermissionLevel?: UserPermissionLevel;
2925
+ /** Whether the authenticated caller is the brain's configured Anchor. */
2926
+ isAnchor?: boolean;
2927
+ }
2928
+ /**
2929
+ * Success response schema
2930
+ */
2931
+ declare const toolSuccessSchema: z.ZodObject<{
2932
+ success: z.ZodLiteral<true>;
2933
+ data: z.ZodOptional<z.ZodUnknown>;
2934
+ message: z.ZodOptional<z.ZodString>;
2935
+ cached: z.ZodOptional<z.ZodLiteral<true>>;
2936
+ }, z.core.$strict>;
2937
+ /**
2938
+ * Error response schema
2939
+ */
2940
+ declare const toolErrorSchema: z.ZodObject<{
2941
+ success: z.ZodLiteral<false>;
2942
+ error: z.ZodString;
2943
+ code: z.ZodOptional<z.ZodString>;
2944
+ }, z.core.$strict>;
2945
+ /**
2946
+ * Confirmation response schema
2947
+ * Tools return this when an operation needs user approval.
2948
+ * The agent service detects this shape and enters the confirmation flow.
2949
+ */
2950
+ declare const toolConfirmationSchema: z.ZodObject<{
2951
+ needsConfirmation: z.ZodLiteral<true>;
2952
+ toolName: z.ZodString;
2953
+ summary: z.ZodString;
2954
+ completionSummary: z.ZodOptional<z.ZodString>;
2955
+ preview: z.ZodOptional<z.ZodString>;
2956
+ args: z.ZodUnknown;
2957
+ }, z.core.$strict>;
2958
+ /**
2959
+ * Standardized tool response schema
2960
+ * All tools return one of: success, error, or confirmation request.
2961
+ */
2962
+ declare const toolResponseSchema: z.ZodUnion<readonly [typeof toolSuccessSchema, typeof toolErrorSchema, typeof toolConfirmationSchema]>;
2963
+ type ToolResponse = z.output<typeof toolResponseSchema>;
2964
+ type ToolSideEffects = "none" | "writes" | "external";
2965
+ type DirectMcpExposure = "none" | "basic" | "debug";
2966
+ type ToolInputSchema = ZodRawShape;
2967
+ type ToolOutputSchema = z.ZodType;
2968
+ type MCPProtocolMode = "basic" | "debug";
2969
+ /**
2970
+ * Tool definition
2971
+ * @template TOutput - The output type, defaults to ToolResponse for backward compatibility
2972
+ */
2973
+ interface Tool<TOutput = ToolResponse> {
2974
+ name: string;
2975
+ description: string;
2976
+ inputSchema: ToolInputSchema;
2977
+ outputSchema?: ToolOutputSchema;
2978
+ handler: (input: unknown, context: ToolContext) => Promise<TOutput>;
2979
+ visibility?: ToolVisibility;
2980
+ /** Declares whether this tool is safe to repeat/cache within one model turn. Undefined defaults to not cacheable. */
2981
+ sideEffects?: ToolSideEffects;
2982
+ /** Whether the LLM agent may receive this tool in its callable tool set. Defaults to true. */
2983
+ agentTool?: boolean;
2984
+ /** Direct external MCP protocol exposure. Defaults to debug; basic exposure requires an explicit opt-in. */
2985
+ directMcpExposure?: DirectMcpExposure;
2986
+ /** MCP protocol annotations advertised to external clients. Derived from sideEffects when omitted. */
2987
+ annotations?: ToolAnnotations;
2988
+ /** Optional CLI metadata — makes this tool invocable as a brain CLI command */
2989
+ cli?: {
2990
+ /** CLI command name (e.g. "list", "sync", "build") */
2991
+ name: string;
2992
+ };
2993
+ }
2994
+ /**
2995
+ * Resource definition
2996
+ */
2997
+ interface Resource {
2998
+ uri: string;
2999
+ name: string;
3000
+ description?: string;
3001
+ mimeType?: string;
3002
+ handler: () => Promise<{
3003
+ contents: Array<{
3004
+ text: string;
3005
+ uri: string;
3006
+ mimeType?: string;
3007
+ }>;
3008
+ }>;
3009
+ }
3010
+ /**
3011
+ * Variables extracted from a URI template.
3012
+ * Generic parameter ensures handlers receive typed vars, not loose index signatures.
3013
+ */
3014
+ type ResourceVars<K extends string = string> = { [P in K]: string; };
3015
+ /**
3016
+ * A parameterized resource with URI template (e.g. "entity://{type}/{id}")
3017
+ */
3018
+ interface ResourceTemplate<K extends string = string> {
3019
+ name: string;
3020
+ uriTemplate: string;
3021
+ description?: string;
3022
+ mimeType?: string;
3023
+ /** List all concrete resources matching this template (for resources/list) */
3024
+ list?: () => Promise<Array<{
3025
+ uri: string;
3026
+ name: string;
3027
+ }>>;
3028
+ /** Autocomplete values for template variables (populates client selectors) */
3029
+ complete?: Record<K, (value: string, context?: {
3030
+ arguments?: Partial<ResourceVars<K>>;
3031
+ }) => string[] | Promise<string[]>>;
3032
+ /** Read a single resource by resolved template variables */
3033
+ handler: (vars: ResourceVars<K>) => Promise<{
3034
+ contents: Array<{
3035
+ text: string;
3036
+ uri: string;
3037
+ mimeType?: string;
3038
+ }>;
3039
+ }>;
3040
+ }
3041
+ /**
3042
+ * An MCP prompt — parameterized message template for client prompt pickers
3043
+ */
3044
+ interface Prompt {
3045
+ name: string;
3046
+ description?: string;
3047
+ args: Record<string, {
3048
+ description: string;
3049
+ required?: boolean;
3050
+ }>;
3051
+ handler: (args: Record<string, string>) => Promise<{
3052
+ messages: Array<{
3053
+ role: "user" | "assistant";
3054
+ content: {
3055
+ type: "text";
3056
+ text: string;
3057
+ };
3058
+ }>;
3059
+ }>;
3060
+ /** Default: "admin" — prompt bodies can reference restricted workflows,
3061
+ * so they ship as admin-only unless explicitly marked. */
3062
+ visibility?: ToolVisibility;
3063
+ }
3064
+ /**
3065
+ * Minimal interface exposed to transport layers
3066
+ * Only provides what's needed to connect transports to the MCP server
3067
+ */
3068
+ interface IMCPTransport {
3069
+ /**
3070
+ * Get the underlying MCP server for transport layers to connect to
3071
+ * Transport layers should import McpServer from @modelcontextprotocol/server directly
3072
+ */
3073
+ getMcpServer(): McpServer;
3074
+ /**
3075
+ * Create a fresh MCP server instance with all registered tools/resources.
3076
+ * Stateless HTTP invokes this for every authenticated request.
3077
+ */
3078
+ createMcpServer(permissionLevel?: UserPermissionLevel): McpServer;
3079
+ /**
3080
+ * Set the permission level for this transport
3081
+ */
3082
+ setPermissionLevel(level: UserPermissionLevel): void;
3083
+ /** Set whether the transport's configured caller is the brain Anchor. */
3084
+ setAnchorStatus?(isAnchor: boolean): void;
3085
+ /** Select which registered tools are exposed on the external MCP protocol server. */
3086
+ setProtocolMode(mode: MCPProtocolMode): void;
3087
+ }
3088
+ /**
3089
+ * Tool registration info
3090
+ */
3091
+ interface ToolInfo {
3092
+ name: string;
3093
+ description: string;
3094
+ pluginId: string;
3095
+ }
3096
+ //#endregion
3097
+ //#region ../../shell/entity-service/src/datasource-registry.d.ts
3098
+ /**
3099
+ * The data source registry as consumers use it.
3100
+ *
3101
+ * They depend on this rather than on `InMemoryDataSourceRegistry`: the class
3102
+ * has private state and a private constructor, so nothing else can be
3103
+ * assignable to it — which is why every test double had to be asserted in.
3104
+ */
3105
+ interface DataSourceRegistry {
3106
+ register(dataSource: DataSource): void;
3107
+ unregister(id: string): void;
3108
+ get(id: string): DataSource | undefined;
3109
+ has(id: string): boolean;
3110
+ list(): DataSource[];
3111
+ getIds(): string[];
3112
+ getByCapability(capability: keyof DataSourceCapabilities): DataSource[];
3113
+ find(predicate: (dataSource: DataSource) => boolean): DataSource[];
3114
+ clear(): void;
3115
+ }
3116
+ //#endregion
3117
+ //#region ../../shell/plugins/src/manager/daemon-types.d.ts
3118
+ /**
3119
+ * Daemon health status schema
3120
+ */
3121
+ declare const DaemonHealthSchema: z.ZodObject<{
3122
+ status: z.ZodEnum<{
3123
+ healthy: "healthy";
3124
+ warning: "warning";
3125
+ error: "error";
3126
+ unknown: "unknown";
3127
+ }>;
3128
+ message: z.ZodOptional<z.ZodString>;
3129
+ lastCheck: z.ZodOptional<z.ZodDate>;
3130
+ details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3131
+ }>;
3132
+ type DaemonHealth = z.output<typeof DaemonHealthSchema>;
3133
+ /**
3134
+ * Daemon status info schema for validation
3135
+ */
3136
+ declare const DaemonStatusInfoSchema: z.ZodObject<{
3137
+ name: z.ZodString;
3138
+ pluginId: z.ZodString;
3139
+ status: z.ZodString;
3140
+ health: z.ZodOptional<typeof DaemonHealthSchema>;
3141
+ }>;
3142
+ /**
3143
+ * Daemon interface for long-running interface processes
3144
+ */
3145
+ interface Daemon {
3146
+ /**
3147
+ * Start the daemon - called when plugin is initialized
3148
+ */
3149
+ start: () => Promise<void>;
3150
+ /**
3151
+ * Stop the daemon - called when plugin is unloaded/shutdown
3152
+ */
3153
+ stop: () => Promise<void>;
3154
+ /**
3155
+ * Optional health check - called periodically to monitor daemon health
3156
+ */
3157
+ healthCheck?: () => Promise<DaemonHealth>;
3158
+ }
3159
+ //#endregion
3160
+ //#region ../../shell/content-service/src/generation-context.d.ts
3161
+ /** Context shared by immediate and durable template-based generation. */
3162
+ declare const generationContextSchema: z.ZodObject<{
3163
+ prompt: z.ZodOptional<z.ZodString>;
3164
+ conversationHistory: z.ZodOptional<z.ZodString>;
3165
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3166
+ representedIdentity: z.ZodOptional<z.ZodEnum<{
3167
+ brain: "brain";
3168
+ anchor: "anchor";
3169
+ none: "none";
3170
+ }>>;
3171
+ styleGuide: z.ZodOptional<z.ZodObject<{
3172
+ voice: z.ZodOptional<z.ZodString>;
3173
+ visual: z.ZodOptional<z.ZodString>;
3174
+ }>>;
3175
+ }>;
3176
+ type GenerationContext = z.output<typeof generationContextSchema>;
3177
+ //#endregion
3178
+ //#region ../../shell/content-service/src/generation-authorization.d.ts
3179
+ /** Supplied by a trusted runtime binding, never by a tool's input schema. */
3180
+ interface GenerationCaller {
3181
+ actor: ActorRef;
3182
+ permissionLevel: UserPermissionLevel;
3183
+ }
3184
+ /** Durable delegation: account binding and an admission-time permission ceiling. */
3185
+ interface GenerationAuthority {
3186
+ actor: ActorRef;
3187
+ permissionCeiling: UserPermissionLevel;
3188
+ principalId?: string | undefined;
3189
+ }
3190
+ interface GenerationAccess {
3191
+ permissionLevel: UserPermissionLevel;
3192
+ visibilityScope: ContentVisibility;
3193
+ }
3194
+ //#endregion
3195
+ //#region ../../shell/content-service/src/generation-contracts.d.ts
3196
+ interface DurableGenerationContext extends Omit<GenerationContext, "data"> {
3197
+ data?: JsonObject | undefined;
3198
+ }
3199
+ interface ContentGenerationDestination {
3200
+ entityType: string;
3201
+ idPath: EntityIdPath;
3202
+ metadata: JsonObject;
3203
+ visibility?: ContentVisibility | undefined;
3204
+ }
3205
+ interface ContentGenerationDestinationInput {
3206
+ entityType: string;
3207
+ idPath: EntityIdPathInput;
3208
+ metadata: JsonObject;
3209
+ visibility?: ContentVisibility | undefined;
3210
+ }
3211
+ interface ContentGenerationTarget {
3212
+ templateName: string;
3213
+ context: DurableGenerationContext;
3214
+ destination: ContentGenerationDestination;
3215
+ }
3216
+ interface ContentGenerationTargetInput {
3217
+ templateName: string;
3218
+ context?: DurableGenerationContext;
3219
+ destination: ContentGenerationDestinationInput;
3220
+ }
3221
+ interface ContentGenerationOptions {
3222
+ dryRun?: boolean;
3223
+ force?: boolean;
3224
+ }
3225
+ interface ContentGenerationRequestInput {
3226
+ caller: GenerationCaller;
3227
+ targets: ContentGenerationTargetInput[];
3228
+ options?: ContentGenerationOptions;
3229
+ /** Template names are local to this plugin and scoped by the runtime. */
3230
+ pluginId?: string;
3231
+ }
3232
+ interface PersistedContentGenerationDestination {
3233
+ entityType: string;
3234
+ entityId: string;
3235
+ metadata: JsonObject;
3236
+ visibility: ContentVisibility;
3237
+ }
3238
+ interface ContentGenerationJobData {
3239
+ authority: GenerationAuthority;
3240
+ templateName: string;
3241
+ context: DurableGenerationContext;
3242
+ destination: PersistedContentGenerationDestination;
3243
+ expectedRevision: string | null;
3244
+ }
3245
+ declare const contentGenerationSkipReasons: readonly ["content-exists", "template-not-found", "template-cannot-generate"];
3246
+ type ContentGenerationSkipReason = (typeof contentGenerationSkipReasons)[number];
3247
+ /** `index` is the target's position in the request, so results keep its order. */
3248
+ interface PlannedContentGeneration {
3249
+ readonly index: number;
3250
+ readonly target: ContentGenerationTarget;
3251
+ readonly entityId: string;
3252
+ readonly jobData: ContentGenerationJobData;
3253
+ }
3254
+ interface SkippedContentGeneration {
3255
+ readonly index: number;
3256
+ readonly target: ContentGenerationTarget;
3257
+ readonly entityId: string;
3258
+ readonly reason: ContentGenerationSkipReason;
3259
+ }
3260
+ interface ContentGenerationPlan {
3261
+ readonly planned: readonly PlannedContentGeneration[];
3262
+ readonly skipped: readonly SkippedContentGeneration[];
3263
+ readonly totalTargets: number;
3264
+ }
3265
+ interface ContentGenerationItemBase {
3266
+ readonly destination: {
3267
+ readonly entityType: string;
3268
+ readonly idPath: EntityIdPath;
3269
+ readonly entityId: string;
3270
+ };
3271
+ readonly templateName: string;
3272
+ }
3273
+ /** One admission decision per requested target, in request order. */
3274
+ type ContentGenerationItemResult = (ContentGenerationItemBase & {
3275
+ readonly status: "planned";
3276
+ }) | (ContentGenerationItemBase & {
3277
+ readonly status: "queued";
3278
+ readonly jobId: string;
3279
+ }) | (ContentGenerationItemBase & {
3280
+ readonly status: "skipped";
3281
+ readonly reason: ContentGenerationSkipReason;
3282
+ });
3283
+ interface ContentGenerationBatchResult {
3284
+ readonly items: readonly ContentGenerationItemResult[];
3285
+ readonly totalTargets: number;
3286
+ readonly plannedTargets: number;
3287
+ readonly queuedTargets: number;
3288
+ readonly skippedTargets: number;
3289
+ readonly batchId?: string;
3290
+ }
3291
+ //#endregion
3292
+ //#region ../../shell/content-service/src/generation-submission.d.ts
3293
+ /**
3294
+ * Runtime wiring, never author-supplied tool input. The plugin layer owns job
3295
+ * options and attribution; content-service only decides what to enqueue.
3296
+ */
3297
+ interface GenerationQueueBinding {
3298
+ /** Existing root job ID to share; a fresh one is allocated otherwise. */
3299
+ batchId?: string | undefined;
3300
+ enqueue(jobData: ContentGenerationJobData, batchId: string): Promise<string>;
3301
+ }
3302
+ //#endregion
3303
+ //#region ../../shell/content-service/src/types.d.ts
3304
+ type ContentTemplateDataSchema<T> = ZodType<T, unknown>;
3305
+ /**
3306
+ * Zod schema for ContentTemplate validation (used in plugin configurations)
3307
+ */
3308
+ declare const ContentTemplateSchema: z.ZodObject<{
3309
+ name: z.ZodString;
3310
+ description: z.ZodString;
3311
+ schema: z.ZodUnknown;
3312
+ basePrompt: z.ZodOptional<z.ZodString>;
3313
+ requiredPermission: z.ZodEnum<{
3314
+ admin: "admin";
3315
+ trusted: "trusted";
3316
+ public: "public";
3317
+ }>;
3318
+ formatter: z.ZodOptional<z.ZodUnknown>;
3319
+ dataSourceId: z.ZodOptional<z.ZodString>;
3320
+ layout: z.ZodOptional<z.ZodObject<{
3321
+ component: z.ZodUnknown;
3322
+ description: z.ZodOptional<z.ZodString>;
3323
+ packageName: z.ZodOptional<z.ZodString>;
3324
+ }>>;
3325
+ }>;
3326
+ type ContentTemplateInput = z.output<typeof ContentTemplateSchema>;
3327
+ /**
3328
+ * ContentTemplate for reusable generation patterns and view rendering
3329
+ */
3330
+ interface ContentTemplate<T = unknown> extends Omit<ContentTemplateInput, "schema" | "formatter"> {
3331
+ schema: ContentTemplateDataSchema<T>;
3332
+ formatter?: ContentFormatter<T>;
3333
+ dataSourceId?: string;
3334
+ }
3335
+ /**
3336
+ * Options for content resolution with multiple strategies
3337
+ */
3338
+ interface ResolutionOptions {
3339
+ /** Look up previously saved content from entity storage */
3340
+ savedContent?: {
3341
+ entityType: string;
3342
+ entityId: string;
3343
+ };
3344
+ /** Parameters for DataSource fetch operation */
3345
+ dataParams?: unknown;
3346
+ /** Format for DataSource transform operation (e.g., "list" or "detail") */
3347
+ transformFormat?: string;
3348
+ /** Static fallback content */
3349
+ fallback?: unknown;
3350
+ /**
3351
+ * Whether to filter to only published/complete content
3352
+ * Set by site-builder: true for production, false for preview
3353
+ */
3354
+ publishedOnly?: boolean;
3355
+ /**
3356
+ * Visibility scope to enforce on entity lookups within this resolution.
3357
+ * Set by site-builder: "public" for production, anchor scope for preview.
3358
+ * Undefined fails closed at the entity-service chokepoint to "public".
3359
+ */
3360
+ visibilityScope?: ContentVisibility;
3361
+ }
3362
+ /**
3363
+ * Public interface for ContentService
3364
+ * Used by plugins and for testing
3365
+ */
3366
+ /** Runtime-only generation settings; never author input. */
3367
+ interface GenerateContentOptions {
3368
+ pluginId?: string | undefined;
3369
+ signal?: AbortSignal | undefined;
3370
+ /** Fixes every read to the authorized output visibility (durable jobs). */
3371
+ visibilityScope?: ContentVisibility | undefined;
3372
+ }
3373
+ interface ContentService {
3374
+ /**
3375
+ * Authorize a durable generation job: the full policy when it starts, and
3376
+ * current authority over the final fields when `persisted` is supplied.
3377
+ */
3378
+ authorizeGenerationWrite(data: ContentGenerationJobData, persisted?: Readonly<BaseEntity>): Promise<GenerationAccess>;
3379
+ submitGeneration(request: ContentGenerationRequestInput, binding: GenerationQueueBinding, signal?: AbortSignal): Promise<ContentGenerationBatchResult>;
3380
+ /** Plan validated, template-backed generation without enqueueing work. */
3381
+ planGeneration(request: ContentGenerationRequestInput, signal?: AbortSignal): Promise<ContentGenerationPlan>;
3382
+ /**
3383
+ * Get a registered template
3384
+ */
3385
+ getTemplate(name: string): ContentTemplate<unknown> | null;
3386
+ /**
3387
+ * List all available templates
3388
+ */
3389
+ listTemplates(): ContentTemplate<unknown>[];
3390
+ /**
3391
+ * Resolve content for a template using multiple resolution strategies
3392
+ * Priority order: DataSource fetch -> saved content -> fallback
3393
+ *
3394
+ * Returns `unknown`: the value is validated against the *template's* schema,
3395
+ * which a caller-chosen type parameter has no relationship to. Callers that
3396
+ * need a specific type should parse it.
3397
+ */
3398
+ resolveContent(templateName: string, options?: ResolutionOptions, pluginId?: string): Promise<unknown>;
3399
+ /**
3400
+ * Generate content using a template with entity-aware context.
3401
+ *
3402
+ * Returns unknown: generation validates against the template's schema, and
3403
+ * callers parse the shape they need.
3404
+ */
3405
+ generateContent(templateName: string, context?: GenerationContext, options?: GenerateContentOptions): Promise<unknown>;
3406
+ /**
3407
+ * Format content using a template's formatter
3408
+ */
3409
+ formatContent<T = unknown>(templateName: string, data: T, options?: {
3410
+ truncate?: number;
3411
+ pluginId?: string;
3412
+ }): string;
3413
+ /**
3414
+ * Parse existing content using a template's formatter. Returns unknown:
3415
+ * the formatter parses to the template's own shape.
3416
+ */
3417
+ parseContent(templateName: string, content: string, pluginId?: string): unknown;
3418
+ }
3419
+ //#endregion
3420
+ //#region ../../shell/ai-service/src/types.d.ts
3421
+ type AIGenerationSchema<T> = ZodType<T>;
3422
+ /**
3423
+ * Aspect ratio for image generation
3424
+ */
3425
+ type AspectRatio = "1:1" | "16:9" | "9:16" | "4:3" | "3:4";
3426
+ /**
3427
+ * Options for image generation
3428
+ */
3429
+ interface ImageGenerationOptions {
3430
+ /** Aspect ratio for the generated image (default: "16:9") */
3431
+ aspectRatio?: AspectRatio;
3432
+ /** Cancel the underlying provider request. */
3433
+ signal?: AbortSignal;
3434
+ }
3435
+ /**
3436
+ * Result of image generation
3437
+ */
3438
+ interface ImageGenerationResult {
3439
+ /** Raw base64-encoded image data */
3440
+ base64: string;
3441
+ /** Data URL format: data:image/png;base64,... */
3442
+ dataUrl: string;
3443
+ }
3444
+ //#endregion
3445
+ //#region ../../shared/contracts/src/chat.d.ts
3446
+ type Strict<Shape extends z.ZodRawShape> = z.ZodObject<Shape, z.core.$strict>;
3447
+ /** Pinned when a guest conversation is created; reads cannot renew retention. */
3448
+ declare const guestRetentionSchema: Strict<{
3449
+ idleSeconds: z.ZodNumber;
3450
+ maxAgeSeconds: z.ZodNumber;
3451
+ }>;
3452
+ declare const guestConversationOwnershipSchema: Strict<{
3453
+ visitorId: z.ZodString;
3454
+ retention: typeof guestRetentionSchema;
3455
+ }>;
3456
+ type GuestConversationOwnership = z.output<typeof guestConversationOwnershipSchema>;
3457
+ //#endregion
3458
+ //#region ../../shell/conversation-service/src/schema.d.ts
3459
+ type ConversationTextColumn<TTable extends string, TName extends string, TNotNull extends boolean, TPrimaryKey extends boolean = false> = SqliteTextColumn<TTable, TName, TNotNull, false, TPrimaryKey, false, TNotNull extends true ? string : string | null>;
3460
+ type ConversationsTable = SQLiteTableWithColumns<{
3461
+ name: "conversations";
3462
+ schema: undefined;
3463
+ columns: {
3464
+ id: ConversationTextColumn<"conversations", "id", true, true>;
3465
+ sessionId: ConversationTextColumn<"conversations", "session_id", true>;
3466
+ interfaceType: ConversationTextColumn<"conversations", "interface_type", true>;
3467
+ channelId: ConversationTextColumn<"conversations", "channel_id", true>;
3468
+ personId: ConversationTextColumn<"conversations", "person_id", false>;
3469
+ started: ConversationTextColumn<"conversations", "started", true>;
3470
+ lastActive: ConversationTextColumn<"conversations", "last_active", true>;
3471
+ metadata: ConversationTextColumn<"conversations", "metadata", false>;
3472
+ created: ConversationTextColumn<"conversations", "created", true>;
3473
+ updated: ConversationTextColumn<"conversations", "updated", true>;
3474
+ };
3475
+ dialect: "sqlite";
3476
+ }>;
3477
+ type MessagesTable = SQLiteTableWithColumns<{
3478
+ name: "messages";
3479
+ schema: undefined;
3480
+ columns: {
3481
+ id: ConversationTextColumn<"messages", "id", true, true>;
3482
+ conversationId: ConversationTextColumn<"messages", "conversation_id", true>;
3483
+ role: ConversationTextColumn<"messages", "role", true>;
3484
+ content: ConversationTextColumn<"messages", "content", true>;
3485
+ timestamp: ConversationTextColumn<"messages", "timestamp", true>;
3486
+ metadata: ConversationTextColumn<"messages", "metadata", false>;
3487
+ };
3488
+ dialect: "sqlite";
3489
+ }>;
3490
+ /**
3491
+ * Conversations table - tracks conversation sessions
3492
+ */
3493
+ declare const conversations: ConversationsTable;
3494
+ /**
3495
+ * Messages table - stores individual messages in conversations
3496
+ */
3497
+ declare const messages: MessagesTable;
3498
+ type Conversation = typeof conversations.$inferSelect;
3499
+ type Message = typeof messages.$inferSelect;
3500
+ //#endregion
3501
+ //#region ../../shell/conversation-service/src/types.d.ts
3502
+ /**
3503
+ * Metadata for a conversation
3504
+ */
3505
+ interface ConversationMetadata {
3506
+ guest?: GuestConversationOwnership;
3507
+ channelName: string;
3508
+ interfaceType: string;
3509
+ channelId: string;
3510
+ }
3511
+ /**
3512
+ * Service interface for conversation storage
3513
+ */
3514
+ /**
3515
+ * Options for retrieving messages
3516
+ */
3517
+ interface GetMessagesOptions {
3518
+ limit?: number;
3519
+ range?: {
3520
+ start: number;
3521
+ end: number;
3522
+ };
3523
+ }
3524
+ interface StartConversationRequest {
3525
+ sessionId: string;
3526
+ interfaceType: string;
3527
+ channelId: string;
3528
+ personId?: string;
3529
+ metadata: ConversationMetadata;
3530
+ }
3531
+ declare const conversationMessageActorSchema: z.ZodObject<{
3532
+ identity: typeof actorRefSchema;
3533
+ interfaceType: z.ZodString;
3534
+ role: typeof messageRoleSchema;
3535
+ displayName: z.ZodOptional<z.ZodString>;
3536
+ username: z.ZodOptional<z.ZodString>;
3537
+ isBot: z.ZodOptional<z.ZodBoolean>;
3538
+ }>;
3539
+ type ConversationMessageActor = z.output<typeof conversationMessageActorSchema>;
3540
+ declare const conversationMessageSourceSchema: z.ZodObject<{
3541
+ messageId: z.ZodOptional<z.ZodString>;
3542
+ channelId: z.ZodOptional<z.ZodString>;
3543
+ channelName: z.ZodOptional<z.ZodString>;
3544
+ threadId: z.ZodOptional<z.ZodString>;
3545
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3546
+ }>;
3547
+ type ConversationMessageSource = z.output<typeof conversationMessageSourceSchema>;
3548
+ interface AddConversationMessageRequest {
3549
+ conversationId: string;
3550
+ role: MessageRole;
3551
+ content: string;
3552
+ metadata?: Record<string, unknown>;
3553
+ }
3554
+ interface UpdateConversationMetadataRequest {
3555
+ conversationId: string;
3556
+ metadata: Record<string, unknown>;
3557
+ }
3558
+ interface ListConversationsOptions {
3559
+ limit?: number;
3560
+ offset?: number;
3561
+ /** Match title or message text literally, case-insensitively. */
3562
+ query?: string;
3563
+ /** Omit to include both active and archived conversations. */
3564
+ archived?: boolean;
3565
+ updatedAfter?: string;
3566
+ interfaceType?: string;
3567
+ sessionId?: string;
3568
+ channelId?: string;
3569
+ personId?: string;
3570
+ }
3571
+ interface IConversationService {
3572
+ /** Settle non-fatal database readiness work (connection pragmas). */
3573
+ initialize?(): Promise<void>;
3574
+ startConversation(request: StartConversationRequest): Promise<string>;
3575
+ addMessage(request: AddConversationMessageRequest): Promise<void>;
3576
+ getMessages(conversationId: string, options?: GetMessagesOptions): Promise<Message[]>;
3577
+ countMessages(conversationId: string): Promise<number>;
3578
+ getConversation(conversationId: string): Promise<Conversation | null>;
3579
+ listConversations(options?: ListConversationsOptions): Promise<Conversation[]>;
3580
+ updateConversationMetadata(request: UpdateConversationMetadataRequest): Promise<boolean>;
3581
+ deleteConversation(conversationId: string): Promise<boolean>;
3582
+ /** Trusted host maintenance; never an anonymous conversation action. */
3583
+ deleteExpiredGuestConversations(limit?: number): Promise<number>;
3584
+ searchConversations(query: string, sessionId?: string): Promise<Conversation[]>;
3585
+ close(): void;
3586
+ }
3587
+ //#endregion
3588
+ //#region ../../shell/identity-service/src/brain-character-schema.d.ts
3589
+ interface BrainCharacter {
3590
+ name: string;
3591
+ role: string;
3592
+ purpose: string;
3593
+ values: string[];
3594
+ }
3595
+ //#endregion
3596
+ //#region ../../shell/identity-service/src/anchor-profile-schema.d.ts
3597
+ interface AnchorProfileSocialLink {
3598
+ platform: "github" | "instagram" | "linkedin" | "email" | "website";
3599
+ url: string;
3600
+ label?: string | undefined;
3601
+ }
3602
+ interface AnchorProfile {
3603
+ name: string;
3604
+ organization?: string | undefined;
3605
+ description?: string | undefined;
3606
+ avatar?: string | undefined;
3607
+ website?: string | undefined;
3608
+ email?: string | undefined;
3609
+ socialLinks?: AnchorProfileSocialLink[] | undefined;
3610
+ }
3611
+ //#endregion
3612
+ //#region ../../shell/identity-service/src/profile-kind-registry.d.ts
3613
+ declare const profileCategorySchema: z.ZodEnum<{
3614
+ person: "person";
3615
+ team: "team";
3616
+ organization: "organization";
3617
+ }>;
3618
+ type ProfileCategory = z.infer<typeof profileCategorySchema>;
3619
+ interface ProfileKindLabels {
3620
+ singular: string;
3621
+ plural: string;
3622
+ }
3623
+ interface ProfileKindDefinition {
3624
+ kind: string;
3625
+ category: ProfileCategory;
3626
+ fields: FrontmatterSchema;
3627
+ labels: ProfileKindLabels;
3628
+ }
3629
+ interface ResolvedProfileKind {
3630
+ kind: string;
3631
+ category: ProfileCategory;
3632
+ labels: ProfileKindLabels;
3633
+ }
3634
+ type ResolvedProfileSelection = ResolvedProfileKind | null;
3635
+ interface IProfileKindRegistry {
3636
+ register(pluginId: string, definition: ProfileKindDefinition): void;
3637
+ unregisterPlugin(pluginId: string): void;
3638
+ finalize(): ResolvedProfileSelection;
3639
+ getResolved(): ResolvedProfileSelection;
3640
+ getSelectedDefinition(): ProfileKindDefinition | undefined;
3641
+ isFinalized(): boolean;
3642
+ }
3643
+ //#endregion
3644
+ //#region ../../shell/ai-service/src/agent-types.d.ts
3645
+ /**
3646
+ * Context for a chat message
3647
+ * Contains per-message information like user permission level
3648
+ */
3649
+ interface ChatAttachmentSource {
3650
+ kind: string;
3651
+ id: string;
3652
+ }
3653
+ interface TextChatAttachment {
3654
+ kind: "text";
3655
+ filename: string;
3656
+ mediaType: string;
3657
+ content: string;
3658
+ sizeBytes?: number | undefined;
3659
+ source?: ChatAttachmentSource | undefined;
3660
+ }
3661
+ interface FileChatAttachment {
3662
+ kind: "file";
3663
+ filename: string;
3664
+ mediaType: string;
3665
+ data: Uint8Array;
3666
+ sizeBytes?: number | undefined;
3667
+ source?: ChatAttachmentSource | undefined;
3668
+ }
3669
+ type ChatAttachment = TextChatAttachment | FileChatAttachment;
3670
+ interface ChatContext {
3671
+ /** Server-owned limits bound to the already-reserved guest execution. */
3672
+ guestExecution?: GuestExecutionPolicy;
3673
+ /** The site's scope and refusal copy a guest question is screened against. */
3674
+ guestScreening?: GuestScreening;
3675
+ userPermissionLevel?: UserPermissionLevel;
3676
+ /** Whether the authenticated caller is the brain's configured Anchor. */
3677
+ isAnchor?: boolean;
3678
+ interfaceType?: string;
3679
+ channelId?: string;
3680
+ channelName?: string;
3681
+ actor?: ConversationMessageActor;
3682
+ source?: ConversationMessageSource;
3683
+ attachments?: ChatAttachment[] | undefined;
3684
+ }
3685
+ /**
3686
+ * Agent service interface
3687
+ */
3688
+ interface IAgentService {
3689
+ /** Guest turns can run: the search index they read is ready. */
3690
+ readonly guestReady?: boolean;
3691
+ /**
3692
+ * Send a message to the agent and get a response
3693
+ * @param message - The user's message
3694
+ * @param conversationId - ID of the conversation for history tracking
3695
+ * @param context - Optional context including user permission level
3696
+ */
3697
+ chat(message: string, conversationId: string, context?: ChatContext, signal?: AbortSignal): Promise<AgentResponse>;
3698
+ /**
3699
+ * Confirm a pending approval-gated action
3700
+ * @param conversationId - ID of the conversation
3701
+ * @param confirmed - Whether the user confirmed the operation
3702
+ * @param approvalId - Explicit approval/action id to resolve
3703
+ */
3704
+ confirmPendingAction(conversationId: string, confirmed: boolean, approvalId: string, context: ChatContext, signal?: AbortSignal): Promise<AgentResponse>;
3705
+ /** Stop active turns and release conversation actors. */
3706
+ shutdown?(): Promise<void>;
3707
+ /**
3708
+ * Invalidate the cached agent so the next conversation rebuilds
3709
+ * with fresh identity, profile, and instructions.
3710
+ */
3711
+ invalidateAgent(): void;
3712
+ }
3713
+ //#endregion
3714
+ //#region ../../shell/plugins/src/channel-registry.d.ts
3715
+ interface ChannelSubjectPattern {
3716
+ source: string;
3717
+ flags?: string | undefined;
3718
+ }
3719
+ interface ChannelDescriptor {
3720
+ type: string;
3721
+ displayName: string;
3722
+ subjectLabel: string;
3723
+ subjectPattern?: ChannelSubjectPattern | undefined;
3724
+ manualDelivery?: boolean | undefined;
3725
+ }
3726
+ type ChannelDeliverySensitivity = "normal" | "secret";
3727
+ interface ChannelDeliveryThreading {
3728
+ inReplyTo: string;
3729
+ references: string[];
3730
+ }
3731
+ interface ChannelDeliveryInput {
3732
+ recipient: string;
3733
+ subject: string;
3734
+ text: string;
3735
+ idempotencyKey: string;
3736
+ /** Optional rich body for transports that render it. */
3737
+ html?: string | undefined;
3738
+ /**
3739
+ * "secret" keeps recipient and subject out of provider logs. Providers that
3740
+ * cannot honour it should treat every delivery as secret.
3741
+ */
3742
+ sensitivity?: ChannelDeliverySensitivity | undefined;
3743
+ /** Optional transport threading metadata. Unsupported channels may ignore it. */
3744
+ threading?: ChannelDeliveryThreading | undefined;
3745
+ }
3746
+ type ChannelDeliveryResult = {
3747
+ status: "sent";
3748
+ providerDeliveryId?: string | undefined;
3749
+ } | {
3750
+ status: "failed";
3751
+ failureCode: string;
3752
+ };
3753
+ interface ChannelDeliveryProvider {
3754
+ channelType: string;
3755
+ isAvailable(): Promise<boolean>;
3756
+ send(input: ChannelDeliveryInput): Promise<ChannelDeliveryResult>;
3757
+ }
3758
+ interface IChannelRegistry {
3759
+ registerDescriptor(pluginId: string, descriptor: ChannelDescriptor): void;
3760
+ registerDeliveryProvider(pluginId: string, provider: ChannelDeliveryProvider): void;
3761
+ unregisterPlugin(pluginId: string): void;
3762
+ finalize(): void;
3763
+ listDescriptors(): ChannelDescriptor[];
3764
+ getDescriptor(channelType: string): ChannelDescriptor | undefined;
3765
+ getDeliveryProvider(channelType: string): ChannelDeliveryProvider | undefined;
3766
+ isFinalized(): boolean;
3767
+ }
3768
+ //#endregion
3769
+ //#region ../../shell/plugins/src/inbox-registry.d.ts
3770
+ declare const inboxUrgencySchema: z.ZodEnum<{
3771
+ high: "high";
3772
+ normal: "normal";
3773
+ }>;
3774
+ type InboxFacetOptionSchema = z.ZodObject<{
3775
+ value: z.ZodString;
3776
+ label: z.ZodString;
3777
+ }, z.core.$strict>;
3778
+ type InboxFacetDefinitionSchema = z.ZodObject<{
3779
+ key: z.ZodString;
3780
+ label: z.ZodString;
3781
+ values: z.ZodArray<InboxFacetOptionSchema>;
3782
+ }, z.core.$strict>;
3783
+ declare const inboxFacetDefinitionsSchema: z.ZodArray<InboxFacetDefinitionSchema>;
3784
+ declare const inboxFacetsSchema: z.ZodRecord<z.ZodString, z.ZodString>;
3785
+ type InboxFollowUpDeclarationSchema = z.ZodObject<{
3786
+ kind: z.ZodString;
3787
+ context: z.ZodRecord<z.ZodString, z.ZodString>;
3788
+ }, z.core.$strict>;
3789
+ declare const inboxFollowUpDeclarationsSchema: z.ZodArray<InboxFollowUpDeclarationSchema>;
3790
+ type InboxActionSchema = z.ZodObject<{
3791
+ id: z.ZodString;
3792
+ label: z.ZodString;
3793
+ confirm: z.ZodOptional<z.ZodBoolean>;
3794
+ }, z.core.$strict>;
3795
+ type InboxEntityRefSchema = z.ZodObject<{
3796
+ entityType: z.ZodString;
3797
+ entityId: z.ZodString;
3798
+ }, z.core.$strict>;
3799
+ type InboxContactSchema = z.ZodObject<{
3800
+ label: z.ZodString;
3801
+ personId: z.ZodOptional<z.ZodString>;
3802
+ }, z.core.$strict>;
3803
+ type InboxItemSchema = z.ZodObject<{
3804
+ id: z.ZodString;
3805
+ title: z.ZodString;
3806
+ summary: z.ZodOptional<z.ZodString>;
3807
+ contact: z.ZodOptional<InboxContactSchema>;
3808
+ threadOrdinal: z.ZodOptional<z.ZodNumber>;
3809
+ receivedAt: z.ZodISODateTime;
3810
+ urgency: typeof inboxUrgencySchema;
3811
+ entityRef: z.ZodOptional<InboxEntityRefSchema>;
3812
+ facets: z.ZodOptional<typeof inboxFacetsSchema>;
3813
+ followUps: z.ZodOptional<typeof inboxFollowUpDeclarationsSchema>;
3814
+ actions: z.ZodArray<InboxActionSchema>;
3815
+ }, z.core.$strict>;
3816
+ declare const inboxItemSchema: InboxItemSchema;
3817
+ type InboxActorSchema = z.ZodObject<{
3818
+ permissionLevel: z.ZodEnum<{
3819
+ admin: "admin";
3820
+ trusted: "trusted";
3821
+ public: "public";
3822
+ }>;
3823
+ }, z.core.$strict>;
3824
+ declare const inboxActorSchema: InboxActorSchema;
3825
+ type InboxItemDetailSchema = z.ZodObject<{
3826
+ kind: z.ZodLiteral<"plain">;
3827
+ text: z.ZodString;
3828
+ truncated: z.ZodBoolean;
3829
+ }, z.core.$strict>;
3830
+ declare const inboxItemDetailSchema: InboxItemDetailSchema;
3831
+ type InboxSourceDescriptorSchema = z.ZodObject<{
3832
+ sourceId: z.ZodString;
3833
+ displayName: z.ZodString;
3834
+ facets: z.ZodOptional<typeof inboxFacetDefinitionsSchema>;
3835
+ }, z.core.$strict>;
3836
+ declare const inboxSourceDescriptorSchema: InboxSourceDescriptorSchema;
3837
+ type InboxItem = z.output<typeof inboxItemSchema>;
3838
+ type InboxActor = z.output<typeof inboxActorSchema>;
3839
+ type InboxItemDetail = z.output<typeof inboxItemDetailSchema>;
3840
+ type InboxSourceDescriptor = z.output<typeof inboxSourceDescriptorSchema>;
3841
+ interface InboxSource extends InboxSourceDescriptor {
3842
+ list(): Promise<InboxItem[]>;
3843
+ resolveDetail?(itemId: string, actor: InboxActor, signal: AbortSignal): Promise<InboxItemDetail>;
3844
+ act(itemId: string, actionId: string, actor: InboxActor): Promise<void>;
3845
+ }
3846
+ interface IInboxRegistry {
3847
+ registerSource(pluginId: string, source: InboxSource): void;
3848
+ unregisterPlugin(pluginId: string): void;
3849
+ finalize(): void;
3850
+ listSources(): InboxSource[];
3851
+ getSource(sourceId: string): InboxSource | undefined;
3852
+ isFinalized(): boolean;
3853
+ }
3854
+ //#endregion
3855
+ //#region ../../shell/plugins/src/inbox-follow-up-registry.d.ts
3856
+ type InboxFollowUpMode = "universal" | "declared";
3857
+ type InboxFollowUpContext = Readonly<Record<string, string>>;
3858
+ interface InboxFollowUpResolutionInput {
3859
+ sourceId: string;
3860
+ item: InboxItem;
3861
+ actor: InboxActor;
3862
+ context?: InboxFollowUpContext | undefined;
3863
+ }
3864
+ interface InboxFollowUpTargetInput {
3865
+ href: string;
3866
+ state?: unknown;
3867
+ }
3868
+ interface InboxFollowUpKindRegistration {
3869
+ kind: string;
3870
+ label: string;
3871
+ priority: number;
3872
+ mode: InboxFollowUpMode;
3873
+ permissionLevel: UserPermissionLevel;
3874
+ contextSchema?: z.ZodType<InboxFollowUpContext, unknown> | undefined;
3875
+ applies(input: InboxFollowUpResolutionInput): boolean | Promise<boolean>;
3876
+ resolve(input: InboxFollowUpResolutionInput): InboxFollowUpTargetInput | undefined | Promise<InboxFollowUpTargetInput | undefined>;
3877
+ }
3878
+ type RegisteredInboxFollowUpKind = Readonly<InboxFollowUpKindRegistration>;
3879
+ interface IInboxFollowUpRegistry {
3880
+ registerKind(pluginId: string, registration: InboxFollowUpKindRegistration): void;
3881
+ unregisterPlugin(pluginId: string): void;
3882
+ finalize(): void;
3883
+ listKinds(): RegisteredInboxFollowUpKind[];
3884
+ getKind(kind: string): RegisteredInboxFollowUpKind | undefined;
3885
+ resolve(input: Omit<InboxFollowUpResolutionInput, "context">): Promise<ResolvedInboxFollowUp[]>;
3886
+ resolveUniversal(input: Omit<InboxFollowUpResolutionInput, "context">): Promise<ResolvedInboxFollowUp[]>;
3887
+ isFinalized(): boolean;
3888
+ }
3889
+ declare const inboxFollowUpStateSchema: z.ZodRecord<z.ZodString, ReturnType<typeof z.json>>;
3890
+ type ResolvedInboxFollowUpSchema = z.ZodObject<{
3891
+ kind: z.ZodString;
3892
+ label: z.ZodString;
3893
+ href: z.ZodString;
3894
+ state: z.ZodOptional<typeof inboxFollowUpStateSchema>;
3895
+ }, z.core.$strict>;
3896
+ declare const resolvedInboxFollowUpSchema: ResolvedInboxFollowUpSchema;
3897
+ type ResolvedInboxFollowUp = z.output<typeof resolvedInboxFollowUpSchema>;
3898
+ //#endregion
3899
+ //#region ../../shell/plugins/src/contracts/runtime-health.d.ts
3900
+ type RuntimeHealthCheckSchema = z.ZodObject<{
3901
+ name: z.ZodString;
3902
+ status: z.ZodEnum<{
3903
+ healthy: "healthy";
3904
+ degraded: "degraded";
3905
+ unhealthy: "unhealthy";
3906
+ }>;
3907
+ message: z.ZodOptional<z.ZodString>;
3908
+ details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3909
+ }>;
3910
+ declare const RuntimeHealthCheckSchema: RuntimeHealthCheckSchema;
3911
+ type RuntimeHealthCheck = z.output<typeof RuntimeHealthCheckSchema>;
3912
+ type RuntimeWorkerSignalsSchema = z.ZodObject<{
3913
+ total: z.ZodNumber;
3914
+ active: z.ZodNumber;
3915
+ stale: z.ZodNumber;
3916
+ latestHeartbeatAgeMs: z.ZodNullable<z.ZodNumber>;
3917
+ }>;
3918
+ type RuntimeQueueSignalsSchema = z.ZodObject<{
3919
+ totals: z.ZodObject<{
3920
+ pending: z.ZodNumber;
3921
+ processing: z.ZodNumber;
3922
+ completed: z.ZodNumber;
3923
+ failed: z.ZodNumber;
3924
+ }>;
3925
+ byType: z.ZodArray<z.ZodObject<{
3926
+ type: z.ZodString;
3927
+ status: z.ZodEnum<{
3928
+ pending: "pending";
3929
+ processing: "processing";
3930
+ completed: "completed";
3931
+ failed: "failed";
3932
+ }>;
3933
+ count: z.ZodNumber;
3934
+ }>>;
3935
+ oldestPendingAgeMs: z.ZodNullable<z.ZodNumber>;
3936
+ duePending: z.ZodNumber;
3937
+ oldestDuePendingAgeMs: z.ZodNullable<z.ZodNumber>;
3938
+ latestClaimAgeMs: z.ZodNullable<z.ZodNumber>;
3939
+ oldestProcessingAgeMs: z.ZodNullable<z.ZodNumber>;
3940
+ staleLeaseCount: z.ZodNumber;
3941
+ workerSessions: RuntimeWorkerSignalsSchema;
3942
+ }>;
3943
+ declare const RuntimeQueueSignalsSchema: RuntimeQueueSignalsSchema;
3944
+ type RuntimeResourceSignalsSchema = z.ZodObject<{
3945
+ memory: z.ZodObject<{
3946
+ rssBytes: z.ZodNumber;
3947
+ heapUsedBytes: z.ZodNumber;
3948
+ heapTotalBytes: z.ZodNumber;
3949
+ }>;
3950
+ fileDescriptors: z.ZodNullable<z.ZodNumber>;
3951
+ processes: z.ZodObject<{
3952
+ total: z.ZodNullable<z.ZodNumber>;
3953
+ zombies: z.ZodNullable<z.ZodNumber>;
3954
+ }>;
3955
+ queue: z.ZodNullable<RuntimeQueueSignalsSchema>;
3956
+ projection: z.ZodObject<{
3957
+ initialized: z.ZodBoolean;
3958
+ trackedRoots: z.ZodNumber;
3959
+ openCircuits: z.ZodArray<z.ZodObject<{
3960
+ projectionId: z.ZodString;
3961
+ reason: z.ZodString;
3962
+ openedAt: z.ZodNumber;
3963
+ expiresAt: z.ZodNumber;
3964
+ }>>;
3965
+ }>;
3966
+ worker: RuntimeWorkerSignalsSchema;
3967
+ }>;
3968
+ declare const RuntimeResourceSignalsSchema: RuntimeResourceSignalsSchema;
3969
+ type RuntimeReadinessSchema = z.ZodObject<{
3970
+ status: z.ZodEnum<{
3971
+ ready: "ready";
3972
+ not_ready: "not_ready";
3973
+ }>;
3974
+ operationalStatus: z.ZodEnum<{
3975
+ operational: "operational";
3976
+ degraded: "degraded";
3977
+ }>;
3978
+ checkedAt: z.ZodISODateTime;
3979
+ checks: z.ZodArray<RuntimeHealthCheckSchema>;
3980
+ resources: RuntimeResourceSignalsSchema;
3981
+ }>;
3982
+ declare const RuntimeReadinessSchema: RuntimeReadinessSchema;
3983
+ type RuntimeReadiness = z.output<typeof RuntimeReadinessSchema>;
3984
+ //#endregion
3985
+ //#region ../../shell/plugins/src/operational-health-registry.d.ts
3986
+ type OperationalHealthProvider = () => Promise<Omit<RuntimeHealthCheck, "name">> | Omit<RuntimeHealthCheck, "name">;
3987
+ interface IOperationalHealthRegistry {
3988
+ register(pluginId: string, name: string, provider: OperationalHealthProvider): () => void;
3989
+ unregisterPlugin(pluginId: string): void;
3990
+ getChecks(): Promise<RuntimeHealthCheck[]>;
3991
+ }
3992
+ //#endregion
3993
+ //#region ../../shell/plugins/src/operator/operator-field-contract.d.ts
3994
+ /** Host-rendered scalar controls shared by Account and Studio action forms. */
3995
+ declare const operatorFieldControlSchema: z.ZodEnum<{
3996
+ text: "text";
3997
+ url: "url";
3998
+ number: "number";
3999
+ checkbox: "checkbox";
4000
+ select: "select";
4001
+ }>;
4002
+ type OperatorFieldControl = z.output<typeof operatorFieldControlSchema>;
4003
+ declare const accountSettingsControlSchema: z.ZodEnum<{
4004
+ text: "text";
4005
+ url: "url";
4006
+ number: "number";
4007
+ checkbox: "checkbox";
4008
+ }>;
4009
+ type AccountSettingsControl = z.output<typeof accountSettingsControlSchema>;
4010
+ interface OperatorFieldDefinitionBase<TControl extends OperatorFieldControl = OperatorFieldControl> {
4011
+ readonly label: string;
4012
+ readonly control: TControl;
4013
+ readonly secret?: boolean | undefined;
4014
+ }
4015
+ //#endregion
4016
+ //#region ../../shell/plugins/src/operator/account-settings-definition-contract.d.ts
4017
+ type AccountSettingsSchema = z.ZodObject<z.ZodRawShape>;
4018
+ interface AccountSettingsFieldDefinition extends Omit<OperatorFieldDefinitionBase<AccountSettingsControl>, "control"> {
4019
+ readonly control?: AccountSettingsControl | undefined;
4020
+ }
4021
+ /**
4022
+ * Every schema field must be declared. Totality is what makes `secret` a
4023
+ * decision rather than an omission: a missing entry would otherwise render a
4024
+ * credential as an ordinary echoing text input.
4025
+ */
4026
+ type AccountSettingsFieldMap<TSchema extends AccountSettingsSchema> = { readonly [K in Extract<keyof z.input<TSchema>, string>]: AccountSettingsFieldDefinition; };
4027
+ interface AccountSettingsDefinition<TSchema extends AccountSettingsSchema = AccountSettingsSchema, TFields extends AccountSettingsFieldMap<TSchema> = AccountSettingsFieldMap<TSchema>> {
4028
+ readonly kind: "rizom-account-settings";
4029
+ readonly title: string;
4030
+ readonly description?: string | undefined;
4031
+ readonly schema: TSchema;
4032
+ readonly fields: TFields;
4033
+ }
4034
+ type AnyAccountSettingsDefinition = AccountSettingsDefinition<AccountSettingsSchema, AccountSettingsFieldMap<AccountSettingsSchema>>;
4035
+ type AccountSettingsValue<TDefinition extends AnyAccountSettingsDefinition> = z.output<TDefinition["schema"]>;
4036
+ //#endregion
4037
+ //#region ../../shell/plugins/src/operator/account-settings-registry.d.ts
4038
+ type AccountSettingsScalar = z.output<typeof accountSettingsScalarSchema>;
4039
+ type AccountSettingsStoredValues = Readonly<Record<string, AccountSettingsScalar>>;
4040
+ interface AccountSettingsStorageIdentity {
4041
+ readonly packageName: string;
4042
+ readonly definitionId: string;
4043
+ readonly actorId: string;
4044
+ }
4045
+ interface StoredAccountSettings {
4046
+ readonly values: AccountSettingsStoredValues;
4047
+ readonly revision: number;
4048
+ }
4049
+ interface AccountSettingsBackend {
4050
+ read(identity: AccountSettingsStorageIdentity): Promise<StoredAccountSettings | null>;
4051
+ list(input: {
4052
+ readonly packageName: string;
4053
+ readonly definitionId: string;
4054
+ }): Promise<readonly {
4055
+ readonly actorId: string;
4056
+ readonly values: AccountSettingsStoredValues;
4057
+ readonly revision: number;
4058
+ }[]>;
4059
+ write(identity: AccountSettingsStorageIdentity, values: AccountSettingsStoredValues): Promise<StoredAccountSettings>;
4060
+ delete(identity: AccountSettingsStorageIdentity): Promise<boolean>;
4061
+ deleteActor(actorId: string): Promise<number>;
4062
+ }
4063
+ interface AccountSettingsRegistration<TDefinition extends AnyAccountSettingsDefinition = AnyAccountSettingsDefinition> {
4064
+ readonly id: string;
4065
+ readonly ownerPluginId: string;
4066
+ readonly packageName: string;
4067
+ readonly definitionId: string;
4068
+ readonly definition: TDefinition;
4069
+ }
4070
+ interface AccountSettingsFormField {
4071
+ readonly name: string;
4072
+ readonly label: string;
4073
+ readonly control: "text" | "url" | "number" | "checkbox";
4074
+ readonly secret: boolean;
4075
+ readonly required: boolean;
4076
+ readonly value?: AccountSettingsScalar | undefined;
4077
+ readonly set?: boolean | undefined;
4078
+ }
4079
+ interface AccountSettingsForm {
4080
+ readonly id: string;
4081
+ readonly title: string;
4082
+ readonly description?: string | undefined;
4083
+ readonly configured: boolean;
4084
+ /** Opaque change token for host form reset; never contains stored values. */
4085
+ readonly revision: number | null;
4086
+ readonly fields: readonly AccountSettingsFormField[];
4087
+ }
4088
+ interface ConfiguredAccountSettings<TDefinition extends AnyAccountSettingsDefinition = AnyAccountSettingsDefinition> {
4089
+ readonly id: string;
4090
+ readonly settings: AccountSettingsValue<TDefinition>;
4091
+ readonly revision: number;
4092
+ }
4093
+ interface RegisterAccountSettingsInput<TDefinition extends AnyAccountSettingsDefinition = AnyAccountSettingsDefinition> {
4094
+ readonly ownerPluginId: string;
4095
+ readonly packageName: string;
4096
+ readonly definitionId: string;
4097
+ readonly definition: TDefinition;
4098
+ }
4099
+ type AccountSettingsChangeListener = () => void;
4100
+ declare const accountSettingsScalarSchema: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>;
4101
+ /** App-scoped definition catalog and guarded access to the auth-owned backend. */
4102
+ declare class AccountSettingsRegistry {
4103
+ private readonly registrations;
4104
+ private readonly listeners;
4105
+ private readonly mutationTails;
4106
+ private backend;
4107
+ register<TDefinition extends AnyAccountSettingsDefinition>(input: RegisterAccountSettingsInput<TDefinition>): AccountSettingsRegistration<TDefinition>;
4108
+ unregister(registration: AccountSettingsRegistration): void;
4109
+ bindBackend(backend: AccountSettingsBackend): () => void;
4110
+ hasRegistrations(): boolean;
4111
+ hasBackend(): boolean;
4112
+ listRegistrations(): readonly AccountSettingsRegistration[];
4113
+ listForms(actorId: string): Promise<readonly AccountSettingsForm[]>;
4114
+ save(registrationIdValue: string, actorId: string, input: Readonly<Record<string, unknown>>): Promise<AccountSettingsForm>;
4115
+ delete(registrationIdValue: string, actorId: string): Promise<boolean>;
4116
+ deleteActor(actorId: string): Promise<number>;
4117
+ /** Notify account-bound supervisors after auth-owned cascade deletion. */
4118
+ accountDeleted(actorId: string): void;
4119
+ private refreshActor;
4120
+ getForActor<TDefinition extends AnyAccountSettingsDefinition>(registration: AccountSettingsRegistration<TDefinition>, actorId: string): Promise<AccountSettingsValue<TDefinition> | null>;
4121
+ listConfigured<TDefinition extends AnyAccountSettingsDefinition>(registration: AccountSettingsRegistration<TDefinition>): Promise<readonly ConfiguredAccountSettings<TDefinition>[]>;
4122
+ subscribe(registration: AccountSettingsRegistration, listener: AccountSettingsChangeListener): () => void;
4123
+ private formFor;
4124
+ private requireRegistration;
4125
+ private requireAttached;
4126
+ private requireBackend;
4127
+ private notify;
4128
+ private serializeMutation;
4129
+ }
4130
+ //#endregion
4131
+ //#region ../../shell/plugins/src/service/attachment-registry.d.ts
4132
+ interface AttachmentResolveRequest {
4133
+ sourceEntityType: string;
4134
+ sourceEntityId: string;
4135
+ attachmentType: string;
4136
+ }
4137
+ interface AttachmentProviderMetadata {
4138
+ outputEntityType: "image" | "document";
4139
+ targetField?: "coverImageId" | "ogImageId";
4140
+ }
4141
+ interface AttachmentProvider {
4142
+ metadata?: AttachmentProviderMetadata;
4143
+ resolve(request: AttachmentResolveRequest): Promise<PublishMediaData | undefined> | PublishMediaData | undefined;
4144
+ }
4145
+ /**
4146
+ * Attachment namespace — source-derived publish artifacts.
4147
+ * Source plugins register providers; publishers resolve by semantic attachment type.
4148
+ */
4149
+ interface IAttachmentsNamespace {
4150
+ /** Register an attachment provider for a source entity type and semantic attachment type. */
4151
+ register: (sourceEntityType: string, attachmentType: string, provider: AttachmentProvider) => () => void;
4152
+ /** Resolve a source-derived attachment if a provider is available. */
4153
+ resolve: (request: AttachmentResolveRequest) => Promise<PublishMediaData | undefined>;
4154
+ /** Check whether a provider exists for the requested source/attachment type. */
4155
+ hasProvider: (sourceEntityType: string, attachmentType: string) => boolean;
4156
+ /** Get registered provider capability metadata, if declared. */
4157
+ getProviderMetadata: (sourceEntityType: string, attachmentType: string) => AttachmentProviderMetadata | undefined;
4158
+ }
4159
+ //#endregion
4160
+ //#region ../../shell/runtime-state/src/types.d.ts
4161
+ type RuntimeStateValueSchema<T> = ZodType<T, unknown>;
4162
+ interface RuntimeStateScopeOptions<T> {
4163
+ /** Stable consumer namespace, e.g. "chat.discord.subscriptions". */
4164
+ namespace: string;
4165
+ /** Schema used to validate values crossing the persistence boundary. */
4166
+ schema: RuntimeStateValueSchema<T>;
4167
+ }
4168
+ interface RuntimeStateRecordValue<T> {
4169
+ key: string;
4170
+ value: T;
4171
+ createdAt: Date;
4172
+ updatedAt: Date;
4173
+ }
4174
+ interface RuntimeStateListOptions {
4175
+ keyPrefix?: string | undefined;
4176
+ /** Exclusive key cursor, ordered using SQLite's binary key order. */
4177
+ afterKey?: string | undefined;
4178
+ /** Optional bounded page size (1–1000); applied before value parsing. */
4179
+ limit?: number | undefined;
4180
+ }
4181
+ interface IRuntimeStateStore<T> {
4182
+ get(key: string): Promise<T | null>;
4183
+ has(key: string): Promise<boolean>;
4184
+ set(key: string, value: T): Promise<void>;
4185
+ setIfNotExists(key: string, value: T): Promise<boolean>;
4186
+ /** Atomically replace an existing value only if its schema-serialized value matches.
4187
+ * Use a revision field when the consumer must distinguish an ABA change.
4188
+ * Independent processes must use the same backing database to coordinate.
4189
+ */
4190
+ compareAndSet(key: string, expected: T, value: T): Promise<boolean>;
4191
+ delete(key: string): Promise<boolean>;
4192
+ list(options?: RuntimeStateListOptions): Promise<RuntimeStateRecordValue<T>[]>;
4193
+ clear(options?: {
4194
+ keyPrefix?: string | undefined;
4195
+ }): Promise<number>;
4196
+ }
4197
+ interface IRuntimeStateNamespace {
4198
+ scoped<T>(options: RuntimeStateScopeOptions<T>): IRuntimeStateStore<T>;
4199
+ }
4200
+ //#endregion
4201
+ //#region ../../shell/recurring-checks/src/types.d.ts
4202
+ type RecurringCheckCadence = "daily" | "weekly";
4203
+ /** Alert payloads are operational state and must not contain secrets. */
4204
+ declare const recurringAlertSchema: z.ZodObject<{
4205
+ dedupeKey: z.ZodString;
4206
+ title: z.ZodString;
4207
+ body: z.ZodString;
4208
+ html: z.ZodOptional<z.ZodString>;
4209
+ sensitivity: z.ZodOptional<z.ZodEnum<{
4210
+ normal: "normal";
4211
+ secret: "secret";
4212
+ }>>;
4213
+ includeInInbox: z.ZodOptional<z.ZodBoolean>;
4214
+ }, z.core.$strict>;
4215
+ declare const recurringCheckResultSchema: z.ZodObject<{
4216
+ alerts: z.ZodOptional<z.ZodArray<typeof recurringAlertSchema>>;
4217
+ }, z.core.$strict>;
4218
+ type RecurringCheckResult = z.output<typeof recurringCheckResultSchema>;
4219
+ interface RecurringCheckRunContext {
4220
+ /** Aborted when the caller cancels or the recurring-check daemon stops. */
4221
+ signal: AbortSignal;
4222
+ }
4223
+ interface RecurringCheckDefinition {
4224
+ id: string;
4225
+ cadence: RecurringCheckCadence;
4226
+ /** Deliver returned alerts and retry pending alerts. False suppresses notification delivery. Defaults to true. */
4227
+ deliverAlerts?: boolean | undefined;
4228
+ /** Project returned alerts into the shared Inbox. Defaults to true. */
4229
+ includeInInbox?: boolean | undefined;
4230
+ run(context: RecurringCheckRunContext): Promise<RecurringCheckResult>;
4231
+ }
4232
+ interface IRecurringChecksNamespace {
4233
+ /** Register a plugin-owned recurring check. Returns an unregister callback. */
4234
+ register(check: RecurringCheckDefinition): () => void;
4235
+ }
4236
+ //#endregion
4237
+ //#region ../../shell/plugins/src/service/upload-registry.d.ts
4238
+ interface RuntimeUploadRef {
4239
+ kind: string;
4240
+ id: string;
4241
+ }
4242
+ interface RuntimeUploadRecord {
4243
+ id: string;
4244
+ ref: RuntimeUploadRef;
4245
+ filename: string;
4246
+ mediaType: string;
4247
+ sizeBytes: number;
4248
+ createdAt: string;
4249
+ metadata?: Record<string, unknown> | undefined;
4250
+ }
4251
+ interface RuntimeUploadResponseBody extends RuntimeUploadRecord {
4252
+ url: string;
4253
+ downloadUrl: string;
4254
+ }
4255
+ interface RuntimeUploadScopeOptions {
4256
+ /** Filesystem namespace below the runtime data directory, e.g. "upload". */
4257
+ namespace: string;
4258
+ /** Ref discriminator exposed to clients, e.g. "upload". */
4259
+ refKind: string;
4260
+ /** HTTP route used to resolve stored uploads, e.g. "/api/chat/uploads". */
4261
+ routePath: string;
4262
+ retentionMs?: number | undefined;
4263
+ maxCount?: number | undefined;
4264
+ createId?: (() => string) | undefined;
4265
+ now?: (() => Date) | undefined;
4266
+ }
4267
+ interface SaveRuntimeUploadInput {
4268
+ filename: string;
4269
+ mediaType: string;
4270
+ content: Buffer;
4271
+ metadata?: Record<string, unknown> | undefined;
4272
+ }
4273
+ interface ResolvedRuntimeUpload {
4274
+ record: RuntimeUploadRecord;
4275
+ content: Buffer;
4276
+ }
4277
+ /**
4278
+ * The store surface consumers get, rather than the class that implements it.
4279
+ *
4280
+ * Declaring the class here made every consumer depend on its private fields
4281
+ * too, so nothing could stand in for a scoped store without asserting it was
4282
+ * one. The class satisfies this by construction.
4283
+ */
4284
+ type ScopedRuntimeUploadStore = Pick<RuntimeUploadStore, "save" | "read" | "readRecord" | "toResponseBody" | "prune" | "getUploadDir" | "remove">;
4285
+ interface IRuntimeUploadsNamespace {
4286
+ /** Create a scoped runtime upload store for an interface/plugin namespace. */
4287
+ scoped(options: RuntimeUploadScopeOptions): ScopedRuntimeUploadStore;
4288
+ }
4289
+ interface RuntimeUploadStoreOptions extends RuntimeUploadScopeOptions {
4290
+ dataDir: string;
4291
+ logger?: Logger | undefined;
4292
+ }
4293
+ declare class RuntimeUploadStore {
4294
+ private readonly options;
4295
+ private readonly retentionMs;
4296
+ private readonly maxCount;
4297
+ private readonly createUploadId;
4298
+ private readonly getNow;
4299
+ private readonly logger;
4300
+ constructor(options: RuntimeUploadStoreOptions);
4301
+ save(input: SaveRuntimeUploadInput): Promise<RuntimeUploadRecord>;
4302
+ remove(uploadId: string): Promise<void>;
4303
+ read(uploadId: string): Promise<ResolvedRuntimeUpload>;
4304
+ readRecord(uploadId: string): Promise<RuntimeUploadRecord>;
4305
+ toResponseBody(record: RuntimeUploadRecord): RuntimeUploadResponseBody;
4306
+ /**
4307
+ * Drop uploads past the retention window or the count cap.
4308
+ *
4309
+ * Returns quietly only when the uploads directory does not exist yet — it is
4310
+ * created on first save. Every other failure raises: an unreadable directory
4311
+ * or a deletion that did not happen means uploads accumulate unbounded, and
4312
+ * a silent catch here made that indistinguishable from a successful prune.
4313
+ */
4314
+ prune(): Promise<void>;
4315
+ getUploadDir(uploadId: string): string;
4316
+ private getUploadsRoot;
4317
+ private getUploadUrl;
4318
+ private assertValidUploadId;
4319
+ }
4320
+ //#endregion
4321
+ //#region ../../shell/plugins/src/contracts/runtime-app-info.d.ts
4322
+ declare const userPermissionLevelSchema: z.ZodEnum<{
4323
+ admin: "admin";
4324
+ trusted: "trusted";
4325
+ public: "public";
4326
+ }>;
4327
+ declare const endpointInfoSchema: z.ZodObject<{
4328
+ label: z.ZodString;
4329
+ url: z.ZodString;
4330
+ pluginId: z.ZodString;
4331
+ priority: z.ZodDefault<z.ZodNumber>;
4332
+ visibility: z.ZodDefault<typeof userPermissionLevelSchema>;
4333
+ requiresActiveSession: z.ZodOptional<z.ZodBoolean>;
4334
+ }>;
4335
+ type EndpointInfo = z.output<typeof endpointInfoSchema>;
4336
+ type EndpointInfoInput = z.input<typeof endpointInfoSchema>;
4337
+ declare const interactionKindSchema: z.ZodEnum<{
4338
+ human: "human";
4339
+ agent: "agent";
4340
+ admin: "admin";
4341
+ protocol: "protocol";
4342
+ }>;
4343
+ declare const interactionStatusSchema: z.ZodEnum<{
4344
+ available: "available";
4345
+ "coming-soon": "coming-soon";
4346
+ disabled: "disabled";
4347
+ }>;
4348
+ declare const interactionInfoSchema: z.ZodObject<{
4349
+ id: z.ZodString;
4350
+ label: z.ZodString;
4351
+ description: z.ZodOptional<z.ZodString>;
4352
+ href: z.ZodString;
4353
+ kind: typeof interactionKindSchema;
4354
+ pluginId: z.ZodString;
4355
+ priority: z.ZodDefault<z.ZodNumber>;
4356
+ visibility: z.ZodDefault<typeof userPermissionLevelSchema>;
4357
+ requiresActiveSession: z.ZodOptional<z.ZodBoolean>;
4358
+ status: z.ZodDefault<typeof interactionStatusSchema>;
4359
+ }>;
4360
+ type InteractionInfo = z.output<typeof interactionInfoSchema>;
4361
+ type InteractionInfoInput = z.input<typeof interactionInfoSchema>;
4362
+ declare const entityCountSchema: z.ZodObject<{
4363
+ entityType: z.ZodString;
4364
+ count: z.ZodNumber;
4365
+ }>;
4366
+ declare const backgroundWorkInfoSchema: z.ZodObject<{
4367
+ status: z.ZodEnum<{
4368
+ operational: "operational";
4369
+ degraded: "degraded";
4370
+ }>;
4371
+ reasons: z.ZodArray<z.ZodString>;
4372
+ worker: z.ZodObject<{
4373
+ state: z.ZodEnum<{
4374
+ active: "active";
4375
+ missing: "missing";
4376
+ stale: "stale";
4377
+ }>;
4378
+ activeSessions: z.ZodNumber;
4379
+ staleSessions: z.ZodNumber;
4380
+ latestHeartbeatAgeMs: z.ZodNullable<z.ZodNumber>;
4381
+ }>;
4382
+ queue: z.ZodObject<{
4383
+ duePending: z.ZodNumber;
4384
+ processing: z.ZodNumber;
4385
+ oldestDuePendingAgeMs: z.ZodNullable<z.ZodNumber>;
4386
+ latestClaimAgeMs: z.ZodNullable<z.ZodNumber>;
4387
+ stalled: z.ZodBoolean;
4388
+ }>;
4389
+ }>;
4390
+ declare const appInfoSchema: z.ZodObject<{
4391
+ model: z.ZodString;
4392
+ version: z.ZodString;
4393
+ uptime: z.ZodNumber;
4394
+ entities: z.ZodNumber;
4395
+ entityCounts: z.ZodArray<typeof entityCountSchema>;
4396
+ embeddings: z.ZodNumber;
4397
+ backgroundWork: typeof backgroundWorkInfoSchema;
4398
+ ai: z.ZodObject<{
4399
+ model: z.ZodString;
4400
+ embeddingModel: z.ZodString;
4401
+ }>;
4402
+ daemons: z.ZodArray<typeof DaemonStatusInfoSchema>;
4403
+ endpoints: z.ZodArray<typeof endpointInfoSchema>;
4404
+ interactions: z.ZodArray<typeof interactionInfoSchema>;
4405
+ }>;
4406
+ type RuntimeAppInfo = z.output<typeof appInfoSchema>;
4407
+ //#endregion
4408
+ //#region ../../shell/plugins/src/contracts/generation.d.ts
4409
+ interface GenerationStyleGuide {
4410
+ voice?: string;
4411
+ visual?: string;
4412
+ }
4413
+ interface ContentGenerationConfig {
4414
+ prompt: string;
4415
+ templateName: string;
4416
+ conversationHistory?: string;
4417
+ data?: Record<string, unknown>;
4418
+ representedIdentity?: "brain" | "anchor" | "none";
4419
+ styleGuide?: GenerationStyleGuide;
4420
+ interfacePermissionGrant?: UserPermissionLevel;
4421
+ }
4422
+ //#endregion
4423
+ //#region ../../shell/plugins/src/types/api-routes.d.ts
4424
+ declare const apiRouteDefinitionSchema: z.ZodObject<{
4425
+ path: z.ZodString;
4426
+ method: z.ZodDefault<z.ZodEnum<{
4427
+ GET: "GET";
4428
+ POST: "POST";
4429
+ PUT: "PUT";
4430
+ DELETE: "DELETE";
4431
+ }>>;
4432
+ tool: z.ZodString;
4433
+ public: z.ZodDefault<z.ZodBoolean>;
4434
+ successRedirect: z.ZodOptional<z.ZodString>;
4435
+ errorRedirect: z.ZodOptional<z.ZodString>;
4436
+ }>;
4437
+ type ApiRouteDefinition = z.output<typeof apiRouteDefinitionSchema>;
4438
+ /**
4439
+ * A registered API route with full path and plugin context
4440
+ * Returned by Shell.getPluginApiRoutes()
4441
+ */
4442
+ interface RegisteredApiRoute {
4443
+ /** The plugin that registered this route */
4444
+ pluginId: string;
4445
+ /** Full path including /api/{pluginId} prefix */
4446
+ fullPath: string;
4447
+ /** The original route definition */
4448
+ definition: ApiRouteDefinition;
4449
+ }
4450
+ //#endregion
4451
+ //#region ../../shell/plugins/src/types/web-routes.d.ts
4452
+ declare const WebRouteMethods: readonly ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
4453
+ type WebRouteMethod = (typeof WebRouteMethods)[number];
4454
+ /** Host-supplied socket metadata. Never derive this from HTTP/forwarding headers. */
4455
+ interface WebRouteTransportContext {
4456
+ readonly remoteAddress?: string;
4457
+ }
4458
+ type WebRouteHandler = (request: Request, transport?: WebRouteTransportContext) => Response | Promise<Response>;
4459
+ type WebRouteMatch = "exact" | "prefix";
4460
+ interface WebRouteDefinition {
4461
+ /** Absolute mounted path (e.g. "/studio" or "/studio-config") */
4462
+ path: string;
4463
+ /** Match only `path` (default) or descendants on a segment boundary. */
4464
+ match?: WebRouteMatch;
4465
+ /** HTTP method */
4466
+ method?: WebRouteMethod;
4467
+ /** Allow unauthenticated access */
4468
+ public?: boolean;
4469
+ /** Also serve on the preview host. Reachability only; admission checks still apply. */
4470
+ preview?: boolean;
4471
+ /** Request handler */
4472
+ handler: WebRouteHandler;
4473
+ }
4474
+ interface RegisteredWebRoute {
4475
+ /** The plugin that registered this route */
4476
+ pluginId: string;
4477
+ /** The mounted path */
4478
+ fullPath: string;
4479
+ /** The original route definition */
4480
+ definition: WebRouteDefinition;
4481
+ }
4482
+ //#endregion
4483
+ //#region ../../shell/plugins/src/contracts/handlers.d.ts
4484
+ type EvalHandler<TInput = unknown, TOutput = unknown> = (input: TInput) => Promise<TOutput>;
4485
+ /**
4486
+ * Computes a domain summary over entities.
4487
+ *
4488
+ * Takes the read-only projection, not the full service: an insight reports on
4489
+ * what exists and must not write. `@brains/plugins` publishes this signature
4490
+ * to plugin authors, so widening it here would promise them less than they
4491
+ * are given.
4492
+ */
4493
+ type InsightHandler = (entityService: ReadOnlyEntityService, visibilityScope: ContentVisibility) => Promise<Record<string, unknown>>;
4494
+ //#endregion
4495
+ //#region ../../shell/plugins/src/interfaces.d.ts
4496
+ /**
4497
+ * Query context for shell queries
4498
+ */
4499
+ interface QueryContext {
4500
+ userId?: string;
4501
+ conversationHistory?: string;
4502
+ messageId?: string;
4503
+ threadId?: string;
4504
+ timestamp?: string;
4505
+ [key: string]: unknown;
4506
+ }
4507
+ /**
4508
+ * Bounded model-as-judge request exposed to plugins.
4509
+ * Kept structural here so public plugin declarations do not import ai-service internals.
4510
+ */
4511
+ interface JudgeInput<T> {
4512
+ instruction: string;
4513
+ material: string;
4514
+ schema: AIGenerationSchema<T>;
4515
+ }
4516
+ /**
4517
+ * Shell interface that plugins use to access core services
4518
+ * This avoids circular dependencies between core and plugin-context
4519
+ */
4520
+ /**
4521
+ * Registry for insight types.
4522
+ * Core registers generic insights; plugins register domain-specific ones.
4523
+ */
4524
+ interface IInsightsRegistry {
4525
+ register(type: string, handler: InsightHandler): void;
4526
+ unregister(type: string): void;
4527
+ getTypes(): string[];
4528
+ get(type: string, entityService: ReadOnlyEntityService, visibilityScope: ContentVisibility): Promise<Record<string, unknown>>;
4529
+ }
4530
+ interface IShell {
4531
+ getMessageBus(): IMessageBus;
4532
+ getContentService(): ContentService;
4533
+ getLogger(): Logger;
4534
+ getEntityService(): EntityService;
4535
+ getEntityRegistry(): EntityRegistry;
4536
+ getJobQueueService(): IJobQueueService;
4537
+ getRenderService(): ViewTemplateRegistry;
4538
+ getConversationService(): IConversationService;
4539
+ getMCPService(): IMCPTransport;
4540
+ listToolsForPermissionLevel(level: UserPermissionLevel): ToolInfo[];
4541
+ getPermissionService(): PermissionService;
4542
+ getDataSourceRegistry(): DataSourceRegistry;
4543
+ getAgentService(): IAgentService;
4544
+ getAttachmentRegistry(): IAttachmentsNamespace;
4545
+ getRuntimeUploadRegistry(): IRuntimeUploadsNamespace;
4546
+ getRuntimeState(): IRuntimeStateNamespace;
4547
+ getRecurringChecks(pluginId: string): IRecurringChecksNamespace;
4548
+ getIdentity(): BrainCharacter;
4549
+ getProfile(): AnchorProfile;
4550
+ getProfileKindRegistry(): IProfileKindRegistry;
4551
+ getChannelRegistry(): IChannelRegistry;
4552
+ getInboxRegistry(): IInboxRegistry;
4553
+ getInboxFollowUpRegistry(): IInboxFollowUpRegistry;
4554
+ getOperationalHealthRegistry(): IOperationalHealthRegistry;
4555
+ getAccountSettingsRegistry(): AccountSettingsRegistry;
4556
+ getDomain(): string | undefined;
4557
+ getLocalSiteUrl(): string | undefined;
4558
+ shouldPreferLocalUrls(): boolean;
4559
+ getThemeCSS(): string;
4560
+ getSpaces(): string[];
4561
+ getDataDir(): string;
4562
+ getGitBrokerSocket(): string | undefined;
4563
+ getGitBrokerCheckout(): string | undefined;
4564
+ getAppInfo(): Promise<RuntimeAppInfo>;
4565
+ getRuntimeReadiness(): Promise<RuntimeReadiness>;
4566
+ generateContent(config: ContentGenerationConfig): Promise<unknown>;
4567
+ generateObject<T>(prompt: string, schema: AIGenerationSchema<T>, signal?: AbortSignal): Promise<{
4568
+ object: T;
4569
+ }>;
4570
+ judge<T>(input: JudgeInput<T>): Promise<{
4571
+ verdict: T;
4572
+ usage: {
4573
+ promptTokens: number;
4574
+ completionTokens: number;
4575
+ totalTokens: number;
4576
+ };
4577
+ }>;
4578
+ query(prompt: string, context?: QueryContext): Promise<DefaultQueryResponse>;
4579
+ generateImage(prompt: string, options?: ImageGenerationOptions): Promise<ImageGenerationResult>;
4580
+ canGenerateImages(): boolean;
4581
+ registerTemplates(templates: Record<string, Template>, pluginId?: string): void;
4582
+ getTemplate(name: string): Template | undefined;
4583
+ registerTools(pluginId: string, tools: Tool[]): void;
4584
+ registerResources(pluginId: string, resources: Resource[]): void;
4585
+ registerResourceTemplate<K extends string = string>(pluginId: string, template: ResourceTemplate<K>): void;
4586
+ registerPrompt(pluginId: string, prompt: Prompt): void;
4587
+ registerInstructions(pluginId: string, instructions: string): void;
4588
+ getPluginPackageName(pluginId: string): string | undefined;
4589
+ hasPlugin(id: string): boolean;
4590
+ readonly jobs: IJobsNamespace;
4591
+ registerDaemon(name: string, daemon: Daemon, pluginId: string): void;
4592
+ registerEndpoint(endpoint: EndpointInfoInput): void;
4593
+ listEndpoints(): EndpointInfo[];
4594
+ registerInteraction(interaction: InteractionInfoInput): void;
4595
+ listInteractions(): InteractionInfo[];
4596
+ registerEvalHandler(pluginId: string, handlerId: string, handler: EvalHandler): void;
4597
+ getInsightsRegistry(): IInsightsRegistry;
4598
+ getPluginApiRoutes(): RegisteredApiRoute[];
4599
+ getPluginWebRoutes(): RegisteredWebRoute[];
4600
+ }
4601
+ //#endregion
4602
+ //#region ../../shared/ui-library/src/highlighted-text.d.ts
4603
+ /**
4604
+ * Render a content string with two lightweight markup conventions:
4605
+ *
4606
+ * - `\n` in the string produces a `<br />` (for multi-line headlines)
4607
+ * - Any `*...*` run is wrapped in a `<span>` carrying `highlightClass`
4608
+ *
4609
+ * Authors write the phrase as one natural string in markdown content;
4610
+ * the renderer does the structural split. Highlight styling is passed
4611
+ * per-brand (rizom.ai uses accent+midline, professional uses italic+accent)
4612
+ * so each consumer owns its own emphasis treatment while the parsing/
4613
+ * structure is shared.
4614
+ */
4615
+ declare function renderHighlightedText(text: string, highlightClass: string): JSX.Element;
4616
+ //#endregion
4617
+ //#region src/rizom/ui/site-info-links.d.ts
4618
+ declare function socialLinksToRizomLinks(siteInfo: Pick<SiteLayoutInfo, "socialLinks">, allowedPlatforms?: string[]): RizomLink[];
4619
+ //#endregion
4620
+ //#region src/rizom/ui/Wordmark.d.ts
4621
+ interface WordmarkProps {
4622
+ /** Brand name before the dot. Defaults to `"rizom"`. */
4623
+ name?: string;
4624
+ /** Suffix after the dot. Any string (e.g. `"ai"`, `"io"`, `"foundation"`). */
4625
+ brandSuffix: RizomBrandSuffix | string;
4626
+ className?: string;
4627
+ dotClassName?: string;
4628
+ suffixClassName?: string;
4629
+ }
4630
+ declare const Wordmark: ({ name, brandSuffix, className, dotClassName, suffixClassName }: WordmarkProps) => JSX.Element;
4631
+ //#endregion
4632
+ //#region src/rizom/ui/Ecosystem.d.ts
4633
+ interface EcosystemCard {
4634
+ suffix: RizomBrandSuffix;
4635
+ title: string;
4636
+ body: string;
4637
+ linkLabel: string;
4638
+ linkHref: string;
4639
+ }
4640
+ interface EcosystemContent {
4641
+ eyebrow: string;
4642
+ headline: string;
4643
+ cards: EcosystemCard[];
4644
+ }
4645
+ declare const Ecosystem: ({ eyebrow, headline, cards }: EcosystemContent) => JSX.Element;
4646
+ //#endregion
4647
+ //#region src/rizom/runtime/default-layout.d.ts
4648
+ declare const DefaultRizomLayout: ({ sections }: RizomLayoutProps) => JSX.Element;
4649
+ //#endregion
4650
+ //#region src/rizom/runtime/base-site.d.ts
4651
+ declare const rizomBaseSite: SiteDefinition;
4652
+ //#endregion
4653
+ //#region src/rizom/create-site.d.ts
4654
+ interface RizomRuntimeHooks {
4655
+ contentNamespace: string;
4656
+ templates?: Record<string, unknown>;
4657
+ dataSources?: unknown[];
4658
+ /** Datasources that need the plugin's runtime, built when it registers. */
4659
+ dataSourceFactories?: Array<(shell: IShell) => unknown>;
4660
+ }
4661
+ interface CreateRizomSiteOptions {
4662
+ packageName: string;
4663
+ layout: unknown;
4664
+ routes: RouteDefinitionInput[];
4665
+ content?: SiteContent;
4666
+ /**
4667
+ * Schema-first section groups (authored via `@rizom/site`'
4668
+ * `defineSection`/`sectionGroup`). Registered as content templates at brain
4669
+ * boot exactly like `content`, so the Studio + directory-sync + resolver treat
4670
+ * them identically — but the section shape is derived from one zod schema.
4671
+ */
4672
+ sections?: SiteSectionGroup | SiteSectionGroup[];
4673
+ themeOverride?: string;
4674
+ /**
4675
+ * Presentation config for entity-backed list/detail routes (labels, plural
4676
+ * names, navigation). Merged onto the base site's empty map. Sites that
4677
+ * surface plugin lists — e.g. `post`→"Essay", `deck`→"Talk" — set it here.
4678
+ */
4679
+ entityDisplay?: Record<string, EntityDisplayEntry>;
4680
+ /** Advanced runtime hooks for in-repo sites that need custom template/data-source wiring. */
4681
+ runtime?: RizomRuntimeHooks;
4682
+ }
4683
+ declare function createRizomSite(options: CreateRizomSiteOptions): SitePackage;
4684
+ //#endregion
4685
+ //#region src/site.d.ts
4686
+ declare const rizomAiSite: SitePackage;
4687
+ //#endregion
4688
+ //#region src/routes.d.ts
4689
+ /**
4690
+ * The consolidated Rizom site routes. The home page composes the living-memory
4691
+ * content namespace; the layout owns navigation (the one bar), so routes stay out of the entity nav.
4692
+ */
4693
+ declare const aiRoutes: RouteDefinitionInput[];
454
4694
  //#endregion
455
4695
  //#region src/living-memory.d.ts
456
4696
  declare const livingMemorySections: SiteSectionGroup;
@@ -461,4 +4701,4 @@ declare const workSections: SiteSectionGroup;
461
4701
  //#region src/foundation.d.ts
462
4702
  declare const foundationSections: SiteSectionGroup;
463
4703
  //#endregion
464
- export { Badge, type BadgeProps, Button, type ButtonProps, type ButtonSize, type ButtonVariant, type CreateRizomSiteOptions, DefaultRizomLayout, Divider, type DividerProps, Ecosystem, type EcosystemCard, type EcosystemContent, type EntityDisplayEntry, Footer, GUTTER, Header, type RizomBrandSuffix, type RizomFooterTagline, RizomFrame, type RizomFrameProps, type RizomLayoutProps, type RizomLink, type RizomSideNavItem, type RouteDefinitionInput, Section, type SectionDefinitionInput, type SectionProps, SideNav, type SiteContentArrayFieldDefinition, type SiteContentDefinition, type SiteContentEnumFieldDefinition, type SiteContentFieldDefinition, type SiteContentNumberFieldDefinition, type SiteContentObjectFieldDefinition, type SiteContentSectionDefinition, type SiteContentStringFieldDefinition, type SiteDefinition, type SiteDefinitionOverrides, type SiteLayoutInfo, type SitePackage, Wordmark, type WordmarkProps, aiRoutes, createRizomSite, rizomAiSite as default, rizomAiSite, foundationSections, homeSections, livingMemorySections, renderHighlightedText, rizomBaseSite, socialLinksToRizomLinks, workSections };
4704
+ export { Badge, type BadgeProps, Button, type ButtonProps, type ButtonSize, type ButtonVariant, type CreateRizomSiteOptions, DefaultRizomLayout, Divider, type DividerProps, Ecosystem, type EcosystemCard, type EcosystemContent, type EntityDisplayEntry, Footer, GUTTER, Header, type RizomBrandSuffix, type RizomFooterTagline, RizomFrame, type RizomFrameProps, type RizomLayoutProps, type RizomLink, type RizomSideNavItem, type RouteDefinitionInput, Section, type SectionDefinitionInput, type SectionProps, SideNav, type SiteContentArrayFieldDefinition, type SiteContentDefinition, type SiteContentEnumFieldDefinition, type SiteContentFieldDefinition, type SiteContentNumberFieldDefinition, type SiteContentObjectFieldDefinition, type SiteContentSectionDefinition, type SiteContentStringFieldDefinition, type SiteDefinition, type SiteDefinitionOverrides, type SiteLayoutInfo, type SitePackage, Wordmark, type WordmarkProps, aiRoutes, createRizomSite, rizomAiSite as default, rizomAiSite, foundationSections, livingMemorySections, renderHighlightedText, rizomBaseSite, socialLinksToRizomLinks, workSections };