@qvac/harness 0.8.11 → 0.8.13
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/CHANGELOG.md +139 -1
- package/dist-lib/index.d.ts +1 -0
- package/dist-lib/index.js +16 -8
- package/dist-lib/lib/capabilities/completion.d.ts +9 -1
- package/dist-lib/lib/capabilities/completion.js +87 -25
- package/dist-lib/lib/capabilities/preview-model-source.d.ts +7 -1
- package/dist-lib/lib/capabilities/preview-model-source.js +80 -22
- package/dist-lib/lib/capabilities/tool-search.d.ts +4 -0
- package/dist-lib/lib/capabilities/tool-search.js +9 -0
- package/dist-lib/lib/capabilities/tool-selection.d.ts +3 -1
- package/dist-lib/lib/capabilities/tool-selection.js +3 -2
- package/dist-lib/lib/connect.js +3 -2
- package/dist-lib/lib/contract-types.d.ts +1 -0
- package/dist-lib/lib/errors.d.ts +4 -0
- package/dist-lib/lib/errors.js +6 -0
- package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
- package/dist-lib/lib/hardware/cpu-placement.js +48 -0
- package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
- package/dist-lib/lib/models/custom-model-cache.js +3 -0
- package/dist-lib/lib/models/gguf-header.d.ts +11 -0
- package/dist-lib/lib/models/gguf-header.js +203 -15
- package/dist-lib/lib/models/kv-cache.d.ts +2 -0
- package/dist-lib/lib/models/kv-cache.js +8 -0
- package/dist-lib/lib/models/llm-presets.d.ts +2 -1
- package/dist-lib/lib/models/llm-presets.js +2 -2
- package/dist-lib/lib/models/model-handle.d.ts +1 -0
- package/dist-lib/lib/models/model-pool.d.ts +6 -1
- package/dist-lib/lib/models/model-pool.js +22 -10
- package/dist-lib/lib/models/model-source.d.ts +1 -0
- package/dist-lib/lib/models/model-source.js +20 -3
- package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
- package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
- package/dist-lib/lib/prompt.d.ts +2 -1
- package/dist-lib/lib/prompt.js +12 -12
- package/dist-lib/lib/serve.js +3 -2
- package/dist-lib/lib/tools/edit-image.js +4 -3
- package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
- package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
- package/dist-lib/lib/tools/exec/obsidian/guidance.js +2 -2
- package/dist-lib/lib/tools/exec/obsidian/vault-read.js +17 -16
- package/dist-lib/lib/tools/generate-image.js +4 -3
- package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
- package/dist-lib/lib/tools/http-request/request.js +2 -1
- package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
- package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
- package/dist-lib/lib/tools/http-request.js +13 -6
- package/dist-lib/lib/tools/mcp-call.js +1 -0
- package/dist-lib/lib/tools/office/ops.d.ts +1 -0
- package/dist-lib/lib/tools/office/ops.js +5 -1
- package/dist-lib/lib/tools/office.d.ts +1 -0
- package/dist-lib/lib/tools/office.js +197 -35
- package/dist-lib/lib/tools/operations/compile.js +4 -4
- package/dist-lib/lib/tools/pdf/build.d.ts +5 -1
- package/dist-lib/lib/tools/pdf/build.js +31 -6
- package/dist-lib/lib/tools/pdf.js +17 -2
- package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
- package/dist-lib/lib/tools/skills/credential-check.js +1 -0
- package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
- package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
- package/dist-lib/schema/harness.js +2 -1
- package/dist-lib/spec/hrpc/messages.js +8 -5
- package/dist-lib/spec/hyperschema/index.js +8 -5
- package/dist-lib/spec/hyperschema/schema.json +6 -1
- package/dist-lib/spec/hyperschema/types.d.ts +2 -1
- package/package.json +5 -5
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
1
2
|
import fs from 'fs';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import path from 'path';
|
|
2
5
|
import defaultFetch from '#fetch';
|
|
3
6
|
import { errorMessage } from '../guards.js';
|
|
4
7
|
import { defaultContextSize } from '../models/context.js';
|
|
5
|
-
import { isRemoteSource, localSourcePath, parseGgufHeader, readGgufHeaderBytes } from '../models/gguf-header.js';
|
|
8
|
+
import { fetchGgufStub, isRemoteSource, localSourcePath, parseGgufHeader, readGgufHeaderBytes } from '../models/gguf-header.js';
|
|
6
9
|
import { shardSet } from '../models/shards.js';
|
|
7
10
|
const HUGGING_FACE = 'https://huggingface.co';
|
|
8
11
|
const HUGGING_FACE_HOSTS = new Set(['huggingface.co', 'www.huggingface.co', 'hf.co']);
|
|
@@ -17,6 +20,7 @@ const PIPELINE_TASKS = {
|
|
|
17
20
|
'text-generation': 'llm',
|
|
18
21
|
'image-text-to-text': 'llm'
|
|
19
22
|
};
|
|
23
|
+
const SD_CPP_TAGS = new Set(['sd.cpp', 'stable-diffusion.cpp']);
|
|
20
24
|
const ARCHITECTURE_TASKS = [
|
|
21
25
|
[/^whisper/i, 'speech-to-text'],
|
|
22
26
|
[/^parakeet/i, 'speech-to-text'],
|
|
@@ -25,8 +29,10 @@ const ARCHITECTURE_TASKS = [
|
|
|
25
29
|
[/bert/i, 'embeddings']
|
|
26
30
|
];
|
|
27
31
|
const NOT_LLM_REASON = 'Fit is estimated only for text-generation models.';
|
|
28
|
-
const
|
|
32
|
+
const NO_ARCHITECTURE_REASON = 'This GGUF names no model architecture, so it cannot run as a text model.';
|
|
29
33
|
const NO_ESTIMATOR_REASON = 'This harness has no fit estimator.';
|
|
34
|
+
const SHARDED_REASON = 'Fit is estimated only for a model in one file, and this one is split.';
|
|
35
|
+
const NO_TENSOR_LIST_REASON = 'Could not read the tensor list the fit estimate needs.';
|
|
30
36
|
export async function previewModelSource(context, deps = {}) {
|
|
31
37
|
const fetch = deps.fetch ?? defaultFetch;
|
|
32
38
|
const src = context.src.trim();
|
|
@@ -37,15 +43,15 @@ export async function previewModelSource(context, deps = {}) {
|
|
|
37
43
|
if ('answer' in weight) {
|
|
38
44
|
return weight.answer;
|
|
39
45
|
}
|
|
40
|
-
const problem = modelProblem(weight.header);
|
|
41
|
-
if (problem) {
|
|
42
|
-
return refuse(problem[0], problem[1]);
|
|
43
|
-
}
|
|
44
46
|
const taskType = taskTypeFor({
|
|
45
47
|
pipelineTag: weight.file.pipelineTag,
|
|
46
48
|
tags: [...(weight.file.tags ?? []), ...(weight.header.tags ?? [])],
|
|
47
|
-
|
|
49
|
+
header: weight.header
|
|
48
50
|
});
|
|
51
|
+
const problem = modelProblem(weight.header, taskType);
|
|
52
|
+
if (problem) {
|
|
53
|
+
return refuse(problem[0], problem[1]);
|
|
54
|
+
}
|
|
49
55
|
let projectionBytes = 0;
|
|
50
56
|
let projectionSrc;
|
|
51
57
|
const mmprojSrc = context.mmprojSrc?.trim();
|
|
@@ -62,7 +68,7 @@ export async function previewModelSource(context, deps = {}) {
|
|
|
62
68
|
projectionBytes = projection.file.sizeBytes;
|
|
63
69
|
projectionSrc = projection.file.src;
|
|
64
70
|
}
|
|
65
|
-
const { fit, fitReasons } = await assess(weight, taskType, deps);
|
|
71
|
+
const { fit, fitReasons } = await assess(weight, taskType, { deps, fetch });
|
|
66
72
|
return defined({
|
|
67
73
|
ok: true,
|
|
68
74
|
src: weight.file.src,
|
|
@@ -331,7 +337,7 @@ function fileOf(ref, sibling) {
|
|
|
331
337
|
sha256: sibling.lfs?.sha256
|
|
332
338
|
});
|
|
333
339
|
}
|
|
334
|
-
function modelProblem(header) {
|
|
340
|
+
function modelProblem(header, taskType) {
|
|
335
341
|
if (isProjection(header)) {
|
|
336
342
|
return [
|
|
337
343
|
'not-a-model',
|
|
@@ -341,35 +347,49 @@ function modelProblem(header) {
|
|
|
341
347
|
if (header.type === 'adapter') {
|
|
342
348
|
return ['not-a-model', 'This is a LoRA adapter, not a model.'];
|
|
343
349
|
}
|
|
350
|
+
if (taskType === 'llm' && !header.architecture) {
|
|
351
|
+
return ['not-a-model', NO_ARCHITECTURE_REASON];
|
|
352
|
+
}
|
|
344
353
|
return null;
|
|
345
354
|
}
|
|
346
355
|
function isProjection(header) {
|
|
347
356
|
return header.architecture === 'clip' || header.type === 'mmproj';
|
|
348
357
|
}
|
|
349
|
-
function taskTypeFor({ pipelineTag, tags = [],
|
|
358
|
+
function taskTypeFor({ pipelineTag, tags = [], header }) {
|
|
350
359
|
const tagged = [pipelineTag, ...tags].find((tag) => tag !== undefined && Object.hasOwn(PIPELINE_TASKS, tag));
|
|
351
360
|
if (tagged) {
|
|
352
361
|
return PIPELINE_TASKS[tagged];
|
|
353
362
|
}
|
|
354
|
-
|
|
363
|
+
if (header && !header.architecture && tags.some((tag) => SD_CPP_TAGS.has(tag))) {
|
|
364
|
+
return 'image-generation';
|
|
365
|
+
}
|
|
366
|
+
const architecture = header?.architecture ?? '';
|
|
367
|
+
return ARCHITECTURE_TASKS.find(([pattern]) => pattern.test(architecture))?.[1] ?? 'llm';
|
|
355
368
|
}
|
|
356
|
-
async function assess({ file, header }, taskType, deps) {
|
|
369
|
+
async function assess({ file, header }, taskType, { deps, fetch }) {
|
|
370
|
+
const { assessFit } = deps;
|
|
357
371
|
if (taskType !== 'llm') {
|
|
358
372
|
return { fit: 'unknown', fitReasons: [NOT_LLM_REASON] };
|
|
359
373
|
}
|
|
360
|
-
if (!
|
|
361
|
-
return { fit: 'unknown', fitReasons: [NO_CHECKSUM_REASON] };
|
|
362
|
-
}
|
|
363
|
-
if (!deps.assessFit) {
|
|
374
|
+
if (!assessFit) {
|
|
364
375
|
return { fit: 'unknown', fitReasons: [NO_ESTIMATOR_REASON] };
|
|
365
376
|
}
|
|
377
|
+
const query = {
|
|
378
|
+
src: file.src,
|
|
379
|
+
name: header.name ?? file.label,
|
|
380
|
+
contextTokens: deps.contextSize || defaultContextSize(file.src, header.contextLength)
|
|
381
|
+
};
|
|
366
382
|
try {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
383
|
+
const catalog = file.sha256
|
|
384
|
+
? await assessFit({ ...query, sha256Checksum: file.sha256 }).catch(() => null)
|
|
385
|
+
: null;
|
|
386
|
+
return catalog && catalog.fit !== 'unknown'
|
|
387
|
+
? catalog
|
|
388
|
+
: await assessTensorList(query, {
|
|
389
|
+
assessFit,
|
|
390
|
+
fetch,
|
|
391
|
+
recentFits: deps.recentFits ?? new Map()
|
|
392
|
+
});
|
|
373
393
|
}
|
|
374
394
|
catch (err) {
|
|
375
395
|
return {
|
|
@@ -378,6 +398,44 @@ async function assess({ file, header }, taskType, deps) {
|
|
|
378
398
|
};
|
|
379
399
|
}
|
|
380
400
|
}
|
|
401
|
+
const RECENT_FIT_MS = 60_000;
|
|
402
|
+
async function assessTensorList(query, tools) {
|
|
403
|
+
const { assessFit, recentFits } = tools;
|
|
404
|
+
if ((shardSet(query.src)?.shards.length ?? 1) > 1) {
|
|
405
|
+
return { fit: 'unknown', fitReasons: [SHARDED_REASON] };
|
|
406
|
+
}
|
|
407
|
+
const local = localSourcePath(query.src);
|
|
408
|
+
if (local !== null) {
|
|
409
|
+
return assessFit({ ...query, src: local });
|
|
410
|
+
}
|
|
411
|
+
const file = path.join(os.tmpdir(), `qvac-fit-stub-${stubName(query.src)}.gguf`);
|
|
412
|
+
const recent = recentFits.get(file);
|
|
413
|
+
if (recent && Date.now() - recent.at < RECENT_FIT_MS) {
|
|
414
|
+
return recent.fit;
|
|
415
|
+
}
|
|
416
|
+
const fit = fitStub(file, query, tools);
|
|
417
|
+
recentFits.set(file, { fit, at: Infinity });
|
|
418
|
+
fit.then((result) => result.fit === 'unknown'
|
|
419
|
+
? recentFits.delete(file)
|
|
420
|
+
: recentFits.set(file, { fit, at: Date.now() }), () => recentFits.delete(file));
|
|
421
|
+
return fit;
|
|
422
|
+
}
|
|
423
|
+
async function fitStub(file, query, { assessFit, fetch }) {
|
|
424
|
+
const stub = await fetchGgufStub(query.src, { fetch });
|
|
425
|
+
if (!stub) {
|
|
426
|
+
return { fit: 'unknown', fitReasons: [NO_TENSOR_LIST_REASON] };
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
await fs.promises.writeFile(file, stub);
|
|
430
|
+
return await assessFit({ ...query, src: file });
|
|
431
|
+
}
|
|
432
|
+
finally {
|
|
433
|
+
await fs.promises.rm(file, { force: true });
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function stubName(src) {
|
|
437
|
+
return crypto.createHash('sha256').update(src, 'utf8').digest('hex').slice(0, 16);
|
|
438
|
+
}
|
|
381
439
|
function modelInfoUrl(ref) {
|
|
382
440
|
const revision = ref.revision === 'main' ? '' : `/revision/${encodeURIComponent(ref.revision)}`;
|
|
383
441
|
return `${HUGGING_FACE}/api/models/${encodePath(ref.repo)}${revision}?blobs=true`;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Tool as SdkTool } from '@qvac/sdk';
|
|
2
|
+
import { executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME } from '#sdk';
|
|
3
|
+
export { executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME };
|
|
4
|
+
export declare function renderedTools(tools: SdkTool[] | undefined): SdkTool[] | undefined;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { buildToolSearchTool, executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME } from '#sdk';
|
|
2
|
+
export { executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME };
|
|
3
|
+
export function renderedTools(tools) {
|
|
4
|
+
const deferred = tools?.filter((tool) => tool.deferLoading);
|
|
5
|
+
if (!tools || !deferred?.length) {
|
|
6
|
+
return tools;
|
|
7
|
+
}
|
|
8
|
+
return [...tools.filter((tool) => !tool.deferLoading), buildToolSearchTool(deferred)];
|
|
9
|
+
}
|
|
@@ -24,6 +24,7 @@ export declare function skillIsActive(name: string, { skillsSelected, enabledSki
|
|
|
24
24
|
export interface SelectableTool {
|
|
25
25
|
name: string;
|
|
26
26
|
skillGated?: boolean | undefined;
|
|
27
|
+
ungatedFor?: ReadonlyArray<string> | undefined;
|
|
27
28
|
rootsRequired?: boolean | undefined;
|
|
28
29
|
writeRootsRequired?: boolean | undefined;
|
|
29
30
|
owningSkill?: string | undefined;
|
|
@@ -37,6 +38,7 @@ export interface ToolGateInputs {
|
|
|
37
38
|
hasRoots: boolean;
|
|
38
39
|
hasWriteRoots: boolean;
|
|
39
40
|
hasActiveSkills: boolean;
|
|
41
|
+
capabilityProfile?: string | undefined;
|
|
40
42
|
}
|
|
41
43
|
export declare function isSelected(scope: 'all' | 'selected' | null | undefined, list?: ReadonlyArray<string> | null): boolean;
|
|
42
|
-
export declare function enabledTools<T extends SelectableTool>(tools: ReadonlyArray<T>, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills }: ToolGateInputs): T[];
|
|
44
|
+
export declare function enabledTools<T extends SelectableTool>(tools: ReadonlyArray<T>, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills, capabilityProfile }: ToolGateInputs): T[];
|
|
@@ -31,7 +31,7 @@ export function skillIsActive(name, { skillsSelected, enabledSkills }) {
|
|
|
31
31
|
export function isSelected(scope, list) {
|
|
32
32
|
return (scope ?? (list?.length ? 'selected' : 'all')) === 'selected';
|
|
33
33
|
}
|
|
34
|
-
export function enabledTools(tools, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills }) {
|
|
34
|
+
export function enabledTools(tools, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills, capabilityProfile }) {
|
|
35
35
|
return tools.filter((tool) => {
|
|
36
36
|
if (tool.name === SKILL_TOOL_NAME)
|
|
37
37
|
return hasActiveSkills;
|
|
@@ -49,7 +49,8 @@ export function enabledTools(tools, { toolsSelected, allowlist, grantedNames, gr
|
|
|
49
49
|
return hasWriteRoots;
|
|
50
50
|
}
|
|
51
51
|
if (tool.skillGated) {
|
|
52
|
-
|
|
52
|
+
const early = capabilityProfile !== undefined && tool.ungatedFor?.includes(capabilityProfile);
|
|
53
|
+
return loadedGrantedNames.has(tool.name) || (early === true && grantedNames.has(tool.name));
|
|
53
54
|
}
|
|
54
55
|
if (!toolsSelected) {
|
|
55
56
|
return true;
|
package/dist-lib/lib/connect.js
CHANGED
|
@@ -108,10 +108,11 @@ export class RemoteHarness extends EventEmitter {
|
|
|
108
108
|
generationParams: context.generationParams,
|
|
109
109
|
responseFormat: context.responseFormat,
|
|
110
110
|
captureInferenceCalls: context.captureInferenceCalls,
|
|
111
|
-
messages: context.messages.map(({ role, content, attachments }) => ({
|
|
111
|
+
messages: context.messages.map(({ role, content, attachments, sentAt }) => ({
|
|
112
112
|
role,
|
|
113
113
|
content,
|
|
114
|
-
attachments: attachments?.map(({ path: file }) => ({ path: file }))
|
|
114
|
+
attachments: attachments?.map(({ path: file }) => ({ path: file })),
|
|
115
|
+
sentAt
|
|
115
116
|
})),
|
|
116
117
|
payload: { typedText: context.typedText },
|
|
117
118
|
toolConfigs: context.toolConfigs,
|
package/dist-lib/lib/errors.d.ts
CHANGED
|
@@ -204,6 +204,10 @@ declare const HARNESS_ERRORS: {
|
|
|
204
204
|
readonly code: 102610;
|
|
205
205
|
readonly message: (filePath: string) => string;
|
|
206
206
|
};
|
|
207
|
+
readonly OBSIDIAN_PATH_IS_FOLDER: {
|
|
208
|
+
readonly code: 102611;
|
|
209
|
+
readonly message: (folder: string) => string;
|
|
210
|
+
};
|
|
207
211
|
readonly SKILL_FILE_NOT_FOUND: {
|
|
208
212
|
readonly code: 102701;
|
|
209
213
|
readonly message: (name: string, file: string) => string;
|
package/dist-lib/lib/errors.js
CHANGED
|
@@ -143,6 +143,12 @@ const HARNESS_ERRORS = {
|
|
|
143
143
|
code: 102610,
|
|
144
144
|
message: (filePath) => `Destination already exists: ${filePath}`
|
|
145
145
|
},
|
|
146
|
+
OBSIDIAN_PATH_IS_FOLDER: {
|
|
147
|
+
code: 102611,
|
|
148
|
+
message: (folder) => `"${folder || '.'}" is a folder, not a note. List it with ` +
|
|
149
|
+
(folder ? `\`obsidian files folder="${folder}"\`` : '`obsidian files`') +
|
|
150
|
+
', then read one note by its path.'
|
|
151
|
+
},
|
|
146
152
|
SKILL_FILE_NOT_FOUND: {
|
|
147
153
|
code: 102701,
|
|
148
154
|
message: (name, file) => `ENOENT: ${name}/${file}`
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface CpuPlacement {
|
|
2
|
+
threads: number;
|
|
3
|
+
mask: string;
|
|
4
|
+
}
|
|
5
|
+
export type ReadSysFile = (path: string) => string | null;
|
|
6
|
+
export declare function parseCpuList(list: string): number[];
|
|
7
|
+
export declare function performanceCorePlacement(read?: ReadSysFile, hostPlatform?: string): CpuPlacement | undefined;
|
|
8
|
+
export declare function androidCpuPlacement(): CpuPlacement | undefined;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import { platform } from 'os';
|
|
3
|
+
const CPU_ROOT = '/sys/devices/system/cpu';
|
|
4
|
+
function readSysFile(path) {
|
|
5
|
+
try {
|
|
6
|
+
return String(fs.readFileSync(path, 'utf8'));
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function cpuRange(part) {
|
|
13
|
+
const [from, to = from] = part.split('-').map(Number);
|
|
14
|
+
if (!Number.isInteger(from) || !Number.isInteger(to) || to < from) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
return Array.from({ length: to - from + 1 }, (_, i) => from + i);
|
|
18
|
+
}
|
|
19
|
+
export function parseCpuList(list) {
|
|
20
|
+
const ranges = list.trim().split(',').map(cpuRange);
|
|
21
|
+
return ranges.some((range) => range === null) ? [] : ranges.flat().filter((cpu) => cpu !== null);
|
|
22
|
+
}
|
|
23
|
+
function readCores(read, possible) {
|
|
24
|
+
return parseCpuList(possible).flatMap((cpu) => {
|
|
25
|
+
const maxFreq = Number(read(`${CPU_ROOT}/cpu${cpu}/cpufreq/cpuinfo_max_freq`)?.trim());
|
|
26
|
+
return Number.isFinite(maxFreq) && maxFreq > 0 ? [{ cpu, maxFreq }] : [];
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function placementOf(cores) {
|
|
30
|
+
const slowest = Math.min(...cores.map((core) => core.maxFreq));
|
|
31
|
+
const fast = cores.filter((core) => core.maxFreq > slowest);
|
|
32
|
+
if (fast.length === 0) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
const mask = fast.reduce((bits, core) => bits | (1n << BigInt(core.cpu)), 0n);
|
|
36
|
+
return { threads: fast.length, mask: mask.toString(16) };
|
|
37
|
+
}
|
|
38
|
+
export function performanceCorePlacement(read = readSysFile, hostPlatform = platform()) {
|
|
39
|
+
if (hostPlatform !== 'android')
|
|
40
|
+
return undefined;
|
|
41
|
+
const possible = read(`${CPU_ROOT}/possible`);
|
|
42
|
+
return possible === null ? undefined : placementOf(readCores(read, possible));
|
|
43
|
+
}
|
|
44
|
+
let cached = null;
|
|
45
|
+
export function androidCpuPlacement() {
|
|
46
|
+
cached ??= { placement: performanceCorePlacement() };
|
|
47
|
+
return cached.placement;
|
|
48
|
+
}
|
|
@@ -9,5 +9,6 @@ export interface CustomShardCache {
|
|
|
9
9
|
readonly files: ReadonlyArray<string>;
|
|
10
10
|
}
|
|
11
11
|
export declare function customShardCache(src: string, modelsDir: string | undefined): CustomShardCache | null;
|
|
12
|
+
export declare function localWeightFile(src: string, modelsDir: string | undefined): string | null;
|
|
12
13
|
export declare function customDownloads(entry: CustomModelEntry, modelsDir: string | undefined): Promise<CustomDownloads>;
|
|
13
14
|
export declare function isCustomModelCached(entry: CustomModelEntry, modelsDir: string | undefined): Promise<boolean>;
|
|
@@ -22,6 +22,9 @@ export function customShardCache(src, modelsDir) {
|
|
|
22
22
|
const dir = path.join(modelsDir, 'sharded', shortHash(`${set.baseUrl}/${set.base}`));
|
|
23
23
|
return { dir, files: set.shards.map((shard) => path.join(dir, shard.filename)) };
|
|
24
24
|
}
|
|
25
|
+
export function localWeightFile(src, modelsDir) {
|
|
26
|
+
return customShardCache(src, modelsDir)?.files[0] ?? customFileCachePath(src, modelsDir);
|
|
27
|
+
}
|
|
25
28
|
export async function customDownloads(entry, modelsDir) {
|
|
26
29
|
const remote = sourcesOf(entry).filter(isRemoteSource);
|
|
27
30
|
const shardDirs = remote.flatMap((src) => customShardCache(src, modelsDir)?.dir ?? []);
|
|
@@ -7,6 +7,12 @@ export interface GgufHeader {
|
|
|
7
7
|
readonly contextLength?: number;
|
|
8
8
|
readonly sizeLabel?: string;
|
|
9
9
|
readonly tags?: ReadonlyArray<string>;
|
|
10
|
+
readonly headDims?: HeadDims;
|
|
11
|
+
readonly chatTemplate?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface HeadDims {
|
|
14
|
+
readonly k?: number;
|
|
15
|
+
readonly v?: number;
|
|
10
16
|
}
|
|
11
17
|
export type GgufRangeFetch = (url: string, init: {
|
|
12
18
|
headers: Record<string, string>;
|
|
@@ -21,6 +27,9 @@ export type GgufRangeFetch = (url: string, init: {
|
|
|
21
27
|
}>;
|
|
22
28
|
export declare const GGUF_HEADER_BYTES = 1048576;
|
|
23
29
|
export declare const GGUF_HEADER_TIMEOUT_MS = 30000;
|
|
30
|
+
export declare const GGUF_HEADER_ATTEMPTS = 3;
|
|
31
|
+
export declare const GGUF_STUB_MAX_BYTES = 33554432;
|
|
32
|
+
export declare const GGUF_STUB_TIMEOUT_MS = 60000;
|
|
24
33
|
export declare function isRemoteSource(src: string): boolean;
|
|
25
34
|
export declare function localSourcePath(src: string): string | null;
|
|
26
35
|
export interface ReadGgufHeaderOptions {
|
|
@@ -28,4 +37,6 @@ export interface ReadGgufHeaderOptions {
|
|
|
28
37
|
maxBytes?: number;
|
|
29
38
|
}
|
|
30
39
|
export declare function readGgufHeaderBytes(src: string, opts?: ReadGgufHeaderOptions): Promise<Uint8Array | null>;
|
|
40
|
+
export declare function fetchGgufStub(src: string, opts?: ReadGgufHeaderOptions): Promise<Uint8Array | null>;
|
|
41
|
+
export declare function ggufDataOffset(bytes: Uint8Array): number | null;
|
|
31
42
|
export declare function parseGgufHeader(bytes: Uint8Array): GgufHeader | null;
|
|
@@ -5,9 +5,15 @@ import os from 'os';
|
|
|
5
5
|
import path from 'path';
|
|
6
6
|
import { fileURLToPath } from 'url';
|
|
7
7
|
import defaultFetch from '#fetch';
|
|
8
|
+
import { errorMessage } from '../guards.js';
|
|
9
|
+
import { log } from '../log.js';
|
|
8
10
|
const rangeFetch = defaultFetch;
|
|
9
11
|
export const GGUF_HEADER_BYTES = 1_048_576;
|
|
10
12
|
export const GGUF_HEADER_TIMEOUT_MS = 30_000;
|
|
13
|
+
export const GGUF_HEADER_ATTEMPTS = 3;
|
|
14
|
+
export const GGUF_STUB_MAX_BYTES = 33_554_432;
|
|
15
|
+
export const GGUF_STUB_TIMEOUT_MS = 60_000;
|
|
16
|
+
const MAX_ALIGNMENT = 1_048_576;
|
|
11
17
|
const UINT8 = 0;
|
|
12
18
|
const INT8 = 1;
|
|
13
19
|
const UINT16 = 2;
|
|
@@ -48,34 +54,179 @@ function filePath(src) {
|
|
|
48
54
|
}
|
|
49
55
|
export function readGgufHeaderBytes(src, opts = {}) {
|
|
50
56
|
const maxBytes = opts.maxBytes ?? GGUF_HEADER_BYTES;
|
|
57
|
+
const fetch = opts.fetch ?? rangeFetch;
|
|
51
58
|
return isRemoteSource(src)
|
|
52
|
-
?
|
|
59
|
+
? withDeadline(GGUF_HEADER_TIMEOUT_MS, (signal) => fetchRange(src, { start: 0, length: maxBytes, fetch, signal }))
|
|
53
60
|
: readLocalHead(src, maxBytes);
|
|
54
61
|
}
|
|
55
|
-
|
|
56
|
-
const
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
export function fetchGgufStub(src, opts = {}) {
|
|
63
|
+
const fetch = opts.fetch ?? rangeFetch;
|
|
64
|
+
const maxBytes = opts.maxBytes ?? GGUF_STUB_MAX_BYTES;
|
|
65
|
+
return withDeadline(GGUF_STUB_TIMEOUT_MS, (signal) => readStub(src, { fetch, maxBytes, signal }));
|
|
66
|
+
}
|
|
67
|
+
async function readStub(src, { fetch, maxBytes, signal }) {
|
|
68
|
+
let bytes = b4a.alloc(0);
|
|
69
|
+
let want = Math.min(GGUF_HEADER_BYTES, maxBytes);
|
|
70
|
+
for (;;) {
|
|
71
|
+
const start = bytes.byteLength;
|
|
72
|
+
const more = await fetchRange(src, { start, length: want - start, fetch, signal });
|
|
73
|
+
if (more === null) {
|
|
64
74
|
return null;
|
|
65
75
|
}
|
|
66
|
-
|
|
67
|
-
|
|
76
|
+
bytes = b4a.concat([bytes, more]);
|
|
77
|
+
const dataOffset = ggufDataOffset(bytes);
|
|
78
|
+
if (dataOffset !== null) {
|
|
79
|
+
return padded(bytes, dataOffset);
|
|
80
|
+
}
|
|
81
|
+
if (more.byteLength < want - start || want >= maxBytes) {
|
|
68
82
|
return null;
|
|
69
83
|
}
|
|
70
|
-
|
|
84
|
+
want = Math.min(want * 2, maxBytes);
|
|
71
85
|
}
|
|
72
|
-
|
|
86
|
+
}
|
|
87
|
+
export function ggufDataOffset(bytes) {
|
|
88
|
+
if (bytes.byteLength < 24 || b4a.toString(bytes.subarray(0, 4), 'latin1') !== 'GGUF') {
|
|
73
89
|
return null;
|
|
74
90
|
}
|
|
91
|
+
const c = {
|
|
92
|
+
view: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
|
|
93
|
+
bytes,
|
|
94
|
+
offset: 8
|
|
95
|
+
};
|
|
96
|
+
const tensors = readU64(c);
|
|
97
|
+
const alignment = skipMetadata(c, readU64(c));
|
|
98
|
+
if (alignment === null || !skipTensorInfos(c, tensors)) {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
return Math.ceil(c.offset / alignment) * alignment;
|
|
102
|
+
}
|
|
103
|
+
function skipTensorInfos(c, count) {
|
|
104
|
+
for (let i = 0; i < count; i += 1) {
|
|
105
|
+
if (readString(c) === null || !has(c, 4)) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
const dims = readU32(c);
|
|
109
|
+
if (!has(c, dims * 8 + 12)) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
c.offset += dims * 8 + 12;
|
|
113
|
+
}
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
function skipMetadata(c, count) {
|
|
117
|
+
let alignment = 32;
|
|
118
|
+
for (let i = 0; i < count; i += 1) {
|
|
119
|
+
const key = readString(c);
|
|
120
|
+
if (key === null || !has(c, 4)) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
const value = readValue(c, readU32(c));
|
|
124
|
+
if (!value.ok) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
if (key === 'general.alignment') {
|
|
128
|
+
if (!isAlignment(value.num)) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
alignment = value.num;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return alignment;
|
|
135
|
+
}
|
|
136
|
+
function isAlignment(value) {
|
|
137
|
+
return (value !== undefined &&
|
|
138
|
+
Number.isInteger(value) &&
|
|
139
|
+
value > 0 &&
|
|
140
|
+
value <= MAX_ALIGNMENT &&
|
|
141
|
+
(value & (value - 1)) === 0);
|
|
142
|
+
}
|
|
143
|
+
function padded(bytes, length) {
|
|
144
|
+
if (length <= bytes.byteLength) {
|
|
145
|
+
return bytes.subarray(0, length);
|
|
146
|
+
}
|
|
147
|
+
const stub = b4a.alloc(length);
|
|
148
|
+
stub.set(bytes);
|
|
149
|
+
return stub;
|
|
150
|
+
}
|
|
151
|
+
async function withDeadline(ms, run) {
|
|
152
|
+
const controller = new AbortController();
|
|
153
|
+
const timeout = setTimeout(() => controller.abort(undefined), ms);
|
|
154
|
+
try {
|
|
155
|
+
return await run(controller.signal);
|
|
156
|
+
}
|
|
75
157
|
finally {
|
|
76
158
|
clearTimeout(timeout);
|
|
77
159
|
}
|
|
78
160
|
}
|
|
161
|
+
async function fetchRange(src, range) {
|
|
162
|
+
for (let attempt = 1; attempt <= GGUF_HEADER_ATTEMPTS; attempt++) {
|
|
163
|
+
const read = await requestRange(src, range);
|
|
164
|
+
if (read.kind === 'read') {
|
|
165
|
+
return read.bytes;
|
|
166
|
+
}
|
|
167
|
+
log.warn('gguf header read failed', { host: hostOf(src), attempt, cause: read.cause });
|
|
168
|
+
if (!read.transient || range.signal.aborted) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
async function requestRange(src, { start, length, fetch, signal }) {
|
|
175
|
+
let response;
|
|
176
|
+
try {
|
|
177
|
+
response = await fetch(src, {
|
|
178
|
+
headers: { Range: `bytes=${start}-${start + length - 1}` },
|
|
179
|
+
signal
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
return { kind: 'failed', transient: true, cause: failureOf(err) };
|
|
184
|
+
}
|
|
185
|
+
const refused = refusedRange(response, { start, length });
|
|
186
|
+
if (refused) {
|
|
187
|
+
return refused;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
return {
|
|
191
|
+
kind: 'read',
|
|
192
|
+
bytes: new Uint8Array(await response.arrayBuffer()).subarray(0, length)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
return { kind: 'failed', transient: true, cause: failureOf(err) };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function refusedRange(response, { start, length }) {
|
|
200
|
+
if (!response.ok) {
|
|
201
|
+
return {
|
|
202
|
+
kind: 'failed',
|
|
203
|
+
transient: retryableStatus(response.status),
|
|
204
|
+
cause: `HTTP ${response.status}`
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
if (start > 0 && response.status !== 206) {
|
|
208
|
+
return { kind: 'failed', transient: false, cause: `HTTP ${response.status} for a range` };
|
|
209
|
+
}
|
|
210
|
+
const announced = response.headers.get('content-length');
|
|
211
|
+
return announced === null || !(Number(announced) <= length)
|
|
212
|
+
? { kind: 'failed', transient: false, cause: `content-length ${announced ?? 'missing'}` }
|
|
213
|
+
: null;
|
|
214
|
+
}
|
|
215
|
+
function failureOf(err) {
|
|
216
|
+
const cause = err instanceof Error ? err.cause : undefined;
|
|
217
|
+
return cause === undefined ? errorMessage(err) : `${errorMessage(err)}: ${errorMessage(cause)}`;
|
|
218
|
+
}
|
|
219
|
+
function retryableStatus(status) {
|
|
220
|
+
return status === 408 || status === 429 || status >= 500;
|
|
221
|
+
}
|
|
222
|
+
function hostOf(src) {
|
|
223
|
+
try {
|
|
224
|
+
return new URL(src).host;
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return '';
|
|
228
|
+
}
|
|
229
|
+
}
|
|
79
230
|
async function readLocalHead(src, maxBytes) {
|
|
80
231
|
const file = localSourcePath(src);
|
|
81
232
|
if (file === null) {
|
|
@@ -111,6 +262,7 @@ export function parseGgufHeader(bytes) {
|
|
|
111
262
|
const count = readU64(c);
|
|
112
263
|
const header = {};
|
|
113
264
|
const contextLengths = new Map();
|
|
265
|
+
const dims = new Map();
|
|
114
266
|
for (let i = 0; i < count; i += 1) {
|
|
115
267
|
const key = readString(c);
|
|
116
268
|
if (key === null || !has(c, 4)) {
|
|
@@ -138,15 +290,40 @@ export function parseGgufHeader(bytes) {
|
|
|
138
290
|
else if (key === 'general.tags') {
|
|
139
291
|
header.tags = value.strs;
|
|
140
292
|
}
|
|
293
|
+
else if (key === 'tokenizer.chat_template') {
|
|
294
|
+
header.chatTemplate = value.str;
|
|
295
|
+
}
|
|
141
296
|
else if (key.endsWith('.context_length')) {
|
|
142
297
|
contextLengths.set(key, value.num);
|
|
143
298
|
}
|
|
299
|
+
else if (HEAD_KEYS.some((suffix) => key.endsWith(suffix))) {
|
|
300
|
+
dims.set(key, value.num);
|
|
301
|
+
}
|
|
144
302
|
}
|
|
145
303
|
header.contextLength =
|
|
146
304
|
contextLengths.get(`${header.architecture}.context_length`) ??
|
|
147
305
|
contextLengths.values().next().value;
|
|
306
|
+
const headDims = headDimsOf(dims, header.architecture);
|
|
307
|
+
if (headDims) {
|
|
308
|
+
header.headDims = headDims;
|
|
309
|
+
}
|
|
148
310
|
return header;
|
|
149
311
|
}
|
|
312
|
+
const HEAD_KEYS = [
|
|
313
|
+
'.attention.key_length',
|
|
314
|
+
'.attention.value_length',
|
|
315
|
+
'.attention.head_count',
|
|
316
|
+
'.embedding_length'
|
|
317
|
+
];
|
|
318
|
+
function headDimsOf(dims, architecture) {
|
|
319
|
+
const of = (suffix) => dims.get(`${architecture}${suffix}`);
|
|
320
|
+
const embedding = of('.embedding_length');
|
|
321
|
+
const heads = of('.attention.head_count');
|
|
322
|
+
const split = embedding && heads ? embedding / heads : undefined;
|
|
323
|
+
const k = of('.attention.key_length') ?? split;
|
|
324
|
+
const v = of('.attention.value_length') ?? split;
|
|
325
|
+
return k || v ? { k, v } : undefined;
|
|
326
|
+
}
|
|
150
327
|
function readValue(c, type, collect = false) {
|
|
151
328
|
switch (type) {
|
|
152
329
|
case UINT8:
|
|
@@ -181,7 +358,7 @@ function readValue(c, type, collect = false) {
|
|
|
181
358
|
const length = readU64(c);
|
|
182
359
|
const strs = new Array();
|
|
183
360
|
for (let i = 0; i < length; i += 1) {
|
|
184
|
-
const element = readValue(c, elementType);
|
|
361
|
+
const element = elementType === STRING && !collect ? skipString(c) : readValue(c, elementType);
|
|
185
362
|
if (!element.ok) {
|
|
186
363
|
return { ok: false };
|
|
187
364
|
}
|
|
@@ -228,3 +405,14 @@ function readString(c) {
|
|
|
228
405
|
c.offset += length;
|
|
229
406
|
return str;
|
|
230
407
|
}
|
|
408
|
+
function skipString(c) {
|
|
409
|
+
if (!has(c, 8)) {
|
|
410
|
+
return { ok: false };
|
|
411
|
+
}
|
|
412
|
+
const length = readU64(c);
|
|
413
|
+
if (!has(c, length)) {
|
|
414
|
+
return { ok: false };
|
|
415
|
+
}
|
|
416
|
+
c.offset += length;
|
|
417
|
+
return { ok: true };
|
|
418
|
+
}
|