@gmickel/gno 2.15.0 → 2.17.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/README.md +1 -1
- package/assets/skill/SKILL.md +27 -0
- package/assets/skill/cli-reference.md +24 -15
- package/assets/spa-production.json.gz +0 -0
- package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
- package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
- package/browser-extension/dist/manifest.json +1 -1
- package/package.json +1 -1
- package/spec/cli.md +43 -3
- package/spec/db/schema.sql +53 -1
- package/spec/mcp.md +9 -3
- package/spec/output-schemas/doctor.schema.json +27 -0
- package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
- package/spec/output-schemas/search-results.schema.json +14 -0
- package/spec/output-schemas/status.schema.json +22 -0
- package/src/cli/commands/agents/commands.ts +1 -1
- package/src/cli/commands/ask.ts +1 -1
- package/src/cli/commands/context-build.ts +1 -1
- package/src/cli/commands/doctor.ts +101 -29
- package/src/cli/commands/embed.ts +2 -2
- package/src/cli/commands/links.ts +30 -6
- package/src/cli/commands/mcp/install.ts +2 -2
- package/src/cli/commands/mcp/status.ts +1 -1
- package/src/cli/commands/mcp/uninstall.ts +1 -1
- package/src/cli/commands/query.ts +1 -1
- package/src/cli/commands/shared.ts +4 -4
- package/src/cli/commands/skill/install.ts +1 -1
- package/src/cli/commands/skill/paths-cmd.ts +1 -1
- package/src/cli/commands/skill/uninstall.ts +1 -1
- package/src/cli/commands/status.ts +75 -58
- package/src/cli/commands/vec.ts +180 -8
- package/src/cli/config-cache.ts +86 -0
- package/src/cli/globals.ts +64 -0
- package/src/cli/program.ts +63 -36
- package/src/cli/run.ts +121 -67
- package/src/cli/runtime-health.ts +132 -122
- package/src/cli/session-binding.ts +11 -2
- package/src/config/saver.ts +8 -0
- package/src/config/types.ts +6 -0
- package/src/converters/adapters/browser-export/formats.ts +25 -15
- package/src/converters/adapters/email/adapter.ts +37 -53
- package/src/converters/adapters/email/html.ts +37 -20
- package/src/converters/adapters/email/mime.ts +71 -39
- package/src/converters/adapters/ical/adapter.ts +20 -12
- package/src/converters/adapters/jsonl/adapter.ts +8 -6
- package/src/converters/adapters/shared/html-text.ts +55 -37
- package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
- package/src/converters/adapters/shared/utf8-lines.ts +69 -31
- package/src/converters/adapters/transcript/adapter.ts +12 -7
- package/src/converters/adapters/xlsx/adapter.ts +10 -7
- package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
- package/src/converters/canonicalize.ts +17 -3
- package/src/converters/native/markdown.ts +24 -17
- package/src/converters/native/plaintext.ts +5 -6
- package/src/converters/registry.ts +130 -8
- package/src/core/activation-status.ts +4 -8
- package/src/core/change-diff.ts +38 -11
- package/src/core/context-compiler.ts +17 -18
- package/src/core/context-evidence.ts +116 -25
- package/src/core/context-verifier.ts +70 -31
- package/src/core/file-lock.ts +10 -2
- package/src/core/graph-analysis.ts +3 -3
- package/src/core/link-inventory-markdown.ts +2 -2
- package/src/core/links.ts +20 -87
- package/src/core/memory-fence.ts +16 -9
- package/src/core/memory-recall.ts +168 -34
- package/src/core/path-rules.ts +143 -0
- package/src/core/retrieval-trace-session.ts +3 -0
- package/src/core/retrieval-trace.ts +9 -0
- package/src/core/section-parse.ts +16 -6
- package/src/core/typed-metadata.ts +68 -0
- package/src/core/vector-partition-status.ts +13 -0
- package/src/core/wiki-link-syntax.ts +88 -0
- package/src/embed/backlog.ts +142 -60
- package/src/embed/retry.ts +39 -33
- package/src/embed/variant-backlog.ts +582 -116
- package/src/embed/variant-retry.ts +157 -48
- package/src/index.ts +3 -3
- package/src/ingestion/budget-error-codes.ts +13 -0
- package/src/ingestion/chunker.ts +60 -49
- package/src/ingestion/compiled-context.ts +4 -5
- package/src/ingestion/convert-file.ts +1 -1
- package/src/ingestion/document-metadata.ts +16 -9
- package/src/ingestion/excluded-ranges.ts +97 -0
- package/src/ingestion/file-processor.ts +122 -37
- package/src/ingestion/frontmatter.ts +35 -7
- package/src/ingestion/graph-reconciliation.ts +187 -51
- package/src/ingestion/language.ts +66 -61
- package/src/ingestion/position.ts +5 -5
- package/src/ingestion/prepare-file.ts +50 -29
- package/src/ingestion/record-adapter-canonical.ts +37 -26
- package/src/ingestion/record-adapter.ts +46 -26
- package/src/ingestion/record-container.ts +121 -53
- package/src/ingestion/record-path.ts +5 -2
- package/src/ingestion/source-availability/darwin-io.ts +10 -7
- package/src/ingestion/source-availability/darwin-path.ts +21 -3
- package/src/ingestion/source-availability/readers.ts +51 -0
- package/src/ingestion/strip.ts +39 -105
- package/src/ingestion/sync.ts +692 -386
- package/src/ingestion/typed-metadata.ts +10 -4
- package/src/ingestion/walker.ts +485 -158
- package/src/llm/cache.ts +128 -84
- package/src/llm/http-inference.ts +112 -35
- package/src/llm/http-policy.ts +101 -0
- package/src/llm/httpEmbedding.ts +8 -1
- package/src/llm/httpGeneration.ts +5 -1
- package/src/llm/httpRerank.ts +5 -1
- package/src/llm/inference-scope.ts +15 -2
- package/src/llm/lazy-ports.ts +33 -3
- package/src/llm/lockfile.ts +34 -7
- package/src/llm/model-cleanup.ts +24 -0
- package/src/llm/native-worker/client.ts +23 -12
- package/src/llm/native-worker/dispatcher.ts +19 -9
- package/src/llm/native-worker/embedding-identity.ts +42 -16
- package/src/llm/native-worker/entry.ts +2 -1
- package/src/llm/native-worker/owner.ts +1 -0
- package/src/llm/native-worker/ports.ts +86 -23
- package/src/llm/native-worker/protocol.ts +386 -55
- package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
- package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
- package/src/llm/nodeLlamaCpp/generation.ts +194 -30
- package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
- package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
- package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
- package/src/llm/types.ts +14 -0
- package/src/mcp/context.ts +342 -23
- package/src/mcp/http-transport.ts +21 -3
- package/src/mcp/tool-profile-types.ts +62 -0
- package/src/mcp/tool-profile.ts +32 -56
- package/src/mcp/tools/context.ts +5 -1
- package/src/mcp/tools/index.ts +269 -191
- package/src/mcp/tools/links.ts +14 -6
- package/src/mcp/tools/query.ts +60 -37
- package/src/mcp/tools/vsearch.ts +25 -14
- package/src/pipeline/answer.ts +133 -40
- package/src/pipeline/claim-verification.ts +293 -189
- package/src/pipeline/claim-verifier.ts +6 -7
- package/src/pipeline/egress-lineage.ts +37 -26
- package/src/pipeline/exclude.ts +34 -11
- package/src/pipeline/expansion.ts +233 -19
- package/src/pipeline/explain.ts +17 -2
- package/src/pipeline/filters.ts +169 -33
- package/src/pipeline/graph-retrieval.ts +117 -61
- package/src/pipeline/hybrid.ts +626 -330
- package/src/pipeline/hydration.ts +86 -24
- package/src/pipeline/intent.ts +15 -7
- package/src/pipeline/owner-fusion.ts +61 -19
- package/src/pipeline/query-language.ts +15 -2
- package/src/pipeline/rerank.ts +15 -22
- package/src/pipeline/search.ts +193 -72
- package/src/pipeline/snippet.ts +15 -2
- package/src/pipeline/temporal.ts +51 -10
- package/src/pipeline/types.ts +7 -0
- package/src/pipeline/vsearch.ts +269 -154
- package/src/publish/attachment-raster.ts +2 -16
- package/src/publish/encrypted-export.ts +15 -5
- package/src/serve/browse-tree.ts +50 -42
- package/src/serve/connectors.ts +2 -1
- package/src/serve/context.ts +13 -4
- package/src/serve/doc-events.ts +3 -0
- package/src/serve/public/app.tsx +49 -21
- package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
- package/src/serve/public/components/CaptureModal.tsx +14 -10
- package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
- package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
- package/src/serve/public/globals.built.css +1 -1
- package/src/serve/public/globals.css +19 -0
- package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
- package/src/serve/public/lib/metadata-filter.ts +234 -9
- package/src/serve/public/pages/Browse.tsx +61 -27
- package/src/serve/public/pages/DocView.tsx +44 -25
- package/src/serve/public/pages/GraphView.tsx +8 -3
- package/src/serve/resident-runtime.ts +199 -48
- package/src/serve/routes/api.ts +98 -67
- package/src/serve/routes/links.ts +25 -5
- package/src/serve/server.ts +1370 -1180
- package/src/serve/spa-bundle-source.ts +52 -27
- package/src/serve/status.ts +101 -52
- package/src/serve/watch-reconciliation-fallback.ts +11 -7
- package/src/serve/watch-reconciliation-shared.ts +42 -4
- package/src/serve/watch-reconciliation.ts +21 -8
- package/src/serve/watch-service-events.ts +7 -1
- package/src/serve/watch-service-hosts.ts +3 -1
- package/src/serve/watch-service.ts +46 -21
- package/src/serve/watch-snapshot-scan.ts +6 -15
- package/src/sessions/archive.ts +20 -8
- package/src/sessions/sanitize.ts +38 -18
- package/src/sessions/service.ts +180 -102
- package/src/store/migrations/037-performance-indexes.ts +56 -0
- package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
- package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
- package/src/store/migrations/index.ts +6 -0
- package/src/store/sqlite/adapter.ts +1260 -651
- package/src/store/sqlite/chunking-policy.ts +15 -1
- package/src/store/sqlite/eligibility.ts +110 -70
- package/src/store/sqlite/graph-neighbors.ts +71 -46
- package/src/store/sqlite/graph-reference-state.ts +27 -3
- package/src/store/sqlite/graph-similarity.ts +59 -12
- package/src/store/sqlite/metadata-predicate.ts +123 -28
- package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
- package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
- package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
- package/src/store/types.ts +32 -0
- package/src/store/vector/coarse-router.ts +312 -0
- package/src/store/vector/eligibility.ts +39 -0
- package/src/store/vector/lazy.ts +17 -0
- package/src/store/vector/partition-index.ts +333 -59
- package/src/store/vector/proof-cache.ts +209 -0
- package/src/store/vector/runtime-compat.ts +6 -0
- package/src/store/vector/sqlite-vec.ts +270 -162
- package/src/store/vector/stats.ts +37 -73
- package/src/store/vector/status.ts +169 -53
- package/src/store/vector/stored-vectors.ts +131 -45
- package/src/store/vector/types.ts +19 -0
- package/src/store/vector/v2-mirror.ts +669 -0
- package/src/store/vector/variant-search.ts +1187 -111
- package/src/store/vector/variants.ts +964 -160
- package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/** Pinned native formatting contract; no context allocation or input clipping. */
|
|
2
2
|
import type { LlamaModel, Token } from "node-llama-cpp";
|
|
3
3
|
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
const installedVersion = await getModuleVersion();
|
|
4
|
+
import { getNativePackageVersion } from "../native-worker/embedding-identity";
|
|
7
5
|
|
|
8
6
|
export const RERANK_NATIVE_VERSION = "3.20.0";
|
|
9
7
|
export const RERANK_TEMPLATE =
|
|
@@ -34,25 +32,52 @@ function supported(model: CapacityModel, version: string): boolean {
|
|
|
34
32
|
);
|
|
35
33
|
}
|
|
36
34
|
|
|
35
|
+
const [RERANK_PREFIX = "", RERANK_REST = ""] = RERANK_TEMPLATE.split("{query}");
|
|
36
|
+
const [RERANK_MIDDLE = "", RERANK_SUFFIX = ""] =
|
|
37
|
+
RERANK_REST.split("{document}");
|
|
38
|
+
|
|
39
|
+
interface CachedTemplateTokens {
|
|
40
|
+
tokenizeFn: CapacityModel["tokenize"];
|
|
41
|
+
prefix: readonly Token[];
|
|
42
|
+
middle: readonly Token[];
|
|
43
|
+
suffix: readonly Token[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const TEMPLATE_TOKEN_CACHE = new WeakMap<object, CachedTemplateTokens>();
|
|
47
|
+
|
|
48
|
+
function getStaticTemplateTokens(model: CapacityModel): CachedTemplateTokens {
|
|
49
|
+
const cached = TEMPLATE_TOKEN_CACHE.get(model as object);
|
|
50
|
+
if (cached && cached.tokenizeFn === model.tokenize) {
|
|
51
|
+
return cached;
|
|
52
|
+
}
|
|
53
|
+
const entry: CachedTemplateTokens = {
|
|
54
|
+
tokenizeFn: model.tokenize,
|
|
55
|
+
prefix: model.tokenize(RERANK_PREFIX, true, "trimLeadingSpace"),
|
|
56
|
+
middle: model.tokenize(RERANK_MIDDLE, true, "trimLeadingSpace"),
|
|
57
|
+
suffix: model.tokenize(RERANK_SUFFIX, true, "trimLeadingSpace"),
|
|
58
|
+
};
|
|
59
|
+
TEMPLATE_TOKEN_CACHE.set(model as object, entry);
|
|
60
|
+
return entry;
|
|
61
|
+
}
|
|
62
|
+
|
|
37
63
|
/** 3.20.0 LlamaRankingContext.js is byte-identical to the audited 3.19.1 source.
|
|
38
64
|
* Mirrors 3.20.0 _getEvaluationInput for the one audited template/vocabulary. */
|
|
39
65
|
export function formatRerankPair(
|
|
40
66
|
model: CapacityModel,
|
|
41
67
|
query: string,
|
|
42
68
|
document: string,
|
|
43
|
-
version =
|
|
69
|
+
version = getNativePackageVersion()
|
|
44
70
|
): Token[] | null {
|
|
45
71
|
if (!supported(model, version)) {
|
|
46
72
|
return null;
|
|
47
73
|
}
|
|
48
|
-
const
|
|
49
|
-
const [middle, suffix = ""] = rest.split("{document}");
|
|
74
|
+
const tpl = getStaticTemplateTokens(model);
|
|
50
75
|
const input = [
|
|
51
|
-
...
|
|
76
|
+
...tpl.prefix,
|
|
52
77
|
...model.tokenizer(query, false, "trimLeadingSpace"),
|
|
53
|
-
...
|
|
78
|
+
...tpl.middle,
|
|
54
79
|
...model.tokenizer(document, false, "trimLeadingSpace"),
|
|
55
|
-
...
|
|
80
|
+
...tpl.suffix,
|
|
56
81
|
];
|
|
57
82
|
const { bos, eos, shouldPrependBosToken, shouldAppendEosToken } =
|
|
58
83
|
model.tokens;
|
|
@@ -66,32 +91,66 @@ export function formatRerankPair(
|
|
|
66
91
|
return input;
|
|
67
92
|
}
|
|
68
93
|
|
|
69
|
-
export
|
|
94
|
+
export interface PreparedRerankBatch {
|
|
95
|
+
capacity: RerankCapacity;
|
|
96
|
+
/** Pre-tokenized query, documents, and complete audited pair token streams. */
|
|
97
|
+
queryTokens?: Token[];
|
|
98
|
+
documentTokens?: Token[][];
|
|
99
|
+
pairTokens?: Token[][];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function prepareRerankBatch(
|
|
70
103
|
model: CapacityModel,
|
|
71
104
|
query: string,
|
|
72
105
|
documents: readonly string[],
|
|
73
|
-
version =
|
|
74
|
-
):
|
|
106
|
+
version = getNativePackageVersion()
|
|
107
|
+
): PreparedRerankBatch {
|
|
75
108
|
if (documents.length === 0) {
|
|
76
|
-
return { kind: "empty" };
|
|
109
|
+
return { capacity: { kind: "empty" } };
|
|
77
110
|
}
|
|
78
111
|
if (!supported(model, version)) {
|
|
79
112
|
return {
|
|
80
|
-
|
|
81
|
-
|
|
113
|
+
capacity: {
|
|
114
|
+
kind: "auto",
|
|
115
|
+
reason: "Unsupported native version, model or template",
|
|
116
|
+
},
|
|
82
117
|
};
|
|
83
118
|
}
|
|
84
119
|
const maximum = model.trainContextSize;
|
|
85
120
|
if (!Number.isSafeInteger(maximum) || maximum <= 0) {
|
|
86
|
-
return {
|
|
121
|
+
return {
|
|
122
|
+
capacity: { kind: "auto", reason: "Unknown model context limit" },
|
|
123
|
+
};
|
|
87
124
|
}
|
|
125
|
+
const tpl = getStaticTemplateTokens(model);
|
|
126
|
+
const queryTokens = model.tokenizer(query, false, "trimLeadingSpace");
|
|
127
|
+
const { bos, eos, shouldPrependBosToken, shouldAppendEosToken } =
|
|
128
|
+
model.tokens;
|
|
129
|
+
|
|
130
|
+
const documentTokens: Token[][] = [];
|
|
131
|
+
const pairTokens: Token[][] = [];
|
|
88
132
|
let requiredTokens = 0;
|
|
89
133
|
for (const document of documents) {
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
134
|
+
const docTokens = model.tokenizer(document, false, "trimLeadingSpace");
|
|
135
|
+
documentTokens.push(docTokens);
|
|
136
|
+
const pair: Token[] = [
|
|
137
|
+
...tpl.prefix,
|
|
138
|
+
...queryTokens,
|
|
139
|
+
...tpl.middle,
|
|
140
|
+
...docTokens,
|
|
141
|
+
...tpl.suffix,
|
|
142
|
+
];
|
|
143
|
+
if (shouldPrependBosToken && bos != null && pair.at(0) !== bos) {
|
|
144
|
+
pair.unshift(bos);
|
|
145
|
+
}
|
|
146
|
+
if (shouldAppendEosToken && eos != null && pair.at(-1) !== eos) {
|
|
147
|
+
// Native 3.20.0 prepends here despite calling this an end token. Preserve parity.
|
|
148
|
+
pair.unshift(eos);
|
|
149
|
+
}
|
|
150
|
+
pairTokens.push(pair);
|
|
151
|
+
if (pair.length > requiredTokens) {
|
|
152
|
+
requiredTokens = pair.length;
|
|
93
153
|
}
|
|
94
|
-
requiredTokens = Math.max(requiredTokens, tokens.length);
|
|
95
154
|
}
|
|
96
155
|
if (requiredTokens > maximum) {
|
|
97
156
|
throw new RangeError(
|
|
@@ -103,9 +162,28 @@ export function getRerankCapacity(
|
|
|
103
162
|
const contextSize = Math.ceil((requiredTokens + 256) / 256) * 256;
|
|
104
163
|
if (contextSize > maximum) {
|
|
105
164
|
return {
|
|
106
|
-
|
|
107
|
-
|
|
165
|
+
capacity: {
|
|
166
|
+
kind: "auto",
|
|
167
|
+
reason: "Padded capacity exceeds model context limit",
|
|
168
|
+
},
|
|
169
|
+
queryTokens,
|
|
170
|
+
documentTokens,
|
|
171
|
+
pairTokens,
|
|
108
172
|
};
|
|
109
173
|
}
|
|
110
|
-
return {
|
|
174
|
+
return {
|
|
175
|
+
capacity: { kind: "sized", contextSize, requiredTokens },
|
|
176
|
+
queryTokens,
|
|
177
|
+
documentTokens,
|
|
178
|
+
pairTokens,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function getRerankCapacity(
|
|
183
|
+
model: CapacityModel,
|
|
184
|
+
query: string,
|
|
185
|
+
documents: readonly string[],
|
|
186
|
+
version = getNativePackageVersion()
|
|
187
|
+
): RerankCapacity {
|
|
188
|
+
return prepareRerankBatch(model, query, documents, version).capacity;
|
|
111
189
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { Token } from "node-llama-cpp";
|
|
2
|
+
|
|
1
3
|
import type { NativeEvaluationOptions } from "../native-worker/evaluation";
|
|
2
4
|
import type { LlmResult, RerankPort, RerankScore } from "../types";
|
|
3
5
|
/**
|
|
@@ -9,7 +11,7 @@ import type { ModelManager } from "./lifecycle";
|
|
|
9
11
|
|
|
10
12
|
import { inferenceFailedError } from "../errors";
|
|
11
13
|
import { checkEvaluation, startEvaluation } from "../native-worker/evaluation";
|
|
12
|
-
import {
|
|
14
|
+
import { prepareRerankBatch } from "./rerank-capacity";
|
|
13
15
|
|
|
14
16
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
15
17
|
// Types
|
|
@@ -20,6 +22,100 @@ type LlamaModel = Awaited<
|
|
|
20
22
|
Awaited<ReturnType<typeof import("node-llama-cpp").getLlama>>["loadModel"]
|
|
21
23
|
>
|
|
22
24
|
>;
|
|
25
|
+
type LlamaRankingContext = Awaited<
|
|
26
|
+
ReturnType<LlamaModel["createRankingContext"]>
|
|
27
|
+
>;
|
|
28
|
+
|
|
29
|
+
const RERANK_HYSTERESIS_MIN_TOKENS = 2048;
|
|
30
|
+
const DUAL_RERANK_MIN_CPU_CORES = 12;
|
|
31
|
+
const DUAL_RERANK_THREADS_PER_CONTEXT = 6;
|
|
32
|
+
|
|
33
|
+
interface NativeDirectRankingContext {
|
|
34
|
+
_evaluateRankingForInput(input: Token[]): Promise<number>;
|
|
35
|
+
_llamaContext?: { contextSize?: number };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function asDirectRankingContext(
|
|
39
|
+
context: LlamaRankingContext
|
|
40
|
+
): NativeDirectRankingContext | null {
|
|
41
|
+
const candidate = context as unknown as Partial<NativeDirectRankingContext>;
|
|
42
|
+
return typeof candidate._evaluateRankingForInput === "function"
|
|
43
|
+
? (candidate as NativeDirectRankingContext)
|
|
44
|
+
: null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function scoreUniqueWithContext(
|
|
48
|
+
context: LlamaRankingContext,
|
|
49
|
+
query: string,
|
|
50
|
+
uniqueDocs: string[],
|
|
51
|
+
pairTokens?: Token[][]
|
|
52
|
+
): Promise<number[]> {
|
|
53
|
+
// Fast path for pinned node-llama-cpp@3.20.0 audited pairs: evaluate the
|
|
54
|
+
// pre-built complete token sequences directly so neither static template
|
|
55
|
+
// fragments, query, nor documents are re-tokenized during scoring.
|
|
56
|
+
const direct = asDirectRankingContext(context);
|
|
57
|
+
if (
|
|
58
|
+
direct !== null &&
|
|
59
|
+
pairTokens !== undefined &&
|
|
60
|
+
pairTokens.length === uniqueDocs.length
|
|
61
|
+
) {
|
|
62
|
+
const limit = direct._llamaContext?.contextSize;
|
|
63
|
+
if (typeof limit === "number" && limit > 0) {
|
|
64
|
+
let maxLen = 0;
|
|
65
|
+
for (const tokens of pairTokens) {
|
|
66
|
+
if (tokens.length > maxLen) maxLen = tokens.length;
|
|
67
|
+
}
|
|
68
|
+
if (maxLen > limit) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`The input lengths of some of the given documents exceed the context size. Try to increase the context size to at least ${maxLen + 1} or use another model that supports longer contexts.`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const raw = await Promise.all(
|
|
75
|
+
pairTokens.map((tokens) => direct._evaluateRankingForInput(tokens))
|
|
76
|
+
);
|
|
77
|
+
if (raw.length !== uniqueDocs.length) {
|
|
78
|
+
throw new Error("Rerank returned incomplete scores");
|
|
79
|
+
}
|
|
80
|
+
for (const score of raw) {
|
|
81
|
+
if (!Number.isFinite(score)) {
|
|
82
|
+
throw new Error("Rerank returned invalid candidate scores");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return raw;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (typeof context.rankAll === "function") {
|
|
89
|
+
const raw = await context.rankAll(query, uniqueDocs);
|
|
90
|
+
if (raw.length !== uniqueDocs.length) {
|
|
91
|
+
throw new Error("Rerank returned incomplete scores");
|
|
92
|
+
}
|
|
93
|
+
for (const score of raw) {
|
|
94
|
+
if (!Number.isFinite(score)) {
|
|
95
|
+
throw new Error("Rerank returned invalid candidate scores");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return raw;
|
|
99
|
+
}
|
|
100
|
+
// Fallback for test doubles that only implement rankAndSort.
|
|
101
|
+
const ranked = await context.rankAndSort(query, uniqueDocs);
|
|
102
|
+
if (ranked.length !== uniqueDocs.length) {
|
|
103
|
+
throw new Error("Rerank returned incomplete scores");
|
|
104
|
+
}
|
|
105
|
+
const indexByDoc = new Map<string, number>();
|
|
106
|
+
for (let i = 0; i < uniqueDocs.length; i += 1) {
|
|
107
|
+
indexByDoc.set(uniqueDocs[i]!, i);
|
|
108
|
+
}
|
|
109
|
+
const scores = Array.from<number>({ length: uniqueDocs.length });
|
|
110
|
+
for (const item of ranked) {
|
|
111
|
+
const idx = indexByDoc.get(item.document);
|
|
112
|
+
if (idx === undefined || !Number.isFinite(item.score)) {
|
|
113
|
+
throw new Error("Rerank returned invalid candidate scores");
|
|
114
|
+
}
|
|
115
|
+
scores[idx] = item.score;
|
|
116
|
+
}
|
|
117
|
+
return scores;
|
|
118
|
+
}
|
|
23
119
|
|
|
24
120
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
25
121
|
// Implementation
|
|
@@ -30,12 +126,11 @@ export class NodeLlamaCppRerank implements RerankPort {
|
|
|
30
126
|
readonly modelUri: string;
|
|
31
127
|
private readonly modelPath: string;
|
|
32
128
|
|
|
33
|
-
private
|
|
34
|
-
ReturnType<LlamaModel["createRankingContext"]>
|
|
35
|
-
> | null = null;
|
|
129
|
+
private contexts: LlamaRankingContext[] = [];
|
|
36
130
|
private contextModel: LlamaModel | null = null;
|
|
37
131
|
private contextSize: number | undefined;
|
|
38
132
|
private contextConfiguration: string | undefined;
|
|
133
|
+
private contextPoolSize = 0;
|
|
39
134
|
private pending: Promise<void> = Promise.resolve();
|
|
40
135
|
private disposed = false;
|
|
41
136
|
|
|
@@ -75,6 +170,34 @@ export class NodeLlamaCppRerank implements RerankPort {
|
|
|
75
170
|
return operation;
|
|
76
171
|
}
|
|
77
172
|
|
|
173
|
+
private contextSizeCompatible(needed: number | undefined): boolean {
|
|
174
|
+
if (needed === undefined) {
|
|
175
|
+
return this.contextSize === undefined;
|
|
176
|
+
}
|
|
177
|
+
return (
|
|
178
|
+
this.contextSize !== undefined &&
|
|
179
|
+
this.contextSize >= needed &&
|
|
180
|
+
this.contextSize <= Math.max(RERANK_HYSTERESIS_MIN_TOKENS, needed * 2)
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private async resolveTargetPoolConfig(): Promise<{
|
|
185
|
+
poolSize: number;
|
|
186
|
+
threads?: number;
|
|
187
|
+
}> {
|
|
188
|
+
if (typeof this.manager.getLlama !== "function") {
|
|
189
|
+
return { poolSize: 1 };
|
|
190
|
+
}
|
|
191
|
+
const llama = await this.manager.getLlama();
|
|
192
|
+
if (
|
|
193
|
+
llama.gpu === false &&
|
|
194
|
+
llama.cpuMathCores >= DUAL_RERANK_MIN_CPU_CORES
|
|
195
|
+
) {
|
|
196
|
+
return { poolSize: 2, threads: DUAL_RERANK_THREADS_PER_CONTEXT };
|
|
197
|
+
}
|
|
198
|
+
return { poolSize: 1 };
|
|
199
|
+
}
|
|
200
|
+
|
|
78
201
|
private async score(
|
|
79
202
|
query: string,
|
|
80
203
|
documents: string[],
|
|
@@ -93,7 +216,24 @@ export class NodeLlamaCppRerank implements RerankPort {
|
|
|
93
216
|
checkEvaluation(options);
|
|
94
217
|
const llamaModel = model.value.model as LlamaModel;
|
|
95
218
|
if (llamaModel.disposed) throw new Error("Rerank model is disposed");
|
|
96
|
-
|
|
219
|
+
|
|
220
|
+
// Deduplicate identical documents before capacity estimation and neural scoring.
|
|
221
|
+
const uniqueDocs: string[] = [];
|
|
222
|
+
const uniqueIndexByDoc = new Map<string, number>();
|
|
223
|
+
const docToUniqueIndex = Array.from<number>({ length: documents.length });
|
|
224
|
+
for (let i = 0; i < documents.length; i += 1) {
|
|
225
|
+
const doc = documents[i]!;
|
|
226
|
+
let u = uniqueIndexByDoc.get(doc);
|
|
227
|
+
if (u === undefined) {
|
|
228
|
+
u = uniqueDocs.length;
|
|
229
|
+
uniqueIndexByDoc.set(doc, u);
|
|
230
|
+
uniqueDocs.push(doc);
|
|
231
|
+
}
|
|
232
|
+
docToUniqueIndex[i] = u;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const prepared = prepareRerankBatch(llamaModel, query, uniqueDocs);
|
|
236
|
+
const { capacity, pairTokens } = prepared;
|
|
97
237
|
const contextSize =
|
|
98
238
|
capacity.kind === "sized" ? capacity.contextSize : undefined;
|
|
99
239
|
const configuration = JSON.stringify([
|
|
@@ -102,54 +242,120 @@ export class NodeLlamaCppRerank implements RerankPort {
|
|
|
102
242
|
llamaModel.vocabularyType,
|
|
103
243
|
llamaModel.trainContextSize,
|
|
104
244
|
]);
|
|
245
|
+
const poolConfig = await this.resolveTargetPoolConfig();
|
|
246
|
+
const anyDisposed = this.contexts.some((ctx) => ctx.disposed);
|
|
105
247
|
if (
|
|
106
248
|
this.contextConfiguration !== configuration ||
|
|
107
249
|
this.contextModel !== llamaModel ||
|
|
108
|
-
this.
|
|
109
|
-
this.
|
|
250
|
+
this.contextPoolSize !== poolConfig.poolSize ||
|
|
251
|
+
!this.contextSizeCompatible(contextSize) ||
|
|
252
|
+
anyDisposed
|
|
110
253
|
) {
|
|
111
254
|
await this.releaseContext();
|
|
112
255
|
}
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
256
|
+
if (this.contexts.length === 0) {
|
|
257
|
+
const created: LlamaRankingContext[] = [];
|
|
258
|
+
try {
|
|
259
|
+
for (let i = 0; i < poolConfig.poolSize; i += 1) {
|
|
260
|
+
const ctx = await llamaModel.createRankingContext({
|
|
261
|
+
...(contextSize === undefined ? {} : { contextSize }),
|
|
262
|
+
...(poolConfig.threads === undefined
|
|
263
|
+
? {}
|
|
264
|
+
: { threads: poolConfig.threads }),
|
|
265
|
+
createSignal: options?.signal,
|
|
266
|
+
});
|
|
267
|
+
created.push(ctx);
|
|
268
|
+
}
|
|
269
|
+
} catch (error) {
|
|
270
|
+
await Promise.allSettled(
|
|
271
|
+
created.map((ctx) => (!ctx.disposed ? ctx.dispose() : undefined))
|
|
272
|
+
);
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
this.contexts = created;
|
|
118
276
|
this.contextModel = llamaModel;
|
|
119
277
|
this.contextSize = contextSize;
|
|
120
278
|
this.contextConfiguration = configuration;
|
|
279
|
+
this.contextPoolSize = poolConfig.poolSize;
|
|
121
280
|
}
|
|
122
|
-
if (this.
|
|
281
|
+
if (this.contexts.some((ctx) => ctx.disposed) || llamaModel.disposed) {
|
|
123
282
|
throw new Error("Rerank context is disposed");
|
|
124
|
-
// Build index map for O(1) lookups (handles duplicates correctly)
|
|
125
|
-
const indexMap = new Map<string, number[]>();
|
|
126
|
-
for (let i = 0; i < documents.length; i += 1) {
|
|
127
|
-
const doc = documents[i] as string; // Guaranteed by loop bounds
|
|
128
|
-
const indices = indexMap.get(doc) ?? [];
|
|
129
|
-
indices.push(i);
|
|
130
|
-
indexMap.set(doc, indices);
|
|
131
283
|
}
|
|
132
284
|
|
|
133
285
|
startEvaluation(options);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
286
|
+
let uniqueScores: number[];
|
|
287
|
+
if (this.contexts.length > 1 && uniqueDocs.length > 1) {
|
|
288
|
+
// LPT bin-packing across the 2 CPU ranking contexts: sort unique docs
|
|
289
|
+
// longest-first and assign each to the lighter context bucket.
|
|
290
|
+
const order = uniqueDocs.map((doc, idx) => ({ idx, len: doc.length }));
|
|
291
|
+
order.sort((a, b) => b.len - a.len || a.idx - b.idx);
|
|
292
|
+
const buckets: Array<{
|
|
293
|
+
indices: number[];
|
|
294
|
+
docs: string[];
|
|
295
|
+
pairs: Token[][];
|
|
296
|
+
load: number;
|
|
297
|
+
}> = this.contexts.map(() => ({
|
|
298
|
+
indices: [],
|
|
299
|
+
docs: [],
|
|
300
|
+
pairs: [],
|
|
301
|
+
load: 0,
|
|
302
|
+
}));
|
|
303
|
+
for (const item of order) {
|
|
304
|
+
let lightest = buckets[0]!;
|
|
305
|
+
for (let b = 1; b < buckets.length; b += 1) {
|
|
306
|
+
if (buckets[b]!.load < lightest.load) {
|
|
307
|
+
lightest = buckets[b]!;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
lightest.indices.push(item.idx);
|
|
311
|
+
lightest.docs.push(uniqueDocs[item.idx]!);
|
|
312
|
+
if (pairTokens) {
|
|
313
|
+
lightest.pairs.push(pairTokens[item.idx]!);
|
|
314
|
+
}
|
|
315
|
+
lightest.load += item.len;
|
|
146
316
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
317
|
+
const bucketResults = await Promise.all(
|
|
318
|
+
buckets.map((bucket, idx) =>
|
|
319
|
+
bucket.docs.length > 0
|
|
320
|
+
? scoreUniqueWithContext(
|
|
321
|
+
this.contexts[idx]!,
|
|
322
|
+
query,
|
|
323
|
+
bucket.docs,
|
|
324
|
+
pairTokens ? bucket.pairs : undefined
|
|
325
|
+
)
|
|
326
|
+
: Promise.resolve([] as number[])
|
|
327
|
+
)
|
|
328
|
+
);
|
|
329
|
+
uniqueScores = Array.from<number>({ length: uniqueDocs.length });
|
|
330
|
+
for (let b = 0; b < buckets.length; b += 1) {
|
|
331
|
+
const indices = buckets[b]!.indices;
|
|
332
|
+
const scores = bucketResults[b]!;
|
|
333
|
+
for (let j = 0; j < indices.length; j += 1) {
|
|
334
|
+
uniqueScores[indices[j]!] = scores[j]!;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
} else {
|
|
338
|
+
uniqueScores = await scoreUniqueWithContext(
|
|
339
|
+
this.contexts[0]!,
|
|
340
|
+
query,
|
|
341
|
+
uniqueDocs,
|
|
342
|
+
pairTokens
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
checkEvaluation(options);
|
|
346
|
+
|
|
347
|
+
// Expand unique scores back to all original indices and stable-sort
|
|
348
|
+
// descending by score (ties preserve original input index order).
|
|
349
|
+
const scored = documents.map((_, index) => ({
|
|
350
|
+
index,
|
|
351
|
+
score: uniqueScores[docToUniqueIndex[index]!]!,
|
|
352
|
+
}));
|
|
353
|
+
scored.sort((a, b) => b.score - a.score || a.index - b.index);
|
|
354
|
+
const scores: RerankScore[] = scored.map((item, rank) => ({
|
|
355
|
+
index: item.index,
|
|
356
|
+
score: item.score,
|
|
357
|
+
rank: rank + 1,
|
|
358
|
+
}));
|
|
153
359
|
|
|
154
360
|
return { ok: true, value: scores };
|
|
155
361
|
} catch (e) {
|
|
@@ -161,15 +367,18 @@ export class NodeLlamaCppRerank implements RerankPort {
|
|
|
161
367
|
}
|
|
162
368
|
|
|
163
369
|
private async releaseContext(): Promise<void> {
|
|
164
|
-
const
|
|
165
|
-
this.
|
|
370
|
+
const contexts = this.contexts;
|
|
371
|
+
this.contexts = [];
|
|
166
372
|
this.contextModel = null;
|
|
167
373
|
this.contextSize = undefined;
|
|
168
374
|
this.contextConfiguration = undefined;
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
375
|
+
this.contextPoolSize = 0;
|
|
376
|
+
for (const context of contexts) {
|
|
377
|
+
if (context && !context.disposed) {
|
|
378
|
+
await context.dispose().catch(() => {
|
|
379
|
+
// A failed native context must never be reused.
|
|
380
|
+
});
|
|
381
|
+
}
|
|
173
382
|
}
|
|
174
383
|
}
|
|
175
384
|
|
package/src/llm/types.ts
CHANGED
|
@@ -117,8 +117,22 @@ export interface EmbeddingPort {
|
|
|
117
117
|
dispose(): Promise<void>;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
export interface GenerationModelIdentity {
|
|
121
|
+
modelPath?: string;
|
|
122
|
+
modelFingerprint?: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
120
125
|
export interface GenerationPort {
|
|
121
126
|
readonly modelUri: string;
|
|
127
|
+
/** Resolved local GGUF path when backed by a local or downloaded file. */
|
|
128
|
+
readonly modelPath?: string;
|
|
129
|
+
/** Optional stable model fingerprint for deterministic cache invalidation. */
|
|
130
|
+
readonly modelFingerprint?: string;
|
|
131
|
+
/**
|
|
132
|
+
* Optional read-only probe returning cached local model identity before
|
|
133
|
+
* initializing a lazy port (must not download models or spawn workers).
|
|
134
|
+
*/
|
|
135
|
+
resolveModelIdentity?(): Promise<GenerationModelIdentity | null>;
|
|
122
136
|
/** Undefined is treated as unsupported for backwards-compatible ports. */
|
|
123
137
|
readonly structuredOutput?: StructuredOutputCapability;
|
|
124
138
|
generate(
|