@axiom-lattice/core 2.1.23 → 2.1.25

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.
package/dist/index.d.mts CHANGED
@@ -2,21 +2,21 @@ import { BaseMessage } from '@langchain/core/messages';
2
2
  import { ZodType } from 'zod/v3';
3
3
  import { $ZodType } from 'zod/v4/core';
4
4
  import { BaseChatModel, BaseChatModelCallOptions } from '@langchain/core/language_models/chat_models';
5
- import { BaseLanguageModelInput } from '@langchain/core/language_models/base';
5
+ import { BaseLanguageModelInput, LanguageModelLike } from '@langchain/core/language_models/base';
6
6
  import { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
7
7
  import { ChatResult } from '@langchain/core/outputs';
8
- import { LLMConfig, ToolConfig, ToolExecutor, AgentConfig, GraphBuildOptions, MessageChunk, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, ThreadStore, AssistantStore, SkillStore, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, Skill, CreateSkillRequest, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient } from '@axiom-lattice/protocols';
9
- import * as protocols from '@axiom-lattice/protocols';
10
- export { protocols as Protocols };
8
+ import * as _axiom_lattice_protocols from '@axiom-lattice/protocols';
9
+ import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, MessageChunk, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, ThreadStore, AssistantStore, SkillStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, UserStore, TenantStore, UserTenantLinkStore, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, Skill, CreateSkillRequest, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient } from '@axiom-lattice/protocols';
10
+ export { _axiom_lattice_protocols as Protocols };
11
11
  export { AgentConfig, AgentType, GraphBuildOptions, MemoryType } from '@axiom-lattice/protocols';
12
12
  import * as langchain from 'langchain';
13
- import { ReactAgent } from 'langchain';
14
- import z from 'zod';
13
+ import { ReactAgent, AgentMiddleware } from 'langchain';
14
+ import z, { z as z$1 } from 'zod';
15
15
  import { SandboxClient } from '@agent-infra/sandbox';
16
16
  import * as _langchain_core_tools from '@langchain/core/tools';
17
17
  import { StructuredTool } from '@langchain/core/tools';
18
18
  import { CompiledStateGraph } from '@langchain/langgraph';
19
- import { BaseCheckpointSaver } from '@langchain/langgraph-checkpoint';
19
+ import { BaseCheckpointSaver, BaseStore } from '@langchain/langgraph-checkpoint';
20
20
  import { ReplaySubject } from 'rxjs';
21
21
  import { Embeddings } from '@langchain/core/embeddings';
22
22
  import { VectorStore } from '@langchain/core/vectorstores';
@@ -300,11 +300,6 @@ interface ISqlDatabase {
300
300
  getDatabaseType(): DatabaseType;
301
301
  }
302
302
 
303
- /**
304
- * SQL Database Manager
305
- * Singleton manager for SQL database connections
306
- */
307
-
308
303
  /**
309
304
  * PostgreSQL Database Implementation
310
305
  * Uses pg library for PostgreSQL connections
@@ -369,58 +364,623 @@ declare class SqlDatabaseManager {
369
364
  * Disconnect all databases
370
365
  */
371
366
  disconnectAll(): Promise<void>;
367
+ /**
368
+ * Load database configurations from a DatabaseConfigStore
369
+ * and register them with this manager
370
+ *
371
+ * @param store - The database configuration store
372
+ * @param tenantId - Tenant identifier
373
+ */
374
+ loadConfigsFromStore(store: _axiom_lattice_protocols.DatabaseConfigStore, tenantId: string): Promise<void>;
375
+ /**
376
+ * Load all database configurations from a DatabaseConfigStore
377
+ * across all tenants and register them with this manager
378
+ *
379
+ * @param store - The database configuration store
380
+ */
381
+ loadAllConfigsFromStore(store: _axiom_lattice_protocols.DatabaseConfigStore): Promise<void>;
372
382
  }
373
383
  declare const sqlDatabaseManager: SqlDatabaseManager;
374
384
 
375
- interface CreateSqlToolParams {
376
- databaseKey?: string;
377
- connectionString?: string;
385
+ interface CreateSqlToolParams$3 {
386
+ databaseKeys: string[];
387
+ databaseDescriptions?: Record<string, string>;
378
388
  }
379
- declare const createListTablesSqlTool: ({ databaseKey, connectionString }: CreateSqlToolParams) => langchain.DynamicStructuredTool<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, Record<string, never>, {}, string>;
389
+ declare const createListTablesSqlTool: ({ databaseKeys, databaseDescriptions }: CreateSqlToolParams$3) => langchain.DynamicStructuredTool<z.ZodObject<{
390
+ databaseKey: z.ZodString;
391
+ }, "strip", z.ZodTypeAny, {
392
+ databaseKey: string;
393
+ }, {
394
+ databaseKey: string;
395
+ }>, {
396
+ databaseKey: string;
397
+ }, {
398
+ databaseKey: string;
399
+ }, string>;
380
400
 
381
- declare const createInfoSqlTool: ({ databaseKey, connectionString }: {
382
- databaseKey?: string;
383
- connectionString?: string;
384
- }) => langchain.DynamicStructuredTool<z.ZodObject<{
401
+ interface CreateSqlToolParams$2 {
402
+ databaseKeys: string[];
403
+ databaseDescriptions?: Record<string, string>;
404
+ }
405
+ declare const createInfoSqlTool: ({ databaseKeys, databaseDescriptions }: CreateSqlToolParams$2) => langchain.DynamicStructuredTool<z.ZodObject<{
385
406
  tables: z.ZodString;
407
+ databaseKey: z.ZodString;
386
408
  }, "strip", z.ZodTypeAny, {
409
+ databaseKey: string;
387
410
  tables: string;
388
411
  }, {
412
+ databaseKey: string;
389
413
  tables: string;
390
414
  }>, {
391
415
  tables: string;
416
+ databaseKey: string;
392
417
  }, {
418
+ databaseKey: string;
393
419
  tables: string;
394
420
  }, string>;
395
421
 
396
- declare const createQueryCheckerSqlTool: ({ databaseKey, connectionString }: {
397
- databaseKey?: string;
398
- connectionString?: string;
399
- }) => langchain.DynamicStructuredTool<z.ZodObject<{
422
+ interface CreateSqlToolParams$1 {
423
+ databaseKeys: string[];
424
+ databaseDescriptions?: Record<string, string>;
425
+ }
426
+ declare const createQueryCheckerSqlTool: ({ databaseKeys, databaseDescriptions }: CreateSqlToolParams$1) => langchain.DynamicStructuredTool<z.ZodObject<{
400
427
  query: z.ZodString;
428
+ databaseKey: z.ZodString;
401
429
  }, "strip", z.ZodTypeAny, {
402
430
  query: string;
431
+ databaseKey: string;
403
432
  }, {
404
433
  query: string;
434
+ databaseKey: string;
405
435
  }>, {
406
436
  query: string;
437
+ databaseKey: string;
407
438
  }, {
408
439
  query: string;
440
+ databaseKey: string;
409
441
  }, string>;
410
442
 
411
- declare const createQuerySqlTool: ({ databaseKey, connectionString }: {
412
- databaseKey?: string;
413
- connectionString?: string;
414
- }) => langchain.DynamicStructuredTool<z.ZodObject<{
443
+ interface CreateSqlToolParams {
444
+ databaseKeys: string[];
445
+ databaseDescriptions?: Record<string, string>;
446
+ }
447
+ declare const createQuerySqlTool: ({ databaseKeys, databaseDescriptions }: CreateSqlToolParams) => langchain.DynamicStructuredTool<z.ZodObject<{
415
448
  query: z.ZodString;
449
+ databaseKey: z.ZodString;
416
450
  }, "strip", z.ZodTypeAny, {
417
451
  query: string;
452
+ databaseKey: string;
418
453
  }, {
419
454
  query: string;
455
+ databaseKey: string;
420
456
  }>, {
421
457
  query: string;
458
+ databaseKey: string;
422
459
  }, {
423
460
  query: string;
461
+ databaseKey: string;
462
+ }, string>;
463
+
464
+ /**
465
+ * SemanticMetricsClient
466
+ * Client implementation for Semantic Metrics Server
467
+ * Provides datasource-aware metrics querying capabilities
468
+ */
469
+
470
+ /**
471
+ * Metric meta item from datasource meta endpoint
472
+ */
473
+ interface MetricMetaItem {
474
+ metricName: string;
475
+ displayName: string;
476
+ domain: string;
477
+ shortDesc: string;
478
+ searchKeywords: string[];
479
+ registered: boolean;
480
+ }
481
+ /**
482
+ * Table meta item from datasource meta endpoint
483
+ */
484
+ interface TableMetaItem {
485
+ tableName: string;
486
+ displayName: string;
487
+ docType: string;
488
+ docTypeEn: string;
489
+ mainTable?: string;
490
+ lineTable?: string;
491
+ columnCount: number;
492
+ shortDesc: string;
493
+ }
494
+ /**
495
+ * Index data from datasource meta endpoint
496
+ */
497
+ interface MetricMetaIndex {
498
+ datasourceId: number;
499
+ datasourceName: string;
500
+ catalogVersion: string;
501
+ domainCategories: string[];
502
+ metrics: MetricMetaItem[];
503
+ tables: TableMetaItem[];
504
+ }
505
+ /**
506
+ * Table column definition
507
+ */
508
+ interface TableColumnDetail {
509
+ name: string;
510
+ label: string;
511
+ description?: string;
512
+ type?: string;
513
+ example?: string;
514
+ }
515
+ /**
516
+ * Table detail from datasource meta endpoint
517
+ */
518
+ interface TableMetaDetail {
519
+ tableName: string;
520
+ docType: string;
521
+ docTypeEn: string;
522
+ objTypeCode?: number;
523
+ mainTable?: string;
524
+ lineTable?: string;
525
+ selectSql: string;
526
+ columns: (TableColumnDetail | null)[];
527
+ }
528
+ /**
529
+ * Datasource meta response data structure
530
+ */
531
+ interface DatasourceMetaData {
532
+ index: MetricMetaIndex;
533
+ metricsDetails: MetricMetaDetail[];
534
+ tablesDetails?: TableMetaDetail[];
535
+ }
536
+ /**
537
+ * Metric meta detail item from datasource meta endpoint
538
+ */
539
+ interface MetricMetaDetail {
540
+ datasourceId: number;
541
+ metricName: string;
542
+ displayName: string;
543
+ domain: string;
544
+ description: string;
545
+ dataType: string;
546
+ format: string;
547
+ defaultTimeContext: {
548
+ timeDimension: string;
549
+ label: string;
550
+ granularity: string;
551
+ window: string;
552
+ supportedGrains: string[];
553
+ };
554
+ supportedDimensions: Array<{
555
+ dim_id: string;
556
+ field_name: string;
557
+ type: string;
558
+ filter_operators?: string[];
559
+ filter_example?: object;
560
+ group_by_example?: string;
561
+ }>;
562
+ aiAgentContext: {
563
+ polarity: string;
564
+ synonyms: string[];
565
+ thresholds: Array<{
566
+ metric: string;
567
+ operator: string;
568
+ value: number;
569
+ level: string;
570
+ }>;
571
+ diagnosticWorkflow: {
572
+ trigger: {
573
+ any_of: Array<{
574
+ metric: string;
575
+ operator: string;
576
+ value: number;
577
+ }>;
578
+ };
579
+ actions: Array<{
580
+ type: string;
581
+ metric?: string;
582
+ dimensions?: string[];
583
+ intent: string;
584
+ }>;
585
+ analysis_logic: string;
586
+ };
587
+ humanReadableExplanation: string;
588
+ };
589
+ }
590
+ /**
591
+ * Semantic Metrics Client Implementation
592
+ * Uses Semantic Metrics HTTP API for queries
593
+ */
594
+ declare class SemanticMetricsClient implements IMetricsServerClient {
595
+ private config;
596
+ private baseUrl;
597
+ constructor(config: SemanticMetricsServerConfig);
598
+ /**
599
+ * Test connection to the semantic metrics server
600
+ * Attempts to fetch data sources as a connectivity test
601
+ */
602
+ testConnection(): Promise<{
603
+ connected: boolean;
604
+ latency?: number;
605
+ error?: string;
606
+ }>;
607
+ /**
608
+ * Get list of available metrics from all selected data sources
609
+ * Aggregates metrics across selected datasources
610
+ */
611
+ listMetrics(): Promise<MetricMeta[]>;
612
+ /**
613
+ * Get metadata for a specific metric
614
+ * Searches across selected datasources for the metric
615
+ */
616
+ getMetricMeta(metricName: string): Promise<MetricMeta | null>;
617
+ /**
618
+ * Query metric data - delegates to semanticQuery
619
+ * Note: For semantic server, use semanticQuery() directly for full functionality
620
+ */
621
+ queryMetricData(metricName: string, options: {
622
+ startTime?: number;
623
+ endTime?: number;
624
+ step?: number;
625
+ labels?: Record<string, string>;
626
+ }): Promise<MetricQueryResult>;
627
+ /**
628
+ * Get the server type
629
+ */
630
+ getServerType(): "semantic";
631
+ /**
632
+ * Get all available data sources from the semantic server
633
+ * GET /datasources
634
+ */
635
+ getDataSources(): Promise<DataSource[]>;
636
+ /**
637
+ * Get metrics meta for a specific data source
638
+ * GET /datasources/{id}/meta
639
+ */
640
+ getDatasourceMetrics(datasourceId: string): Promise<DatasourceMetaData>;
641
+ /**
642
+ * Execute a semantic metrics query
643
+ * POST /metrics/query
644
+ */
645
+ semanticQuery(request: SemanticMetricsQueryRequest): Promise<SemanticMetricsQueryResponse>;
646
+ /**
647
+ * Get selected data sources for this configuration
648
+ */
649
+ getSelectedDataSources(): string[];
650
+ /**
651
+ * Build request headers with authentication
652
+ */
653
+ private getHeaders;
654
+ }
655
+
656
+ /**
657
+ * Metrics Server Client Interface
658
+ * Defines the contract for metrics server implementations
659
+ */
660
+ interface IMetricsServerClient {
661
+ /**
662
+ * Test connection to the metrics server
663
+ */
664
+ testConnection(): Promise<{
665
+ connected: boolean;
666
+ latency?: number;
667
+ error?: string;
668
+ }>;
669
+ /**
670
+ * Get list of available metrics
671
+ */
672
+ listMetrics(): Promise<MetricMeta[]>;
673
+ /**
674
+ * Get metadata for a specific metric
675
+ * @param metricName - Name of the metric
676
+ */
677
+ getMetricMeta(metricName: string): Promise<MetricMeta | null>;
678
+ /**
679
+ * Query metric data
680
+ * @param metricName - Name of the metric
681
+ * @param options - Query options
682
+ */
683
+ queryMetricData(metricName: string, options: {
684
+ startTime?: number;
685
+ endTime?: number;
686
+ step?: number;
687
+ labels?: Record<string, string>;
688
+ }): Promise<MetricQueryResult>;
689
+ /**
690
+ * Get the server type
691
+ */
692
+ getServerType(): MetricsServerType;
693
+ }
694
+ /**
695
+ * Prometheus Client Implementation
696
+ * Uses Prometheus HTTP API for queries
697
+ */
698
+ declare class PrometheusClient implements IMetricsServerClient {
699
+ private config;
700
+ constructor(config: MetricsServerConfig);
701
+ testConnection(): Promise<{
702
+ connected: boolean;
703
+ latency?: number;
704
+ error?: string;
705
+ }>;
706
+ listMetrics(): Promise<MetricMeta[]>;
707
+ getMetricMeta(metricName: string): Promise<MetricMeta | null>;
708
+ queryMetricData(metricName: string, options: {
709
+ startTime?: number;
710
+ endTime?: number;
711
+ step?: number;
712
+ labels?: Record<string, string>;
713
+ }): Promise<MetricQueryResult>;
714
+ getServerType(): MetricsServerType;
715
+ private getHeaders;
716
+ }
717
+ /**
718
+ * Custom/Generic Metrics Client Implementation
719
+ * Uses a generic REST API approach
720
+ */
721
+ declare class CustomMetricsClient implements IMetricsServerClient {
722
+ private config;
723
+ constructor(config: MetricsServerConfig);
724
+ testConnection(): Promise<{
725
+ connected: boolean;
726
+ latency?: number;
727
+ error?: string;
728
+ }>;
729
+ listMetrics(): Promise<MetricMeta[]>;
730
+ getMetricMeta(metricName: string): Promise<MetricMeta | null>;
731
+ queryMetricData(metricName: string, options: {
732
+ startTime?: number;
733
+ endTime?: number;
734
+ step?: number;
735
+ labels?: Record<string, string>;
736
+ }): Promise<MetricQueryResult>;
737
+ getServerType(): MetricsServerType;
738
+ private getHeaders;
739
+ }
740
+ /**
741
+ * Metrics Server Manager
742
+ * Manages metrics server connections and provides a unified interface
743
+ */
744
+ declare class MetricsServerManager {
745
+ private static instance;
746
+ private clients;
747
+ private configs;
748
+ private defaultServerKey;
749
+ private constructor();
750
+ /**
751
+ * Get the singleton instance
752
+ */
753
+ static getInstance(): MetricsServerManager;
754
+ /**
755
+ * Register a metrics server
756
+ * @param key - Unique identifier for the server
757
+ * @param config - Metrics server configuration
758
+ */
759
+ registerServer(key: string, config: MetricsServerConfig): void;
760
+ /**
761
+ * Set the default metrics server
762
+ * @param key - Server key to set as default
763
+ */
764
+ setDefaultServer(key: string): void;
765
+ /**
766
+ * Get a metrics server client by key
767
+ * @param key - Server key (optional, uses default if not provided)
768
+ */
769
+ getClient(key?: string): IMetricsServerClient;
770
+ /**
771
+ * Get metrics server configuration by key
772
+ * @param key - Server key (optional, uses default if not provided)
773
+ */
774
+ getConfig(key?: string): MetricsServerConfig;
775
+ /**
776
+ * Check if a metrics server is registered
777
+ * @param key - Server key
778
+ */
779
+ hasServer(key: string): boolean;
780
+ /**
781
+ * Get all registered metrics server keys with their types
782
+ */
783
+ getServerKeys(): {
784
+ key: string;
785
+ type: MetricsServerType;
786
+ name?: string;
787
+ }[];
788
+ /**
789
+ * Remove a metrics server
790
+ * @param key - Server key
791
+ */
792
+ removeServer(key: string): void;
793
+ /**
794
+ * Load metrics server configurations from a store
795
+ * and register them with this manager
796
+ *
797
+ * @param store - The metrics server configuration store
798
+ * @param tenantId - Tenant identifier
799
+ */
800
+ loadConfigsFromStore(store: _axiom_lattice_protocols.MetricsServerConfigStore, tenantId: string): Promise<void>;
801
+ /**
802
+ * Load all metrics server configurations from a store
803
+ * across all tenants and register them with this manager
804
+ *
805
+ * @param store - The metrics server configuration store
806
+ */
807
+ loadAllConfigsFromStore(store: _axiom_lattice_protocols.MetricsServerConfigStore): Promise<void>;
808
+ }
809
+ declare const metricsServerManager: MetricsServerManager;
810
+
811
+ interface CreateMetricsToolParams$4 {
812
+ serverKeys: string[];
813
+ serverDescriptions?: Record<string, string>;
814
+ }
815
+ declare const createListMetricsServersTool: ({ serverKeys, serverDescriptions }: CreateMetricsToolParams$4) => langchain.DynamicStructuredTool<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, {}, {}, string>;
816
+
817
+ interface CreateMetricsToolParams$3 {
818
+ serverKeys: string[];
819
+ serverDescriptions?: Record<string, string>;
820
+ }
821
+ declare const createListMetricsDataSourcesTool: ({ serverKeys, serverDescriptions }: CreateMetricsToolParams$3) => langchain.DynamicStructuredTool<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, {}, {}, string>;
822
+
823
+ interface CreateMetricsToolParams$2 {
824
+ serverKeys: string[];
825
+ serverDescriptions?: Record<string, string>;
826
+ }
827
+ declare const createQueryMetricsListTool: ({ serverKeys, serverDescriptions }: CreateMetricsToolParams$2) => langchain.DynamicStructuredTool<z.ZodObject<{
828
+ serverKey: z.ZodString;
829
+ datasourceIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
830
+ }, "strip", z.ZodTypeAny, {
831
+ serverKey: string;
832
+ datasourceIds?: string[] | undefined;
833
+ }, {
834
+ serverKey: string;
835
+ datasourceIds?: string[] | undefined;
836
+ }>, {
837
+ serverKey: string;
838
+ datasourceIds?: string[];
839
+ }, {
840
+ serverKey: string;
841
+ datasourceIds?: string[] | undefined;
842
+ }, string>;
843
+
844
+ interface CreateMetricsToolParams$1 {
845
+ serverKeys: string[];
846
+ serverDescriptions?: Record<string, string>;
847
+ }
848
+ declare const createQueryMetricDefinitionTool: ({ serverKeys, serverDescriptions }: CreateMetricsToolParams$1) => langchain.DynamicStructuredTool<z.ZodObject<{
849
+ serverKey: z.ZodString;
850
+ metricName: z.ZodString;
851
+ datasourceId: z.ZodOptional<z.ZodString>;
852
+ }, "strip", z.ZodTypeAny, {
853
+ metricName: string;
854
+ serverKey: string;
855
+ datasourceId?: string | undefined;
856
+ }, {
857
+ metricName: string;
858
+ serverKey: string;
859
+ datasourceId?: string | undefined;
860
+ }>, {
861
+ serverKey: string;
862
+ metricName: string;
863
+ datasourceId?: string;
864
+ }, {
865
+ metricName: string;
866
+ serverKey: string;
867
+ datasourceId?: string | undefined;
868
+ }, string>;
869
+
870
+ interface CreateMetricsToolParams {
871
+ serverKeys: string[];
872
+ serverDescriptions?: Record<string, string>;
873
+ }
874
+ declare const createQuerySemanticMetricDataTool: ({ serverKeys, serverDescriptions }: CreateMetricsToolParams) => langchain.DynamicStructuredTool<z.ZodObject<{
875
+ serverKey: z.ZodString;
876
+ datasourceId: z.ZodString;
877
+ metrics: z.ZodArray<z.ZodString, "many">;
878
+ groupBy: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
879
+ filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
880
+ dimension: z.ZodString;
881
+ operator: z.ZodString;
882
+ values: z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean]>, "many">;
883
+ }, "strip", z.ZodTypeAny, {
884
+ values: (string | number | boolean)[];
885
+ dimension: string;
886
+ operator: string;
887
+ }, {
888
+ values: (string | number | boolean)[];
889
+ dimension: string;
890
+ operator: string;
891
+ }>, "many">>;
892
+ limit: z.ZodOptional<z.ZodNumber>;
893
+ }, "strip", z.ZodTypeAny, {
894
+ serverKey: string;
895
+ datasourceId: string;
896
+ metrics: string[];
897
+ groupBy?: string[] | undefined;
898
+ filters?: {
899
+ values: (string | number | boolean)[];
900
+ dimension: string;
901
+ operator: string;
902
+ }[] | undefined;
903
+ limit?: number | undefined;
904
+ }, {
905
+ serverKey: string;
906
+ datasourceId: string;
907
+ metrics: string[];
908
+ groupBy?: string[] | undefined;
909
+ filters?: {
910
+ values: (string | number | boolean)[];
911
+ dimension: string;
912
+ operator: string;
913
+ }[] | undefined;
914
+ limit?: number | undefined;
915
+ }>, {
916
+ serverKey: string;
917
+ datasourceId: string;
918
+ metrics: string[];
919
+ groupBy?: string[];
920
+ filters?: Array<{
921
+ dimension: string;
922
+ operator: string;
923
+ values: (string | number | boolean)[];
924
+ }>;
925
+ limit?: number;
926
+ }, {
927
+ serverKey: string;
928
+ datasourceId: string;
929
+ metrics: string[];
930
+ groupBy?: string[] | undefined;
931
+ filters?: {
932
+ values: (string | number | boolean)[];
933
+ dimension: string;
934
+ operator: string;
935
+ }[] | undefined;
936
+ limit?: number | undefined;
937
+ }, string>;
938
+
939
+ interface CreateTablesToolParams {
940
+ serverKeys: string[];
941
+ serverDescriptions?: Record<string, string>;
942
+ }
943
+ declare const createQueryTablesListTool: ({ serverKeys, serverDescriptions }: CreateTablesToolParams) => langchain.DynamicStructuredTool<z.ZodObject<{
944
+ serverKey: z.ZodString;
945
+ datasourceIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
946
+ }, "strip", z.ZodTypeAny, {
947
+ serverKey: string;
948
+ datasourceIds?: string[] | undefined;
949
+ }, {
950
+ serverKey: string;
951
+ datasourceIds?: string[] | undefined;
952
+ }>, {
953
+ serverKey: string;
954
+ datasourceIds?: string[];
955
+ }, {
956
+ serverKey: string;
957
+ datasourceIds?: string[] | undefined;
958
+ }, string>;
959
+
960
+ interface CreateTableToolParams {
961
+ serverKeys: string[];
962
+ serverDescriptions?: Record<string, string>;
963
+ }
964
+ declare const createQueryTableDefinitionTool: ({ serverKeys, serverDescriptions }: CreateTableToolParams) => langchain.DynamicStructuredTool<z.ZodObject<{
965
+ serverKey: z.ZodString;
966
+ tableName: z.ZodString;
967
+ datasourceId: z.ZodOptional<z.ZodString>;
968
+ }, "strip", z.ZodTypeAny, {
969
+ serverKey: string;
970
+ tableName: string;
971
+ datasourceId?: string | undefined;
972
+ }, {
973
+ serverKey: string;
974
+ tableName: string;
975
+ datasourceId?: string | undefined;
976
+ }>, {
977
+ serverKey: string;
978
+ tableName: string;
979
+ datasourceId?: string;
980
+ }, {
981
+ serverKey: string;
982
+ tableName: string;
983
+ datasourceId?: string | undefined;
424
984
  }, string>;
425
985
 
426
986
  interface SandboxManagerProtocol {
@@ -544,6 +1104,31 @@ interface AgentLattice {
544
1104
  config: AgentConfig;
545
1105
  client?: AgentClient | undefined;
546
1106
  }
1107
+ interface MiddlewareConfig {
1108
+ id: string;
1109
+ type: MiddlewareType;
1110
+ name: string;
1111
+ description: string;
1112
+ enabled: boolean;
1113
+ config: Record<string, any>;
1114
+ }
1115
+ interface AgentBuildParams {
1116
+ middleware?: MiddlewareConfig[];
1117
+ skillCategories?: string[];
1118
+ tools: Array<{
1119
+ key: string;
1120
+ definition: any;
1121
+ executor: any;
1122
+ }>;
1123
+ model: ModelLattice;
1124
+ subAgents: Array<{
1125
+ key: string;
1126
+ config: AgentConfig;
1127
+ client: AgentClient | undefined;
1128
+ }>;
1129
+ prompt: string;
1130
+ stateSchema?: z$1.ZodObject<any, any, any, any, any>;
1131
+ }
547
1132
 
548
1133
  /**
549
1134
  * AgentLatticeManager - 单例Agent Lattice管理器
@@ -570,6 +1155,19 @@ declare class AgentLatticeManager extends BaseLatticeManager<AgentLattice> {
570
1155
  * @param config Agent配置
571
1156
  */
572
1157
  registerLattice(config: AgentConfig): void;
1158
+ /**
1159
+ * Register a pre-built teammate agent client for dynamic team spawning.
1160
+ * Used when spawning teammates via agentWorkerGraph - the agent must exist
1161
+ * in the lattice before the worker invokes it.
1162
+ *
1163
+ * @param key Unique key (e.g. `team:${teamId}:${agentName}`)
1164
+ * @param client Pre-built AgentClient (ReactAgent or CompiledGraph)
1165
+ */
1166
+ registerTeammateAgent(key: string, client: AgentClient): void;
1167
+ /**
1168
+ * Unregister a teammate agent. Call when a team is done to clean up.
1169
+ */
1170
+ unregisterTeammateAgent(key: string): boolean;
573
1171
  /**
574
1172
  * 获取AgentLattice
575
1173
  * @param key Lattice键名
@@ -651,6 +1249,8 @@ declare const getAgentLattice: (key: string) => AgentLattice | undefined;
651
1249
  declare const getAgentConfig: (key: string) => AgentConfig | undefined;
652
1250
  declare const getAllAgentConfigs: () => Promise<AgentConfig[]>;
653
1251
  declare const validateAgentInput: (key: string, input: any) => boolean;
1252
+ declare const registerTeammateAgent: (key: string, client: AgentClient) => void;
1253
+ declare const unregisterTeammateAgent: (key: string) => boolean;
654
1254
  /**
655
1255
  * 获取或初始化Agent客户端
656
1256
  *
@@ -1277,6 +1877,13 @@ type StoreTypeMap = {
1277
1877
  thread: ThreadStore;
1278
1878
  assistant: AssistantStore;
1279
1879
  skill: SkillStore;
1880
+ workspace: WorkspaceStore;
1881
+ project: ProjectStore;
1882
+ database: DatabaseConfigStore;
1883
+ metrics: MetricsServerConfigStore;
1884
+ user: UserStore;
1885
+ tenant: TenantStore;
1886
+ userTenantLink: UserTenantLinkStore;
1280
1887
  };
1281
1888
  /**
1282
1889
  * Store type keys
@@ -1477,6 +2084,13 @@ interface FileSystemSkillStoreOptions {
1477
2084
  */
1478
2085
  rootDir?: string;
1479
2086
  }
2087
+ /**
2088
+ * Skill resource metadata
2089
+ */
2090
+ interface SkillResource {
2091
+ path: string;
2092
+ isDirectory: boolean;
2093
+ }
1480
2094
  /**
1481
2095
  * Filesystem-based implementation of SkillStore
1482
2096
  */
@@ -1550,6 +2164,125 @@ declare class FileSystemSkillStore implements SkillStore {
1550
2164
  * Get sub-skills of a parent skill
1551
2165
  */
1552
2166
  getSubSkills(parentSkillName: string): Promise<Skill[]>;
2167
+ /**
2168
+ * List all resources in a skill's resources directory
2169
+ * @param skillName The skill name
2170
+ * @returns Array of resource paths relative to resources/ directory
2171
+ */
2172
+ listSkillResources(skillName: string): Promise<string[]>;
2173
+ /**
2174
+ * Load a specific resource from a skill's resources directory
2175
+ * @param skillName The skill name
2176
+ * @param resourcePath Path to the resource relative to resources/ directory
2177
+ * @returns The resource content as string
2178
+ */
2179
+ loadSkillResource(skillName: string, resourcePath: string): Promise<string | null>;
2180
+ }
2181
+
2182
+ /**
2183
+ * InMemoryDatabaseConfigStore
2184
+ *
2185
+ * In-memory implementation of DatabaseConfigStore
2186
+ * Provides CRUD operations for database configuration data stored in memory
2187
+ *
2188
+ * Note: This implementation does NOT encrypt passwords - use with caution
2189
+ * For production use, prefer PostgreSQLDatabaseConfigStore
2190
+ */
2191
+
2192
+ /**
2193
+ * In-memory implementation of DatabaseConfigStore
2194
+ */
2195
+ declare class InMemoryDatabaseConfigStore implements DatabaseConfigStore {
2196
+ private configs;
2197
+ /**
2198
+ * Get composite key for storage
2199
+ */
2200
+ private getKey;
2201
+ /**
2202
+ * Get all database configurations for a tenant
2203
+ */
2204
+ getAllConfigs(tenantId: string): Promise<DatabaseConfigEntry[]>;
2205
+ /**
2206
+ * Get all database configurations across all tenants
2207
+ */
2208
+ getAllConfigsWithoutTenant(): Promise<DatabaseConfigEntry[]>;
2209
+ /**
2210
+ * Get database configuration by ID
2211
+ */
2212
+ getConfigById(tenantId: string, id: string): Promise<DatabaseConfigEntry | null>;
2213
+ /**
2214
+ * Get database configuration by business key
2215
+ */
2216
+ getConfigByKey(tenantId: string, key: string): Promise<DatabaseConfigEntry | null>;
2217
+ /**
2218
+ * Create a new database configuration
2219
+ */
2220
+ createConfig(tenantId: string, id: string, data: CreateDatabaseConfigRequest): Promise<DatabaseConfigEntry>;
2221
+ /**
2222
+ * Update an existing database configuration
2223
+ */
2224
+ updateConfig(tenantId: string, id: string, updates: Partial<UpdateDatabaseConfigRequest>): Promise<DatabaseConfigEntry | null>;
2225
+ /**
2226
+ * Delete a database configuration by ID
2227
+ */
2228
+ deleteConfig(tenantId: string, id: string): Promise<boolean>;
2229
+ /**
2230
+ * Check if configuration exists
2231
+ */
2232
+ hasConfig(tenantId: string, id: string): Promise<boolean>;
2233
+ /**
2234
+ * Clear all configurations (useful for testing)
2235
+ */
2236
+ clear(): void;
2237
+ /**
2238
+ * Clear configurations for a specific tenant
2239
+ */
2240
+ clearByTenant(tenantId: string): void;
2241
+ }
2242
+
2243
+ declare class InMemoryUserStore implements UserStore {
2244
+ private users;
2245
+ constructor();
2246
+ getAllUsers(): Promise<User[]>;
2247
+ getUserById(id: string): Promise<User | null>;
2248
+ getUserByEmail(email: string): Promise<User | null>;
2249
+ createUser(id: string, data: CreateUserRequest): Promise<User>;
2250
+ updateUser(id: string, updates: UpdateUserRequest): Promise<User | null>;
2251
+ deleteUser(id: string): Promise<boolean>;
2252
+ clear(): void;
2253
+ }
2254
+
2255
+ /**
2256
+ * InMemoryTenantStore
2257
+ *
2258
+ * In-memory implementation of TenantStore
2259
+ * Provides CRUD operations for tenant data stored in memory
2260
+ * Tenant is a top-level entity with single key storage
2261
+ */
2262
+
2263
+ declare class InMemoryTenantStore implements TenantStore {
2264
+ private tenants;
2265
+ constructor();
2266
+ private initDefaultData;
2267
+ getAllTenants(): Promise<Tenant[]>;
2268
+ getTenantById(id: string): Promise<Tenant | null>;
2269
+ createTenant(id: string, data: CreateTenantRequest): Promise<Tenant>;
2270
+ updateTenant(id: string, updates: UpdateTenantRequest): Promise<Tenant | null>;
2271
+ deleteTenant(id: string): Promise<boolean>;
2272
+ clear(): void;
2273
+ }
2274
+
2275
+ declare class InMemoryUserTenantLinkStore implements UserTenantLinkStore {
2276
+ private links;
2277
+ private getKey;
2278
+ getTenantsByUser(userId: string): Promise<UserTenantLink[]>;
2279
+ getUsersByTenant(tenantId: string): Promise<UserTenantLink[]>;
2280
+ getLink(userId: string, tenantId: string): Promise<UserTenantLink | null>;
2281
+ createLink(data: CreateUserTenantLinkRequest): Promise<UserTenantLink>;
2282
+ updateLink(userId: string, tenantId: string, updates: UpdateUserTenantLinkRequest): Promise<UserTenantLink | null>;
2283
+ deleteLink(userId: string, tenantId: string): Promise<boolean>;
2284
+ hasLink(userId: string, tenantId: string): Promise<boolean>;
2285
+ clear(): void;
1553
2286
  }
1554
2287
 
1555
2288
  /**
@@ -2107,20 +2840,1408 @@ declare function normalizeSandboxName(name: string): string;
2107
2840
  declare function isValidSandboxName(name: string): boolean;
2108
2841
 
2109
2842
  /**
2110
- * Event bus service
2111
- * Used for event publishing and subscription between internal system components
2843
+ * Agent Team - Store Protocols
2844
+ *
2845
+ * Defines the TaskListStore and MailboxStore interfaces.
2846
+ * These are external shared stores (not agent internal state), following the
2847
+ * same Protocol -> Implementation pattern as ThreadStore / InMemoryThreadStore.
2848
+ *
2849
+ * All methods are scoped by `teamId` so a single store instance can serve
2850
+ * multiple concurrent teams (like ThreadStore is scoped by assistantId).
2112
2851
  */
2113
- declare class EventBus {
2114
- private emitter;
2115
- private defaultQueueKey;
2116
- constructor();
2852
+
2853
+ /**
2854
+ * External shared storage for team tasks.
2855
+ *
2856
+ * Leader and teammates access the same store instance to add, claim,
2857
+ * complete, and query tasks. Implementations can be in-memory, filesystem,
2858
+ * database, etc.
2859
+ */
2860
+ interface TaskListStore {
2117
2861
  /**
2118
- * Set the default queue key for queue operations
2119
- * @param queueKey Queue key name
2862
+ * Add a single task to the team's task list.
2863
+ * @returns The created task with generated id and timestamps.
2120
2864
  */
2121
- setDefaultQueueKey(queueKey: string): void;
2865
+ addTask(teamId: string, spec: TaskSpec): Promise<TeamTask>;
2122
2866
  /**
2123
- * Publish event
2867
+ * Add multiple tasks at once. Dependency references (by title) are
2868
+ * resolved to task IDs within this batch + existing tasks.
2869
+ */
2870
+ addTasks(teamId: string, specs: TaskSpec[]): Promise<TeamTask[]>;
2871
+ /**
2872
+ * Update mutable fields of an existing task.
2873
+ * @returns The updated task, or null if not found.
2874
+ */
2875
+ updateTask(teamId: string, taskId: string, updates: Partial<TaskUpdatable>): Promise<TeamTask | null>;
2876
+ /**
2877
+ * Remove a task from the list.
2878
+ * @returns true if removed, false if not found.
2879
+ */
2880
+ removeTask(teamId: string, taskId: string): Promise<boolean>;
2881
+ /**
2882
+ * Claim a specific task by ID: set assignee to agentId and status to CLAIMED.
2883
+ * Only succeeds if the task is PENDING and all its dependencies are COMPLETED.
2884
+ * @returns The claimed task, or null if not found / not claimable.
2885
+ */
2886
+ claimTaskById(teamId: string, taskId: string, agentId: string): Promise<TeamTask | null>;
2887
+ /**
2888
+ * Mark a task as completed with a result summary.
2889
+ * @returns The updated task, or null if not found.
2890
+ */
2891
+ completeTask(teamId: string, taskId: string, result: string): Promise<TeamTask | null>;
2892
+ /**
2893
+ * Mark a task as failed with an error message.
2894
+ * @returns The updated task, or null if not found.
2895
+ */
2896
+ failTask(teamId: string, taskId: string, error: string): Promise<TeamTask | null>;
2897
+ /**
2898
+ * Get a single task by ID.
2899
+ */
2900
+ getTask(teamId: string, taskId: string): Promise<TeamTask | null>;
2901
+ /**
2902
+ * Get all tasks with a given status.
2903
+ */
2904
+ getTasksByStatus(teamId: string, status: TaskStatus): Promise<TeamTask[]>;
2905
+ /**
2906
+ * Get all tasks for the team.
2907
+ */
2908
+ getAllTasks(teamId: string): Promise<TeamTask[]>;
2909
+ /**
2910
+ * Check whether all tasks are in a terminal state (COMPLETED or FAILED)
2911
+ * and no tasks are PENDING, CLAIMED, or IN_PROGRESS.
2912
+ */
2913
+ isAllDone(teamId: string): Promise<boolean>;
2914
+ /**
2915
+ * Check whether there is at least one PENDING task whose dependencies
2916
+ * are all COMPLETED (i.e. a task that can be claimed right now).
2917
+ */
2918
+ hasClaimable(teamId: string): Promise<boolean>;
2919
+ /**
2920
+ * Subscribe to task events. Used by persistent teammates to sleep
2921
+ * until new claimable tasks appear (via "task:added" / "task:completed").
2922
+ */
2923
+ onTaskEvent(teamId: string, event: TaskEvent, callback: (task: TeamTask) => void): void;
2924
+ /**
2925
+ * Remove all tasks for a team (used when disbanding a team).
2926
+ */
2927
+ clearTeam(teamId: string): void;
2928
+ }
2929
+ /**
2930
+ * External shared storage for inter-agent messages.
2931
+ *
2932
+ * Leader and teammates use the same store instance to send and receive
2933
+ * messages. Implementations can be in-memory, database, etc.
2934
+ */
2935
+ interface MailboxStore {
2936
+ /**
2937
+ * Send a direct message from one agent to another.
2938
+ * @returns The created message.
2939
+ */
2940
+ sendMessage(teamId: string, from: string, to: string, content: string, type?: MessageType): Promise<MailboxMessage>;
2941
+ /**
2942
+ * Send a message to all registered agents in the team.
2943
+ * @returns Array of created messages (one per recipient).
2944
+ */
2945
+ broadcastMessage(teamId: string, from: string, content: string, type?: MessageType): Promise<MailboxMessage[]>;
2946
+ /**
2947
+ * Get all messages addressed to a specific agent (including broadcasts).
2948
+ */
2949
+ getMessages(teamId: string, agentId: string): Promise<MailboxMessage[]>;
2950
+ /**
2951
+ * Get only unread messages for an agent.
2952
+ */
2953
+ getUnreadMessages(teamId: string, agentId: string): Promise<MailboxMessage[]>;
2954
+ /**
2955
+ * Mark a specific message as read.
2956
+ */
2957
+ markAsRead(teamId: string, agentId: string, messageId: string): Promise<void>;
2958
+ /**
2959
+ * Register an agent so it can receive broadcast messages.
2960
+ */
2961
+ registerAgent(teamId: string, agentId: string): Promise<void>;
2962
+ /**
2963
+ * Unregister an agent.
2964
+ */
2965
+ unregisterAgent(teamId: string, agentId: string): Promise<void>;
2966
+ /**
2967
+ * Get all registered agent IDs for a team.
2968
+ */
2969
+ getRegisteredAgents(teamId: string): Promise<string[]>;
2970
+ /**
2971
+ * Subscribe to new messages for a specific agent.
2972
+ * Used for real-time notification so teammates can react promptly.
2973
+ */
2974
+ onMessage(teamId: string, agentId: string, callback: (msg: MailboxMessage) => void): void;
2975
+ /**
2976
+ * Unsubscribe from message events.
2977
+ */
2978
+ offMessage(teamId: string, agentId: string, callback: (msg: MailboxMessage) => void): void;
2979
+ /**
2980
+ * Subscribe to all new messages in a team.
2981
+ * Used for real-time notification of any message in the team.
2982
+ */
2983
+ onTeamMessage(teamId: string, callback: (msg: MailboxMessage) => void): void;
2984
+ /**
2985
+ * Unsubscribe from team message events.
2986
+ */
2987
+ offTeamMessage(teamId: string, callback: (msg: MailboxMessage) => void): void;
2988
+ /**
2989
+ * Get all messages for all agents in a team.
2990
+ */
2991
+ getAllTeamMessages(teamId: string): Promise<MailboxMessage[]>;
2992
+ /**
2993
+ * Remove all messages for a team (used when disbanding a team).
2994
+ */
2995
+ clearTeam(teamId: string): void;
2996
+ }
2997
+
2998
+ /**
2999
+ * Agent Team - Core Type Definitions
3000
+ *
3001
+ * Shared types used by TaskListStore, MailboxStore, middleware, and the AgentTeam facade.
3002
+ */
3003
+
3004
+ /**
3005
+ * Status of a task in the shared task list.
3006
+ */
3007
+ declare enum TaskStatus {
3008
+ PENDING = "pending",
3009
+ CLAIMED = "claimed",
3010
+ IN_PROGRESS = "in_progress",
3011
+ COMPLETED = "completed",
3012
+ FAILED = "failed"
3013
+ }
3014
+ /**
3015
+ * Events emitted by a TaskListStore when task state changes.
3016
+ */
3017
+ type TaskEvent = "task:added" | "task:claimed" | "task:completed" | "task:failed" | "task:removed";
3018
+ /**
3019
+ * A task stored in the shared task list.
3020
+ */
3021
+ interface TeamTask {
3022
+ /** Unique task identifier */
3023
+ id: string;
3024
+ /** Short title for the task */
3025
+ title: string;
3026
+ /** Detailed description of what needs to be done */
3027
+ description: string;
3028
+ /** Current status */
3029
+ status: TaskStatus;
3030
+ /** Name of the teammate that claimed this task */
3031
+ assignee?: string;
3032
+ /** Result summary when completed */
3033
+ result?: string;
3034
+ /** Error message when failed */
3035
+ error?: string;
3036
+ /** IDs of tasks that must be completed before this one can be claimed */
3037
+ dependencies: string[];
3038
+ /** When the task was created */
3039
+ createdAt: Date;
3040
+ /** When the task was last updated */
3041
+ updatedAt: Date;
3042
+ }
3043
+ /**
3044
+ * Input for creating a new task.
3045
+ */
3046
+ interface TaskSpec {
3047
+ id: string;
3048
+ title: string;
3049
+ description: string;
3050
+ assignee?: string;
3051
+ dependencies?: string[];
3052
+ }
3053
+ /**
3054
+ * Fields that can be updated on an existing task.
3055
+ */
3056
+ interface TaskUpdatable {
3057
+ title?: string;
3058
+ description?: string;
3059
+ assignee?: string;
3060
+ status?: TaskStatus;
3061
+ dependencies?: string[];
3062
+ }
3063
+ /**
3064
+ * Type of an inter-agent message in the mailbox.
3065
+ * Different tools and flows use different types when storing messages.
3066
+ */
3067
+ declare enum MessageType {
3068
+ /** One-to-one message (send_message tool) */
3069
+ DIRECT_MESSAGE = "direct_message",
3070
+ /** Message to all teammates (broadcast_message tool) */
3071
+ BROADCAST = "broadcast",
3072
+ /** Teammate submits execution plan to team_lead for approval */
3073
+ PLAN_REQUEST = "plan_request",
3074
+ /** Team_lead approves or rejects plan (feedback to teammate) */
3075
+ PLAN_FEEDBACK = "plan_feedback",
3076
+ /** Team_lead instructs team to shut down (e.g. disband_team) */
3077
+ SHUTDOWN_REQUEST = "shutdown_request",
3078
+ /** Teammate acknowledges shutdown */
3079
+ SHUTDOWN_RESPONSE = "shutdown_response",
3080
+ /** From TaskCompleted/TeammateIdle hook or system: quality issue or continue-work reminder */
3081
+ TASK_FEEDBACK = "task_feedback",
3082
+ /** Idle notification, task status change, or other status update */
3083
+ STATUS_UPDATE = "status_update"
3084
+ }
3085
+ /**
3086
+ * A message stored in the mailbox.
3087
+ */
3088
+ interface MailboxMessage {
3089
+ /** Unique message identifier */
3090
+ id: string;
3091
+ /** Sender agent name */
3092
+ from: string;
3093
+ /** Recipient agent name (or "__broadcast__" for broadcasts) */
3094
+ to: string;
3095
+ /** Message content */
3096
+ content: string;
3097
+ /** When the message was sent */
3098
+ timestamp: Date;
3099
+ /** Message type */
3100
+ type: MessageType;
3101
+ /** Whether the recipient has read this message */
3102
+ read: boolean;
3103
+ }
3104
+ /**
3105
+ * Specification for a teammate agent.
3106
+ * Configured at team creation time; the `create_team` tool matches teammate
3107
+ * names from the LLM's plan against these specs to get tools/model/prompt.
3108
+ */
3109
+ interface TeammateSpec {
3110
+ /** Unique name for this teammate (used as agent ID) */
3111
+ name: string;
3112
+ /** Role category (e.g. "research", "writing", "review") */
3113
+ role: string;
3114
+ /** Human-readable description of what this teammate does */
3115
+ description: string;
3116
+ /** Model override (defaults to team-level model) */
3117
+ model?: LanguageModelLike | string;
3118
+ /** Tools this teammate has access to (in addition to team tools) */
3119
+ tools?: StructuredTool[];
3120
+ /** Custom system prompt for this teammate */
3121
+ systemPrompt?: string;
3122
+ /** Additional middleware for this teammate */
3123
+ middleware?: AgentMiddleware[];
3124
+ }
3125
+ /**
3126
+ * Configuration for creating an agent team.
3127
+ */
3128
+ interface TeamConfig {
3129
+ /** Available teammate specifications (the LLM picks from these by name) */
3130
+ teammates: TeammateSpec[];
3131
+ /** Maximum number of teammates running concurrently (default: teammates.length) */
3132
+ maxConcurrency?: number;
3133
+ /** Model for the team lead agent */
3134
+ model?: LanguageModelLike | string;
3135
+ /** Custom system prompt for the team lead */
3136
+ systemPrompt?: string;
3137
+ /** Tools available to the team lead */
3138
+ tools?: StructuredTool[];
3139
+ /** Checkpointer for persisting agent state between runs */
3140
+ checkpointer?: BaseCheckpointSaver | boolean;
3141
+ /** Pluggable task list store (default: InMemoryTaskListStore) */
3142
+ taskListStore?: TaskListStore;
3143
+ /** Pluggable mailbox store (default: InMemoryMailboxStore) */
3144
+ mailboxStore?: MailboxStore;
3145
+ /** Additional middleware for the team lead agent */
3146
+ middleware?: AgentMiddleware[];
3147
+ /**
3148
+ * Schedule lattice key for polling task list / mailbox.
3149
+ * When set, teammates use scheduled polling instead of event-driven wait.
3150
+ * Requires the app to register the schedule lattice first.
3151
+ */
3152
+ scheduleLatticeKey?: string;
3153
+ /** Poll interval in ms when using schedule lattice (default: 5000) */
3154
+ pollIntervalMs?: number;
3155
+ /** Filesystem backend for sandboxed file operations */
3156
+ backend?: (config: {
3157
+ state: unknown;
3158
+ store?: any;
3159
+ }) => Promise<any>;
3160
+ }
3161
+
3162
+ /**
3163
+ * InMemoryTaskListStore
3164
+ *
3165
+ * In-memory implementation of TaskListStore.
3166
+ * Tasks are organised by teamId, following the same pattern as
3167
+ * InMemoryThreadStore (Map<teamId, Map<taskId, TeamTask>>).
3168
+ *
3169
+ * Uses an internal EventEmitter so persistent teammates can sleep
3170
+ * until claimable tasks appear instead of busy-polling.
3171
+ */
3172
+
3173
+ declare class InMemoryTaskListStore implements TaskListStore {
3174
+ /** Map<teamId, Map<taskId, TeamTask>> */
3175
+ private tasks;
3176
+ /** EventEmitter for task lifecycle events */
3177
+ private emitter;
3178
+ /** Auto-incrementing ID counter */
3179
+ private idCounter;
3180
+ constructor();
3181
+ /** Get or create the task map for a team. */
3182
+ private getTeamTasks;
3183
+ /** Generate a unique task ID. */
3184
+ private nextId;
3185
+ /** Emit a scoped event: `${teamId}:${event}`. */
3186
+ private emit;
3187
+ /**
3188
+ * Resolve dependency references by task IDs.
3189
+ */
3190
+ private resolveDependencies;
3191
+ /**
3192
+ * Check whether all dependencies of a task are in COMPLETED status.
3193
+ */
3194
+ private areDependenciesSatisfied;
3195
+ addTask(teamId: string, spec: TaskSpec): Promise<TeamTask>;
3196
+ addTasks(teamId: string, specs: TaskSpec[]): Promise<TeamTask[]>;
3197
+ updateTask(teamId: string, taskId: string, updates: Partial<TaskUpdatable>): Promise<TeamTask | null>;
3198
+ removeTask(teamId: string, taskId: string): Promise<boolean>;
3199
+ /**
3200
+ * Claim a specific task by ID: set assignee to agentId and status to CLAIMED.
3201
+ * Only succeeds if the task is PENDING and all dependencies are COMPLETED.
3202
+ */
3203
+ claimTaskById(teamId: string, taskId: string, agentId: string): Promise<TeamTask | null>;
3204
+ completeTask(teamId: string, taskId: string, result: string): Promise<TeamTask | null>;
3205
+ failTask(teamId: string, taskId: string, error: string): Promise<TeamTask | null>;
3206
+ getTask(teamId: string, taskId: string): Promise<TeamTask | null>;
3207
+ getTasksByStatus(teamId: string, status: TaskStatus): Promise<TeamTask[]>;
3208
+ getAllTasks(teamId: string): Promise<TeamTask[]>;
3209
+ isAllDone(teamId: string): Promise<boolean>;
3210
+ hasClaimable(teamId: string): Promise<boolean>;
3211
+ onTaskEvent(teamId: string, event: TaskEvent, callback: (task: TeamTask) => void): void;
3212
+ offTaskEvent(teamId: string, event: TaskEvent, callback: (task: TeamTask) => void): void;
3213
+ /** Remove all tasks for a team (useful for cleanup / testing). */
3214
+ clearTeam(teamId: string): void;
3215
+ /** Remove all tasks across all teams (useful for testing). */
3216
+ clear(): void;
3217
+ }
3218
+
3219
+ /**
3220
+ * InMemoryMailboxStore
3221
+ *
3222
+ * In-memory implementation of MailboxStore.
3223
+ * Messages are organised by teamId -> agentId, following the same
3224
+ * Map nesting pattern as InMemoryThreadStore.
3225
+ *
3226
+ * Uses an internal EventEmitter so agents can be notified of new
3227
+ * messages in real time without polling.
3228
+ */
3229
+
3230
+ declare class InMemoryMailboxStore implements MailboxStore {
3231
+ /** Map<teamId, Map<agentId, MailboxMessage[]>> */
3232
+ private messages;
3233
+ /** Map<teamId, Set<agentId>> -- registered agents for broadcast */
3234
+ private agents;
3235
+ /** EventEmitter for real-time message notifications */
3236
+ private emitter;
3237
+ /** Auto-incrementing message ID counter */
3238
+ private idCounter;
3239
+ constructor();
3240
+ /** Get or create the agent message list for a team. */
3241
+ private getAgentMessages;
3242
+ /** Generate a unique message ID. */
3243
+ private nextId;
3244
+ /** Store a message and emit a real-time event for the recipient. */
3245
+ private storeAndNotify;
3246
+ sendMessage(teamId: string, from: string, to: string, content: string, type?: MessageType): Promise<MailboxMessage>;
3247
+ broadcastMessage(teamId: string, from: string, content: string, type?: MessageType): Promise<MailboxMessage[]>;
3248
+ getMessages(teamId: string, agentId: string): Promise<MailboxMessage[]>;
3249
+ getUnreadMessages(teamId: string, agentId: string): Promise<MailboxMessage[]>;
3250
+ markAsRead(teamId: string, agentId: string, messageId: string): Promise<void>;
3251
+ registerAgent(teamId: string, agentId: string): Promise<void>;
3252
+ unregisterAgent(teamId: string, agentId: string): Promise<void>;
3253
+ getRegisteredAgents(teamId: string): Promise<string[]>;
3254
+ onMessage(teamId: string, agentId: string, callback: (msg: MailboxMessage) => void): void;
3255
+ offMessage(teamId: string, agentId: string, callback: (msg: MailboxMessage) => void): void;
3256
+ onTeamMessage(teamId: string, callback: (msg: MailboxMessage) => void): void;
3257
+ offTeamMessage(teamId: string, callback: (msg: MailboxMessage) => void): void;
3258
+ getAllTeamMessages(teamId: string): Promise<MailboxMessage[]>;
3259
+ /** Remove all data for a team (messages + registrations). */
3260
+ clearTeam(teamId: string): void;
3261
+ /** Remove all data across all teams. */
3262
+ clear(): void;
3263
+ }
3264
+
3265
+ /**
3266
+ * Agent Team - Team Middleware
3267
+ *
3268
+ * createTeamMiddleware() provides the TeamLead agent with tools to
3269
+ * manage a dynamic team:
3270
+ *
3271
+ * create_team -- non-blocking: spawn teammates + populate task list
3272
+ * add_tasks -- add new tasks at any time (evolutionary)
3273
+ * assign_task -- set a task's assignee (reassign to a teammate)
3274
+ * set_task_status -- set a task's status (pending, claimed, in_progress, completed, failed)
3275
+ * set_task_dependencies -- set a task's dependency list
3276
+ * check_tasks -- get current task list status
3277
+ * send_message -- send message to a teammate
3278
+ * read_messages -- read unread messages from teammates
3279
+ *
3280
+ * Patterns referenced from deep_agent_new/middleware/subagents.ts:
3281
+ * - createMiddleware() + wrapModelCall for system prompt injection
3282
+ * - Agent creation via createAgent() from langchain
3283
+ * - State filtering (filterStateForSubagent logic)
3284
+ * - ToolMessage returns
3285
+ */
3286
+
3287
+ /**
3288
+ * Options for creating the team middleware.
3289
+ */
3290
+ interface TeamMiddlewareOptions {
3291
+ /** Team configuration with teammate specs */
3292
+ teamConfig: TeamConfig;
3293
+ /** Task list store instance (shared across all agents) */
3294
+ taskListStore: TaskListStore;
3295
+ /** Mailbox store instance (shared across all agents) */
3296
+ mailboxStore: MailboxStore;
3297
+ }
3298
+ /**
3299
+ * Create the team middleware that gives the TeamLead agent tools to
3300
+ * manage a dynamic team with shared task list and mailbox.
3301
+ */
3302
+ declare function createTeamMiddleware(options: TeamMiddlewareOptions): AgentMiddleware;
3303
+
3304
+ /**
3305
+ * Agent Team - Teammate Tools
3306
+ *
3307
+ * Factory that creates LangChain StructuredTools injected into each
3308
+ * teammate agent. These tools let teammates interact with the shared
3309
+ * TaskListStore and MailboxStore.
3310
+ *
3311
+ * Tools: claim_task, complete_task, fail_task, send_message, read_messages
3312
+ */
3313
+
3314
+ /**
3315
+ * Options for creating teammate tools.
3316
+ */
3317
+ interface TeammateToolsOptions {
3318
+ /** Team identifier (scopes store operations) */
3319
+ teamId: string;
3320
+ /** This teammate's agent name / ID */
3321
+ agentId: string;
3322
+ /** Shared task list store */
3323
+ taskListStore: TaskListStore;
3324
+ /** Shared mailbox store */
3325
+ mailboxStore: MailboxStore;
3326
+ }
3327
+ /**
3328
+ * Create the set of tools injected into each teammate agent.
3329
+ *
3330
+ * These tools give the teammate access to:
3331
+ * - Task lifecycle: claim_task, complete_task, fail_task
3332
+ * - Communication: send_message, read_messages
3333
+ */
3334
+ declare function createTeammateTools(options: TeammateToolsOptions): StructuredTool[];
3335
+
3336
+ /**
3337
+ * Agent Graph Builder 接口
3338
+ *
3339
+ * 策略模式的核心接口,定义了构建Agent Graph的方法
3340
+ */
3341
+
3342
+ interface AgentGraphBuilder {
3343
+ /**
3344
+ * 构建Agent Graph
3345
+ *
3346
+ * @param agentLattice Agent Lattice对象
3347
+ * @param params Agent构建参数
3348
+ * @returns 返回CompiledGraph对象
3349
+ */
3350
+ build(agentLattice: AgentLattice, params: AgentBuildParams): AgentClient;
3351
+ }
3352
+
3353
+ /**
3354
+ * Team Agent Graph Builder
3355
+ *
3356
+ * Implements AgentGraphBuilder for AgentType.TEAM.
3357
+ * Bridges the AgentConfig registration system with createAgentTeam(),
3358
+ * resolving tool keys and model keys into concrete instances.
3359
+ */
3360
+
3361
+ declare class TeamAgentGraphBuilder implements AgentGraphBuilder {
3362
+ /**
3363
+ * Build a Team agent from the registered AgentLattice config.
3364
+ *
3365
+ * @param agentLattice - The AgentLattice containing the TeamAgentConfig
3366
+ * @param params - Build params with resolved tools and model
3367
+ * @returns AgentClient (the TeamLead ReactAgent)
3368
+ */
3369
+ build(agentLattice: AgentLattice, params: AgentBuildParams): AgentClient;
3370
+ }
3371
+
3372
+ /**
3373
+ * Agent Team - High-level Facade
3374
+ *
3375
+ * createAgentTeam() wires together the TaskListStore, MailboxStore,
3376
+ * and team middleware to produce a ready-to-use TeamLead ReactAgent.
3377
+ *
3378
+ * Usage:
3379
+ *
3380
+ * ```typescript
3381
+ * import { createAgentTeam } from "@axiom-lattice/core";
3382
+ *
3383
+ * const team = createAgentTeam({
3384
+ * teammates: [
3385
+ * { name: "researcher", role: "research", description: "Web research", tools: [searchTool] },
3386
+ * { name: "writer", role: "writing", description: "Report writing", tools: [writeTool] },
3387
+ * ],
3388
+ * maxConcurrency: 3,
3389
+ * });
3390
+ *
3391
+ * await team.invoke({
3392
+ * messages: [{ role: "human", content: "Research and write a report on X" }],
3393
+ * });
3394
+ * ```
3395
+ */
3396
+
3397
+ /**
3398
+ * Create an agent team: a TeamLead ReactAgent backed by shared
3399
+ * TaskListStore and MailboxStore with pre-configured teammates.
3400
+ *
3401
+ * @param config - Team configuration (teammates, model, stores, etc.)
3402
+ * @returns A ReactAgent that acts as the TeamLead
3403
+ */
3404
+ declare function createAgentTeam(config: TeamConfig): ReactAgent<any, any, any, any>;
3405
+
3406
+ /**
3407
+ * Protocol definition for pluggable memory backends.
3408
+ *
3409
+ * This module defines the BackendProtocol that all backend implementations
3410
+ * must follow. Backends can store files in different locations (state, filesystem,
3411
+ * database, etc.) and provide a uniform interface for file operations.
3412
+ */
3413
+
3414
+ type MaybePromise<T> = T | Promise<T>;
3415
+ /**
3416
+ * Structured file listing info.
3417
+ *
3418
+ * Minimal contract used across backends. Only "path" is required.
3419
+ * Other fields are best-effort and may be absent depending on backend.
3420
+ */
3421
+ interface FileInfo {
3422
+ /** File path */
3423
+ path: string;
3424
+ /** Whether this is a directory */
3425
+ is_dir?: boolean;
3426
+ /** File size in bytes (approximate) */
3427
+ size?: number;
3428
+ /** ISO 8601 timestamp of last modification */
3429
+ modified_at?: string;
3430
+ }
3431
+ /**
3432
+ * Structured grep match entry.
3433
+ */
3434
+ interface GrepMatch {
3435
+ /** File path where match was found */
3436
+ path: string;
3437
+ /** Line number (1-indexed) */
3438
+ line: number;
3439
+ /** The matching line text */
3440
+ text: string;
3441
+ }
3442
+ /**
3443
+ * File data structure used by backends.
3444
+ *
3445
+ * All file data is represented as objects with this structure:
3446
+ */
3447
+ interface FileData {
3448
+ /** Lines of text content */
3449
+ content: string[];
3450
+ /** ISO format timestamp of creation */
3451
+ created_at: string;
3452
+ /** ISO format timestamp of last modification */
3453
+ modified_at: string;
3454
+ }
3455
+ /**
3456
+ * Result from backend write operations.
3457
+ *
3458
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
3459
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
3460
+ */
3461
+ interface WriteResult {
3462
+ /** Error message on failure, undefined on success */
3463
+ error?: string;
3464
+ /** File path of written file, undefined on failure */
3465
+ path?: string;
3466
+ /**
3467
+ * State update dict for checkpoint backends, null for external storage.
3468
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
3469
+ * External backends set null (already persisted to disk/S3/database/etc).
3470
+ */
3471
+ filesUpdate?: Record<string, FileData> | null;
3472
+ /** Metadata for the write operation, attached to the ToolMessage */
3473
+ metadata?: Record<string, unknown>;
3474
+ }
3475
+ /**
3476
+ * Result from backend edit operations.
3477
+ *
3478
+ * Checkpoint backends populate filesUpdate with {file_path: file_data} for LangGraph state.
3479
+ * External backends set filesUpdate to null (already persisted to disk/S3/database/etc).
3480
+ */
3481
+ interface EditResult {
3482
+ /** Error message on failure, undefined on success */
3483
+ error?: string;
3484
+ /** File path of edited file, undefined on failure */
3485
+ path?: string;
3486
+ /**
3487
+ * State update dict for checkpoint backends, null for external storage.
3488
+ * Checkpoint backends populate this with {file_path: file_data} for LangGraph state.
3489
+ * External backends set null (already persisted to disk/S3/database/etc).
3490
+ */
3491
+ filesUpdate?: Record<string, FileData> | null;
3492
+ /** Number of replacements made, undefined on failure */
3493
+ occurrences?: number;
3494
+ /** Metadata for the edit operation, attached to the ToolMessage */
3495
+ metadata?: Record<string, unknown>;
3496
+ }
3497
+ /**
3498
+ * Protocol for pluggable memory backends (single, unified).
3499
+ *
3500
+ * Backends can store files in different locations (state, filesystem, database, etc.)
3501
+ * and provide a uniform interface for file operations.
3502
+ *
3503
+ * All file data is represented as objects with the FileData structure.
3504
+ *
3505
+ * Methods can return either direct values or Promises, allowing both
3506
+ * synchronous and asynchronous implementations.
3507
+ */
3508
+ interface BackendProtocol {
3509
+ /**
3510
+ * Structured listing with file metadata.
3511
+ *
3512
+ * Lists files and directories in the specified directory (non-recursive).
3513
+ * Directories have a trailing / in their path and is_dir=true.
3514
+ *
3515
+ * @param path - Absolute path to directory
3516
+ * @returns List of FileInfo objects for files and directories directly in the directory
3517
+ */
3518
+ lsInfo(path: string): MaybePromise<FileInfo[]>;
3519
+ /**
3520
+ * Read file content with line numbers or an error string.
3521
+ *
3522
+ * @param filePath - Absolute file path
3523
+ * @param offset - Line offset to start reading from (0-indexed), default 0
3524
+ * @param limit - Maximum number of lines to read, default 2000
3525
+ * @returns Formatted file content with line numbers, or error message
3526
+ */
3527
+ read(filePath: string, offset?: number, limit?: number): MaybePromise<string>;
3528
+ /**
3529
+ * Read file content as raw FileData.
3530
+ *
3531
+ * @param filePath - Absolute file path
3532
+ * @returns Raw file content as FileData
3533
+ */
3534
+ readRaw(filePath: string): MaybePromise<FileData>;
3535
+ /**
3536
+ * Structured search results or error string for invalid input.
3537
+ *
3538
+ * Searches file contents for a regex pattern.
3539
+ *
3540
+ * @param pattern - Regex pattern to search for
3541
+ * @param path - Base path to search from (default: null)
3542
+ * @param glob - Optional glob pattern to filter files (e.g., "*.py")
3543
+ * @returns List of GrepMatch objects or error string for invalid regex
3544
+ */
3545
+ grepRaw(pattern: string, path?: string | null, glob?: string | null): MaybePromise<GrepMatch[] | string>;
3546
+ /**
3547
+ * Structured glob matching returning FileInfo objects.
3548
+ *
3549
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
3550
+ * @param path - Base path to search from (default: "/")
3551
+ * @returns List of FileInfo objects matching the pattern
3552
+ */
3553
+ globInfo(pattern: string, path?: string): MaybePromise<FileInfo[]>;
3554
+ /**
3555
+ * Create a new file.
3556
+ *
3557
+ * @param filePath - Absolute file path
3558
+ * @param content - File content as string
3559
+ * @returns WriteResult with error populated on failure
3560
+ */
3561
+ write(filePath: string, content: string): MaybePromise<WriteResult>;
3562
+ /**
3563
+ * Edit a file by replacing string occurrences.
3564
+ *
3565
+ * @param filePath - Absolute file path
3566
+ * @param oldString - String to find and replace
3567
+ * @param newString - Replacement string
3568
+ * @param replaceAll - If true, replace all occurrences (default: false)
3569
+ * @returns EditResult with error, path, filesUpdate, and occurrences
3570
+ */
3571
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): MaybePromise<EditResult>;
3572
+ }
3573
+ /**
3574
+ * State and store container for backend initialization.
3575
+ *
3576
+ * This provides a clean interface for what backends need to access:
3577
+ * - state: Current agent state (with files, messages, etc.)
3578
+ * - store: Optional persistent store for cross-conversation data
3579
+ *
3580
+ * Different contexts build this differently:
3581
+ * - Tools: Extract state via getCurrentTaskInput(config)
3582
+ * - Middleware: Use request.state directly
3583
+ */
3584
+ interface StateAndStore {
3585
+ /** Current agent state with files, messages, etc. */
3586
+ state: unknown;
3587
+ /** Optional BaseStore for persistent cross-conversation storage */
3588
+ store?: BaseStore;
3589
+ /** Optional assistant ID for per-assistant isolation in store */
3590
+ assistantId?: string;
3591
+ threadId?: string;
3592
+ workspaceId?: string;
3593
+ projectId?: string;
3594
+ }
3595
+ /**
3596
+ * Factory function type for creating backend instances.
3597
+ *
3598
+ * Backends receive StateAndStore which contains the current state
3599
+ * and optional store, extracted from the execution context.
3600
+ *
3601
+ * @example
3602
+ * ```typescript
3603
+ * // Using in middleware
3604
+ * const middleware = createFilesystemMiddleware({
3605
+ * backend: (stateAndStore) => new StateBackend(stateAndStore)
3606
+ * });
3607
+ * ```
3608
+ */
3609
+ type BackendFactory = (stateAndStore: StateAndStore) => Promise<BackendProtocol>;
3610
+
3611
+ /**
3612
+ * StateBackend: Store files in LangGraph agent state (ephemeral).
3613
+ */
3614
+
3615
+ /**
3616
+ * Backend that stores files in agent state (ephemeral).
3617
+ *
3618
+ * Uses LangGraph's state management and checkpointing. Files persist within
3619
+ * a conversation thread but not across threads. State is automatically
3620
+ * checkpointed after each agent step.
3621
+ *
3622
+ * Special handling: Since LangGraph state must be updated via Command objects
3623
+ * (not direct mutation), operations return filesUpdate in WriteResult/EditResult
3624
+ * for the middleware to apply via Command.
3625
+ */
3626
+ declare class StateBackend implements BackendProtocol {
3627
+ private stateAndStore;
3628
+ constructor(stateAndStore: StateAndStore);
3629
+ /**
3630
+ * Get files from current state.
3631
+ */
3632
+ private getFiles;
3633
+ /**
3634
+ * List files and directories in the specified directory (non-recursive).
3635
+ *
3636
+ * @param path - Absolute path to directory
3637
+ * @returns List of FileInfo objects for files and directories directly in the directory.
3638
+ * Directories have a trailing / in their path and is_dir=true.
3639
+ */
3640
+ lsInfo(path: string): FileInfo[];
3641
+ /**
3642
+ * Read file content with line numbers.
3643
+ *
3644
+ * @param filePath - Absolute file path
3645
+ * @param offset - Line offset to start reading from (0-indexed)
3646
+ * @param limit - Maximum number of lines to read
3647
+ * @returns Formatted file content with line numbers, or error message
3648
+ */
3649
+ read(filePath: string, offset?: number, limit?: number): string;
3650
+ /**
3651
+ * Read file content as raw FileData.
3652
+ *
3653
+ * @param filePath - Absolute file path
3654
+ * @returns Raw file content as FileData
3655
+ */
3656
+ readRaw(filePath: string): FileData;
3657
+ /**
3658
+ * Create a new file with content.
3659
+ * Returns WriteResult with filesUpdate to update LangGraph state.
3660
+ */
3661
+ write(filePath: string, content: string): WriteResult;
3662
+ /**
3663
+ * Edit a file by replacing string occurrences.
3664
+ * Returns EditResult with filesUpdate and occurrences.
3665
+ */
3666
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): EditResult;
3667
+ /**
3668
+ * Structured search results or error string for invalid input.
3669
+ */
3670
+ grepRaw(pattern: string, path?: string, glob?: string | null): GrepMatch[] | string;
3671
+ /**
3672
+ * Structured glob matching returning FileInfo objects.
3673
+ */
3674
+ globInfo(pattern: string, path?: string): FileInfo[];
3675
+ }
3676
+
3677
+ /**
3678
+ * StoreBackend: Adapter for LangGraph's BaseStore (persistent, cross-thread).
3679
+ */
3680
+
3681
+ /**
3682
+ * Backend that stores files in LangGraph's BaseStore (persistent).
3683
+ *
3684
+ * Uses LangGraph's Store for persistent, cross-conversation storage.
3685
+ * Files are organized via namespaces and persist across all threads.
3686
+ *
3687
+ * The namespace can include an optional assistant_id for multi-agent isolation.
3688
+ */
3689
+ declare class StoreBackend implements BackendProtocol {
3690
+ private stateAndStore;
3691
+ constructor(stateAndStore: StateAndStore);
3692
+ /**
3693
+ * Get the store instance.
3694
+ *
3695
+ * @returns BaseStore instance
3696
+ * @throws Error if no store is available
3697
+ */
3698
+ private getStore;
3699
+ /**
3700
+ * Get the namespace for store operations.
3701
+ *
3702
+ * If an assistant_id is available in stateAndStore, return
3703
+ * [assistant_id, "filesystem"] to provide per-assistant isolation.
3704
+ * Otherwise return ["filesystem"].
3705
+ */
3706
+ protected getNamespace(): string[];
3707
+ /**
3708
+ * Convert a store Item to FileData format.
3709
+ *
3710
+ * @param storeItem - The store Item containing file data
3711
+ * @returns FileData object
3712
+ * @throws Error if required fields are missing or have incorrect types
3713
+ */
3714
+ private convertStoreItemToFileData;
3715
+ /**
3716
+ * Convert FileData to a value suitable for store.put().
3717
+ *
3718
+ * @param fileData - The FileData to convert
3719
+ * @returns Object with content, created_at, and modified_at fields
3720
+ */
3721
+ private convertFileDataToStoreValue;
3722
+ /**
3723
+ * Search store with automatic pagination to retrieve all results.
3724
+ *
3725
+ * @param store - The store to search
3726
+ * @param namespace - Hierarchical path prefix to search within
3727
+ * @param options - Optional query, filter, and page_size
3728
+ * @returns List of all items matching the search criteria
3729
+ */
3730
+ private searchStorePaginated;
3731
+ /**
3732
+ * List files and directories in the specified directory (non-recursive).
3733
+ *
3734
+ * @param path - Absolute path to directory
3735
+ * @returns List of FileInfo objects for files and directories directly in the directory.
3736
+ * Directories have a trailing / in their path and is_dir=true.
3737
+ */
3738
+ lsInfo(path: string): Promise<FileInfo[]>;
3739
+ /**
3740
+ * Read file content with line numbers.
3741
+ *
3742
+ * @param filePath - Absolute file path
3743
+ * @param offset - Line offset to start reading from (0-indexed)
3744
+ * @param limit - Maximum number of lines to read
3745
+ * @returns Formatted file content with line numbers, or error message
3746
+ */
3747
+ read(filePath: string, offset?: number, limit?: number): Promise<string>;
3748
+ /**
3749
+ * Read file content as raw FileData.
3750
+ *
3751
+ * @param filePath - Absolute file path
3752
+ * @returns Raw file content as FileData
3753
+ */
3754
+ readRaw(filePath: string): Promise<FileData>;
3755
+ /**
3756
+ * Create a new file with content.
3757
+ * Returns WriteResult. External storage sets filesUpdate=null.
3758
+ */
3759
+ write(filePath: string, content: string): Promise<WriteResult>;
3760
+ /**
3761
+ * Edit a file by replacing string occurrences.
3762
+ * Returns EditResult. External storage sets filesUpdate=null.
3763
+ */
3764
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3765
+ /**
3766
+ * Structured search results or error string for invalid input.
3767
+ */
3768
+ grepRaw(pattern: string, path?: string, glob?: string | null): Promise<GrepMatch[] | string>;
3769
+ /**
3770
+ * Structured glob matching returning FileInfo objects.
3771
+ */
3772
+ globInfo(pattern: string, path?: string): Promise<FileInfo[]>;
3773
+ }
3774
+
3775
+ /**
3776
+ * FilesystemBackend: Read and write files directly from the filesystem.
3777
+ *
3778
+ * Security and search upgrades:
3779
+ * - Secure path resolution with root containment when in virtual_mode (sandboxed to cwd)
3780
+ * - Prevent symlink-following on file I/O using O_NOFOLLOW when available
3781
+ * - Ripgrep-powered grep with JSON parsing, plus regex fallback
3782
+ * and optional glob include filtering, while preserving virtual path behavior
3783
+ */
3784
+
3785
+ /**
3786
+ * Backend that reads and writes files directly from the filesystem.
3787
+ *
3788
+ * Files are accessed using their actual filesystem paths. Relative paths are
3789
+ * resolved relative to the current working directory. Content is read/written
3790
+ * as plain text, and metadata (timestamps) are derived from filesystem stats.
3791
+ */
3792
+ declare class FilesystemBackend implements BackendProtocol {
3793
+ private cwd;
3794
+ private virtualMode;
3795
+ private maxFileSizeBytes;
3796
+ constructor(options?: {
3797
+ rootDir?: string;
3798
+ virtualMode?: boolean;
3799
+ maxFileSizeMb?: number;
3800
+ });
3801
+ /**
3802
+ * Resolve a file path with security checks.
3803
+ *
3804
+ * When virtualMode=true, treat incoming paths as virtual absolute paths under
3805
+ * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.
3806
+ * When virtualMode=false, preserve legacy behavior: absolute paths are allowed
3807
+ * as-is; relative paths resolve under cwd.
3808
+ *
3809
+ * @param key - File path (absolute, relative, or virtual when virtualMode=true)
3810
+ * @returns Resolved absolute path string
3811
+ * @throws Error if path traversal detected or path outside root
3812
+ */
3813
+ private resolvePath;
3814
+ /**
3815
+ * List files and directories in the specified directory (non-recursive).
3816
+ *
3817
+ * @param dirPath - Absolute directory path to list files from
3818
+ * @returns List of FileInfo objects for files and directories directly in the directory.
3819
+ * Directories have a trailing / in their path and is_dir=true.
3820
+ */
3821
+ lsInfo(dirPath: string): Promise<FileInfo[]>;
3822
+ /**
3823
+ * Read file content with line numbers.
3824
+ *
3825
+ * @param filePath - Absolute or relative file path
3826
+ * @param offset - Line offset to start reading from (0-indexed)
3827
+ * @param limit - Maximum number of lines to read
3828
+ * @returns Formatted file content with line numbers, or error message
3829
+ */
3830
+ read(filePath: string, offset?: number, limit?: number): Promise<string>;
3831
+ /**
3832
+ * Read file content as raw FileData.
3833
+ *
3834
+ * @param filePath - Absolute file path
3835
+ * @returns Raw file content as FileData
3836
+ */
3837
+ readRaw(filePath: string): Promise<FileData>;
3838
+ /**
3839
+ * Create a new file with content.
3840
+ * Returns WriteResult. External storage sets filesUpdate=null.
3841
+ */
3842
+ write(filePath: string, content: string): Promise<WriteResult>;
3843
+ /**
3844
+ * Edit a file by replacing string occurrences.
3845
+ * Returns EditResult. External storage sets filesUpdate=null.
3846
+ */
3847
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3848
+ /**
3849
+ * Structured search results or error string for invalid input.
3850
+ */
3851
+ grepRaw(pattern: string, dirPath?: string, glob?: string | null): Promise<GrepMatch[] | string>;
3852
+ /**
3853
+ * Try to use ripgrep for fast searching.
3854
+ * Returns null if ripgrep is not available or fails.
3855
+ */
3856
+ private ripgrepSearch;
3857
+ /**
3858
+ * Fallback regex search implementation.
3859
+ */
3860
+ private pythonSearch;
3861
+ /**
3862
+ * Structured glob matching returning FileInfo objects.
3863
+ */
3864
+ globInfo(pattern: string, searchPath?: string): Promise<FileInfo[]>;
3865
+ }
3866
+
3867
+ /**
3868
+ * CompositeBackend: Route operations to different backends based on path prefix.
3869
+ */
3870
+
3871
+ /**
3872
+ * Backend that routes file operations to different backends based on path prefix.
3873
+ *
3874
+ * This enables hybrid storage strategies like:
3875
+ * - `/memories/` → StoreBackend (persistent, cross-thread)
3876
+ * - Everything else → StateBackend (ephemeral, per-thread)
3877
+ *
3878
+ * The CompositeBackend handles path prefix stripping/re-adding transparently.
3879
+ */
3880
+ declare class CompositeBackend implements BackendProtocol {
3881
+ private default;
3882
+ private routes;
3883
+ private sortedRoutes;
3884
+ constructor(defaultBackend: BackendProtocol, routes: Record<string, BackendProtocol>);
3885
+ /**
3886
+ * Determine which backend handles this key and strip prefix.
3887
+ *
3888
+ * @param key - Original file path
3889
+ * @returns Tuple of [backend, stripped_key] where stripped_key has the route
3890
+ * prefix removed (but keeps leading slash).
3891
+ */
3892
+ private getBackendAndKey;
3893
+ /**
3894
+ * List files and directories in the specified directory (non-recursive).
3895
+ *
3896
+ * @param path - Absolute path to directory
3897
+ * @returns List of FileInfo objects with route prefixes added, for files and directories
3898
+ * directly in the directory. Directories have a trailing / in their path and is_dir=true.
3899
+ */
3900
+ lsInfo(path: string): Promise<FileInfo[]>;
3901
+ /**
3902
+ * Read file content, routing to appropriate backend.
3903
+ *
3904
+ * @param filePath - Absolute file path
3905
+ * @param offset - Line offset to start reading from (0-indexed)
3906
+ * @param limit - Maximum number of lines to read
3907
+ * @returns Formatted file content with line numbers, or error message
3908
+ */
3909
+ read(filePath: string, offset?: number, limit?: number): Promise<string>;
3910
+ /**
3911
+ * Read file content as raw FileData.
3912
+ *
3913
+ * @param filePath - Absolute file path
3914
+ * @returns Raw file content as FileData
3915
+ */
3916
+ readRaw(filePath: string): Promise<FileData>;
3917
+ /**
3918
+ * Structured search results or error string for invalid input.
3919
+ */
3920
+ grepRaw(pattern: string, path?: string, glob?: string | null): Promise<GrepMatch[] | string>;
3921
+ /**
3922
+ * Structured glob matching returning FileInfo objects.
3923
+ */
3924
+ globInfo(pattern: string, path?: string): Promise<FileInfo[]>;
3925
+ /**
3926
+ * Create a new file, routing to appropriate backend.
3927
+ *
3928
+ * @param filePath - Absolute file path
3929
+ * @param content - File content as string
3930
+ * @returns WriteResult with path or error
3931
+ */
3932
+ write(filePath: string, content: string): Promise<WriteResult>;
3933
+ /**
3934
+ * Edit a file, routing to appropriate backend.
3935
+ *
3936
+ * @param filePath - Absolute file path
3937
+ * @param oldString - String to find and replace
3938
+ * @param newString - Replacement string
3939
+ * @param replaceAll - If true, replace all occurrences
3940
+ * @returns EditResult with path, occurrences, or error
3941
+ */
3942
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
3943
+ }
3944
+
3945
+ /**
3946
+ * MemoryBackend: In-memory file storage backend.
3947
+ *
3948
+ * Stores files in a shared Map instance. Useful for sharing file state
3949
+ * across multiple agents within the same process (e.g., team members).
3950
+ *
3951
+ * All operations are synchronous and use in-memory storage.
3952
+ */
3953
+
3954
+ declare class MemoryBackend implements BackendProtocol {
3955
+ private files;
3956
+ constructor(files?: Map<string, FileData>);
3957
+ private getFiles;
3958
+ lsInfo(path: string): FileInfo[];
3959
+ read(filePath: string, offset?: number, limit?: number): string;
3960
+ readRaw(filePath: string): FileData;
3961
+ write(filePath: string, content: string): WriteResult;
3962
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): EditResult;
3963
+ grepRaw(pattern: string, path?: string, glob?: string | null): GrepMatch[] | string;
3964
+ globInfo(pattern: string, path?: string): FileInfo[];
3965
+ }
3966
+
3967
+ /**
3968
+ * SandboxFilesystem: A sandboxed filesystem backend that connects to a remote sandbox via SDK.
3969
+ *
3970
+ * This backend provides a secure, isolated filesystem environment by connecting to a remote
3971
+ * sandbox service through the @agent-infra/sandbox SDK. It implements the BackendProtocol
3972
+ * interface and delegates all file operations to the remote sandbox.
3973
+ *
3974
+ * Features:
3975
+ * - Remote sandbox connection via HTTP API
3976
+ * - Virtual path support (all paths start with /)
3977
+ * - Path traversal prevention
3978
+ * - Full BackendProtocol implementation
3979
+ */
3980
+
3981
+ /**
3982
+ * Sandboxed filesystem backend that connects to a remote sandbox service.
3983
+ *
3984
+ * All file operations are delegated to the remote sandbox via the SDK.
3985
+ * Paths are treated as virtual absolute paths (starting with /).
3986
+ */
3987
+ declare class SandboxFilesystem implements BackendProtocol {
3988
+ private sandbox;
3989
+ private maxFileSizeBytes;
3990
+ private workingDirectory;
3991
+ private baseURL;
3992
+ private homeDir;
3993
+ /**
3994
+ * Create a new SandboxFilesystem instance.
3995
+ *
3996
+ * @param options - Configuration options
3997
+ * @param options.baseURL - Base URL of the sandbox service (default: 'http://localhost:8080')
3998
+ * @param options.maxFileSizeMb - Maximum file size in MB (default: 10)
3999
+ * @param options.sandboxInstance - Optional Sandbox instance (if provided, baseURL is ignored)
4000
+ */
4001
+ constructor(options?: {
4002
+ baseURL?: string;
4003
+ workingDirectory?: string;
4004
+ maxFileSizeMb?: number;
4005
+ sandboxInstance?: SandboxClient;
4006
+ });
4007
+ private resolvePath;
4008
+ /**
4009
+ * Convert a real filesystem path to a virtual path.
4010
+ *
4011
+ * @param realPath - Real filesystem path
4012
+ * @returns Virtual path starting with /
4013
+ */
4014
+ private toVirtualPath;
4015
+ /**
4016
+ * List files and directories in the specified directory (non-recursive).
4017
+ *
4018
+ * @param dirPath - Virtual directory path (must start with /)
4019
+ * @returns List of FileInfo objects for files and directories directly in the directory.
4020
+ * Directories have a trailing / in their path and is_dir=true.
4021
+ */
4022
+ lsInfo(dirPath: string): Promise<FileInfo[]>;
4023
+ /**
4024
+ * Read file content with line numbers.
4025
+ *
4026
+ * @param filePath - Virtual file path (must start with /)
4027
+ * @param offset - Line offset to start reading from (0-indexed)
4028
+ * @param limit - Maximum number of lines to read
4029
+ * @returns Formatted file content with line numbers, or error message
4030
+ */
4031
+ read(filePath: string, offset?: number, limit?: number): Promise<string>;
4032
+ /**
4033
+ * Read file content as raw FileData.
4034
+ *
4035
+ * @param filePath - Virtual file path (must start with /)
4036
+ * @returns Raw file content as FileData
4037
+ */
4038
+ readRaw(filePath: string): Promise<FileData>;
4039
+ /**
4040
+ * Create a new file with content.
4041
+ * Returns WriteResult. External storage sets filesUpdate=null.
4042
+ *
4043
+ * @param filePath - Virtual file path (must start with /)
4044
+ * @param content - File content as string
4045
+ * @returns WriteResult with error populated on failure
4046
+ */
4047
+ write(filePath: string, content: string): Promise<WriteResult>;
4048
+ /**
4049
+ * Edit a file by replacing string occurrences.
4050
+ * Returns EditResult. External storage sets filesUpdate=null.
4051
+ *
4052
+ * @param filePath - Virtual file path (must start with /)
4053
+ * @param oldString - String to find and replace
4054
+ * @param newString - Replacement string
4055
+ * @param replaceAll - If true, replace all occurrences (default: false)
4056
+ * @returns EditResult with error, path, filesUpdate, and occurrences
4057
+ */
4058
+ edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult>;
4059
+ /**
4060
+ * Structured search results or error string for invalid input.
4061
+ *
4062
+ * Searches file contents for a regex pattern within the sandbox.
4063
+ *
4064
+ * @param pattern - Regex pattern to search for
4065
+ * @param searchPath - Base path to search from (default: "/")
4066
+ * @param glob - Optional glob pattern to filter files (e.g., "*.py")
4067
+ * @returns List of GrepMatch objects or error string for invalid regex
4068
+ */
4069
+ grepRaw(pattern: string, searchPath?: string | null, glob?: string | null): Promise<GrepMatch[] | string>;
4070
+ /**
4071
+ * Structured glob matching returning FileInfo objects.
4072
+ *
4073
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
4074
+ * @param searchPath - Base path to search from (default: "/")
4075
+ * @returns List of FileInfo objects matching the pattern
4076
+ */
4077
+ globInfo(pattern: string, searchPath?: string): Promise<FileInfo[]>;
4078
+ }
4079
+
4080
+ /**
4081
+ * Shared utility functions for memory backend implementations.
4082
+ *
4083
+ * This module contains both user-facing string formatters and structured
4084
+ * helpers used by backends and the composite router. Structured helpers
4085
+ * enable composition without fragile string parsing.
4086
+ */
4087
+
4088
+ declare const EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents";
4089
+ declare const MAX_LINE_LENGTH = 10000;
4090
+ declare const LINE_NUMBER_WIDTH = 6;
4091
+ declare const TOOL_RESULT_TOKEN_LIMIT = 20000;
4092
+ declare const TRUNCATION_GUIDANCE = "... [results truncated, try being more specific with your parameters]";
4093
+ /**
4094
+ * Sanitize tool_call_id to prevent path traversal and separator issues.
4095
+ *
4096
+ * Replaces dangerous characters (., /, \) with underscores.
4097
+ */
4098
+ declare function sanitizeToolCallId(toolCallId: string): string;
4099
+ /**
4100
+ * Format file content with line numbers (cat -n style).
4101
+ *
4102
+ * Chunks lines longer than MAX_LINE_LENGTH with continuation markers (e.g., 5.1, 5.2).
4103
+ *
4104
+ * @param content - File content as string or list of lines
4105
+ * @param startLine - Starting line number (default: 1)
4106
+ * @returns Formatted content with line numbers and continuation markers
4107
+ */
4108
+ declare function formatContentWithLineNumbers(content: string | string[], startLine?: number): string;
4109
+ /**
4110
+ * Check if content is empty and return warning message.
4111
+ *
4112
+ * @param content - Content to check
4113
+ * @returns Warning message if empty, null otherwise
4114
+ */
4115
+ declare function checkEmptyContent(content: string): string | null;
4116
+ /**
4117
+ * Convert FileData to plain string content.
4118
+ *
4119
+ * @param fileData - FileData object with 'content' key
4120
+ * @returns Content as string with lines joined by newlines
4121
+ */
4122
+ declare function fileDataToString(fileData: FileData): string;
4123
+ /**
4124
+ * Create a FileData object with timestamps.
4125
+ *
4126
+ * @param content - File content as string
4127
+ * @param createdAt - Optional creation timestamp (ISO format)
4128
+ * @returns FileData object with content and timestamps
4129
+ */
4130
+ declare function createFileData(content: string, createdAt?: string): FileData;
4131
+ /**
4132
+ * Update FileData with new content, preserving creation timestamp.
4133
+ *
4134
+ * @param fileData - Existing FileData object
4135
+ * @param content - New content as string
4136
+ * @returns Updated FileData object
4137
+ */
4138
+ declare function updateFileData(fileData: FileData, content: string): FileData;
4139
+ /**
4140
+ * Format file data for read response with line numbers.
4141
+ *
4142
+ * @param fileData - FileData object
4143
+ * @param offset - Line offset (0-indexed)
4144
+ * @param limit - Maximum number of lines
4145
+ * @returns Formatted content or error message
4146
+ */
4147
+ declare function formatReadResponse(fileData: FileData, offset: number, limit: number): string;
4148
+ /**
4149
+ * Perform string replacement with occurrence validation.
4150
+ *
4151
+ * @param content - Original content
4152
+ * @param oldString - String to replace
4153
+ * @param newString - Replacement string
4154
+ * @param replaceAll - Whether to replace all occurrences
4155
+ * @returns Tuple of [new_content, occurrences] on success, or error message string
4156
+ */
4157
+ declare function performStringReplacement(content: string, oldString: string, newString: string, replaceAll: boolean): [string, number] | string;
4158
+ /**
4159
+ * Truncate list or string result if it exceeds token limit (rough estimate: 4 chars/token).
4160
+ */
4161
+ declare function truncateIfTooLong(result: string[] | string): string[] | string;
4162
+ /**
4163
+ * Validate and normalize a path.
4164
+ *
4165
+ * @param path - Path to validate
4166
+ * @returns Normalized path starting with / and ending with /
4167
+ * @throws Error if path is invalid
4168
+ */
4169
+ declare function validatePath(path: string | null | undefined): string;
4170
+ /**
4171
+ * Search files dict for paths matching glob pattern.
4172
+ *
4173
+ * @param files - Dictionary of file paths to FileData
4174
+ * @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`)
4175
+ * @param path - Base path to search from
4176
+ * @returns Newline-separated file paths, sorted by modification time (most recent first).
4177
+ * Returns "No files found" if no matches.
4178
+ *
4179
+ * @example
4180
+ * ```typescript
4181
+ * const files = {"/src/main.py": FileData(...), "/test.py": FileData(...)};
4182
+ * globSearchFiles(files, "*.py", "/");
4183
+ * // Returns: "/test.py\n/src/main.py" (sorted by modified_at)
4184
+ * ```
4185
+ */
4186
+ declare function globSearchFiles(files: Record<string, FileData>, pattern: string, path?: string): string;
4187
+ /**
4188
+ * Format grep search results based on output mode.
4189
+ *
4190
+ * @param results - Dictionary mapping file paths to list of [line_num, line_content] tuples
4191
+ * @param outputMode - Output format - "files_with_matches", "content", or "count"
4192
+ * @returns Formatted string output
4193
+ */
4194
+ declare function formatGrepResults(results: Record<string, Array<[number, string]>>, outputMode: "files_with_matches" | "content" | "count"): string;
4195
+ /**
4196
+ * Search file contents for regex pattern.
4197
+ *
4198
+ * @param files - Dictionary of file paths to FileData
4199
+ * @param pattern - Regex pattern to search for
4200
+ * @param path - Base path to search from
4201
+ * @param glob - Optional glob pattern to filter files (e.g., "*.py")
4202
+ * @param outputMode - Output format - "files_with_matches", "content", or "count"
4203
+ * @returns Formatted search results. Returns "No matches found" if no results.
4204
+ *
4205
+ * @example
4206
+ * ```typescript
4207
+ * const files = {"/file.py": FileData({content: ["import os", "print('hi')"], ...})};
4208
+ * grepSearchFiles(files, "import", "/");
4209
+ * // Returns: "/file.py" (with output_mode="files_with_matches")
4210
+ * ```
4211
+ */
4212
+ declare function grepSearchFiles(files: Record<string, FileData>, pattern: string, path?: string | null, glob?: string | null, outputMode?: "files_with_matches" | "content" | "count"): string;
4213
+ /**
4214
+ * Return structured grep matches from an in-memory files mapping.
4215
+ *
4216
+ * Returns a list of GrepMatch on success, or a string for invalid inputs
4217
+ * (e.g., invalid regex). We deliberately do not raise here to keep backends
4218
+ * non-throwing in tool contexts and preserve user-facing error messages.
4219
+ */
4220
+ declare function grepMatchesFromFiles(files: Record<string, FileData>, pattern: string, path?: string | null, glob?: string | null): GrepMatch[] | string;
4221
+ /**
4222
+ * Group structured matches into the legacy dict form used by formatters.
4223
+ */
4224
+ declare function buildGrepResultsDict(matches: GrepMatch[]): Record<string, Array<[number, string]>>;
4225
+ /**
4226
+ * Format structured grep matches using existing formatting logic.
4227
+ */
4228
+ declare function formatGrepMatches(matches: GrepMatch[], outputMode: "files_with_matches" | "content" | "count"): string;
4229
+
4230
+ /**
4231
+ * Event bus service
4232
+ * Used for event publishing and subscription between internal system components
4233
+ */
4234
+ declare class EventBus {
4235
+ private emitter;
4236
+ private defaultQueueKey;
4237
+ constructor();
4238
+ /**
4239
+ * Set the default queue key for queue operations
4240
+ * @param queueKey Queue key name
4241
+ */
4242
+ setDefaultQueueKey(queueKey: string): void;
4243
+ /**
4244
+ * Publish event
2124
4245
  * @param eventName Event name
2125
4246
  * @param data Event data
2126
4247
  * @param useQueue Whether to use queue for publishing
@@ -2163,4 +4284,47 @@ declare class AgentManager {
2163
4284
 
2164
4285
  declare const AGENT_TASK_EVENT = "agent:execute";
2165
4286
 
2166
- export { AGENT_TASK_EVENT, type AgentClient, type AgentLattice, AgentLatticeManager, AgentManager, type BufferStats, type Chunk, ChunkBuffer, ChunkBufferLatticeManager, type ColumnInfo, ConsoleLoggerClient, type CronFields, type DatabaseConfig, type DatabaseType, DefaultScheduleClient, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, FileSystemSkillStore, type FileSystemSkillStoreOptions, type ISqlDatabase, InMemoryAssistantStore, InMemoryChunkBuffer, InMemoryThreadStore, type IsolatedLevel, type LoggerLattice, LoggerLatticeManager, type McpLatticeInterface, McpLatticeManager, type McpServerInfo, MemoryLatticeManager, MemoryQueueClient, MemoryScheduleStorage, type ModelConfig, type ModelLatticeInterface, ModelLatticeManager, PinoLoggerClient, PostgresDatabase, type QueryResult, type QueueLattice, QueueLatticeManager, type RunSandboxConfig, SandboxLatticeManager, type SandboxManagerProtocol, type ScheduleLattice, ScheduleLatticeManager, type SkillLattice, SkillLatticeManager, SqlDatabaseManager, type StoreLattice, StoreLatticeManager, type StoreType, type StoreTypeMap, type TableInfo, type TableSchema, type ThreadBuffer, type ThreadBufferConfig, ThreadStatus, type ToolDefinition, type ToolLattice, ToolLatticeManager, type VectorStoreLatticeInterface, VectorStoreLatticeManager, agentLatticeManager, createInfoSqlTool, createListTablesSqlTool, createQueryCheckerSqlTool, createQuerySqlTool, describeCronExpression, embeddingsLatticeManager, eventBus, eventBus as eventBusDefault, getAgentClient, getAgentConfig, getAgentLattice, getAllAgentConfigs, getAllToolDefinitions, getCheckpointSaver, getChunkBuffer, getEmbeddingsClient, getEmbeddingsLattice, getLoggerLattice, getModelLattice, getNextCronTime, getQueueLattice, getSandBoxManager, getScheduleLattice, getStoreLattice, getToolClient, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, hasChunkBuffer, isValidCronExpression, isValidSandboxName, isValidSkillName, loggerLatticeManager, mcpManager, modelLatticeManager, normalizeSandboxName, parseCronExpression, queueLatticeManager, registerAgentLattice, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerLoggerLattice, registerModelLattice, registerQueueLattice, registerScheduleLattice, registerStoreLattice, registerToolLattice, registerVectorStoreLattice, sandboxLatticeManager, scheduleLatticeManager, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, toolLatticeManager, validateAgentInput, validateSkillName, validateToolInput, vectorStoreLatticeManager };
4287
+ /**
4288
+ * 全局加密工具
4289
+ * 用于敏感数据加密存储(如数据库密码、API 密钥等)
4290
+ *
4291
+ * @module @axiom-lattice/core/util/encryption
4292
+ */
4293
+ /**
4294
+ * 获取加密密钥
4295
+ * 优先从环境变量读取,否则使用默认值
4296
+ * @returns 32 字节的 Buffer 密钥
4297
+ */
4298
+ declare function getEncryptionKey(): Buffer;
4299
+ /**
4300
+ * 加密字符串
4301
+ * @param plaintext 明文字符串
4302
+ * @param key 可选的加密密钥,默认使用全局密钥
4303
+ * @returns 加密后的字符串 (salt:iv:ciphertext:authTag 的 base64 编码)
4304
+ */
4305
+ declare function encrypt(plaintext: string, key?: Buffer): string;
4306
+ /**
4307
+ * 解密字符串
4308
+ * @param encrypted 加密的字符串 (base64 编码)
4309
+ * @param key 可选的解密密钥,默认使用全局密钥
4310
+ * @returns 解密后的明文
4311
+ * @throws 如果解密失败(密钥错误或数据损坏)
4312
+ */
4313
+ declare function decrypt(encrypted: string, key?: Buffer): string;
4314
+ /**
4315
+ * 检查是否使用默认密钥
4316
+ * @returns 如果使用默认密钥返回 true
4317
+ */
4318
+ declare function isUsingDefaultKey(): boolean;
4319
+ /**
4320
+ * 验证加密密钥
4321
+ * 生产环境未设置 LATTICE_ENCRYPTION_KEY 时会抛出错误
4322
+ * 开发环境仅输出警告
4323
+ */
4324
+ declare function validateEncryptionKey(): void;
4325
+ /**
4326
+ * 清除缓存的密钥(用于测试或重新加载配置)
4327
+ */
4328
+ declare function clearEncryptionKeyCache(): void;
4329
+
4330
+ export { AGENT_TASK_EVENT, type AgentClient, type AgentLattice, AgentLatticeManager, AgentManager, type BackendFactory, type BackendProtocol, type BufferStats, type Chunk, ChunkBuffer, ChunkBufferLatticeManager, type ColumnInfo, CompositeBackend, ConsoleLoggerClient, type CronFields, CustomMetricsClient, type DatabaseConfig, type DatabaseType, DefaultScheduleClient, EMPTY_CONTENT_WARNING, type EditResult, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, type FileData, type FileInfo, FileSystemSkillStore, type FileSystemSkillStoreOptions, FilesystemBackend, type GrepMatch, type IMetricsServerClient, type ISqlDatabase, InMemoryAssistantStore, InMemoryChunkBuffer, InMemoryDatabaseConfigStore, InMemoryMailboxStore, InMemoryTaskListStore, InMemoryTenantStore, InMemoryThreadStore, InMemoryUserStore, InMemoryUserTenantLinkStore, type IsolatedLevel, LINE_NUMBER_WIDTH, type LoggerLattice, LoggerLatticeManager, MAX_LINE_LENGTH, type MailboxMessage, type MailboxStore, type McpLatticeInterface, McpLatticeManager, type McpServerInfo, MemoryBackend, MemoryLatticeManager, MemoryQueueClient, MemoryScheduleStorage, MessageType, MetricsServerManager, type ModelConfig, type ModelLatticeInterface, ModelLatticeManager, PinoLoggerClient, PostgresDatabase, PrometheusClient, type QueryResult, type QueueLattice, QueueLatticeManager, type RunSandboxConfig, SandboxFilesystem, SandboxLatticeManager, type SandboxManagerProtocol, type ScheduleLattice, ScheduleLatticeManager, SemanticMetricsClient, type SkillLattice, SkillLatticeManager, type SkillResource, SqlDatabaseManager, type StateAndStore, StateBackend, StoreBackend, type StoreLattice, StoreLatticeManager, type StoreType, type StoreTypeMap, TOOL_RESULT_TOKEN_LIMIT, TRUNCATION_GUIDANCE, type TableInfo, type TableSchema, type TaskEvent, type TaskListStore, type TaskSpec, TaskStatus, type TaskUpdatable, TeamAgentGraphBuilder, type TeamConfig, type TeamMiddlewareOptions, type TeamTask, type TeammateSpec, type TeammateToolsOptions, type ThreadBuffer, type ThreadBufferConfig, ThreadStatus, type ToolDefinition, type ToolLattice, ToolLatticeManager, type VectorStoreLatticeInterface, VectorStoreLatticeManager, type WriteResult, agentLatticeManager, buildGrepResultsDict, checkEmptyContent, clearEncryptionKeyCache, createAgentTeam, createFileData, createInfoSqlTool, createListMetricsDataSourcesTool, createListMetricsServersTool, createListTablesSqlTool, createQueryCheckerSqlTool, createQueryMetricDefinitionTool, createQueryMetricsListTool, createQuerySemanticMetricDataTool, createQuerySqlTool, createQueryTableDefinitionTool, createQueryTablesListTool, createTeamMiddleware, createTeammateTools, decrypt, describeCronExpression, embeddingsLatticeManager, encrypt, eventBus, eventBus as eventBusDefault, fileDataToString, formatContentWithLineNumbers, formatGrepMatches, formatGrepResults, formatReadResponse, getAgentClient, getAgentConfig, getAgentLattice, getAllAgentConfigs, getAllToolDefinitions, getCheckpointSaver, getChunkBuffer, getEmbeddingsClient, getEmbeddingsLattice, getEncryptionKey, getLoggerLattice, getModelLattice, getNextCronTime, getQueueLattice, getSandBoxManager, getScheduleLattice, getStoreLattice, getToolClient, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, globSearchFiles, grepMatchesFromFiles, grepSearchFiles, hasChunkBuffer, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, loggerLatticeManager, mcpManager, metricsServerManager, modelLatticeManager, normalizeSandboxName, parseCronExpression, performStringReplacement, queueLatticeManager, registerAgentLattice, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerLoggerLattice, registerModelLattice, registerQueueLattice, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, toolLatticeManager, truncateIfTooLong, unregisterTeammateAgent, updateFileData, validateAgentInput, validateEncryptionKey, validatePath, validateSkillName, validateToolInput, vectorStoreLatticeManager };