@jini-ai/search 0.0.0-stage → 0.1.0
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 +201 -0
- package/README.md +76 -2
- package/dist/api.d.ts +92 -0
- package/dist/api.js +2 -0
- package/dist/contract.d.ts +219 -0
- package/dist/contract.js +46 -0
- package/dist/contribution.d.ts +61 -0
- package/dist/contribution.js +124 -0
- package/dist/digest.d.ts +13 -0
- package/dist/digest.js +55 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/indexer.d.ts +50 -0
- package/dist/indexer.js +402 -0
- package/dist/ports.d.ts +194 -0
- package/dist/ports.js +2 -0
- package/dist/registry.d.ts +33 -0
- package/dist/registry.js +81 -0
- package/dist/service.d.ts +37 -0
- package/dist/service.js +118 -0
- package/dist/testkit/assert.d.ts +14 -0
- package/dist/testkit/assert.js +20 -0
- package/dist/testkit/conformance.d.ts +32 -0
- package/dist/testkit/conformance.js +453 -0
- package/dist/testkit/fakes.d.ts +56 -0
- package/dist/testkit/fakes.js +114 -0
- package/dist/testkit/index.d.ts +9 -0
- package/dist/testkit/index.js +9 -0
- package/dist/testkit/memory-provider.d.ts +23 -0
- package/dist/testkit/memory-provider.js +237 -0
- package/dist/tokens.d.ts +9 -0
- package/dist/tokens.js +12 -0
- package/dist/tools.d.ts +74 -0
- package/dist/tools.js +194 -0
- package/package.json +75 -3
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type SearchProvider, type SearchProviderContext } from '../contract.js';
|
|
2
|
+
export interface InMemorySearchProviderOptions {
|
|
3
|
+
readonly id?: string;
|
|
4
|
+
readonly label?: string;
|
|
5
|
+
readonly acceptsRestricted?: boolean;
|
|
6
|
+
readonly asyncIndexing?: boolean;
|
|
7
|
+
readonly typoTolerance?: boolean;
|
|
8
|
+
readonly locales?: readonly string[] | 'any';
|
|
9
|
+
readonly maxBatch?: number;
|
|
10
|
+
/** `false` turns every call for that context into `unknown`/`provider_unavailable`. */
|
|
11
|
+
readonly available?: (required: {
|
|
12
|
+
readonly ctx: SearchProviderContext;
|
|
13
|
+
}) => boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The reference provider. Case-insensitive word matching over title + body (every query word must
|
|
17
|
+
* match), plain-text snippet windows with highlight ranges, versioned tombstones, cursor = offset.
|
|
18
|
+
* With `asyncIndexing`, a non-stale write answers `pending` with a task id and becomes visible only
|
|
19
|
+
* when that task (and every earlier one) is settled by the next `awaitTask` call.
|
|
20
|
+
* @complexity Writes O(batch); queries O(documents in the index × words).
|
|
21
|
+
*/
|
|
22
|
+
export declare function createInMemorySearchProvider(_required?: Record<string, never>, optional?: InMemorySearchProviderOptions): SearchProvider;
|
|
23
|
+
//# sourceMappingURL=memory-provider.d.ts.map
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The in-memory REFERENCE search provider. It exists so the conformance kit has something
|
|
3
|
+
* real to run against in tests, and as a readable executable statement of the contract's write and
|
|
4
|
+
* query semantics.
|
|
5
|
+
*
|
|
6
|
+
* It is NOT the built-in provider: the owner builds the real built-in (`id: 'builtin'`) on the host's
|
|
7
|
+
* storage kernel with its own tables and migration, and it must pass the same conformance kit. Never
|
|
8
|
+
* register this one in a running host — all state lives in one process's memory.
|
|
9
|
+
*/
|
|
10
|
+
import { providerOk, providerRejected, providerUnknown, } from '@jini-ai/core/provider-registry';
|
|
11
|
+
import { encodeSearchKey, } from '../contract.js';
|
|
12
|
+
const DEFAULT_LIMIT = 10;
|
|
13
|
+
const MAX_LIMIT = 100;
|
|
14
|
+
const SNIPPET_LEAD = 40;
|
|
15
|
+
const SNIPPET_LENGTH = 160;
|
|
16
|
+
/** Typo tolerance (when enabled) allows one edit on words of at least this length. */
|
|
17
|
+
const TYPO_MIN_LENGTH = 5;
|
|
18
|
+
const WORD = /[\p{L}\p{N}]+/gu;
|
|
19
|
+
const words = (text) => (text.toLowerCase().match(WORD) ?? []);
|
|
20
|
+
/** True when `a` and `b` are at most one insertion, deletion or substitution apart. */
|
|
21
|
+
function withinOneEdit(a, b) {
|
|
22
|
+
if (Math.abs(a.length - b.length) > 1)
|
|
23
|
+
return false;
|
|
24
|
+
let i = 0;
|
|
25
|
+
while (i < a.length && a[i] === b[i])
|
|
26
|
+
i += 1;
|
|
27
|
+
// Skip one char of the longer word (or one of each when equal length) and compare the rests.
|
|
28
|
+
const restA = a.length >= b.length ? a.slice(i + 1) : a.slice(i);
|
|
29
|
+
const restB = b.length >= a.length ? b.slice(i + 1) : b.slice(i);
|
|
30
|
+
return restA === restB;
|
|
31
|
+
}
|
|
32
|
+
function makeMatcher(required) {
|
|
33
|
+
const { terms, typoTolerance } = required;
|
|
34
|
+
return word => terms.some(term => term === word || (typoTolerance && term.length >= TYPO_MIN_LENGTH && withinOneEdit(term, word)));
|
|
35
|
+
}
|
|
36
|
+
/** Plain-text excerpt around the first matching word, with every matching word in it highlighted. */
|
|
37
|
+
function snippetOf(required) {
|
|
38
|
+
const { body, matches } = required;
|
|
39
|
+
const located = [...body.matchAll(WORD)].map(found => ({ start: found.index, end: found.index + found[0].length, hit: matches(found[0].toLowerCase()) }));
|
|
40
|
+
const first = located.find(word => word.hit);
|
|
41
|
+
const start = first === undefined ? 0 : Math.max(0, first.start - SNIPPET_LEAD);
|
|
42
|
+
const end = Math.min(body.length, start + SNIPPET_LENGTH);
|
|
43
|
+
const highlights = located
|
|
44
|
+
.filter(word => word.hit && word.start >= start && word.end <= end)
|
|
45
|
+
.map(word => ({ start: word.start - start, end: word.end - start }));
|
|
46
|
+
return { snippet: body.slice(start, end), highlights };
|
|
47
|
+
}
|
|
48
|
+
function audienceAllows(document, audiences) {
|
|
49
|
+
const { visibility } = document;
|
|
50
|
+
return visibility.kind === 'public' || visibility.audiences.some(audience => audiences.includes(audience));
|
|
51
|
+
}
|
|
52
|
+
function fieldsMatch(document, filters) {
|
|
53
|
+
return Object.entries(filters).every(([name, expected]) => {
|
|
54
|
+
const actual = document.fields?.[name];
|
|
55
|
+
return Array.isArray(actual) ? actual.includes(expected) : actual === expected;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
function scopeMatches(document, query) {
|
|
59
|
+
const collectionOk = query.collections === undefined || query.collections.includes(document.key.collection);
|
|
60
|
+
return collectionOk && (query.locale === undefined || document.locale === query.locale);
|
|
61
|
+
}
|
|
62
|
+
function passesFilters(document, query, tenant) {
|
|
63
|
+
const ownTenant = document.key.siteId === tenant.siteId && document.key.workspaceId === tenant.workspaceId;
|
|
64
|
+
return ownTenant && scopeMatches(document, query) && fieldsMatch(document, query.filters ?? {}) && audienceAllows(document, query.audiences ?? []);
|
|
65
|
+
}
|
|
66
|
+
function pageBounds(query) {
|
|
67
|
+
const limit = query.limit ?? DEFAULT_LIMIT;
|
|
68
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT)
|
|
69
|
+
return `limit must be an integer from 1 to ${MAX_LIMIT}`;
|
|
70
|
+
const cursor = query.cursor ?? '0';
|
|
71
|
+
if (!/^\d+$/.test(cursor))
|
|
72
|
+
return 'cursor is not a cursor of this provider';
|
|
73
|
+
return { offset: Number(cursor), limit };
|
|
74
|
+
}
|
|
75
|
+
/** 0 unless every query term matches some word (AND semantics); title words weigh double. */
|
|
76
|
+
function scoreOf(document, required) {
|
|
77
|
+
const titleWords = words(document.title);
|
|
78
|
+
const bodyWords = words(document.body);
|
|
79
|
+
const all = [...titleWords, ...bodyWords];
|
|
80
|
+
if (!required.termMatchers.every(matcher => all.some(matcher)))
|
|
81
|
+
return 0;
|
|
82
|
+
return titleWords.filter(required.matches).length * 2 + bodyWords.filter(required.matches).length;
|
|
83
|
+
}
|
|
84
|
+
function hitOf(document, score, matches) {
|
|
85
|
+
const { snippet, highlights } = snippetOf({ body: document.body, matches });
|
|
86
|
+
return { key: document.key, revision: document.revision, url: document.url, title: document.title, snippet, highlights, score };
|
|
87
|
+
}
|
|
88
|
+
function runQuery(index, query, typoTolerance, tenant) {
|
|
89
|
+
const terms = words(query.text);
|
|
90
|
+
if (terms.length === 0)
|
|
91
|
+
return providerRejected({ code: 'invalid_request', message: 'query text must not be empty' });
|
|
92
|
+
const bounds = pageBounds(query);
|
|
93
|
+
if (typeof bounds === 'string')
|
|
94
|
+
return providerRejected({ code: 'invalid_request', message: bounds });
|
|
95
|
+
const matches = makeMatcher({ terms, typoTolerance });
|
|
96
|
+
const termMatchers = terms.map(term => makeMatcher({ terms: [term], typoTolerance }));
|
|
97
|
+
const ranked = [...index.entries()]
|
|
98
|
+
.flatMap(([encoded, entry]) => entry.document !== undefined && passesFilters(entry.document, query, tenant) ? [{ encoded, document: entry.document, score: scoreOf(entry.document, { termMatchers, matches }) }] : [])
|
|
99
|
+
.filter(candidate => candidate.score > 0)
|
|
100
|
+
// Score first, then the encoded key: a total order, so cursors over offsets are stable.
|
|
101
|
+
.sort((a, b) => b.score - a.score || (a.encoded < b.encoded ? -1 : 1));
|
|
102
|
+
const end = bounds.offset + bounds.limit;
|
|
103
|
+
const hits = ranked.slice(bounds.offset, end).map(candidate => hitOf(candidate.document, candidate.score, matches));
|
|
104
|
+
return providerOk({ value: end < ranked.length ? { hits, nextCursor: String(end) } : { hits } });
|
|
105
|
+
}
|
|
106
|
+
const isRevision = (revision) => typeof revision === 'number' && Number.isSafeInteger(revision) && revision >= 0;
|
|
107
|
+
function resolveOptions(optional) {
|
|
108
|
+
const { id = 'memory', label = 'In-memory reference provider', acceptsRestricted = true, asyncIndexing = false, typoTolerance = false, locales = 'any', maxBatch = 100, available = () => true, } = optional;
|
|
109
|
+
return { id, label, acceptsRestricted, asyncIndexing, typoTolerance, locales, maxBatch, available };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The reference provider. Case-insensitive word matching over title + body (every query word must
|
|
113
|
+
* match), plain-text snippet windows with highlight ranges, versioned tombstones, cursor = offset.
|
|
114
|
+
* With `asyncIndexing`, a non-stale write answers `pending` with a task id and becomes visible only
|
|
115
|
+
* when that task (and every earlier one) is settled by the next `awaitTask` call.
|
|
116
|
+
* @complexity Writes O(batch); queries O(documents in the index × words).
|
|
117
|
+
*/
|
|
118
|
+
export function createInMemorySearchProvider(_required = {}, optional = {}) {
|
|
119
|
+
const { id, label, acceptsRestricted, asyncIndexing, typoTolerance, locales, maxBatch, available } = resolveOptions(optional);
|
|
120
|
+
const indexes = new Map();
|
|
121
|
+
const queued = new Map();
|
|
122
|
+
const settled = new Set();
|
|
123
|
+
let taskCounter = 0;
|
|
124
|
+
const capabilities = { acceptsRestricted, typoTolerance, locales, maxBatch, asyncIndexing };
|
|
125
|
+
const unavailable = () => providerUnknown({ code: 'provider_unavailable', message: 'the in-memory provider is unavailable for this context' });
|
|
126
|
+
const missing = (indexName) => providerRejected({ code: 'not_found', message: `index '${indexName}' does not exist` });
|
|
127
|
+
const store = (index, entry) => {
|
|
128
|
+
const encoded = encodeSearchKey({ key: entry.key });
|
|
129
|
+
const current = index.get(encoded);
|
|
130
|
+
if (current !== undefined && current.revision >= entry.revision)
|
|
131
|
+
return false;
|
|
132
|
+
index.set(encoded, entry);
|
|
133
|
+
return true;
|
|
134
|
+
};
|
|
135
|
+
const restrictedRefusal = (entry) => !acceptsRestricted && entry.document?.visibility.kind === 'restricted' ? 'this provider accepts public documents only' : undefined;
|
|
136
|
+
function outcomeOf(index, entry, pending) {
|
|
137
|
+
const base = { key: entry.key, revision: entry.revision };
|
|
138
|
+
const refusal = isRevision(entry.revision) ? restrictedRefusal(entry) : 'revision must be a non-negative safe integer';
|
|
139
|
+
if (refusal !== undefined)
|
|
140
|
+
return { ...base, status: 'rejected', message: refusal };
|
|
141
|
+
const current = index.get(encodeSearchKey({ key: entry.key }));
|
|
142
|
+
if (current !== undefined && current.revision >= entry.revision)
|
|
143
|
+
return { ...base, status: 'stale' };
|
|
144
|
+
if (!asyncIndexing) {
|
|
145
|
+
store(index, entry);
|
|
146
|
+
return { ...base, status: 'applied' };
|
|
147
|
+
}
|
|
148
|
+
pending.push(entry);
|
|
149
|
+
return { ...base, status: 'pending' };
|
|
150
|
+
}
|
|
151
|
+
function write(ctx, entries) {
|
|
152
|
+
if (!available({ ctx }))
|
|
153
|
+
return unavailable();
|
|
154
|
+
if (entries.length > maxBatch)
|
|
155
|
+
return providerRejected({ code: 'invalid_request', message: `at most ${maxBatch} items per write` });
|
|
156
|
+
const index = indexes.get(ctx.indexName);
|
|
157
|
+
if (index === undefined)
|
|
158
|
+
return missing(ctx.indexName);
|
|
159
|
+
const pending = [];
|
|
160
|
+
const outcomes = entries.map(entry => outcomeOf(index, entry, pending));
|
|
161
|
+
if (pending.length === 0)
|
|
162
|
+
return providerOk({ value: { outcomes } });
|
|
163
|
+
taskCounter += 1;
|
|
164
|
+
const taskId = `task_${taskCounter}`;
|
|
165
|
+
queued.set(taskId, { indexName: ctx.indexName, entries: pending });
|
|
166
|
+
return providerOk({ value: { outcomes, taskId } });
|
|
167
|
+
}
|
|
168
|
+
/** Settle every queued task up to and including `taskId`, in write order. */
|
|
169
|
+
function settleThrough(taskId) {
|
|
170
|
+
const ids = [...queued.keys()];
|
|
171
|
+
// awaitTask calls this only when `taskId` is queued, so indexOf is never -1.
|
|
172
|
+
for (const queuedId of ids.slice(0, ids.indexOf(taskId) + 1)) {
|
|
173
|
+
const task = queued.get(queuedId);
|
|
174
|
+
const index = indexes.get(task.indexName);
|
|
175
|
+
// A task whose index was dropped meanwhile has nothing left to write into.
|
|
176
|
+
if (index !== undefined)
|
|
177
|
+
for (const entry of task.entries)
|
|
178
|
+
store(index, entry);
|
|
179
|
+
queued.delete(queuedId);
|
|
180
|
+
settled.add(queuedId);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async function guarded(ctx, run) {
|
|
184
|
+
if (!available({ ctx }))
|
|
185
|
+
return unavailable();
|
|
186
|
+
const index = indexes.get(ctx.indexName);
|
|
187
|
+
return index === undefined ? missing(ctx.indexName) : run(index);
|
|
188
|
+
}
|
|
189
|
+
const provider = {
|
|
190
|
+
id, label, capabilities, credentialKeys: [],
|
|
191
|
+
async ensureIndex(ctx) {
|
|
192
|
+
if (!available({ ctx }))
|
|
193
|
+
return unavailable();
|
|
194
|
+
if (!indexes.has(ctx.indexName))
|
|
195
|
+
indexes.set(ctx.indexName, new Map());
|
|
196
|
+
return providerOk({ value: undefined });
|
|
197
|
+
},
|
|
198
|
+
async dropIndex(ctx) {
|
|
199
|
+
if (!available({ ctx }))
|
|
200
|
+
return unavailable();
|
|
201
|
+
indexes.delete(ctx.indexName);
|
|
202
|
+
return providerOk({ value: undefined });
|
|
203
|
+
},
|
|
204
|
+
async upsert(ctx, { documents }) {
|
|
205
|
+
return write(ctx, documents.map(document => ({ key: document.key, revision: document.revision, document })));
|
|
206
|
+
},
|
|
207
|
+
async remove(ctx, { tombstones }) {
|
|
208
|
+
return write(ctx, tombstones.map((tombstone) => ({ key: tombstone.key, revision: tombstone.revision })));
|
|
209
|
+
},
|
|
210
|
+
async query(ctx, { query }) {
|
|
211
|
+
return guarded(ctx, index => runQuery(index, query, typoTolerance, ctx));
|
|
212
|
+
},
|
|
213
|
+
async revisionOf(ctx, { keys }) {
|
|
214
|
+
return guarded(ctx, index => providerOk({
|
|
215
|
+
value: keys.map((key) => {
|
|
216
|
+
const entry = index.get(encodeSearchKey({ key }));
|
|
217
|
+
return entry === undefined ? { key, revision: null, deleted: false } : { key, revision: entry.revision, deleted: entry.document === undefined };
|
|
218
|
+
}),
|
|
219
|
+
}));
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
if (!asyncIndexing)
|
|
223
|
+
return provider;
|
|
224
|
+
return {
|
|
225
|
+
...provider,
|
|
226
|
+
async awaitTask(ctx, { taskId }) {
|
|
227
|
+
if (!available({ ctx }))
|
|
228
|
+
return unavailable();
|
|
229
|
+
if (queued.has(taskId))
|
|
230
|
+
settleThrough(taskId);
|
|
231
|
+
if (settled.has(taskId))
|
|
232
|
+
return providerOk({ value: 'succeeded' });
|
|
233
|
+
return providerRejected({ code: 'not_found', message: `task '${taskId}' is not known` });
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
//# sourceMappingURL=memory-provider.js.map
|
package/dist/tokens.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SearchIndexer, SearchService } from './api.js';
|
|
2
|
+
import type { SearchDocumentSource } from './ports.js';
|
|
3
|
+
import type { SearchProviderRegistry } from './registry.js';
|
|
4
|
+
export declare const SearchProviderRegistryToken: import("@jini-ai/core").Token<SearchProviderRegistry, string>;
|
|
5
|
+
export declare const SearchServiceToken: import("@jini-ai/core").Token<SearchService, string>;
|
|
6
|
+
export declare const SearchIndexerToken: import("@jini-ai/core").Token<SearchIndexer, string>;
|
|
7
|
+
/** Many-bound: every collection that can be searched contributes its own source. */
|
|
8
|
+
export declare const SearchDocumentSourceToken: import("@jini-ai/core").ManyToken<SearchDocumentSource, string>;
|
|
9
|
+
//# sourceMappingURL=tokens.d.ts.map
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Composition tokens of the search capability. Consumers (routes, theme blocks, agent tools)
|
|
3
|
+
* resolve only {@link SearchServiceToken}; the composition root alone resolves the indexer and binds
|
|
4
|
+
* one {@link SearchDocumentSourceToken} per collection (CMS posts, pages, a plugin's catalog …).
|
|
5
|
+
*/
|
|
6
|
+
import { manyToken, token } from '@jini-ai/core';
|
|
7
|
+
export const SearchProviderRegistryToken = token({ id: 'search.provider-registry' });
|
|
8
|
+
export const SearchServiceToken = token({ id: 'search.service' });
|
|
9
|
+
export const SearchIndexerToken = token({ id: 'search.indexer' });
|
|
10
|
+
/** Many-bound: every collection that can be searched contributes its own source. */
|
|
11
|
+
export const SearchDocumentSourceToken = manyToken({ id: 'search.document-source' });
|
|
12
|
+
//# sourceMappingURL=tokens.js.map
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Agent tools for site search (lot S6), subpath `@jini-ai/search/tools`.
|
|
3
|
+
*
|
|
4
|
+
* `search_query` and `search_status` are reads. `search_reindex` (bulk vendor writes = cost) and
|
|
5
|
+
* `search_set_provider` (a settings change plus a full backfill into another backend) ask the human
|
|
6
|
+
* first through core's approval lifecycle; only the reindex grant may be remembered, per provider.
|
|
7
|
+
*
|
|
8
|
+
* Agents only ever see PUBLIC results: `search_query` never passes viewer audiences to the service,
|
|
9
|
+
* so a members-only document cannot reach a model context through this tool.
|
|
10
|
+
*
|
|
11
|
+
* Permission is checked through an injected `requirePermission` port (the `@jini-ai/db` transfer
|
|
12
|
+
* tools' shape) rather than `@jini-ai/cms/core`'s helper, so this generic package keeps its single
|
|
13
|
+
* `@jini-ai/core` dependency; the host binds the port to its own permission catalog.
|
|
14
|
+
*/
|
|
15
|
+
import { type AgentToolDefinition, type ApprovalAnswer, type DerivedRiskByToolId, type RememberedApprovalPort, type ToolExecutionContext, type ToolExecutionOptions, type ToolRegistration } from '@jini-ai/core';
|
|
16
|
+
import type { ProviderRegistry } from '@jini-ai/core/provider-registry';
|
|
17
|
+
import type { SearchProvider } from './contract.js';
|
|
18
|
+
import type { SearchIndexer, SearchService } from './api.js';
|
|
19
|
+
export declare const SEARCH_TOOL_DOMAIN = "search";
|
|
20
|
+
/** Reads: the setting and index health are site settings; results are public content only. */
|
|
21
|
+
export declare const SEARCH_READ_PERMISSION = "settings.read";
|
|
22
|
+
/** Writes: choosing and re-filling a search backend is an integration change. */
|
|
23
|
+
export declare const SEARCH_MANAGE_PERMISSION = "admin.integrations.manage";
|
|
24
|
+
/** What the human is asked to approve. */
|
|
25
|
+
export interface SearchApprovalDescription {
|
|
26
|
+
readonly action: 'reindex' | 'set_provider';
|
|
27
|
+
readonly siteId: string;
|
|
28
|
+
readonly providerId: string;
|
|
29
|
+
/** The provider the site uses now (null when search was never configured). */
|
|
30
|
+
readonly fromProviderId: string | null;
|
|
31
|
+
readonly summary: string;
|
|
32
|
+
}
|
|
33
|
+
export interface SearchToolDeps {
|
|
34
|
+
readonly workspaceId: string;
|
|
35
|
+
readonly siteId: string;
|
|
36
|
+
readonly service: SearchService;
|
|
37
|
+
readonly indexer: Pick<SearchIndexer, 'startRebuild'>;
|
|
38
|
+
readonly registry: ProviderRegistry<SearchProvider>;
|
|
39
|
+
/** @throws When the principal lacks the permission (the host's own error). */
|
|
40
|
+
requirePermission(required: {
|
|
41
|
+
readonly principalId: string;
|
|
42
|
+
readonly permission: string;
|
|
43
|
+
}): Promise<void>;
|
|
44
|
+
/** The host's confirmation transport (e.g. an approval card). */
|
|
45
|
+
askHuman(required: {
|
|
46
|
+
readonly ctx: ToolExecutionContext;
|
|
47
|
+
readonly description: SearchApprovalDescription;
|
|
48
|
+
}, optional: ToolExecutionOptions): Promise<ApprovalAnswer>;
|
|
49
|
+
/**
|
|
50
|
+
* Persist the per-site `search.provider` setting. `principalId` is the calling tool principal, so
|
|
51
|
+
* the host's settings ledger records who made the change (added 2026-10-21, additive).
|
|
52
|
+
*/
|
|
53
|
+
setProviderSetting(required: {
|
|
54
|
+
readonly siteId: string;
|
|
55
|
+
readonly providerId: string;
|
|
56
|
+
readonly principalId: string;
|
|
57
|
+
}): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
export declare const catalog: AgentToolDefinition[];
|
|
60
|
+
/** Independently derived from the calls each handler below makes. */
|
|
61
|
+
export declare const derivedRisk: DerivedRiskByToolId;
|
|
62
|
+
/**
|
|
63
|
+
* Build the four search tool registrations.
|
|
64
|
+
* @param required - Site scope, the service/indexer/registry and the host's permission, approval and
|
|
65
|
+
* setting ports.
|
|
66
|
+
* @param optional.remembered - Persisted approval grants; only `search_reindex:<providerId>` uses it.
|
|
67
|
+
* @returns Registrations through core's `buildDomainRegistrations` (risk corroborated, schemas required).
|
|
68
|
+
* @throws Permission and port failures propagate; malformed input is a `ToolInputError`.
|
|
69
|
+
* @complexity O(1) wiring; each handler is one or two port calls.
|
|
70
|
+
*/
|
|
71
|
+
export declare function buildSearchToolRegistrations(required: SearchToolDeps, optional?: {
|
|
72
|
+
readonly remembered?: RememberedApprovalPort;
|
|
73
|
+
}): ToolRegistration[];
|
|
74
|
+
//# sourceMappingURL=tools.d.ts.map
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Agent tools for site search (lot S6), subpath `@jini-ai/search/tools`.
|
|
3
|
+
*
|
|
4
|
+
* `search_query` and `search_status` are reads. `search_reindex` (bulk vendor writes = cost) and
|
|
5
|
+
* `search_set_provider` (a settings change plus a full backfill into another backend) ask the human
|
|
6
|
+
* first through core's approval lifecycle; only the reindex grant may be remembered, per provider.
|
|
7
|
+
*
|
|
8
|
+
* Agents only ever see PUBLIC results: `search_query` never passes viewer audiences to the service,
|
|
9
|
+
* so a members-only document cannot reach a model context through this tool.
|
|
10
|
+
*
|
|
11
|
+
* Permission is checked through an injected `requirePermission` port (the `@jini-ai/db` transfer
|
|
12
|
+
* tools' shape) rather than `@jini-ai/cms/core`'s helper, so this generic package keeps its single
|
|
13
|
+
* `@jini-ai/core` dependency; the host binds the port to its own permission catalog.
|
|
14
|
+
*/
|
|
15
|
+
import { buildDomainRegistrations, createApprovalHandler, indexCatalogById, optionalString, readToolLimit, requireInputRecord, requireNoInput, requireString, ToolInputError, } from '@jini-ai/core';
|
|
16
|
+
export const SEARCH_TOOL_DOMAIN = 'search';
|
|
17
|
+
/** Reads: the setting and index health are site settings; results are public content only. */
|
|
18
|
+
export const SEARCH_READ_PERMISSION = 'settings.read';
|
|
19
|
+
/** Writes: choosing and re-filling a search backend is an integration change. */
|
|
20
|
+
export const SEARCH_MANAGE_PERMISSION = 'admin.integrations.manage';
|
|
21
|
+
const NO_INPUT = { type: 'object', additionalProperties: false, properties: {} };
|
|
22
|
+
export const catalog = [
|
|
23
|
+
{
|
|
24
|
+
name: 'search_query',
|
|
25
|
+
description: "Searches this site's published content. Returns {status:'ok', providerId, page:{hits:[{key, url, title, snippet, highlights, score}], nextCursor?}}, or {status:'invalid', message} / {status:'unavailable', reason}. Results are PUBLIC content only (never members-only or draft documents), each re-checked as visible right now. Snippets are plain text; highlights are character ranges into the snippet. Pass nextCursor back as cursor for the next page.",
|
|
26
|
+
sideEffects: 'none',
|
|
27
|
+
authorization: { permission: SEARCH_READ_PERMISSION },
|
|
28
|
+
inputSchema: {
|
|
29
|
+
type: 'object', additionalProperties: false, required: ['text'],
|
|
30
|
+
properties: {
|
|
31
|
+
text: { type: 'string', minLength: 1, description: 'What to search for.' },
|
|
32
|
+
collections: { type: 'array', items: { type: 'string' }, description: 'Limit to these collections, e.g. ["post","page"].' },
|
|
33
|
+
locale: { type: 'string' },
|
|
34
|
+
filters: { type: 'object', additionalProperties: { type: ['string', 'number', 'boolean'] }, description: 'Exact-match field filters.' },
|
|
35
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Hits per page (default 10, server-capped at 100).' },
|
|
36
|
+
cursor: { type: 'string', description: 'nextCursor from the previous page of the same query.' },
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: 'search_status',
|
|
42
|
+
description: "Reports this site's search setup. Returns {siteId, active, building}, each null or {providerId, generation, registered, counts:{pending, indexed, unknown, failed}}. `building` is set while a reindex or provider switch is filling a new index; `registered:false` means that provider's plugin is not loaded. Read-only.",
|
|
43
|
+
sideEffects: 'none',
|
|
44
|
+
authorization: { permission: SEARCH_READ_PERMISSION },
|
|
45
|
+
inputSchema: NO_INPUT,
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: 'search_reindex',
|
|
49
|
+
description: "Rebuilds this site's search index from scratch in the current provider (a new generation, filled in the background; the old index keeps serving until the new one is complete). This writes every public document to the provider and may cost money with a hosted vendor, so the human is asked to approve. Returns {started:true, providerId, generation} or {started:false, code|reason}.",
|
|
50
|
+
sideEffects: 'mutates-durable-state',
|
|
51
|
+
authorization: { permission: SEARCH_MANAGE_PERMISSION },
|
|
52
|
+
actorClassRule: 'confirmer-must-equal-own-delegatedBy',
|
|
53
|
+
inputSchema: NO_INPUT,
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'search_set_provider',
|
|
57
|
+
description: "Switches this site's search backend to a registered provider id and starts filling it in the background; the current provider keeps serving until the new index is complete. Always asks the human. Returns {started:true, providerId, generation} or {started:false, reason}. An unknown provider id is an input error listing the registered ids.",
|
|
58
|
+
sideEffects: 'mutates-durable-state',
|
|
59
|
+
authorization: { permission: SEARCH_MANAGE_PERMISSION },
|
|
60
|
+
actorClassRule: 'confirmer-must-equal-own-delegatedBy',
|
|
61
|
+
inputSchema: {
|
|
62
|
+
type: 'object', additionalProperties: false, required: ['providerId'],
|
|
63
|
+
properties: { providerId: { type: 'string', minLength: 1, description: 'A registered search provider id, e.g. "builtin".' } },
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
];
|
|
67
|
+
/** Independently derived from the calls each handler below makes. */
|
|
68
|
+
export const derivedRisk = new Map([
|
|
69
|
+
// service.query -> provider.query + access.visibleKeys: reads only.
|
|
70
|
+
['search_query', 'none'],
|
|
71
|
+
// service.status -> targets.get + state.counts: reads only.
|
|
72
|
+
['search_status', 'none'],
|
|
73
|
+
// indexer.startRebuild -> targets.setBuilding: persists a new building generation.
|
|
74
|
+
['search_reindex', 'mutates-durable-state'],
|
|
75
|
+
// setProviderSetting + indexer.startRebuild: persists the setting and a building generation.
|
|
76
|
+
['search_set_provider', 'mutates-durable-state'],
|
|
77
|
+
]);
|
|
78
|
+
function optionalStringList(input, key) {
|
|
79
|
+
const value = input[key];
|
|
80
|
+
if (value === undefined)
|
|
81
|
+
return undefined;
|
|
82
|
+
if (!Array.isArray(value) || !value.every(item => typeof item === 'string'))
|
|
83
|
+
throw new ToolInputError({ message: `'${key}' must be an array of strings` });
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
function optionalFilters(input) {
|
|
87
|
+
const value = input.filters;
|
|
88
|
+
if (value === undefined)
|
|
89
|
+
return undefined;
|
|
90
|
+
const scalar = (item) => ['string', 'number', 'boolean'].includes(typeof item);
|
|
91
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value) || !Object.values(value).every(scalar)) {
|
|
92
|
+
throw new ToolInputError({ message: "'filters' must be an object of string, number or boolean values" });
|
|
93
|
+
}
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
/** The tool input as a service query; audiences can never be part of it. */
|
|
97
|
+
function readQuery(rawInput) {
|
|
98
|
+
const input = requireInputRecord({ input: rawInput });
|
|
99
|
+
const optionals = {
|
|
100
|
+
collections: optionalStringList(input, 'collections'),
|
|
101
|
+
locale: optionalString({ input, key: 'locale' }),
|
|
102
|
+
filters: optionalFilters(input),
|
|
103
|
+
cursor: optionalString({ input, key: 'cursor' }),
|
|
104
|
+
};
|
|
105
|
+
const present = Object.fromEntries(Object.entries(optionals).filter(([, value]) => value !== undefined));
|
|
106
|
+
return { text: requireString({ input, key: 'text' }), limit: readToolLimit({ input, max: 100, fallback: 10 }), ...present };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Build the four search tool registrations.
|
|
110
|
+
* @param required - Site scope, the service/indexer/registry and the host's permission, approval and
|
|
111
|
+
* setting ports.
|
|
112
|
+
* @param optional.remembered - Persisted approval grants; only `search_reindex:<providerId>` uses it.
|
|
113
|
+
* @returns Registrations through core's `buildDomainRegistrations` (risk corroborated, schemas required).
|
|
114
|
+
* @throws Permission and port failures propagate; malformed input is a `ToolInputError`.
|
|
115
|
+
* @complexity O(1) wiring; each handler is one or two port calls.
|
|
116
|
+
*/
|
|
117
|
+
export function buildSearchToolRegistrations(required, optional = {}) {
|
|
118
|
+
const { workspaceId, siteId, service, indexer, registry } = required;
|
|
119
|
+
const allow = (ctx, permission) => required.requirePermission({ principalId: ctx.principal.id, permission });
|
|
120
|
+
const activeProviderId = async () => (await service.status({ siteId })).active?.providerId ?? null;
|
|
121
|
+
/** Shared approval lifecycle for the two writes; `run` re-checks permission after the human wait. */
|
|
122
|
+
const approvalTool = (spec) => createApprovalHandler({
|
|
123
|
+
prepare: ({ ctx }) => spec.prepare(ctx),
|
|
124
|
+
describe: ({ prepared }) => {
|
|
125
|
+
if ('refusal' in prepared)
|
|
126
|
+
return { ask: false, description: undefined };
|
|
127
|
+
const key = spec.rememberKey(prepared.providerId);
|
|
128
|
+
const description = { action: spec.action, siteId, ...prepared, summary: spec.summary(prepared) };
|
|
129
|
+
return { ask: true, description, ...(key === undefined ? {} : { rememberKey: key }) };
|
|
130
|
+
},
|
|
131
|
+
askHuman: ({ ctx, description }, options) => required.askHuman({ ctx, description: description }, options),
|
|
132
|
+
notConfirmed: ({ reason }) => ({ started: false, reason }),
|
|
133
|
+
run: async ({ ctx, prepared }) => {
|
|
134
|
+
if ('refusal' in prepared)
|
|
135
|
+
return prepared.refusal;
|
|
136
|
+
await allow(ctx, SEARCH_MANAGE_PERMISSION);
|
|
137
|
+
await spec.effect(prepared.providerId, ctx);
|
|
138
|
+
const targets = await indexer.startRebuild({ siteId, workspaceId, providerId: prepared.providerId });
|
|
139
|
+
return { started: true, providerId: prepared.providerId, generation: targets.building?.generation ?? null };
|
|
140
|
+
},
|
|
141
|
+
}, optional.remembered ? { remembered: optional.remembered } : {});
|
|
142
|
+
const reindex = approvalTool({
|
|
143
|
+
action: 'reindex',
|
|
144
|
+
prepare: async (ctx) => {
|
|
145
|
+
requireNoInput({ input: ctx.input });
|
|
146
|
+
await allow(ctx, SEARCH_MANAGE_PERMISSION);
|
|
147
|
+
const providerId = await activeProviderId();
|
|
148
|
+
if (providerId === null)
|
|
149
|
+
return { refusal: { started: false, code: 'not_configured', message: 'search has no active provider yet; use search_set_provider' } };
|
|
150
|
+
if (!registry.has({ id: providerId }))
|
|
151
|
+
return { refusal: { started: false, code: 'provider_not_registered', message: `the active search provider '${providerId}' is not loaded` } };
|
|
152
|
+
return { providerId, fromProviderId: providerId };
|
|
153
|
+
},
|
|
154
|
+
// A reindex of the same provider is a repeatable cost decision, so a grant may be remembered per provider.
|
|
155
|
+
rememberKey: providerId => `search_reindex:${providerId}`,
|
|
156
|
+
summary: ({ providerId }) => `Rebuild the search index in '${providerId}' (writes every public document to it).`,
|
|
157
|
+
effect: async () => undefined,
|
|
158
|
+
});
|
|
159
|
+
const setProvider = approvalTool({
|
|
160
|
+
action: 'set_provider',
|
|
161
|
+
prepare: async (ctx) => {
|
|
162
|
+
const providerId = requireString({ input: requireInputRecord({ input: ctx.input }), key: 'providerId' });
|
|
163
|
+
await allow(ctx, SEARCH_MANAGE_PERMISSION);
|
|
164
|
+
if (!registry.has({ id: providerId })) {
|
|
165
|
+
throw new ToolInputError({ message: `unknown search provider '${providerId}'; registered: ${registry.list().map(entry => entry.id).join(', ') || 'none'}` });
|
|
166
|
+
}
|
|
167
|
+
return { providerId, fromProviderId: await activeProviderId() };
|
|
168
|
+
},
|
|
169
|
+
// Never remembered: each switch moves the site's content to a different backend.
|
|
170
|
+
rememberKey: () => undefined,
|
|
171
|
+
summary: ({ providerId, fromProviderId }) => `Switch site search from '${fromProviderId ?? 'none'}' to '${providerId}' and copy every public document into it.`,
|
|
172
|
+
effect: (providerId, ctx) => required.setProviderSetting({ siteId, providerId, principalId: ctx.principal.id }),
|
|
173
|
+
});
|
|
174
|
+
return buildDomainRegistrations({
|
|
175
|
+
domain: SEARCH_TOOL_DOMAIN, catalogModule: '@jini-ai/search/tools',
|
|
176
|
+
catalog: indexCatalogById({ catalog }), derivedRisk,
|
|
177
|
+
handlers: {
|
|
178
|
+
search_query: async (ctx) => {
|
|
179
|
+
const query = readQuery(ctx.input);
|
|
180
|
+
await allow(ctx, SEARCH_READ_PERMISSION);
|
|
181
|
+
// No audiences: agents get public results only.
|
|
182
|
+
return service.query({ siteId, workspaceId, query });
|
|
183
|
+
},
|
|
184
|
+
search_status: async (ctx) => {
|
|
185
|
+
requireNoInput({ input: ctx.input });
|
|
186
|
+
await allow(ctx, SEARCH_READ_PERMISSION);
|
|
187
|
+
return service.status({ siteId });
|
|
188
|
+
},
|
|
189
|
+
search_reindex: reindex,
|
|
190
|
+
search_set_provider: setProvider,
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
//# sourceMappingURL=tools.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/search",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Generic site-search contract: provider interface, registry, single-writer indexer, query service with access revalidation, agent tools and a provider conformance test-kit.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/AINSEP/Jini.git",
|
|
9
|
+
"directory": "packages/search"
|
|
10
|
+
},
|
|
11
|
+
"jini": {
|
|
12
|
+
"domain": "capability",
|
|
13
|
+
"kind": "search",
|
|
14
|
+
"runtime": "universal",
|
|
15
|
+
"entries": {
|
|
16
|
+
".": "universal",
|
|
17
|
+
"./tools": "universal",
|
|
18
|
+
"./testkit": "universal",
|
|
19
|
+
"./contribution": "node"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"sideEffects": false,
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./tools": {
|
|
31
|
+
"types": "./dist/tools.d.ts",
|
|
32
|
+
"import": "./dist/tools.js",
|
|
33
|
+
"default": "./dist/tools.js"
|
|
34
|
+
},
|
|
35
|
+
"./contribution": {
|
|
36
|
+
"types": "./dist/contribution.d.ts",
|
|
37
|
+
"import": "./dist/contribution.js",
|
|
38
|
+
"default": "./dist/contribution.js"
|
|
39
|
+
},
|
|
40
|
+
"./testkit": {
|
|
41
|
+
"types": "./dist/testkit/index.d.ts",
|
|
42
|
+
"import": "./dist/testkit/index.js",
|
|
43
|
+
"default": "./dist/testkit/index.js"
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"dist",
|
|
48
|
+
"README.md",
|
|
49
|
+
"LICENSE",
|
|
50
|
+
"!dist/**/__tests__/**"
|
|
51
|
+
],
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public",
|
|
54
|
+
"registry": "https://registry.npmjs.org"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@jini-ai/core": "^0.4.9"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@vitest/coverage-v8": "^2.1.9",
|
|
61
|
+
"vitest": "^2.1.9",
|
|
62
|
+
"@jini-ai/agent-plugins": "0.4.8"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@jini-ai/agent-plugins": "^0.4.7"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"@jini-ai/agent-plugins": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"scripts": {
|
|
73
|
+
"build": "tsc -p tsconfig.json",
|
|
74
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
75
|
+
"test": "vitest run --maxWorkers=2 --minWorkers=1",
|
|
76
|
+
"test:coverage": "vitest run --maxWorkers=2 --minWorkers=1 --coverage"
|
|
77
|
+
}
|
|
6
78
|
}
|