@anvia/graph 0.0.0-bootstrap.0 → 1.0.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Indra Zulfi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
1
  # @anvia/graph
2
2
 
3
- Bootstrap placeholder. The production package is published from the Anvia release workflow.
3
+ Provider-neutral schema, extraction, retrieval-context, and tool primitives for knowledge graphs.
4
+
5
+ ```ts
6
+ import { defineGraphSchema, extractGraphFacts } from "@anvia/graph";
7
+ import { z } from "zod";
8
+
9
+ const schema = defineGraphSchema({
10
+ nodes: {
11
+ Product: {
12
+ description: "A product or service.",
13
+ identity: ["id"],
14
+ properties: z.strictObject({ id: z.string(), name: z.string() }),
15
+ },
16
+ },
17
+ relationships: {},
18
+ });
19
+
20
+ const facts = await extractGraphFacts({ model, schema, chunks });
21
+ ```
22
+
23
+ Database provisioning, persistence, and query execution belong to graph adapter packages such as
24
+ `@anvia/neo4j` and `@anvia/memgraph`.
25
+
26
+ ## Search tool
27
+
28
+ Create the same Agent tool for any graph adapter implementing `GraphContextRetriever`:
29
+
30
+ ```ts
31
+ import { createGraphSearchTool } from "@anvia/graph";
32
+
33
+ const searchGraph = createGraphSearchTool({
34
+ name: "search_graph",
35
+ description: "Search connected entities and supporting evidence.",
36
+ graph,
37
+ model: embeddingModel,
38
+ search: {
39
+ type: "vector",
40
+ seeds: ["entities"],
41
+ topK: 8,
42
+ },
43
+ traversal: {
44
+ relationships: ["AFFECTS"],
45
+ direction: "both",
46
+ maxDepth: 2,
47
+ maxNodes: 40,
48
+ maxRelationships: 80,
49
+ },
50
+ evidence: { type: "chunks", maxChunks: 12 },
51
+ });
52
+ ```
53
+
54
+ The graph registration controls which evidence modes are valid. Managed graphs can hydrate stored
55
+ chunks, while existing graph registrations use `{ type: "none" }`.
56
+
57
+ ## Exploration
58
+
59
+ Adapters implementing `GraphExplorer` expose a portable, bounded view for visualization:
60
+
61
+ ```ts
62
+ const overview = await graph.explore({
63
+ mode: "overview",
64
+ nodeTypes: ["Product"],
65
+ maxNodes: 100,
66
+ maxRelationships: 200,
67
+ });
68
+
69
+ const neighborhood = await graph.explore({
70
+ mode: "expand",
71
+ nodeIds: [overview.nodes[0]!.id],
72
+ direction: "both",
73
+ maxDepth: 1,
74
+ });
75
+ ```
76
+
77
+ Explorer IDs are opaque and provider-specific. They are intended for follow-up expansion within the
78
+ same graph, not persistence or cross-provider migration. Adapters cap overview and expansion requests,
79
+ return truncation metadata, and omit reserved Anvia properties such as stored embeddings.
@@ -0,0 +1,85 @@
1
+ // src/explore.ts
2
+ var defaultMaxNodes = 100;
3
+ var maximumNodes = 500;
4
+ var defaultMaxRelationships = 200;
5
+ var maximumRelationships = 1e3;
6
+ var defaultMaxDepth = 1;
7
+ var maximumDepth = 4;
8
+ var maximumRoots = 20;
9
+ function resolveGraphExploreOptions(schema, options) {
10
+ const nodeTypes = resolveNames(options.nodeTypes, Object.keys(schema.nodes), "node type");
11
+ const relationships = resolveNames(
12
+ options.relationships,
13
+ Object.keys(schema.relationships),
14
+ "relationship type",
15
+ true
16
+ );
17
+ const base = {
18
+ nodeTypes,
19
+ relationships,
20
+ maxNodes: boundedInteger(options.maxNodes, defaultMaxNodes, maximumNodes, "maxNodes"),
21
+ maxRelationships: boundedInteger(
22
+ options.maxRelationships,
23
+ defaultMaxRelationships,
24
+ maximumRelationships,
25
+ "maxRelationships"
26
+ )
27
+ };
28
+ if (options.abortSignal !== void 0) base.abortSignal = options.abortSignal;
29
+ if (options.mode === "overview") {
30
+ return { ...base, mode: "overview" };
31
+ }
32
+ const nodeIds = uniqueNonEmptyStrings(options.nodeIds, "node id");
33
+ if (nodeIds.length === 0) {
34
+ throw new TypeError("Graph expansion requires at least one node id.");
35
+ }
36
+ if (nodeIds.length > maximumRoots) {
37
+ throw new RangeError(`Graph expansion accepts at most ${maximumRoots} root nodes.`);
38
+ }
39
+ const direction = options.direction ?? "both";
40
+ if (direction !== "outgoing" && direction !== "incoming" && direction !== "both") {
41
+ throw new TypeError("Graph expansion direction must be outgoing, incoming, or both.");
42
+ }
43
+ return {
44
+ ...base,
45
+ mode: "expand",
46
+ nodeIds,
47
+ direction,
48
+ maxDepth: boundedInteger(options.maxDepth, defaultMaxDepth, maximumDepth, "maxDepth")
49
+ };
50
+ }
51
+ function resolveNames(selected, available, label, allowEmpty = false) {
52
+ const values = selected === void 0 ? [...available] : uniqueNonEmptyStrings(selected, label);
53
+ if (!allowEmpty && values.length === 0) {
54
+ throw new TypeError(`Graph exploration requires at least one ${label}.`);
55
+ }
56
+ const known = new Set(available);
57
+ for (const value of values) {
58
+ if (!known.has(value))
59
+ throw new TypeError(`Graph exploration references unknown ${label} ${value}.`);
60
+ }
61
+ return values;
62
+ }
63
+ function uniqueNonEmptyStrings(values, label) {
64
+ const unique = /* @__PURE__ */ new Set();
65
+ for (const value of values) {
66
+ if (typeof value !== "string" || value.length === 0) {
67
+ throw new TypeError(`Graph ${label} must be a non-empty string.`);
68
+ }
69
+ if (unique.has(value)) throw new TypeError(`Duplicate graph ${label}: ${value}.`);
70
+ unique.add(value);
71
+ }
72
+ return [...unique];
73
+ }
74
+ function boundedInteger(value, fallback, maximum, label) {
75
+ const resolved = value ?? fallback;
76
+ if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > maximum) {
77
+ throw new RangeError(`Graph exploration ${label} must be between 1 and ${maximum}.`);
78
+ }
79
+ return resolved;
80
+ }
81
+
82
+ export {
83
+ resolveGraphExploreOptions
84
+ };
85
+ //# sourceMappingURL=chunk-N3CKMOPE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/explore.ts"],"sourcesContent":["import type { GraphExploreDirection, GraphExploreOptions, GraphSchemaLike } from \"./types.js\";\n\nconst defaultMaxNodes = 100;\nconst maximumNodes = 500;\nconst defaultMaxRelationships = 200;\nconst maximumRelationships = 1_000;\nconst defaultMaxDepth = 1;\nconst maximumDepth = 4;\nconst maximumRoots = 20;\n\ntype ResolvedGraphExploreBase = Readonly<{\n nodeTypes: readonly string[];\n relationships: readonly string[];\n maxNodes: number;\n maxRelationships: number;\n abortSignal?: AbortSignal | undefined;\n}>;\n\nexport type ResolvedGraphExploreOverviewOptions = ResolvedGraphExploreBase &\n Readonly<{ mode: \"overview\" }>;\n\nexport type ResolvedGraphExploreExpandOptions = ResolvedGraphExploreBase &\n Readonly<{\n mode: \"expand\";\n nodeIds: readonly string[];\n direction: GraphExploreDirection;\n maxDepth: number;\n }>;\n\nexport type ResolvedGraphExploreOptions =\n | ResolvedGraphExploreOverviewOptions\n | ResolvedGraphExploreExpandOptions;\n\nexport function resolveGraphExploreOptions<Schema extends GraphSchemaLike>(\n schema: Schema,\n options: GraphExploreOptions<Schema>,\n): ResolvedGraphExploreOptions {\n const nodeTypes = resolveNames(options.nodeTypes, Object.keys(schema.nodes), \"node type\");\n const relationships = resolveNames(\n options.relationships,\n Object.keys(schema.relationships),\n \"relationship type\",\n true,\n );\n const base: {\n nodeTypes: string[];\n relationships: string[];\n maxNodes: number;\n maxRelationships: number;\n abortSignal?: AbortSignal | undefined;\n } = {\n nodeTypes,\n relationships,\n maxNodes: boundedInteger(options.maxNodes, defaultMaxNodes, maximumNodes, \"maxNodes\"),\n maxRelationships: boundedInteger(\n options.maxRelationships,\n defaultMaxRelationships,\n maximumRelationships,\n \"maxRelationships\",\n ),\n };\n if (options.abortSignal !== undefined) base.abortSignal = options.abortSignal;\n if (options.mode === \"overview\") {\n return { ...base, mode: \"overview\" };\n }\n const nodeIds = uniqueNonEmptyStrings(options.nodeIds, \"node id\");\n if (nodeIds.length === 0) {\n throw new TypeError(\"Graph expansion requires at least one node id.\");\n }\n if (nodeIds.length > maximumRoots) {\n throw new RangeError(`Graph expansion accepts at most ${maximumRoots} root nodes.`);\n }\n const direction = options.direction ?? \"both\";\n if (direction !== \"outgoing\" && direction !== \"incoming\" && direction !== \"both\") {\n throw new TypeError(\"Graph expansion direction must be outgoing, incoming, or both.\");\n }\n return {\n ...base,\n mode: \"expand\",\n nodeIds,\n direction,\n maxDepth: boundedInteger(options.maxDepth, defaultMaxDepth, maximumDepth, \"maxDepth\"),\n };\n}\n\nfunction resolveNames(\n selected: readonly string[] | undefined,\n available: readonly string[],\n label: string,\n allowEmpty = false,\n): string[] {\n const values = selected === undefined ? [...available] : uniqueNonEmptyStrings(selected, label);\n if (!allowEmpty && values.length === 0) {\n throw new TypeError(`Graph exploration requires at least one ${label}.`);\n }\n const known = new Set(available);\n for (const value of values) {\n if (!known.has(value))\n throw new TypeError(`Graph exploration references unknown ${label} ${value}.`);\n }\n return values;\n}\n\nfunction uniqueNonEmptyStrings(values: readonly string[], label: string): string[] {\n const unique = new Set<string>();\n for (const value of values) {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`Graph ${label} must be a non-empty string.`);\n }\n if (unique.has(value)) throw new TypeError(`Duplicate graph ${label}: ${value}.`);\n unique.add(value);\n }\n return [...unique];\n}\n\nfunction boundedInteger(\n value: number | undefined,\n fallback: number,\n maximum: number,\n label: string,\n): number {\n const resolved = value ?? fallback;\n if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > maximum) {\n throw new RangeError(`Graph exploration ${label} must be between 1 and ${maximum}.`);\n }\n return resolved;\n}\n"],"mappings":";AAEA,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,eAAe;AAyBd,SAAS,2BACd,QACA,SAC6B;AAC7B,QAAM,YAAY,aAAa,QAAQ,WAAW,OAAO,KAAK,OAAO,KAAK,GAAG,WAAW;AACxF,QAAM,gBAAgB;AAAA,IACpB,QAAQ;AAAA,IACR,OAAO,KAAK,OAAO,aAAa;AAAA,IAChC;AAAA,IACA;AAAA,EACF;AACA,QAAM,OAMF;AAAA,IACF;AAAA,IACA;AAAA,IACA,UAAU,eAAe,QAAQ,UAAU,iBAAiB,cAAc,UAAU;AAAA,IACpF,kBAAkB;AAAA,MAChB,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,OAAW,MAAK,cAAc,QAAQ;AAClE,MAAI,QAAQ,SAAS,YAAY;AAC/B,WAAO,EAAE,GAAG,MAAM,MAAM,WAAW;AAAA,EACrC;AACA,QAAM,UAAU,sBAAsB,QAAQ,SAAS,SAAS;AAChE,MAAI,QAAQ,WAAW,GAAG;AACxB,UAAM,IAAI,UAAU,gDAAgD;AAAA,EACtE;AACA,MAAI,QAAQ,SAAS,cAAc;AACjC,UAAM,IAAI,WAAW,mCAAmC,YAAY,cAAc;AAAA,EACpF;AACA,QAAM,YAAY,QAAQ,aAAa;AACvC,MAAI,cAAc,cAAc,cAAc,cAAc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/core';
2
+ import { EmbeddingModel } from '@anvia/core/embeddings';
3
+ import { Tool } from '@anvia/core/tool';
4
+ import { z } from 'zod';
5
+
6
+ type GraphPropertyPrimitive = string | number | boolean;
7
+ type GraphPropertyValue = GraphPropertyPrimitive | readonly string[] | readonly number[] | readonly boolean[];
8
+ type GraphProperties = Readonly<Record<string, GraphPropertyValue>>;
9
+ type GraphNodeIdentity = Readonly<Record<string, GraphPropertyPrimitive>>;
10
+ type GraphNodeDefinition = Readonly<{
11
+ description: string;
12
+ identity: readonly string[];
13
+ properties: z.ZodObject<z.ZodRawShape>;
14
+ }>;
15
+ type GraphRelationshipDefinition = Readonly<{
16
+ description: string;
17
+ from: string;
18
+ to: string;
19
+ identity?: readonly string[] | undefined;
20
+ properties: z.ZodObject<z.ZodRawShape>;
21
+ }>;
22
+ type GraphSchemaOptions = Readonly<{
23
+ nodes: Readonly<Record<string, GraphNodeDefinition>>;
24
+ relationships: Readonly<Record<string, GraphRelationshipDefinition>>;
25
+ }>;
26
+ type GraphSchema<Options extends GraphSchemaOptions = GraphSchemaOptions> = Readonly<Options & {
27
+ kind: "graph-schema";
28
+ }>;
29
+ type GraphSchemaLike<Options extends GraphSchemaOptions = GraphSchemaOptions> = Readonly<Options & {
30
+ kind: string;
31
+ }>;
32
+ type NodeDefinitions<Schema extends GraphSchemaLike> = Schema["nodes"];
33
+ type RelationshipDefinitions<Schema extends GraphSchemaLike> = Schema["relationships"];
34
+ type GraphEntity<Schema extends GraphSchemaLike = GraphSchemaLike> = {
35
+ [Type in keyof NodeDefinitions<Schema> & string]: Readonly<{
36
+ key: string;
37
+ type: Type;
38
+ identity: GraphNodeIdentity;
39
+ properties: z.output<NodeDefinitions<Schema>[Type]["properties"]> & GraphProperties;
40
+ sourceChunkIds: readonly string[];
41
+ }>;
42
+ }[keyof NodeDefinitions<Schema> & string];
43
+ type GraphRelationship<Schema extends GraphSchemaLike = GraphSchemaLike> = {
44
+ [Type in keyof RelationshipDefinitions<Schema> & string]: Readonly<{
45
+ key: string;
46
+ type: Type;
47
+ from: string;
48
+ to: string;
49
+ properties: z.output<RelationshipDefinitions<Schema>[Type]["properties"]> & GraphProperties;
50
+ sourceChunkIds: readonly string[];
51
+ }>;
52
+ }[keyof RelationshipDefinitions<Schema> & string];
53
+ type GraphMention = Readonly<{
54
+ chunkId: string;
55
+ entityKey: string;
56
+ }>;
57
+ type GraphFacts<Schema extends GraphSchemaLike = GraphSchemaLike> = Readonly<{
58
+ entities: readonly GraphEntity<Schema>[];
59
+ relationships: readonly GraphRelationship<Schema>[];
60
+ mentions: readonly GraphMention[];
61
+ }>;
62
+ type GraphChunk<Metadata extends GraphProperties = GraphProperties> = Readonly<{
63
+ id: string;
64
+ documentId: string;
65
+ index: number;
66
+ text: string;
67
+ metadata?: Metadata | undefined;
68
+ }>;
69
+ type GraphDocument<Properties extends GraphProperties = GraphProperties> = Readonly<{
70
+ id: string;
71
+ properties?: Properties | undefined;
72
+ }>;
73
+ type ExtractGraphFactsOptions<Schema extends GraphSchemaLike, Model extends CompletionModel> = Readonly<{
74
+ model: Model;
75
+ schema: Schema;
76
+ chunks: readonly GraphChunk[];
77
+ instructions?: string | undefined;
78
+ retries?: RetrySetting | undefined;
79
+ concurrency?: number | undefined;
80
+ abortSignal?: AbortSignal | undefined;
81
+ }>;
82
+ type ExtractGraphFactsResult<Schema extends GraphSchemaLike> = Readonly<{
83
+ output: GraphFacts<Schema>;
84
+ usage: Usage;
85
+ }>;
86
+ type GraphVectorSearchOptions = Readonly<{
87
+ type: "vector";
88
+ seeds: readonly string[];
89
+ topK: number;
90
+ minScore?: number | undefined;
91
+ }>;
92
+ type GraphHybridSearchOptions = Readonly<{
93
+ type: "hybrid";
94
+ seeds: readonly string[];
95
+ topK: number;
96
+ candidatesPerSeed: number;
97
+ rrfK: number;
98
+ }>;
99
+ type GraphSearchOptions = GraphVectorSearchOptions | GraphHybridSearchOptions;
100
+ type GraphEvidenceOptions = Readonly<{
101
+ type: "none";
102
+ }> | Readonly<{
103
+ type: "chunks";
104
+ maxChunks: number;
105
+ }>;
106
+ type GraphTraversalOptions<Schema extends GraphSchemaLike = GraphSchemaLike> = Readonly<{
107
+ relationships: readonly (keyof Schema["relationships"] & string)[];
108
+ direction: "outgoing" | "incoming" | "both";
109
+ maxDepth: number;
110
+ maxNodes: number;
111
+ maxRelationships: number;
112
+ }>;
113
+ type GraphContextSeed = Readonly<{
114
+ key: string;
115
+ type: string;
116
+ score: number;
117
+ properties: GraphProperties;
118
+ sourceChunkIds: readonly string[];
119
+ }>;
120
+ type GraphContextNode = Readonly<{
121
+ key: string;
122
+ type: string;
123
+ identity: GraphNodeIdentity;
124
+ properties: GraphProperties;
125
+ sourceChunkIds: readonly string[];
126
+ }>;
127
+ type GraphContextRelationship = Readonly<{
128
+ key: string;
129
+ type: string;
130
+ from: string;
131
+ to: string;
132
+ properties: GraphProperties;
133
+ sourceChunkIds: readonly string[];
134
+ }>;
135
+ type GraphEvidence = Readonly<{
136
+ chunkId: string;
137
+ documentId: string;
138
+ index: number;
139
+ text: string;
140
+ metadata: GraphProperties;
141
+ }>;
142
+ type GraphContext = Readonly<{
143
+ seeds: readonly GraphContextSeed[];
144
+ nodes: readonly GraphContextNode[];
145
+ relationships: readonly GraphContextRelationship[];
146
+ evidence: readonly GraphEvidence[];
147
+ }>;
148
+ type GraphEvidenceCapability = "none" | "chunks";
149
+ type GraphEvidenceFor<Capability extends GraphEvidenceCapability> = Extract<GraphEvidenceOptions, {
150
+ type: "none";
151
+ }> | (Capability extends "chunks" ? Extract<GraphEvidenceOptions, {
152
+ type: "chunks";
153
+ }> : never);
154
+ type GraphRetrieveOptions<Schema extends GraphSchemaLike, Evidence extends GraphEvidenceCapability = GraphEvidenceCapability> = Readonly<{
155
+ model: EmbeddingModel;
156
+ query: string;
157
+ search: GraphSearchOptions;
158
+ traversal: GraphTraversalOptions<Schema>;
159
+ evidence: GraphEvidenceFor<Evidence>;
160
+ retries?: RetrySetting | undefined;
161
+ abortSignal?: AbortSignal | undefined;
162
+ }>;
163
+ interface GraphContextRetriever<Schema extends GraphSchemaLike = GraphSchemaLike, Evidence extends GraphEvidenceCapability = GraphEvidenceCapability> {
164
+ readonly evidenceCapability: Evidence;
165
+ retrieve(options: GraphRetrieveOptions<Schema, Evidence>): Promise<GraphContext>;
166
+ }
167
+ type GraphExploreDirection = "outgoing" | "incoming" | "both";
168
+ type GraphExploreOverviewOptions<Schema extends GraphSchemaLike> = Readonly<{
169
+ mode: "overview";
170
+ nodeTypes?: readonly (keyof Schema["nodes"] & string)[] | undefined;
171
+ relationships?: readonly (keyof Schema["relationships"] & string)[] | undefined;
172
+ maxNodes?: number | undefined;
173
+ maxRelationships?: number | undefined;
174
+ abortSignal?: AbortSignal | undefined;
175
+ }>;
176
+ type GraphExploreExpandOptions<Schema extends GraphSchemaLike> = Readonly<{
177
+ mode: "expand";
178
+ nodeIds: readonly string[];
179
+ nodeTypes?: readonly (keyof Schema["nodes"] & string)[] | undefined;
180
+ relationships?: readonly (keyof Schema["relationships"] & string)[] | undefined;
181
+ direction?: GraphExploreDirection | undefined;
182
+ maxDepth?: number | undefined;
183
+ maxNodes?: number | undefined;
184
+ maxRelationships?: number | undefined;
185
+ abortSignal?: AbortSignal | undefined;
186
+ }>;
187
+ type GraphExploreOptions<Schema extends GraphSchemaLike> = GraphExploreOverviewOptions<Schema> | GraphExploreExpandOptions<Schema>;
188
+ type GraphExploreNode = Readonly<{
189
+ id: string;
190
+ key?: string | undefined;
191
+ type: string;
192
+ identity: GraphNodeIdentity;
193
+ properties: GraphProperties;
194
+ }>;
195
+ type GraphExploreRelationship = Readonly<{
196
+ id: string;
197
+ key?: string | undefined;
198
+ type: string;
199
+ from: string;
200
+ to: string;
201
+ properties: GraphProperties;
202
+ }>;
203
+ type GraphExploreResult = Readonly<{
204
+ nodes: readonly GraphExploreNode[];
205
+ relationships: readonly GraphExploreRelationship[];
206
+ truncated: Readonly<{
207
+ nodes: boolean;
208
+ relationships: boolean;
209
+ }>;
210
+ }>;
211
+ interface GraphExplorer<Schema extends GraphSchemaLike = GraphSchemaLike> {
212
+ readonly schema: Schema;
213
+ explore(options: GraphExploreOptions<Schema>): Promise<GraphExploreResult>;
214
+ }
215
+ type CreateGraphSearchToolOptions<Schema extends GraphSchemaLike, Retriever extends GraphContextRetriever<Schema> = GraphContextRetriever<Schema>> = Readonly<{
216
+ name: string;
217
+ description: string;
218
+ graph: Retriever;
219
+ model: EmbeddingModel;
220
+ search: GraphSearchOptions;
221
+ traversal: GraphTraversalOptions<Schema>;
222
+ evidence: GraphEvidenceFor<Retriever["evidenceCapability"]>;
223
+ retries?: RetrySetting | undefined;
224
+ }>;
225
+ type GraphSearchTool = Tool<{
226
+ query: string;
227
+ }, GraphContext>;
228
+ type GraphChangeCounts = Readonly<{
229
+ created: number;
230
+ updated: number;
231
+ deleted: number;
232
+ unchanged: number;
233
+ }>;
234
+ type GraphWriteResult = Readonly<{
235
+ documents: GraphChangeCounts;
236
+ chunks: GraphChangeCounts;
237
+ entities: GraphChangeCounts;
238
+ relationships: GraphChangeCounts;
239
+ mentions: GraphChangeCounts;
240
+ }>;
241
+
242
+ type ResolvedGraphExploreBase = Readonly<{
243
+ nodeTypes: readonly string[];
244
+ relationships: readonly string[];
245
+ maxNodes: number;
246
+ maxRelationships: number;
247
+ abortSignal?: AbortSignal | undefined;
248
+ }>;
249
+ type ResolvedGraphExploreOverviewOptions = ResolvedGraphExploreBase & Readonly<{
250
+ mode: "overview";
251
+ }>;
252
+ type ResolvedGraphExploreExpandOptions = ResolvedGraphExploreBase & Readonly<{
253
+ mode: "expand";
254
+ nodeIds: readonly string[];
255
+ direction: GraphExploreDirection;
256
+ maxDepth: number;
257
+ }>;
258
+ type ResolvedGraphExploreOptions = ResolvedGraphExploreOverviewOptions | ResolvedGraphExploreExpandOptions;
259
+ declare function resolveGraphExploreOptions<Schema extends GraphSchemaLike>(schema: Schema, options: GraphExploreOptions<Schema>): ResolvedGraphExploreOptions;
260
+
261
+ export { type GraphExplorer as A, type GraphFacts as B, type CreateGraphSearchToolOptions as C, type GraphHybridSearchOptions as D, type ExtractGraphFactsOptions as E, type GraphMention as F, type GraphSchemaLike as G, type GraphNodeDefinition as H, type GraphNodeIdentity as I, type GraphPropertyPrimitive as J, type GraphRelationship as K, type GraphRelationshipDefinition as L, type GraphRetrieveOptions as M, type GraphSearchOptions as N, type GraphTraversalOptions as O, type GraphVectorSearchOptions as P, type GraphWriteResult as Q, type ResolvedGraphExploreExpandOptions as R, type ResolvedGraphExploreOptions as S, type ResolvedGraphExploreOverviewOptions as T, resolveGraphExploreOptions as U, type ExtractGraphFactsResult as a, type GraphSchemaOptions as b, type GraphSchema as c, type GraphProperties as d, type GraphPropertyValue as e, type GraphContextRetriever as f, type GraphSearchTool as g, type GraphChangeCounts as h, type GraphChunk as i, type GraphContext as j, type GraphContextNode as k, type GraphContextRelationship as l, type GraphContextSeed as m, type GraphDocument as n, type GraphEntity as o, type GraphEvidence as p, type GraphEvidenceCapability as q, type GraphEvidenceFor as r, type GraphEvidenceOptions as s, type GraphExploreDirection as t, type GraphExploreExpandOptions as u, type GraphExploreNode as v, type GraphExploreOptions as w, type GraphExploreOverviewOptions as x, type GraphExploreRelationship as y, type GraphExploreResult as z };
@@ -0,0 +1,5 @@
1
+ export { R as ResolvedGraphExploreExpandOptions, S as ResolvedGraphExploreOptions, T as ResolvedGraphExploreOverviewOptions, U as resolveGraphExploreOptions } from './explore-B2BuWiSK.js';
2
+ import '@anvia/core';
3
+ import '@anvia/core/embeddings';
4
+ import '@anvia/core/tool';
5
+ import 'zod';
@@ -0,0 +1,7 @@
1
+ import {
2
+ resolveGraphExploreOptions
3
+ } from "./chunk-N3CKMOPE.js";
4
+ export {
5
+ resolveGraphExploreOptions
6
+ };
7
+ //# sourceMappingURL=explore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,28 @@
1
+ import * as _anvia_core from '@anvia/core';
2
+ import { G as GraphSchemaLike, E as ExtractGraphFactsOptions, a as ExtractGraphFactsResult, b as GraphSchemaOptions, c as GraphSchema, d as GraphProperties, e as GraphPropertyValue, f as GraphContextRetriever, C as CreateGraphSearchToolOptions, g as GraphSearchTool } from './explore-B2BuWiSK.js';
3
+ export { h as GraphChangeCounts, i as GraphChunk, j as GraphContext, k as GraphContextNode, l as GraphContextRelationship, m as GraphContextSeed, n as GraphDocument, o as GraphEntity, p as GraphEvidence, q as GraphEvidenceCapability, r as GraphEvidenceFor, s as GraphEvidenceOptions, t as GraphExploreDirection, u as GraphExploreExpandOptions, v as GraphExploreNode, w as GraphExploreOptions, x as GraphExploreOverviewOptions, y as GraphExploreRelationship, z as GraphExploreResult, A as GraphExplorer, B as GraphFacts, D as GraphHybridSearchOptions, F as GraphMention, H as GraphNodeDefinition, I as GraphNodeIdentity, J as GraphPropertyPrimitive, K as GraphRelationship, L as GraphRelationshipDefinition, M as GraphRetrieveOptions, N as GraphSearchOptions, O as GraphTraversalOptions, P as GraphVectorSearchOptions, Q as GraphWriteResult, R as ResolvedGraphExploreExpandOptions, S as ResolvedGraphExploreOptions, T as ResolvedGraphExploreOverviewOptions, U as resolveGraphExploreOptions } from './explore-B2BuWiSK.js';
4
+ import '@anvia/core/embeddings';
5
+ import '@anvia/core/tool';
6
+ import 'zod';
7
+
8
+ declare function extractGraphFacts<Schema extends GraphSchemaLike, Model extends _anvia_core.CompletionModel>(options: ExtractGraphFactsOptions<Schema, Model>): Promise<ExtractGraphFactsResult<Schema>>;
9
+ declare class GraphFactConflictError extends Error {
10
+ readonly factKey: string;
11
+ readonly sourceChunkIds: readonly string[];
12
+ constructor(factKey: string, sourceChunkIds: readonly string[]);
13
+ }
14
+
15
+ declare const graphReservedPropertyPrefix = "__anvia_";
16
+ declare function defineGraphSchema<const Options extends GraphSchemaOptions>(options: Options): GraphSchema<Options>;
17
+ declare function validateGraphSchemaOptions(options: GraphSchemaOptions): void;
18
+ declare function freezeGraphSchema<const Options extends GraphSchemaOptions, const Kind extends string>(options: Options, kind: Kind): Readonly<Options & {
19
+ kind: Kind;
20
+ }>;
21
+ declare function parseGraphProperties(value: unknown, label: string): GraphProperties;
22
+ declare function parseGraphPropertyValue(value: unknown, label: string): GraphPropertyValue;
23
+ declare function assertGraphName(value: string, label: string): void;
24
+ declare function assertGraphPropertyName(value: string): void;
25
+
26
+ declare function createGraphSearchTool<Schema extends GraphSchemaLike, Retriever extends GraphContextRetriever<Schema>>(options: CreateGraphSearchToolOptions<Schema, Retriever>): GraphSearchTool;
27
+
28
+ export { CreateGraphSearchToolOptions, ExtractGraphFactsOptions, ExtractGraphFactsResult, GraphContextRetriever, GraphFactConflictError, GraphProperties, GraphPropertyValue, GraphSchema, GraphSchemaLike, GraphSchemaOptions, GraphSearchTool, assertGraphName, assertGraphPropertyName, createGraphSearchTool, defineGraphSchema, extractGraphFacts, freezeGraphSchema, graphReservedPropertyPrefix, parseGraphProperties, parseGraphPropertyValue, validateGraphSchemaOptions };
package/dist/index.js ADDED
@@ -0,0 +1,507 @@
1
+ import {
2
+ resolveGraphExploreOptions
3
+ } from "./chunk-N3CKMOPE.js";
4
+
5
+ // src/extract.ts
6
+ import { Usage } from "@anvia/core";
7
+ import { extract } from "@anvia/core/extractor";
8
+ import { z as z2 } from "zod";
9
+
10
+ // src/schema.ts
11
+ import { z } from "zod";
12
+ var graphReservedPropertyPrefix = "__anvia_";
13
+ function defineGraphSchema(options) {
14
+ validateGraphSchemaOptions(options);
15
+ return freezeGraphSchema(options, "graph-schema");
16
+ }
17
+ function validateGraphSchemaOptions(options) {
18
+ if (Object.keys(options.nodes).length === 0) {
19
+ throw new TypeError("A graph schema requires at least one node type.");
20
+ }
21
+ for (const [type, definition] of Object.entries(options.nodes)) {
22
+ assertGraphName(type, "node type");
23
+ assertDescription(definition.description, `node ${type}`);
24
+ if (!(definition.properties instanceof z.ZodObject)) {
25
+ throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);
26
+ }
27
+ assertExactPropertySchema(definition.properties, `node ${type}`);
28
+ if (definition.identity.length === 0 || new Set(definition.identity).size !== definition.identity.length) {
29
+ throw new TypeError(`Node ${type} must declare unique identity properties.`);
30
+ }
31
+ for (const property of definition.identity) {
32
+ assertGraphPropertyName(property);
33
+ if (!(property in definition.properties.shape)) {
34
+ throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);
35
+ }
36
+ }
37
+ for (const property of Object.keys(definition.properties.shape)) {
38
+ assertGraphPropertyName(property);
39
+ }
40
+ }
41
+ for (const [type, definition] of Object.entries(options.relationships)) {
42
+ assertGraphName(type, "relationship type");
43
+ assertDescription(definition.description, `relationship ${type}`);
44
+ if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {
45
+ throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);
46
+ }
47
+ if (!(definition.properties instanceof z.ZodObject)) {
48
+ throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);
49
+ }
50
+ assertExactPropertySchema(definition.properties, `relationship ${type}`);
51
+ const identity = definition.identity ?? [];
52
+ if (new Set(identity).size !== identity.length) {
53
+ throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);
54
+ }
55
+ for (const property of Object.keys(definition.properties.shape)) {
56
+ assertGraphPropertyName(property);
57
+ }
58
+ for (const property of identity) {
59
+ if (!(property in definition.properties.shape)) {
60
+ throw new TypeError(
61
+ `Identity property ${property} is not declared by relationship ${type}.`
62
+ );
63
+ }
64
+ }
65
+ }
66
+ }
67
+ function freezeGraphSchema(options, kind) {
68
+ const nodes = Object.fromEntries(
69
+ Object.entries(options.nodes).map(([type, definition]) => [
70
+ type,
71
+ Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) })
72
+ ])
73
+ );
74
+ const relationships = Object.fromEntries(
75
+ Object.entries(options.relationships).map(([type, definition]) => {
76
+ const copy = { ...definition };
77
+ if (definition.identity !== void 0) {
78
+ Object.assign(copy, { identity: Object.freeze([...definition.identity]) });
79
+ }
80
+ return [type, Object.freeze(copy)];
81
+ })
82
+ );
83
+ return Object.freeze({
84
+ nodes: Object.freeze(nodes),
85
+ relationships: Object.freeze(relationships),
86
+ kind
87
+ });
88
+ }
89
+ function parseGraphProperties(value, label) {
90
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
91
+ throw new TypeError(`${label} must be an object of graph property values.`);
92
+ }
93
+ const output = {};
94
+ for (const [key, item] of Object.entries(value)) {
95
+ assertGraphPropertyName(key);
96
+ output[key] = parseGraphPropertyValue(item, `${label}.${key}`);
97
+ }
98
+ return output;
99
+ }
100
+ function parseGraphPropertyValue(value, label) {
101
+ if (typeof value === "string" || typeof value === "boolean") return value;
102
+ if (typeof value === "number") {
103
+ if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);
104
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
105
+ throw new TypeError(`${label} must be a safe integer.`);
106
+ }
107
+ return value;
108
+ }
109
+ if (Array.isArray(value)) {
110
+ if (value.length === 0) return [];
111
+ const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));
112
+ const type = typeof parsed[0];
113
+ if (!parsed.every((item) => typeof item === type)) {
114
+ throw new TypeError(`${label} must be a homogeneous array.`);
115
+ }
116
+ return parsed;
117
+ }
118
+ throw new TypeError(`${label} is not a supported graph property value.`);
119
+ }
120
+ function assertGraphName(value, label) {
121
+ if (typeof value !== "string" || value.length === 0) {
122
+ throw new TypeError(`${label} must be a non-empty string.`);
123
+ }
124
+ }
125
+ function assertGraphPropertyName(value) {
126
+ assertGraphName(value, "graph property name");
127
+ if (value.startsWith(graphReservedPropertyPrefix)) {
128
+ throw new TypeError(
129
+ `Graph property names beginning with ${graphReservedPropertyPrefix} are reserved.`
130
+ );
131
+ }
132
+ }
133
+ function parsePrimitive(value, label) {
134
+ const parsed = parseGraphPropertyValue(value, label);
135
+ if (typeof parsed === "string" || typeof parsed === "number" || typeof parsed === "boolean") {
136
+ return parsed;
137
+ }
138
+ throw new TypeError(`${label} must be a primitive property value.`);
139
+ }
140
+ function assertDescription(value, label) {
141
+ if (typeof value !== "string" || value.trim().length === 0) {
142
+ throw new TypeError(`${label} requires a non-empty description.`);
143
+ }
144
+ }
145
+ function assertExactPropertySchema(schema, label) {
146
+ const definition = schema._zod.def;
147
+ if (!(definition.catchall instanceof z.ZodNever)) {
148
+ throw new TypeError(`${label} properties must use a strict Zod object schema.`);
149
+ }
150
+ for (const [property, propertySchema] of Object.entries(schema.shape)) {
151
+ assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, /* @__PURE__ */ new Set());
152
+ }
153
+ }
154
+ function assertNonEffectfulSchema(value, label, visited) {
155
+ if (!(value instanceof z.ZodType)) throw new TypeError(`${label} must be a Zod schema.`);
156
+ if (visited.has(value)) return;
157
+ visited.add(value);
158
+ const definition = value._zod.def;
159
+ const type = definition.type;
160
+ if (definition.coerce === true || type === "default" || type === "prefault" || type === "catch" || type === "transform" || type === "pipe") {
161
+ throw new TypeError(
162
+ `${label} must not coerce, default, transform, preprocess, or catch values.`
163
+ );
164
+ }
165
+ const checks = definition.checks;
166
+ if (Array.isArray(checks) && checks.some((check) => {
167
+ if (typeof check !== "object" || check === null) return false;
168
+ return check._zod?.def?.check === "overwrite";
169
+ })) {
170
+ throw new TypeError(`${label} must not normalize or overwrite values.`);
171
+ }
172
+ for (const child of schemaChildren(definition)) assertNonEffectfulSchema(child, label, visited);
173
+ }
174
+ function schemaChildren(definition) {
175
+ const children = [];
176
+ for (const key of ["innerType", "element", "left", "right", "rest", "keyType", "valueType"]) {
177
+ const value = definition[key];
178
+ if (value instanceof z.ZodType) children.push(value);
179
+ }
180
+ for (const key of ["options", "items"]) {
181
+ const value = definition[key];
182
+ if (Array.isArray(value)) {
183
+ for (const item of value) if (item instanceof z.ZodType) children.push(item);
184
+ }
185
+ }
186
+ return children;
187
+ }
188
+
189
+ // src/extract.ts
190
+ async function extractGraphFacts(options) {
191
+ assertConcurrency(options.concurrency);
192
+ throwIfAborted(options.abortSignal);
193
+ const ids = /* @__PURE__ */ new Set();
194
+ for (const chunk of options.chunks) {
195
+ if (ids.has(chunk.id)) throw new TypeError(`Duplicate graph chunk id: ${chunk.id}`);
196
+ ids.add(chunk.id);
197
+ if (typeof chunk.text !== "string") {
198
+ throw new TypeError(`Graph chunk ${chunk.id} text must be a string.`);
199
+ }
200
+ }
201
+ const outputSchema = extractionSchema(options.schema);
202
+ const instructions = graphInstructions(options.schema, options.instructions);
203
+ const extractions = await mapConcurrent(
204
+ options.chunks,
205
+ options.concurrency ?? 1,
206
+ async (chunk) => {
207
+ throwIfAborted(options.abortSignal);
208
+ const result = await extract({
209
+ model: options.model,
210
+ text: chunk.text,
211
+ outputSchema,
212
+ instructions,
213
+ retries: options.retries,
214
+ abortSignal: options.abortSignal
215
+ });
216
+ return { chunkId: chunk.id, output: result.output, usage: result.usage };
217
+ }
218
+ );
219
+ return {
220
+ output: normalizeFacts(options.schema, extractions),
221
+ usage: extractions.reduce((usage, item) => Usage.add(usage, item.usage), Usage.empty())
222
+ };
223
+ }
224
+ function extractionSchema(schema) {
225
+ const entities = Object.entries(schema.nodes).map(
226
+ ([type, definition]) => z2.object({ ref: z2.string().min(1), type: z2.literal(type), properties: definition.properties })
227
+ );
228
+ const relationships = Object.entries(schema.relationships).map(
229
+ ([type, definition]) => z2.object({
230
+ type: z2.literal(type),
231
+ from: z2.string().min(1),
232
+ to: z2.string().min(1),
233
+ properties: definition.properties
234
+ })
235
+ );
236
+ return z2.object({
237
+ entities: z2.array(union(entities, z2.never())),
238
+ relationships: z2.array(union(relationships, z2.never()))
239
+ });
240
+ }
241
+ function union(items, empty) {
242
+ if (items.length === 0) return empty;
243
+ if (items.length === 1) return items[0];
244
+ return z2.union(items);
245
+ }
246
+ function graphInstructions(schema, extra) {
247
+ const nodes = Object.entries(schema.nodes).map(([type, definition]) => `- ${type}: ${definition.description}`).join("\n");
248
+ const relationships = Object.entries(schema.relationships).map(
249
+ ([type, definition]) => `- ${type}: ${definition.from} -> ${definition.to}. ${definition.description}`
250
+ ).join("\n");
251
+ return [
252
+ "Extract only facts directly supported by the source text.",
253
+ "Give every extracted entity a unique local ref and use those refs as relationship endpoints.",
254
+ "Do not invent entity or relationship types outside the declared schema.",
255
+ `Node types:
256
+ ${nodes}`,
257
+ relationships.length === 0 ? "No relationship types are allowed." : `Relationship types:
258
+ ${relationships}`,
259
+ extra
260
+ ].filter((part) => part !== void 0 && part.length > 0).join("\n\n");
261
+ }
262
+ function normalizeFacts(schema, extractions) {
263
+ const entities = /* @__PURE__ */ new Map();
264
+ const relationships = /* @__PURE__ */ new Map();
265
+ const mentions = /* @__PURE__ */ new Map();
266
+ for (const extraction of extractions) {
267
+ const refs = /* @__PURE__ */ new Map();
268
+ for (const raw of extraction.output.entities) {
269
+ if (refs.has(raw.ref)) {
270
+ throw new TypeError(`Duplicate entity ref ${raw.ref} in chunk ${extraction.chunkId}.`);
271
+ }
272
+ const definition = schema.nodes[raw.type];
273
+ if (definition === void 0) throw new TypeError(`Unknown graph entity type: ${raw.type}`);
274
+ const properties2 = parseGraphProperties(
275
+ definition.properties.parse(raw.properties),
276
+ `entity ${raw.type}`
277
+ );
278
+ const identity = identityFromProperties(definition.identity, properties2, raw.type);
279
+ const key = `${raw.type}:${stableObject(identity)}`;
280
+ const current = entities.get(key);
281
+ const next = {
282
+ key,
283
+ type: raw.type,
284
+ identity,
285
+ properties: properties2,
286
+ sourceChunkIds: [extraction.chunkId]
287
+ };
288
+ if (current === void 0) {
289
+ entities.set(key, next);
290
+ refs.set(raw.ref, next);
291
+ } else {
292
+ assertSameProperties(
293
+ current.properties,
294
+ properties2,
295
+ key,
296
+ current.sourceChunkIds,
297
+ extraction.chunkId
298
+ );
299
+ const merged = {
300
+ ...current,
301
+ sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId]
302
+ };
303
+ entities.set(key, merged);
304
+ refs.set(raw.ref, merged);
305
+ }
306
+ mentions.set(`${extraction.chunkId}\0${key}`, {
307
+ chunkId: extraction.chunkId,
308
+ entityKey: key
309
+ });
310
+ }
311
+ for (const raw of extraction.output.relationships) {
312
+ const definition = schema.relationships[raw.type];
313
+ if (definition === void 0) {
314
+ throw new TypeError(`Unknown graph relationship type: ${raw.type}`);
315
+ }
316
+ const from = refs.get(raw.from);
317
+ const to = refs.get(raw.to);
318
+ if (from === void 0 || to === void 0) {
319
+ throw new TypeError(
320
+ `Relationship ${raw.type} in chunk ${extraction.chunkId} references an unknown entity ref.`
321
+ );
322
+ }
323
+ if (from.type !== definition.from || to.type !== definition.to) {
324
+ throw new TypeError(
325
+ `Relationship ${raw.type} has invalid endpoint types ${from.type} -> ${to.type}.`
326
+ );
327
+ }
328
+ const properties2 = parseGraphProperties(
329
+ definition.properties.parse(raw.properties),
330
+ `relationship ${raw.type}`
331
+ );
332
+ const identity = identityFromProperties(definition.identity ?? [], properties2, raw.type);
333
+ const key = `${raw.type}:${from.key}->${to.key}:${stableObject(identity)}`;
334
+ const current = relationships.get(key);
335
+ const next = {
336
+ key,
337
+ type: raw.type,
338
+ from: from.key,
339
+ to: to.key,
340
+ properties: properties2,
341
+ sourceChunkIds: [extraction.chunkId]
342
+ };
343
+ if (current === void 0) relationships.set(key, next);
344
+ else {
345
+ assertSameProperties(
346
+ current.properties,
347
+ properties2,
348
+ key,
349
+ current.sourceChunkIds,
350
+ extraction.chunkId
351
+ );
352
+ relationships.set(key, {
353
+ ...current,
354
+ sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId]
355
+ });
356
+ }
357
+ }
358
+ }
359
+ return {
360
+ entities: [...entities.values()],
361
+ relationships: [...relationships.values()],
362
+ mentions: [...mentions.values()]
363
+ };
364
+ }
365
+ function identityFromProperties(keys, properties2, type) {
366
+ const identity = {};
367
+ for (const key of keys) {
368
+ const value = properties2[key];
369
+ if (value === void 0 || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean")) {
370
+ throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);
371
+ }
372
+ identity[key] = value;
373
+ }
374
+ return identity;
375
+ }
376
+ function stableObject(value) {
377
+ return JSON.stringify(
378
+ Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)))
379
+ );
380
+ }
381
+ function assertSameProperties(left, right, key, sourceChunkIds, nextChunkId) {
382
+ if (stableObject(left) !== stableObject(right)) {
383
+ throw new GraphFactConflictError(key, [...sourceChunkIds, nextChunkId]);
384
+ }
385
+ }
386
+ var GraphFactConflictError = class extends Error {
387
+ constructor(factKey, sourceChunkIds) {
388
+ super(
389
+ `Conflicting graph fact ${factKey} was extracted from chunks ${sourceChunkIds.join(", ")}.`
390
+ );
391
+ this.factKey = factKey;
392
+ this.sourceChunkIds = sourceChunkIds;
393
+ this.name = "GraphFactConflictError";
394
+ }
395
+ factKey;
396
+ sourceChunkIds;
397
+ };
398
+ function assertConcurrency(value) {
399
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1)) {
400
+ throw new RangeError("Graph extraction concurrency must be a positive safe integer.");
401
+ }
402
+ }
403
+ function throwIfAborted(signal) {
404
+ if (signal?.aborted !== true) return;
405
+ if (signal.reason instanceof Error) throw signal.reason;
406
+ throw new DOMException("The operation was aborted.", "AbortError");
407
+ }
408
+ async function mapConcurrent(values, concurrency, run) {
409
+ const output = Array(values.length);
410
+ let cursor = 0;
411
+ await Promise.all(
412
+ Array.from({ length: Math.min(concurrency, values.length) }, async () => {
413
+ for (; ; ) {
414
+ const index = cursor;
415
+ cursor += 1;
416
+ if (index >= values.length) return;
417
+ output[index] = await run(values[index]);
418
+ }
419
+ })
420
+ );
421
+ return output;
422
+ }
423
+
424
+ // src/tool.ts
425
+ import { createTool } from "@anvia/core/tool";
426
+ import { z as z3 } from "zod";
427
+ var primitive = z3.union([z3.string(), z3.number().finite(), z3.boolean()]);
428
+ var propertyValue = z3.union([
429
+ primitive,
430
+ z3.array(z3.string()),
431
+ z3.array(z3.number().finite()),
432
+ z3.array(z3.boolean())
433
+ ]);
434
+ var properties = z3.record(z3.string(), propertyValue);
435
+ var contextSchema = z3.object({
436
+ seeds: z3.array(
437
+ z3.object({
438
+ key: z3.string(),
439
+ type: z3.string(),
440
+ score: z3.number().finite(),
441
+ properties,
442
+ sourceChunkIds: z3.array(z3.string())
443
+ })
444
+ ),
445
+ nodes: z3.array(
446
+ z3.object({
447
+ key: z3.string(),
448
+ type: z3.string(),
449
+ identity: z3.record(z3.string(), primitive),
450
+ properties,
451
+ sourceChunkIds: z3.array(z3.string())
452
+ })
453
+ ),
454
+ relationships: z3.array(
455
+ z3.object({
456
+ key: z3.string(),
457
+ type: z3.string(),
458
+ from: z3.string(),
459
+ to: z3.string(),
460
+ properties,
461
+ sourceChunkIds: z3.array(z3.string())
462
+ })
463
+ ),
464
+ evidence: z3.array(
465
+ z3.object({
466
+ chunkId: z3.string(),
467
+ documentId: z3.string(),
468
+ index: z3.number().int(),
469
+ text: z3.string(),
470
+ metadata: properties
471
+ })
472
+ )
473
+ });
474
+ function createGraphSearchTool(options) {
475
+ return createTool({
476
+ name: options.name,
477
+ description: options.description,
478
+ inputSchema: z3.object({
479
+ query: z3.string().min(1).describe("The question or concept to search for in the graph.")
480
+ }),
481
+ outputSchema: contextSchema,
482
+ execute: async ({ query }, context) => await options.graph.retrieve({
483
+ model: options.model,
484
+ query,
485
+ search: options.search,
486
+ traversal: options.traversal,
487
+ evidence: options.evidence,
488
+ retries: options.retries,
489
+ abortSignal: context.abortSignal
490
+ })
491
+ });
492
+ }
493
+ export {
494
+ GraphFactConflictError,
495
+ assertGraphName,
496
+ assertGraphPropertyName,
497
+ createGraphSearchTool,
498
+ defineGraphSchema,
499
+ extractGraphFacts,
500
+ freezeGraphSchema,
501
+ graphReservedPropertyPrefix,
502
+ parseGraphProperties,
503
+ parseGraphPropertyValue,
504
+ resolveGraphExploreOptions,
505
+ validateGraphSchemaOptions
506
+ };
507
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extract.ts","../src/schema.ts","../src/tool.ts"],"sourcesContent":["import { Usage } from \"@anvia/core\";\nimport { extract } from \"@anvia/core/extractor\";\nimport { z } from \"zod\";\nimport { parseGraphProperties } from \"./schema.js\";\nimport type {\n ExtractGraphFactsOptions,\n ExtractGraphFactsResult,\n GraphEntity,\n GraphFacts,\n GraphMention,\n GraphNodeIdentity,\n GraphProperties,\n GraphRelationship,\n GraphSchemaLike,\n} from \"./types.js\";\n\ntype RawEntity = { ref: string; type: string; properties: Record<string, unknown> };\ntype RawRelationship = {\n type: string;\n from: string;\n to: string;\n properties: Record<string, unknown>;\n};\ntype RawChunkFacts = { entities: RawEntity[]; relationships: RawRelationship[] };\ntype ChunkExtraction = { chunkId: string; output: RawChunkFacts; usage: Usage };\n\nexport async function extractGraphFacts<\n Schema extends GraphSchemaLike,\n Model extends import(\"@anvia/core\").CompletionModel,\n>(options: ExtractGraphFactsOptions<Schema, Model>): Promise<ExtractGraphFactsResult<Schema>> {\n assertConcurrency(options.concurrency);\n throwIfAborted(options.abortSignal);\n const ids = new Set<string>();\n for (const chunk of options.chunks) {\n if (ids.has(chunk.id)) throw new TypeError(`Duplicate graph chunk id: ${chunk.id}`);\n ids.add(chunk.id);\n if (typeof chunk.text !== \"string\") {\n throw new TypeError(`Graph chunk ${chunk.id} text must be a string.`);\n }\n }\n\n const outputSchema = extractionSchema(options.schema);\n const instructions = graphInstructions(options.schema, options.instructions);\n const extractions = await mapConcurrent(\n options.chunks,\n options.concurrency ?? 1,\n async (chunk): Promise<ChunkExtraction> => {\n throwIfAborted(options.abortSignal);\n const result = await extract({\n model: options.model,\n text: chunk.text,\n outputSchema,\n instructions,\n retries: options.retries,\n abortSignal: options.abortSignal,\n });\n return { chunkId: chunk.id, output: result.output as RawChunkFacts, usage: result.usage };\n },\n );\n return {\n output: normalizeFacts(options.schema, extractions),\n usage: extractions.reduce((usage, item) => Usage.add(usage, item.usage), Usage.empty()),\n };\n}\n\nfunction extractionSchema(schema: GraphSchemaLike): z.ZodType<RawChunkFacts> {\n const entities = Object.entries(schema.nodes).map(([type, definition]) =>\n z.object({ ref: z.string().min(1), type: z.literal(type), properties: definition.properties }),\n );\n const relationships = Object.entries(schema.relationships).map(([type, definition]) =>\n z.object({\n type: z.literal(type),\n from: z.string().min(1),\n to: z.string().min(1),\n properties: definition.properties,\n }),\n );\n return z.object({\n entities: z.array(union(entities, z.never())),\n relationships: z.array(union(relationships, z.never())),\n }) as unknown as z.ZodType<RawChunkFacts>;\n}\n\nfunction union(items: z.ZodType[], empty: z.ZodType): z.ZodType {\n if (items.length === 0) return empty;\n if (items.length === 1) return items[0] as z.ZodType;\n return z.union(items as [z.ZodType, z.ZodType, ...z.ZodType[]]);\n}\n\nfunction graphInstructions(schema: GraphSchemaLike, extra: string | undefined): string {\n const nodes = Object.entries(schema.nodes)\n .map(([type, definition]) => `- ${type}: ${definition.description}`)\n .join(\"\\n\");\n const relationships = Object.entries(schema.relationships)\n .map(\n ([type, definition]) =>\n `- ${type}: ${definition.from} -> ${definition.to}. ${definition.description}`,\n )\n .join(\"\\n\");\n return [\n \"Extract only facts directly supported by the source text.\",\n \"Give every extracted entity a unique local ref and use those refs as relationship endpoints.\",\n \"Do not invent entity or relationship types outside the declared schema.\",\n `Node types:\\n${nodes}`,\n relationships.length === 0\n ? \"No relationship types are allowed.\"\n : `Relationship types:\\n${relationships}`,\n extra,\n ]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join(\"\\n\\n\");\n}\n\nfunction normalizeFacts<Schema extends GraphSchemaLike>(\n schema: Schema,\n extractions: readonly ChunkExtraction[],\n): GraphFacts<Schema> {\n const entities = new Map<string, GraphEntity<Schema>>();\n const relationships = new Map<string, GraphRelationship<Schema>>();\n const mentions = new Map<string, GraphMention>();\n\n for (const extraction of extractions) {\n const refs = new Map<string, GraphEntity<Schema>>();\n for (const raw of extraction.output.entities) {\n if (refs.has(raw.ref)) {\n throw new TypeError(`Duplicate entity ref ${raw.ref} in chunk ${extraction.chunkId}.`);\n }\n const definition = schema.nodes[raw.type];\n if (definition === undefined) throw new TypeError(`Unknown graph entity type: ${raw.type}`);\n const properties = parseGraphProperties(\n definition.properties.parse(raw.properties),\n `entity ${raw.type}`,\n );\n const identity = identityFromProperties(definition.identity, properties, raw.type);\n const key = `${raw.type}:${stableObject(identity)}`;\n const current = entities.get(key);\n const next = {\n key,\n type: raw.type,\n identity,\n properties,\n sourceChunkIds: [extraction.chunkId],\n } as unknown as GraphEntity<Schema>;\n if (current === undefined) {\n entities.set(key, next);\n refs.set(raw.ref, next);\n } else {\n assertSameProperties(\n current.properties,\n properties,\n key,\n current.sourceChunkIds,\n extraction.chunkId,\n );\n const merged = {\n ...current,\n sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId],\n } as GraphEntity<Schema>;\n entities.set(key, merged);\n refs.set(raw.ref, merged);\n }\n mentions.set(`${extraction.chunkId}\\u0000${key}`, {\n chunkId: extraction.chunkId,\n entityKey: key,\n });\n }\n\n for (const raw of extraction.output.relationships) {\n const definition = schema.relationships[raw.type];\n if (definition === undefined) {\n throw new TypeError(`Unknown graph relationship type: ${raw.type}`);\n }\n const from = refs.get(raw.from);\n const to = refs.get(raw.to);\n if (from === undefined || to === undefined) {\n throw new TypeError(\n `Relationship ${raw.type} in chunk ${extraction.chunkId} references an unknown entity ref.`,\n );\n }\n if (from.type !== definition.from || to.type !== definition.to) {\n throw new TypeError(\n `Relationship ${raw.type} has invalid endpoint types ${from.type} -> ${to.type}.`,\n );\n }\n const properties = parseGraphProperties(\n definition.properties.parse(raw.properties),\n `relationship ${raw.type}`,\n );\n const identity = identityFromProperties(definition.identity ?? [], properties, raw.type);\n const key = `${raw.type}:${from.key}->${to.key}:${stableObject(identity)}`;\n const current = relationships.get(key);\n const next = {\n key,\n type: raw.type,\n from: from.key,\n to: to.key,\n properties,\n sourceChunkIds: [extraction.chunkId],\n } as unknown as GraphRelationship<Schema>;\n if (current === undefined) relationships.set(key, next);\n else {\n assertSameProperties(\n current.properties,\n properties,\n key,\n current.sourceChunkIds,\n extraction.chunkId,\n );\n relationships.set(key, {\n ...current,\n sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId],\n } as GraphRelationship<Schema>);\n }\n }\n }\n return {\n entities: [...entities.values()],\n relationships: [...relationships.values()],\n mentions: [...mentions.values()],\n };\n}\n\nfunction identityFromProperties(\n keys: readonly string[],\n properties: GraphProperties,\n type: string,\n): GraphNodeIdentity {\n const identity: Record<string, string | number | boolean> = {};\n for (const key of keys) {\n const value = properties[key];\n if (\n value === undefined ||\n !(typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\")\n ) {\n throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);\n }\n identity[key] = value;\n }\n return identity;\n}\n\nfunction stableObject(value: Readonly<Record<string, unknown>>): string {\n return JSON.stringify(\n Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))),\n );\n}\n\nfunction assertSameProperties(\n left: GraphProperties,\n right: GraphProperties,\n key: string,\n sourceChunkIds: readonly string[],\n nextChunkId: string,\n): void {\n if (stableObject(left) !== stableObject(right)) {\n throw new GraphFactConflictError(key, [...sourceChunkIds, nextChunkId]);\n }\n}\n\nexport class GraphFactConflictError extends Error {\n constructor(\n readonly factKey: string,\n readonly sourceChunkIds: readonly string[],\n ) {\n super(\n `Conflicting graph fact ${factKey} was extracted from chunks ${sourceChunkIds.join(\", \")}.`,\n );\n this.name = \"GraphFactConflictError\";\n }\n}\n\nfunction assertConcurrency(value: number | undefined): void {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(\"Graph extraction concurrency must be a positive safe integer.\");\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\nasync function mapConcurrent<Input, Output>(\n values: readonly Input[],\n concurrency: number,\n run: (value: Input) => Promise<Output>,\n): Promise<Output[]> {\n const output = Array<Output>(values.length);\n let cursor = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, values.length) }, async () => {\n for (;;) {\n const index = cursor;\n cursor += 1;\n if (index >= values.length) return;\n output[index] = await run(values[index] as Input);\n }\n }),\n );\n return output;\n}\n","import { z } from \"zod\";\nimport type {\n GraphProperties,\n GraphPropertyPrimitive,\n GraphPropertyValue,\n GraphSchema,\n GraphSchemaOptions,\n} from \"./types.js\";\n\nexport const graphReservedPropertyPrefix = \"__anvia_\";\n\nexport function defineGraphSchema<const Options extends GraphSchemaOptions>(\n options: Options,\n): GraphSchema<Options> {\n validateGraphSchemaOptions(options);\n return freezeGraphSchema(options, \"graph-schema\");\n}\n\nexport function validateGraphSchemaOptions(options: GraphSchemaOptions): void {\n if (Object.keys(options.nodes).length === 0) {\n throw new TypeError(\"A graph schema requires at least one node type.\");\n }\n for (const [type, definition] of Object.entries(options.nodes)) {\n assertGraphName(type, \"node type\");\n assertDescription(definition.description, `node ${type}`);\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `node ${type}`);\n if (\n definition.identity.length === 0 ||\n new Set(definition.identity).size !== definition.identity.length\n ) {\n throw new TypeError(`Node ${type} must declare unique identity properties.`);\n }\n for (const property of definition.identity) {\n assertGraphPropertyName(property);\n if (!(property in definition.properties.shape)) {\n throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);\n }\n }\n for (const property of Object.keys(definition.properties.shape)) {\n assertGraphPropertyName(property);\n }\n }\n for (const [type, definition] of Object.entries(options.relationships)) {\n assertGraphName(type, \"relationship type\");\n assertDescription(definition.description, `relationship ${type}`);\n if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {\n throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);\n }\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `relationship ${type}`);\n const identity = definition.identity ?? [];\n if (new Set(identity).size !== identity.length) {\n throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);\n }\n for (const property of Object.keys(definition.properties.shape)) {\n assertGraphPropertyName(property);\n }\n for (const property of identity) {\n if (!(property in definition.properties.shape)) {\n throw new TypeError(\n `Identity property ${property} is not declared by relationship ${type}.`,\n );\n }\n }\n }\n}\n\nexport function freezeGraphSchema<\n const Options extends GraphSchemaOptions,\n const Kind extends string,\n>(options: Options, kind: Kind): Readonly<Options & { kind: Kind }> {\n const nodes = Object.fromEntries(\n Object.entries(options.nodes).map(([type, definition]) => [\n type,\n Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) }),\n ]),\n );\n const relationships = Object.fromEntries(\n Object.entries(options.relationships).map(([type, definition]) => {\n const copy = { ...definition };\n if (definition.identity !== undefined) {\n Object.assign(copy, { identity: Object.freeze([...definition.identity]) });\n }\n return [type, Object.freeze(copy)];\n }),\n );\n return Object.freeze({\n nodes: Object.freeze(nodes),\n relationships: Object.freeze(relationships),\n kind,\n }) as Readonly<Options & { kind: Kind }>;\n}\n\nexport function parseGraphProperties(value: unknown, label: string): GraphProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object of graph property values.`);\n }\n const output: Record<string, GraphPropertyValue> = {};\n for (const [key, item] of Object.entries(value)) {\n assertGraphPropertyName(key);\n output[key] = parseGraphPropertyValue(item, `${label}.${key}`);\n }\n return output;\n}\n\nexport function parseGraphPropertyValue(value: unknown, label: string): GraphPropertyValue {\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n throw new TypeError(`${label} must be a safe integer.`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return [];\n const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));\n const type = typeof parsed[0];\n if (!parsed.every((item) => typeof item === type)) {\n throw new TypeError(`${label} must be a homogeneous array.`);\n }\n return parsed as GraphPropertyValue;\n }\n throw new TypeError(`${label} is not a supported graph property value.`);\n}\n\nexport function assertGraphName(value: string, label: string): void {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string.`);\n }\n}\n\nexport function assertGraphPropertyName(value: string): void {\n assertGraphName(value, \"graph property name\");\n if (value.startsWith(graphReservedPropertyPrefix)) {\n throw new TypeError(\n `Graph property names beginning with ${graphReservedPropertyPrefix} are reserved.`,\n );\n }\n}\n\nfunction parsePrimitive(value: unknown, label: string): GraphPropertyPrimitive {\n const parsed = parseGraphPropertyValue(value, label);\n if (typeof parsed === \"string\" || typeof parsed === \"number\" || typeof parsed === \"boolean\") {\n return parsed;\n }\n throw new TypeError(`${label} must be a primitive property value.`);\n}\n\nfunction assertDescription(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty description.`);\n }\n}\n\nfunction assertExactPropertySchema(schema: z.ZodObject<z.ZodRawShape>, label: string): void {\n const definition = schema._zod.def;\n if (!(definition.catchall instanceof z.ZodNever)) {\n throw new TypeError(`${label} properties must use a strict Zod object schema.`);\n }\n for (const [property, propertySchema] of Object.entries(schema.shape)) {\n assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, new Set());\n }\n}\n\nfunction assertNonEffectfulSchema(value: unknown, label: string, visited: Set<z.ZodType>): void {\n if (!(value instanceof z.ZodType)) throw new TypeError(`${label} must be a Zod schema.`);\n if (visited.has(value)) return;\n visited.add(value);\n const definition = value._zod.def as unknown as Record<string, unknown>;\n const type = definition.type;\n if (\n definition.coerce === true ||\n type === \"default\" ||\n type === \"prefault\" ||\n type === \"catch\" ||\n type === \"transform\" ||\n type === \"pipe\"\n ) {\n throw new TypeError(\n `${label} must not coerce, default, transform, preprocess, or catch values.`,\n );\n }\n const checks = definition.checks;\n if (\n Array.isArray(checks) &&\n checks.some((check) => {\n if (typeof check !== \"object\" || check === null) return false;\n return (check as { _zod?: { def?: { check?: unknown } } })._zod?.def?.check === \"overwrite\";\n })\n ) {\n throw new TypeError(`${label} must not normalize or overwrite values.`);\n }\n for (const child of schemaChildren(definition)) assertNonEffectfulSchema(child, label, visited);\n}\n\nfunction schemaChildren(definition: Record<string, unknown>): z.ZodType[] {\n const children: z.ZodType[] = [];\n for (const key of [\"innerType\", \"element\", \"left\", \"right\", \"rest\", \"keyType\", \"valueType\"]) {\n const value = definition[key];\n if (value instanceof z.ZodType) children.push(value);\n }\n for (const key of [\"options\", \"items\"]) {\n const value = definition[key];\n if (Array.isArray(value)) {\n for (const item of value) if (item instanceof z.ZodType) children.push(item);\n }\n }\n return children;\n}\n","import { createTool } from \"@anvia/core/tool\";\nimport { z } from \"zod\";\nimport type {\n CreateGraphSearchToolOptions,\n GraphContextRetriever,\n GraphSchemaLike,\n GraphSearchTool,\n} from \"./types.js\";\n\nconst primitive = z.union([z.string(), z.number().finite(), z.boolean()]);\nconst propertyValue = z.union([\n primitive,\n z.array(z.string()),\n z.array(z.number().finite()),\n z.array(z.boolean()),\n]);\nconst properties = z.record(z.string(), propertyValue);\nconst contextSchema = z.object({\n seeds: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n score: z.number().finite(),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n nodes: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n identity: z.record(z.string(), primitive),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n relationships: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n from: z.string(),\n to: z.string(),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n evidence: z.array(\n z.object({\n chunkId: z.string(),\n documentId: z.string(),\n index: z.number().int(),\n text: z.string(),\n metadata: properties,\n }),\n ),\n});\n\nexport function createGraphSearchTool<\n Schema extends GraphSchemaLike,\n Retriever extends GraphContextRetriever<Schema>,\n>(options: CreateGraphSearchToolOptions<Schema, Retriever>): GraphSearchTool {\n return createTool({\n name: options.name,\n description: options.description,\n inputSchema: z.object({\n query: z.string().min(1).describe(\"The question or concept to search for in the graph.\"),\n }),\n outputSchema: contextSchema,\n execute: async ({ query }, context) =>\n (await options.graph.retrieve({\n model: options.model,\n query,\n search: options.search,\n traversal: options.traversal,\n evidence: options.evidence,\n retries: options.retries,\n abortSignal: context.abortSignal,\n })) as unknown as z.input<typeof contextSchema>,\n }) as unknown as GraphSearchTool;\n}\n"],"mappings":";;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,KAAAA,UAAS;;;ACFlB,SAAS,SAAS;AASX,IAAM,8BAA8B;AAEpC,SAAS,kBACd,SACsB;AACtB,6BAA2B,OAAO;AAClC,SAAO,kBAAkB,SAAS,cAAc;AAClD;AAEO,SAAS,2BAA2B,SAAmC;AAC5E,MAAI,OAAO,KAAK,QAAQ,KAAK,EAAE,WAAW,GAAG;AAC3C,UAAM,IAAI,UAAU,iDAAiD;AAAA,EACvE;AACA,aAAW,CAAC,MAAM,UAAU,KAAK,OAAO,QAAQ,QAAQ,KAAK,GAAG;AAC9D,oBAAgB,MAAM,WAAW;AACjC,sBAAkB,WAAW,aAAa,QAAQ,IAAI,EAAE;AACxD,QAAI,EAAE,WAAW,sBAAsB,EAAE,YAAY;AACnD,YAAM,IAAI,UAAU,uBAAuB,IAAI,+BAA+B;AAAA,IAChF;AACA,8BAA0B,WAAW,YAAY,QAAQ,IAAI,EAAE;AAC/D,QACE,WAAW,SAAS,WAAW,KAC/B,IAAI,IAAI,WAAW,QAAQ,EAAE,SAAS,WAAW,SAAS,QAC1D;AACA,YAAM,IAAI,UAAU,QAAQ,IAAI,2CAA2C;AAAA,IAC7E;AACA,eAAW,YAAY,WAAW,UAAU;AAC1C,8BAAwB,QAAQ;AAChC,UAAI,EAAE,YAAY,WAAW,WAAW,QAAQ;AAC9C,cAAM,IAAI,UAAU,qBAAqB,QAAQ,4BAA4B,IAAI,GAAG;AAAA,MACtF;AAAA,IACF;AACA,eAAW,YAAY,OAAO,KAAK,WAAW,WAAW,KAA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ACD,cAAc;AAAA,IACd,SAAS,OAAO,EAAE,MAAM,GAAG,YACxB,MAAM,QAAQ,MAAM,SAAS;AAAA,MAC5B,OAAO,QAAQ;AAAA,MACf;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB,WAAW,QAAQ;AAAA,MACnB,UAAU,QAAQ;AAAA,MAClB,SAAS,QAAQ;AAAA,MACjB,aAAa,QAAQ;AAAA,IACvB,CAAC;AAAA,EACL,CAAC;AACH;","names":["z","z","properties","z"]}
package/package.json CHANGED
@@ -1,15 +1,50 @@
1
1
  {
2
2
  "name": "@anvia/graph",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "Reserved for the Anvia graph package.",
3
+ "version": "1.0.3",
4
+ "description": "Provider-neutral knowledge graph primitives for Anvia.",
5
+ "author": "anvia",
6
+ "maintainer": "Indra Zulfi",
5
7
  "license": "MIT",
6
- "type": "module",
7
8
  "repository": {
8
9
  "type": "git",
9
- "url": "https://github.com/anvia-hq/anvia.git",
10
+ "url": "https://github.com/anvia-hq/anvia",
10
11
  "directory": "packages/graph"
11
12
  },
13
+ "files": [
14
+ "dist"
15
+ ],
12
16
  "publishConfig": {
13
17
  "access": "public"
18
+ },
19
+ "type": "module",
20
+ "main": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ },
27
+ "./explore": {
28
+ "types": "./dist/explore.d.ts",
29
+ "import": "./dist/explore.js"
30
+ }
31
+ },
32
+ "dependencies": {
33
+ "zod": "^4.4.3"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^24.9.1",
37
+ "tsup": "^8.5.0",
38
+ "typescript": "^5.9.3",
39
+ "vitest": "^4.0.8",
40
+ "@anvia/core": "1.0.2"
41
+ },
42
+ "peerDependencies": {
43
+ "@anvia/core": "1.0.2"
44
+ },
45
+ "scripts": {
46
+ "build": "tsup src/index.ts src/explore.ts --format esm --dts --sourcemap --clean",
47
+ "test": "vitest run",
48
+ "typecheck": "tsc --noEmit"
14
49
  }
15
- }
50
+ }
package/index.js DELETED
@@ -1 +0,0 @@
1
- export {};