@gmickel/gno 2.14.0 → 2.16.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/cli-reference.md +4 -2
- package/assets/spa-production.json.gz +0 -0
- package/browser-extension/artifacts/{gno-browser-clipper-v2.14.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
- package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
- package/browser-extension/dist/manifest.json +1 -1
- package/package.json +1 -1
- package/spec/cli.md +88 -45
- package/spec/db/schema.sql +45 -0
- package/spec/output-schemas/embed-receipt.schema.json +89 -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/embed.ts +341 -20
- package/src/cli/commands/links.ts +1 -1
- 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/config-cache.ts +86 -0
- package/src/cli/globals.ts +64 -0
- package/src/cli/options.ts +23 -0
- package/src/cli/program.ts +44 -37
- 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/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/section-parse.ts +16 -6
- package/src/core/typed-metadata.ts +68 -0
- package/src/core/wiki-link-syntax.ts +88 -0
- package/src/embed/backlog.ts +173 -60
- package/src/embed/batch.ts +83 -12
- package/src/embed/resume-cursor.ts +103 -0
- package/src/embed/retry.ts +41 -32
- package/src/embed/variant-backlog.ts +697 -63
- package/src/embed/variant-plan.ts +41 -45
- package/src/embed/variant-retry.ts +157 -44
- 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 +7 -5
- 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/filters.ts +169 -33
- package/src/pipeline/graph-retrieval.ts +117 -61
- package/src/pipeline/hybrid.ts +598 -329
- 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/vsearch.ts +250 -152
- 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 +18 -4
- 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/036-vector-mirror-state.ts +83 -0
- package/src/store/migrations/037-performance-indexes.ts +56 -0
- package/src/store/migrations/index.ts +4 -0
- package/src/store/sqlite/adapter.ts +1217 -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/eligibility.ts +39 -0
- package/src/store/vector/lazy.ts +17 -0
- package/src/store/vector/partition-index.ts +49 -47
- package/src/store/vector/proof-cache.ts +103 -0
- package/src/store/vector/sqlite-vec.ts +230 -139
- package/src/store/vector/stats.ts +29 -73
- package/src/store/vector/status.ts +151 -52
- package/src/store/vector/stored-vectors.ts +131 -45
- package/src/store/vector/types.ts +10 -0
- package/src/store/vector/variant-search.ts +771 -109
- package/src/store/vector/variants.ts +785 -144
- package/browser-extension/artifacts/gno-browser-clipper-v2.14.0.zip.sha256 +0 -1
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
* @module src/llm/nodeLlamaCpp/adapter
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
// Bun has no canonical-path API. Approval binds the real file identity.
|
|
8
|
+
// Bun has no canonical-path or sync stat API. Approval binds the real file identity.
|
|
9
|
+
import { statSync } from "node:fs";
|
|
9
10
|
import { realpath } from "node:fs/promises";
|
|
10
11
|
|
|
11
|
-
import type { Config } from "../../config/types";
|
|
12
|
+
import type { Config, ModelPreset } from "../../config/types";
|
|
12
13
|
import type { NativeDisposeOptions } from "../native-worker/owned-exit";
|
|
13
14
|
import type { DownloadPolicy } from "../policy";
|
|
14
15
|
import type {
|
|
@@ -32,12 +33,7 @@ import {
|
|
|
32
33
|
NativeGenerationPort,
|
|
33
34
|
NativeRerankPort,
|
|
34
35
|
} from "../native-worker/ports";
|
|
35
|
-
import {
|
|
36
|
-
getActivePreset,
|
|
37
|
-
getAnswerModelUri,
|
|
38
|
-
getExpandModelUri,
|
|
39
|
-
getModelConfig,
|
|
40
|
-
} from "../registry";
|
|
36
|
+
import { getActivePreset, getModelConfig } from "../registry";
|
|
41
37
|
|
|
42
38
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
43
39
|
// Types
|
|
@@ -72,15 +68,18 @@ export class LlmAdapter {
|
|
|
72
68
|
private readonly worker: NativeWorkerClient;
|
|
73
69
|
private readonly cache: ModelCache;
|
|
74
70
|
private readonly config: Config;
|
|
71
|
+
private readonly modelConfig: ReturnType<typeof getModelConfig>;
|
|
72
|
+
private readonly activePreset: ModelPreset;
|
|
75
73
|
|
|
76
74
|
constructor(config: Config, cacheDir?: string) {
|
|
77
75
|
this.config = config;
|
|
78
|
-
|
|
76
|
+
this.modelConfig = getModelConfig(config);
|
|
77
|
+
this.activePreset = getActivePreset(config);
|
|
79
78
|
this.worker = new NativeWorkerClient({
|
|
80
79
|
models: [],
|
|
81
|
-
loadTimeout: modelConfig.loadTimeout,
|
|
82
|
-
inferenceTimeout: modelConfig.inferenceTimeout,
|
|
83
|
-
warmModelTtl: modelConfig.warmModelTtl,
|
|
80
|
+
loadTimeout: this.modelConfig.loadTimeout,
|
|
81
|
+
inferenceTimeout: this.modelConfig.inferenceTimeout,
|
|
82
|
+
warmModelTtl: this.modelConfig.warmModelTtl,
|
|
84
83
|
});
|
|
85
84
|
this.cache = new ModelCache(cacheDir);
|
|
86
85
|
}
|
|
@@ -94,14 +93,13 @@ export class LlmAdapter {
|
|
|
94
93
|
modelUri: string | undefined,
|
|
95
94
|
options: CreatePortOptions
|
|
96
95
|
): Promise<LlmResult<EmbeddingPort>> {
|
|
97
|
-
const
|
|
98
|
-
const uri = modelUri ?? preset.embed;
|
|
96
|
+
const uri = modelUri ?? this.activePreset.embed;
|
|
99
97
|
const policy = options.policy ?? DEFAULT_POLICY;
|
|
100
98
|
|
|
101
99
|
// Use HTTP embedding for remote endpoints
|
|
102
100
|
if (isHttpModelUri(uri)) {
|
|
103
101
|
const httpEmbed = new HttpEmbedding(uri, {
|
|
104
|
-
inferenceTimeout:
|
|
102
|
+
inferenceTimeout: this.modelConfig.inferenceTimeout,
|
|
105
103
|
collections: this.config.collections,
|
|
106
104
|
collectionNames: resolveEgressCollectionNames(
|
|
107
105
|
this.config,
|
|
@@ -131,7 +129,7 @@ export class LlmAdapter {
|
|
|
131
129
|
if (!approved.ok) return approved;
|
|
132
130
|
return {
|
|
133
131
|
ok: true,
|
|
134
|
-
value: new NativeEmbeddingPort(this.worker, approved.value, uri),
|
|
132
|
+
value: new NativeEmbeddingPort(this.worker, approved.value.id, uri),
|
|
135
133
|
};
|
|
136
134
|
}
|
|
137
135
|
|
|
@@ -144,13 +142,13 @@ export class LlmAdapter {
|
|
|
144
142
|
modelUri: string | undefined,
|
|
145
143
|
options: CreatePortOptions
|
|
146
144
|
): Promise<LlmResult<GenerationPort>> {
|
|
147
|
-
const uri =
|
|
145
|
+
const uri = modelUri ?? this.activePreset.gen;
|
|
148
146
|
const policy = options.policy ?? DEFAULT_POLICY;
|
|
149
147
|
|
|
150
148
|
// Use HTTP generation for remote endpoints
|
|
151
149
|
if (isHttpGenUri(uri)) {
|
|
152
150
|
const httpGen = new HttpGeneration(uri, {
|
|
153
|
-
inferenceTimeout:
|
|
151
|
+
inferenceTimeout: this.modelConfig.inferenceTimeout,
|
|
154
152
|
collections: this.config.collections,
|
|
155
153
|
collectionNames: resolveEgressCollectionNames(
|
|
156
154
|
this.config,
|
|
@@ -175,7 +173,13 @@ export class LlmAdapter {
|
|
|
175
173
|
if (!approved.ok) return approved;
|
|
176
174
|
return {
|
|
177
175
|
ok: true,
|
|
178
|
-
value: new NativeGenerationPort(
|
|
176
|
+
value: new NativeGenerationPort(
|
|
177
|
+
this.worker,
|
|
178
|
+
approved.value.id,
|
|
179
|
+
uri,
|
|
180
|
+
approved.value.path,
|
|
181
|
+
approved.value.fingerprint
|
|
182
|
+
),
|
|
179
183
|
};
|
|
180
184
|
}
|
|
181
185
|
|
|
@@ -187,12 +191,12 @@ export class LlmAdapter {
|
|
|
187
191
|
modelUri: string | undefined,
|
|
188
192
|
options: CreatePortOptions
|
|
189
193
|
): Promise<LlmResult<GenerationPort>> {
|
|
190
|
-
const uri =
|
|
194
|
+
const uri = modelUri ?? this.activePreset.expand ?? this.activePreset.gen;
|
|
191
195
|
const policy = options.policy ?? DEFAULT_POLICY;
|
|
192
196
|
|
|
193
197
|
if (isHttpGenUri(uri)) {
|
|
194
198
|
const httpGen = new HttpGeneration(uri, {
|
|
195
|
-
inferenceTimeout:
|
|
199
|
+
inferenceTimeout: this.modelConfig.inferenceTimeout,
|
|
196
200
|
collections: this.config.collections,
|
|
197
201
|
collectionNames: resolveEgressCollectionNames(
|
|
198
202
|
this.config,
|
|
@@ -216,7 +220,13 @@ export class LlmAdapter {
|
|
|
216
220
|
if (!approved.ok) return approved;
|
|
217
221
|
return {
|
|
218
222
|
ok: true,
|
|
219
|
-
value: new NativeGenerationPort(
|
|
223
|
+
value: new NativeGenerationPort(
|
|
224
|
+
this.worker,
|
|
225
|
+
approved.value.id,
|
|
226
|
+
uri,
|
|
227
|
+
approved.value.path,
|
|
228
|
+
approved.value.fingerprint
|
|
229
|
+
),
|
|
220
230
|
};
|
|
221
231
|
}
|
|
222
232
|
|
|
@@ -229,14 +239,13 @@ export class LlmAdapter {
|
|
|
229
239
|
modelUri: string | undefined,
|
|
230
240
|
options: CreatePortOptions
|
|
231
241
|
): Promise<LlmResult<RerankPort>> {
|
|
232
|
-
const
|
|
233
|
-
const uri = modelUri ?? preset.rerank;
|
|
242
|
+
const uri = modelUri ?? this.activePreset.rerank;
|
|
234
243
|
const policy = options.policy ?? DEFAULT_POLICY;
|
|
235
244
|
|
|
236
245
|
// Use HTTP rerank for remote endpoints
|
|
237
246
|
if (isHttpRerankUri(uri)) {
|
|
238
247
|
const httpRerank = new HttpRerank(uri, {
|
|
239
|
-
inferenceTimeout:
|
|
248
|
+
inferenceTimeout: this.modelConfig.inferenceTimeout,
|
|
240
249
|
collections: this.config.collections,
|
|
241
250
|
collectionNames: resolveEgressCollectionNames(
|
|
242
251
|
this.config,
|
|
@@ -261,7 +270,7 @@ export class LlmAdapter {
|
|
|
261
270
|
if (!approved.ok) return approved;
|
|
262
271
|
return {
|
|
263
272
|
ok: true,
|
|
264
|
-
value: new NativeRerankPort(this.worker, approved.value, uri),
|
|
273
|
+
value: new NativeRerankPort(this.worker, approved.value.id, uri),
|
|
265
274
|
};
|
|
266
275
|
}
|
|
267
276
|
|
|
@@ -269,16 +278,24 @@ export class LlmAdapter {
|
|
|
269
278
|
uri: string,
|
|
270
279
|
path: string,
|
|
271
280
|
type: ModelType
|
|
272
|
-
): Promise<LlmResult<string>> {
|
|
281
|
+
): Promise<LlmResult<{ id: string; path: string; fingerprint?: string }>> {
|
|
273
282
|
try {
|
|
274
283
|
const id = `${type}:${uri}`;
|
|
284
|
+
const canonicalPath = await realpath(path);
|
|
285
|
+
let fingerprint: string | undefined;
|
|
286
|
+
try {
|
|
287
|
+
const stat = statSync(canonicalPath);
|
|
288
|
+
fingerprint = `file:${stat.size}:${Math.trunc(stat.mtimeMs)}`;
|
|
289
|
+
} catch {
|
|
290
|
+
fingerprint = undefined;
|
|
291
|
+
}
|
|
275
292
|
await this.worker.registerModel({
|
|
276
293
|
id,
|
|
277
294
|
modelUri: uri,
|
|
278
|
-
path:
|
|
295
|
+
path: canonicalPath,
|
|
279
296
|
type,
|
|
280
297
|
});
|
|
281
|
-
return { ok: true, value: id };
|
|
298
|
+
return { ok: true, value: { id, path: canonicalPath, fingerprint } };
|
|
282
299
|
} catch (cause) {
|
|
283
300
|
return {
|
|
284
301
|
ok: false,
|
|
@@ -249,54 +249,107 @@ export class NodeLlamaCppEmbedding implements EmbeddingPort {
|
|
|
249
249
|
}
|
|
250
250
|
|
|
251
251
|
try {
|
|
252
|
-
const preparedInputs: EmbeddingInput[] = [];
|
|
253
|
-
for (const text of texts) {
|
|
254
|
-
const prepared = this.truncateForEmbedding(text, "batch");
|
|
255
|
-
if (!prepared.ok) {
|
|
256
|
-
return { ok: false, error: prepared.error };
|
|
257
|
-
}
|
|
258
|
-
preparedInputs.push(prepared.value.input);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
252
|
const allResults = Array.from(
|
|
262
253
|
{ length: texts.length },
|
|
263
254
|
() => [] as number[]
|
|
264
255
|
);
|
|
265
|
-
let nextIndex = 0;
|
|
266
|
-
|
|
267
|
-
const settled = await Promise.allSettled(
|
|
268
|
-
this.workers.map(async (worker) => {
|
|
269
|
-
while (true) {
|
|
270
|
-
checkEvaluation(options);
|
|
271
|
-
const index = nextIndex;
|
|
272
|
-
nextIndex += 1;
|
|
273
|
-
if (index >= preparedInputs.length) {
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
256
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
257
|
+
if (this.workers.length === 1) {
|
|
258
|
+
// Single-context / GPU path: dispatch native getEmbeddingFor() of chunk i
|
|
259
|
+
// first, then schedule JS tokenization of chunk i+1 on the next macrotask
|
|
260
|
+
// tick so getEmbeddingFor's microtask sequence-erase continuation has
|
|
261
|
+
// already submitted native C++ evaluation before JS tokenizes chunk i+1.
|
|
262
|
+
const worker = this.workers[0]!;
|
|
263
|
+
let current = this.truncateForEmbedding(texts[0]!, "batch");
|
|
264
|
+
if (!current.ok) {
|
|
265
|
+
return { ok: false, error: current.error };
|
|
266
|
+
}
|
|
267
|
+
for (let i = 0; i < texts.length; i += 1) {
|
|
268
|
+
checkEvaluation(options);
|
|
269
|
+
startEvaluation(options);
|
|
270
|
+
const input = current.value.input;
|
|
271
|
+
const pending = this.runOnSpecificWorker(worker, (w) =>
|
|
272
|
+
w.context.getEmbeddingFor(input)
|
|
273
|
+
);
|
|
274
|
+
const nextPromise =
|
|
275
|
+
i + 1 < texts.length
|
|
276
|
+
? new Promise<LlmResult<{ input: EmbeddingInput }>>((resolve) => {
|
|
277
|
+
setImmediate(() => {
|
|
278
|
+
resolve(this.truncateForEmbedding(texts[i + 1]!, "batch"));
|
|
279
|
+
});
|
|
280
|
+
})
|
|
281
|
+
: null;
|
|
282
|
+
const embedding = await pending;
|
|
283
|
+
allResults[i] = embeddingVectorToArray(embedding.vector);
|
|
284
|
+
if (nextPromise) {
|
|
285
|
+
const next = await nextPromise;
|
|
286
|
+
if (!next.ok) {
|
|
287
|
+
return { ok: false, error: next.error };
|
|
280
288
|
}
|
|
281
|
-
|
|
282
|
-
const embedding = await this.runOnSpecificWorker(
|
|
283
|
-
worker,
|
|
284
|
-
(current) => current.context.getEmbeddingFor(input)
|
|
285
|
-
);
|
|
286
|
-
allResults[index] = embeddingVectorToArray(embedding.vector);
|
|
289
|
+
current = next;
|
|
287
290
|
}
|
|
288
|
-
}
|
|
289
|
-
|
|
291
|
+
}
|
|
292
|
+
} else {
|
|
293
|
+
// Multi-context CPU path: schedule chunks in descending token-length
|
|
294
|
+
// order (LPT) so long chunks start first and eliminate tail-straggler
|
|
295
|
+
// idle time, writing each vector back to its original index.
|
|
296
|
+
const workItems: Array<{
|
|
297
|
+
originalIndex: number;
|
|
298
|
+
input: EmbeddingInput;
|
|
299
|
+
length: number;
|
|
300
|
+
}> = [];
|
|
301
|
+
for (let i = 0; i < texts.length; i += 1) {
|
|
302
|
+
const prepared = this.truncateForEmbedding(texts[i]!, "batch");
|
|
303
|
+
if (!prepared.ok) {
|
|
304
|
+
return { ok: false, error: prepared.error };
|
|
305
|
+
}
|
|
306
|
+
const input = prepared.value.input;
|
|
307
|
+
workItems.push({
|
|
308
|
+
originalIndex: i,
|
|
309
|
+
input,
|
|
310
|
+
length:
|
|
311
|
+
typeof input === "string" || Array.isArray(input)
|
|
312
|
+
? input.length
|
|
313
|
+
: 0,
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
workItems.sort(
|
|
317
|
+
(a, b) => b.length - a.length || a.originalIndex - b.originalIndex
|
|
318
|
+
);
|
|
290
319
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
320
|
+
let nextIndex = 0;
|
|
321
|
+
const settled = await Promise.allSettled(
|
|
322
|
+
this.workers.map(async (worker) => {
|
|
323
|
+
while (true) {
|
|
324
|
+
checkEvaluation(options);
|
|
325
|
+
const workIdx = nextIndex;
|
|
326
|
+
nextIndex += 1;
|
|
327
|
+
const item = workItems[workIdx];
|
|
328
|
+
if (!item) {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
startEvaluation(options);
|
|
332
|
+
const embedding = await this.runOnSpecificWorker(
|
|
333
|
+
worker,
|
|
334
|
+
(current) => current.context.getEmbeddingFor(item.input)
|
|
335
|
+
);
|
|
336
|
+
allResults[item.originalIndex] = embeddingVectorToArray(
|
|
337
|
+
embedding.vector
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
})
|
|
341
|
+
);
|
|
342
|
+
|
|
343
|
+
const firstRejection = settled.find(
|
|
344
|
+
(result): result is PromiseRejectedResult =>
|
|
345
|
+
result.status === "rejected"
|
|
346
|
+
);
|
|
347
|
+
if (firstRejection) {
|
|
348
|
+
return {
|
|
349
|
+
ok: false,
|
|
350
|
+
error: inferenceFailedError(this.modelUri, firstRejection.reason),
|
|
351
|
+
};
|
|
352
|
+
}
|
|
300
353
|
}
|
|
301
354
|
|
|
302
355
|
checkEvaluation(options);
|
|
@@ -19,9 +19,68 @@ type LlamaModel = Awaited<
|
|
|
19
19
|
Awaited<ReturnType<typeof import("node-llama-cpp").getLlama>>["loadModel"]
|
|
20
20
|
>
|
|
21
21
|
>;
|
|
22
|
+
type LlamaContext = Awaited<ReturnType<LlamaModel["createContext"]>>;
|
|
23
|
+
type LlamaContextSequence = ReturnType<LlamaContext["getSequence"]>;
|
|
22
24
|
type Llama = Awaited<ReturnType<typeof import("node-llama-cpp").getLlama>>;
|
|
23
25
|
type JsonGrammarSchema = Parameters<Llama["createGrammarForJsonSchema"]>[0];
|
|
24
26
|
|
|
27
|
+
const MAX_CACHED_GRAMMARS_PER_LLAMA = 64;
|
|
28
|
+
const GEN_CONTEXT_REUSE_SHRINK_MIN_TOKENS = 4096;
|
|
29
|
+
|
|
30
|
+
const GRAMMAR_CACHE = new WeakMap<
|
|
31
|
+
object,
|
|
32
|
+
Map<string, Promise<JsonSchemaGrammarLike>>
|
|
33
|
+
>();
|
|
34
|
+
let cachedLlamaChatSessionPromise: Promise<
|
|
35
|
+
(typeof import("node-llama-cpp"))["LlamaChatSession"]
|
|
36
|
+
> | null = null;
|
|
37
|
+
|
|
38
|
+
function getLlamaChatSessionClass(): Promise<
|
|
39
|
+
(typeof import("node-llama-cpp"))["LlamaChatSession"]
|
|
40
|
+
> {
|
|
41
|
+
cachedLlamaChatSessionPromise ??= import("node-llama-cpp").then(
|
|
42
|
+
(mod) => mod.LlamaChatSession
|
|
43
|
+
);
|
|
44
|
+
return cachedLlamaChatSessionPromise;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function getCachedJsonSchemaGrammar(
|
|
48
|
+
llama: Llama,
|
|
49
|
+
schema: JsonGrammarSchema
|
|
50
|
+
): Promise<JsonSchemaGrammarLike> {
|
|
51
|
+
const key = JSON.stringify(schema);
|
|
52
|
+
let bySchema = GRAMMAR_CACHE.get(llama as object);
|
|
53
|
+
if (!bySchema) {
|
|
54
|
+
bySchema = new Map();
|
|
55
|
+
GRAMMAR_CACHE.set(llama as object, bySchema);
|
|
56
|
+
}
|
|
57
|
+
const existing = bySchema.get(key);
|
|
58
|
+
if (existing) {
|
|
59
|
+
// Refresh insertion order for LRU eviction.
|
|
60
|
+
bySchema.delete(key);
|
|
61
|
+
bySchema.set(key, existing);
|
|
62
|
+
return existing;
|
|
63
|
+
}
|
|
64
|
+
const created = Promise.resolve(
|
|
65
|
+
llama.createGrammarForJsonSchema(schema)
|
|
66
|
+
) as Promise<JsonSchemaGrammarLike>;
|
|
67
|
+
bySchema.set(key, created);
|
|
68
|
+
if (bySchema.size > MAX_CACHED_GRAMMARS_PER_LLAMA) {
|
|
69
|
+
const oldestKey = bySchema.keys().next().value;
|
|
70
|
+
if (oldestKey !== undefined) {
|
|
71
|
+
bySchema.delete(oldestKey);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return await created;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (bySchema.get(key) === created) {
|
|
78
|
+
bySchema.delete(key);
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
25
84
|
export interface JsonSchemaGrammarLike {
|
|
26
85
|
parse(response: string): unknown;
|
|
27
86
|
}
|
|
@@ -96,7 +155,14 @@ export class NodeLlamaCppGeneration implements GenerationPort {
|
|
|
96
155
|
private readonly manager: ModelManager;
|
|
97
156
|
readonly modelUri: string;
|
|
98
157
|
readonly structuredOutput = "json_schema" as const;
|
|
99
|
-
|
|
158
|
+
readonly modelPath: string;
|
|
159
|
+
|
|
160
|
+
private context: LlamaContext | null = null;
|
|
161
|
+
private sequence: LlamaContextSequence | null = null;
|
|
162
|
+
private contextModel: LlamaModel | null = null;
|
|
163
|
+
private contextSize = 0;
|
|
164
|
+
private pending: Promise<void> = Promise.resolve();
|
|
165
|
+
private disposed = false;
|
|
100
166
|
|
|
101
167
|
constructor(manager: ModelManager, modelUri: string, modelPath: string) {
|
|
102
168
|
this.manager = manager;
|
|
@@ -109,6 +175,39 @@ export class NodeLlamaCppGeneration implements GenerationPort {
|
|
|
109
175
|
params?: GenParams,
|
|
110
176
|
options?: NativeEvaluationOptions
|
|
111
177
|
): Promise<LlmResult<string>> {
|
|
178
|
+
if (this.disposed) {
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
error: inferenceFailedError(
|
|
182
|
+
this.modelUri,
|
|
183
|
+
new Error("Generation port is disposed")
|
|
184
|
+
),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
const operation = this.pending.then(() =>
|
|
188
|
+
this.runGenerate(prompt, params, options)
|
|
189
|
+
);
|
|
190
|
+
this.pending = operation.then(
|
|
191
|
+
() => {},
|
|
192
|
+
() => {}
|
|
193
|
+
);
|
|
194
|
+
return operation;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private async runGenerate(
|
|
198
|
+
prompt: string,
|
|
199
|
+
params?: GenParams,
|
|
200
|
+
options?: NativeEvaluationOptions
|
|
201
|
+
): Promise<LlmResult<string>> {
|
|
202
|
+
if (this.disposed) {
|
|
203
|
+
return {
|
|
204
|
+
ok: false,
|
|
205
|
+
error: inferenceFailedError(
|
|
206
|
+
this.modelUri,
|
|
207
|
+
new Error("Generation port is disposed")
|
|
208
|
+
),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
112
211
|
const lease = this.manager.acquireLease(this.modelUri);
|
|
113
212
|
try {
|
|
114
213
|
return await this.generateLeased(prompt, params, options);
|
|
@@ -130,63 +229,128 @@ export class NodeLlamaCppGeneration implements GenerationPort {
|
|
|
130
229
|
options?.signal
|
|
131
230
|
);
|
|
132
231
|
if (!model.ok) {
|
|
232
|
+
await this.releaseContext();
|
|
133
233
|
return model;
|
|
134
234
|
}
|
|
135
235
|
|
|
136
236
|
const llamaModel = model.value.model as LlamaModel;
|
|
137
|
-
let context: Awaited<ReturnType<LlamaModel["createContext"]>> | null = null;
|
|
138
237
|
try {
|
|
139
238
|
checkEvaluation(options);
|
|
239
|
+
if (llamaModel.disposed) {
|
|
240
|
+
throw new Error("Generation model is disposed");
|
|
241
|
+
}
|
|
140
242
|
const grammar = params?.jsonSchema
|
|
141
|
-
? await (
|
|
142
|
-
await this.manager.getLlama()
|
|
143
|
-
|
|
243
|
+
? await getCachedJsonSchemaGrammar(
|
|
244
|
+
await this.manager.getLlama(),
|
|
245
|
+
params.jsonSchema as JsonGrammarSchema
|
|
246
|
+
)
|
|
144
247
|
: undefined;
|
|
145
|
-
const contextSize
|
|
248
|
+
const explicitContextSize = params?.contextSize !== undefined;
|
|
249
|
+
const needed =
|
|
146
250
|
params?.contextSize ??
|
|
147
251
|
resolveGenContextSize({
|
|
148
252
|
promptTokenCount: llamaModel.tokenize(prompt).length,
|
|
149
253
|
maxTokens: params?.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
150
254
|
trainContextSize: llamaModel.trainContextSize,
|
|
151
255
|
});
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
256
|
+
|
|
257
|
+
const sizeCompatible = explicitContextSize
|
|
258
|
+
? this.contextSize === needed
|
|
259
|
+
: this.contextSize >= needed &&
|
|
260
|
+
this.contextSize <=
|
|
261
|
+
Math.max(GEN_CONTEXT_REUSE_SHRINK_MIN_TOKENS, needed * 2);
|
|
262
|
+
|
|
263
|
+
const canReuse =
|
|
264
|
+
this.context !== null &&
|
|
265
|
+
this.sequence !== null &&
|
|
266
|
+
!this.context.disposed &&
|
|
267
|
+
this.contextModel === llamaModel &&
|
|
268
|
+
sizeCompatible;
|
|
269
|
+
|
|
270
|
+
if (canReuse && this.sequence) {
|
|
271
|
+
// Clear KV state so each call starts identically from empty pos 0.
|
|
272
|
+
if (typeof this.sequence.clearHistory === "function") {
|
|
273
|
+
await this.sequence.clearHistory();
|
|
274
|
+
} else {
|
|
275
|
+
await this.releaseContext();
|
|
276
|
+
}
|
|
277
|
+
} else {
|
|
278
|
+
await this.releaseContext();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (!this.context || !this.sequence) {
|
|
282
|
+
const context = await llamaModel.createContext({
|
|
283
|
+
contextSize: needed,
|
|
284
|
+
createSignal: options?.signal,
|
|
285
|
+
});
|
|
286
|
+
const sequence = context.getSequence();
|
|
287
|
+
this.context = context;
|
|
288
|
+
this.sequence = sequence;
|
|
289
|
+
this.contextModel = llamaModel;
|
|
290
|
+
this.contextSize = needed;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const LlamaChatSession = await getLlamaChatSessionClass();
|
|
158
294
|
const session = new LlamaChatSession({
|
|
159
|
-
contextSequence:
|
|
295
|
+
contextSequence: this.sequence,
|
|
160
296
|
});
|
|
161
297
|
|
|
162
298
|
// Note: stop sequences not yet supported - requires stopOnTrigger API
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
299
|
+
let response: string;
|
|
300
|
+
try {
|
|
301
|
+
startEvaluation(options);
|
|
302
|
+
response = await promptWithJsonSchemaGrammar(
|
|
303
|
+
session as StructuredPromptSession,
|
|
304
|
+
prompt,
|
|
305
|
+
{
|
|
306
|
+
signal: options?.signal,
|
|
307
|
+
stopOnAbortSignal: false,
|
|
308
|
+
temperature: params?.temperature ?? DEFAULT_TEMPERATURE,
|
|
309
|
+
seed: params?.seed ?? DEFAULT_SEED,
|
|
310
|
+
maxTokens: params?.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
311
|
+
},
|
|
312
|
+
grammar
|
|
313
|
+
);
|
|
314
|
+
} finally {
|
|
315
|
+
// Detach the session's disposal listener from the retained sequence so
|
|
316
|
+
// repeated calls never accumulate old sessions or chat histories.
|
|
317
|
+
if (typeof session.dispose === "function") {
|
|
318
|
+
session.dispose({ disposeSequence: false });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
176
321
|
|
|
177
322
|
checkEvaluation(options);
|
|
178
323
|
return { ok: true, value: response };
|
|
179
324
|
} catch (e) {
|
|
325
|
+
await this.releaseContext();
|
|
180
326
|
return { ok: false, error: inferenceFailedError(this.modelUri, e) };
|
|
181
|
-
}
|
|
182
|
-
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private async releaseContext(): Promise<void> {
|
|
331
|
+
const context = this.context;
|
|
332
|
+
this.context = null;
|
|
333
|
+
this.sequence = null;
|
|
334
|
+
this.contextModel = null;
|
|
335
|
+
this.contextSize = 0;
|
|
336
|
+
if (context && !context.disposed) {
|
|
337
|
+
await context.dispose().catch(() => {
|
|
183
338
|
// Ignore disposal errors
|
|
184
339
|
});
|
|
185
340
|
}
|
|
186
341
|
}
|
|
187
342
|
|
|
188
343
|
async dispose(): Promise<void> {
|
|
189
|
-
|
|
190
|
-
|
|
344
|
+
this.disposed = true;
|
|
345
|
+
await this.pending;
|
|
346
|
+
if (!this.context) {
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const lease = this.manager.acquireLease(this.modelUri, false);
|
|
350
|
+
try {
|
|
351
|
+
await this.releaseContext();
|
|
352
|
+
} finally {
|
|
353
|
+
lease.release();
|
|
354
|
+
}
|
|
191
355
|
}
|
|
192
356
|
}
|
|
@@ -18,6 +18,7 @@ import type { ModelConfig } from "../../config/types";
|
|
|
18
18
|
import type { LlmResult, LoadedModel, ModelType } from "../types";
|
|
19
19
|
|
|
20
20
|
import { loadFailedError, outOfMemoryError, timeoutError } from "../errors";
|
|
21
|
+
import { registerModelManagerReset } from "../model-cleanup";
|
|
21
22
|
import { installSimulatorLifetimeGuard } from "./simulator-install";
|
|
22
23
|
|
|
23
24
|
// Types
|
|
@@ -543,6 +544,7 @@ let defaultManager: ModelManager | null = null;
|
|
|
543
544
|
export function getModelManager(config: ModelConfig): ModelManager {
|
|
544
545
|
if (!defaultManager) {
|
|
545
546
|
defaultManager = new ModelManager(config);
|
|
547
|
+
registerModelManagerReset(resetModelManager);
|
|
546
548
|
}
|
|
547
549
|
return defaultManager;
|
|
548
550
|
}
|