@qvac/harness 0.8.12 → 0.8.14
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 +101 -1
- package/dist-lib/index.js +9 -4
- package/dist-lib/lib/capabilities/completion.d.ts +6 -1
- package/dist-lib/lib/capabilities/completion.js +135 -66
- package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
- package/dist-lib/lib/capabilities/tool-turns.js +14 -3
- package/dist-lib/lib/connect.js +3 -2
- package/dist-lib/lib/contract-types.d.ts +1 -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 +6 -0
- package/dist-lib/lib/models/gguf-header.js +38 -1
- 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/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 +20 -8
- 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 +6 -3
- package/dist-lib/lib/prompt.js +28 -17
- 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/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 +12 -6
- 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 +151 -21
- package/dist-lib/lib/tools/operations/compile.js +4 -4
- 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 +2 -2
|
@@ -3,14 +3,25 @@ import { SKILL_TOOL_NAME } from './tool-names.js';
|
|
|
3
3
|
export const DIRECT_CALL_ID = 'call-direct';
|
|
4
4
|
export const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
|
|
5
5
|
export const FILE_DELIVERED_NUDGE = '[Tool results above. The file is attached to the chat and shown to the user. Answer now, unless the request still needs a file that is not made yet.]';
|
|
6
|
+
const MENTION_NUDGE_PREFIX = '[Tool results above. The user picked @';
|
|
7
|
+
export function skillMentionNudge(handle) {
|
|
8
|
+
return `${MENTION_NUDGE_PREFIX}${handle} for this request. If @${handle} cannot do what they asked, or what it works on is not in this chat, call no tool: tell them in one sentence that @${handle} cannot do this, and why. Otherwise continue: call the next tool, or answer.]`;
|
|
9
|
+
}
|
|
6
10
|
export function isContinuationNudge(content) {
|
|
7
|
-
return content === TOOL_CONTINUATION_NUDGE ||
|
|
11
|
+
return (content === TOOL_CONTINUATION_NUDGE ||
|
|
12
|
+
content === FILE_DELIVERED_NUDGE ||
|
|
13
|
+
content.startsWith(MENTION_NUDGE_PREFIX));
|
|
8
14
|
}
|
|
9
15
|
export function deliversFile(output) {
|
|
10
16
|
return isRecord(output) && Array.isArray(output.attachments) && output.attachments.length > 0;
|
|
11
17
|
}
|
|
12
18
|
export function toolResultTurn(name, id, output) {
|
|
13
|
-
|
|
19
|
+
const header = `[Tool: ${name} (${id})]`;
|
|
20
|
+
if (name === SKILL_TOOL_NAME && isRecord(output) && typeof output.content === 'string') {
|
|
21
|
+
const { content, ...rest } = output;
|
|
22
|
+
return `${header}\n${JSON.stringify(historyPayload(rest))}\n\n${content}`;
|
|
23
|
+
}
|
|
24
|
+
return `${header}\n${JSON.stringify(historyPayload(output))}`;
|
|
14
25
|
}
|
|
15
26
|
export function skillLoadedTurn(name) {
|
|
16
27
|
return toolResultTurn(SKILL_TOOL_NAME, DIRECT_CALL_ID, {
|
|
@@ -87,7 +98,7 @@ function skillLoadPayload(turn) {
|
|
|
87
98
|
return null;
|
|
88
99
|
}
|
|
89
100
|
try {
|
|
90
|
-
const payload = JSON.parse(text.
|
|
101
|
+
const payload = JSON.parse(text.split('\n')[1] ?? '');
|
|
91
102
|
if (typeof payload !== 'object' || payload === null) {
|
|
92
103
|
return null;
|
|
93
104
|
}
|
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,
|
|
@@ -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>;
|
|
@@ -262,6 +262,7 @@ export function parseGgufHeader(bytes) {
|
|
|
262
262
|
const count = readU64(c);
|
|
263
263
|
const header = {};
|
|
264
264
|
const contextLengths = new Map();
|
|
265
|
+
const dims = new Map();
|
|
265
266
|
for (let i = 0; i < count; i += 1) {
|
|
266
267
|
const key = readString(c);
|
|
267
268
|
if (key === null || !has(c, 4)) {
|
|
@@ -289,15 +290,40 @@ export function parseGgufHeader(bytes) {
|
|
|
289
290
|
else if (key === 'general.tags') {
|
|
290
291
|
header.tags = value.strs;
|
|
291
292
|
}
|
|
293
|
+
else if (key === 'tokenizer.chat_template') {
|
|
294
|
+
header.chatTemplate = value.str;
|
|
295
|
+
}
|
|
292
296
|
else if (key.endsWith('.context_length')) {
|
|
293
297
|
contextLengths.set(key, value.num);
|
|
294
298
|
}
|
|
299
|
+
else if (HEAD_KEYS.some((suffix) => key.endsWith(suffix))) {
|
|
300
|
+
dims.set(key, value.num);
|
|
301
|
+
}
|
|
295
302
|
}
|
|
296
303
|
header.contextLength =
|
|
297
304
|
contextLengths.get(`${header.architecture}.context_length`) ??
|
|
298
305
|
contextLengths.values().next().value;
|
|
306
|
+
const headDims = headDimsOf(dims, header.architecture);
|
|
307
|
+
if (headDims) {
|
|
308
|
+
header.headDims = headDims;
|
|
309
|
+
}
|
|
299
310
|
return header;
|
|
300
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
|
+
}
|
|
301
327
|
function readValue(c, type, collect = false) {
|
|
302
328
|
switch (type) {
|
|
303
329
|
case UINT8:
|
|
@@ -332,7 +358,7 @@ function readValue(c, type, collect = false) {
|
|
|
332
358
|
const length = readU64(c);
|
|
333
359
|
const strs = new Array();
|
|
334
360
|
for (let i = 0; i < length; i += 1) {
|
|
335
|
-
const element = readValue(c, elementType);
|
|
361
|
+
const element = elementType === STRING && !collect ? skipString(c) : readValue(c, elementType);
|
|
336
362
|
if (!element.ok) {
|
|
337
363
|
return { ok: false };
|
|
338
364
|
}
|
|
@@ -379,3 +405,14 @@ function readString(c) {
|
|
|
379
405
|
c.offset += length;
|
|
380
406
|
return str;
|
|
381
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
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import type { HeadDims } from './gguf-header.ts';
|
|
1
2
|
export interface KvCacheTypes {
|
|
2
3
|
k: string | undefined;
|
|
3
4
|
v: string | undefined;
|
|
4
5
|
}
|
|
6
|
+
export declare function headSafeKvCache({ k, v }: KvCacheTypes, heads: HeadDims | undefined): KvCacheTypes;
|
|
5
7
|
export declare function adrenoSafeKvCache(device: 'cpu' | 'gpu' | undefined, { k, v }: KvCacheTypes, hostPlatform?: string): KvCacheTypes;
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import { platform } from 'os';
|
|
2
|
+
const QUANT_BLOCK = 32;
|
|
3
|
+
const UNBLOCKED = new Set(['f32', 'f16', 'bf16']);
|
|
4
|
+
export function headSafeKvCache({ k, v }, heads) {
|
|
5
|
+
return { k: blockFits(k, heads?.k) ? k : 'f16', v: blockFits(v, heads?.v) ? v : 'f16' };
|
|
6
|
+
}
|
|
7
|
+
function blockFits(type, width) {
|
|
8
|
+
return !type || !width || UNBLOCKED.has(type) || width % QUANT_BLOCK === 0;
|
|
9
|
+
}
|
|
2
10
|
export function adrenoSafeKvCache(device, { k, v }, hostPlatform = platform()) {
|
|
3
11
|
if (device === 'cpu' || hostPlatform !== 'android') {
|
|
4
12
|
return { k, v };
|
|
@@ -5,6 +5,7 @@ export interface LlmGenerationParams {
|
|
|
5
5
|
presence_penalty?: number;
|
|
6
6
|
repeat_penalty?: number;
|
|
7
7
|
frequency_penalty?: number;
|
|
8
|
-
reasoning_budget
|
|
8
|
+
reasoning_budget?: -1 | 0;
|
|
9
|
+
tool_choice?: 'none';
|
|
9
10
|
}
|
|
10
11
|
export declare function resolveLlmGenerationParams(modelName: string | undefined, reasoningEnabled: boolean | undefined, deviceDefault?: boolean): LlmGenerationParams | undefined;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import ResourcePuddle from 'resource-puddle';
|
|
2
2
|
import { ModelHandle } from './model-handle.ts';
|
|
3
3
|
import { type ModelSrc } from './context.ts';
|
|
4
|
+
import type { CpuPlacement } from '../hardware/cpu-placement.ts';
|
|
4
5
|
import { type ModelAddon } from './model-source.ts';
|
|
5
6
|
import type { GpuFaultState } from './sdk-faults.ts';
|
|
6
7
|
import type { HoldFn } from './download-gate.ts';
|
|
@@ -34,6 +35,7 @@ export interface LlmDeviceConfig {
|
|
|
34
35
|
kvCacheV?: string;
|
|
35
36
|
mainGpu?: () => Promise<string | undefined>;
|
|
36
37
|
openclCacheDir?: () => string | undefined;
|
|
38
|
+
cpuPlacement?: () => CpuPlacement | undefined;
|
|
37
39
|
}
|
|
38
40
|
export type TrackedLoad = Promise<string> & {
|
|
39
41
|
requestId?: string;
|
|
@@ -66,6 +68,8 @@ export type ModelLifecycleSdk = Pick<SdkModule, 'unloadModel' | 'modelRegistrySe
|
|
|
66
68
|
gpu_layers?: number;
|
|
67
69
|
'main-gpu'?: string;
|
|
68
70
|
openclCacheDir?: string;
|
|
71
|
+
threads?: number;
|
|
72
|
+
'cpu-mask'?: string;
|
|
69
73
|
};
|
|
70
74
|
onProgress?: (progress: Record<string, unknown>) => void;
|
|
71
75
|
}): TrackedLoad;
|
|
@@ -160,8 +164,9 @@ export interface ModelPoolOptions {
|
|
|
160
164
|
beforeLoad?: BeforeLoad;
|
|
161
165
|
chooseContext?: ChooseContext;
|
|
162
166
|
hold?: HoldFn;
|
|
167
|
+
modelsDir?: string | undefined;
|
|
163
168
|
}
|
|
164
|
-
export declare function createModelPool(loadSdk: LoadSdk, notify: NotifyFn, { deviceConfig, loads, beforeLoad, chooseContext, hold }?: ModelPoolOptions): ModelPuddle;
|
|
169
|
+
export declare function createModelPool(loadSdk: LoadSdk, notify: NotifyFn, { deviceConfig, loads, beforeLoad, chooseContext, hold, modelsDir }?: ModelPoolOptions): ModelPuddle;
|
|
165
170
|
export interface EmbedPoolOptions {
|
|
166
171
|
faults: GpuFaultState;
|
|
167
172
|
batchSize?: number;
|
|
@@ -5,7 +5,9 @@ import ResourcePuddle from 'resource-puddle';
|
|
|
5
5
|
import { ModelHandle } from './model-handle.js';
|
|
6
6
|
import { defaultContextSize } from './context.js';
|
|
7
7
|
import { customContextLength } from './model-catalog.js';
|
|
8
|
-
import {
|
|
8
|
+
import { localWeightFile } from './custom-model-cache.js';
|
|
9
|
+
import { GGUF_STUB_MAX_BYTES, parseGgufHeader, readGgufHeaderBytes } from './gguf-header.js';
|
|
10
|
+
import { adrenoSafeKvCache, headSafeKvCache } from './kv-cache.js';
|
|
9
11
|
import { DEFAULT_EMBED_BATCH_SIZE } from './embed-config.js';
|
|
10
12
|
import { log } from '../log.js';
|
|
11
13
|
import { RUNAWAY_STOP_SEQUENCES } from '../helpers/control-tokens.js';
|
|
@@ -358,11 +360,12 @@ export function loadClockGuard(model, sdk, { now = () => Date.now(), monoMs = mo
|
|
|
358
360
|
};
|
|
359
361
|
return { race };
|
|
360
362
|
}
|
|
361
|
-
export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = createLoadTracker(), beforeLoad, chooseContext, hold } = {}) {
|
|
363
|
+
export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = createLoadTracker(), beforeLoad, chooseContext, hold, modelsDir } = {}) {
|
|
362
364
|
const load = async (key, model, opts) => {
|
|
363
365
|
const sdk = await loadSdk();
|
|
364
366
|
const modelSrc = await resolveModelSrc(sdk, model);
|
|
365
367
|
const resolved = resolveLoadOptions(opts, deviceConfig);
|
|
368
|
+
const header = await weightHeader(modelSrc, modelsDir);
|
|
366
369
|
const tier = defaultContextSize(modelSrc, customContextLength(model));
|
|
367
370
|
const projectionModelSrc = resolved.projectionModel
|
|
368
371
|
? await resolveProjectionSrc(sdk, resolved.projectionModel)
|
|
@@ -370,13 +373,11 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
|
|
|
370
373
|
const mainGpu = deviceConfig.device !== 'cpu' && deviceConfig.mainGpu
|
|
371
374
|
? await deviceConfig.mainGpu()
|
|
372
375
|
: undefined;
|
|
373
|
-
const kvCache = adrenoSafeKvCache(deviceConfig.device, {
|
|
374
|
-
k: resolved.kvCacheK,
|
|
375
|
-
v: resolved.kvCacheV
|
|
376
|
-
});
|
|
376
|
+
const kvCache = headSafeKvCache(adrenoSafeKvCache(deviceConfig.device, { k: resolved.kvCacheK, v: resolved.kvCacheV }), header?.headDims);
|
|
377
377
|
const openclCache = deviceConfig.device !== 'cpu' && deviceConfig.openclCacheDir
|
|
378
378
|
? deviceConfig.openclCacheDir()
|
|
379
379
|
: undefined;
|
|
380
|
+
const placement = deviceConfig.device === 'cpu' ? deviceConfig.cpuPlacement?.() : undefined;
|
|
380
381
|
const config = definedFields({
|
|
381
382
|
verbosity: llmVerbosity(),
|
|
382
383
|
tools: true,
|
|
@@ -387,7 +388,9 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
|
|
|
387
388
|
device: deviceConfig.device,
|
|
388
389
|
gpu_layers: deviceConfig.gpuLayers,
|
|
389
390
|
'main-gpu': mainGpu,
|
|
390
|
-
openclCacheDir: openclCache || undefined
|
|
391
|
+
openclCacheDir: openclCache || undefined,
|
|
392
|
+
threads: placement?.threads,
|
|
393
|
+
'cpu-mask': placement?.mask
|
|
391
394
|
});
|
|
392
395
|
const pending = { key, model, modelSrc, modelType: 'llamacpp-completion' };
|
|
393
396
|
const ctxSize = resolved.ctxSize ||
|
|
@@ -406,7 +409,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
|
|
|
406
409
|
})))
|
|
407
410
|
.finally(() => admission?.release());
|
|
408
411
|
log.info('llm loaded', { model, loadMs: Date.now() - loadStarted });
|
|
409
|
-
return { model, modelId, ctxSize, bytes: admission?.bytes };
|
|
412
|
+
return { model, modelId, ctxSize, bytes: admission?.bytes, canThink: canThink(header) };
|
|
410
413
|
};
|
|
411
414
|
return new ModelPuddle({
|
|
412
415
|
open: (key, model = key, opts = {}) => reportedHandle({ notify, model, addon: 'llm', hold, load: () => load(key, model, opts) }),
|
|
@@ -414,6 +417,15 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
|
|
|
414
417
|
...NO_IDLE_GC
|
|
415
418
|
});
|
|
416
419
|
}
|
|
420
|
+
async function weightHeader(modelSrc, modelsDir) {
|
|
421
|
+
const file = typeof modelSrc === 'string' ? localWeightFile(modelSrc, modelsDir) : null;
|
|
422
|
+
const bytes = file ? await readGgufHeaderBytes(file, { maxBytes: GGUF_STUB_MAX_BYTES }) : null;
|
|
423
|
+
return bytes && parseGgufHeader(bytes);
|
|
424
|
+
}
|
|
425
|
+
function canThink(header) {
|
|
426
|
+
const template = header?.chatTemplate;
|
|
427
|
+
return template === undefined ? undefined : /<think(?:ing)?>/.test(template);
|
|
428
|
+
}
|
|
417
429
|
export function createEmbedPool(loadSdk, notify, { faults, batchSize = DEFAULT_EMBED_BATCH_SIZE, openclCacheDir, loads = createLoadTracker(), beforeLoad, hold }) {
|
|
418
430
|
const load = async (key, model) => {
|
|
419
431
|
const sdk = await loadSdk();
|
|
@@ -3,7 +3,22 @@ import { HarnessError } from './errors.js';
|
|
|
3
3
|
import { DEFAULT_USER_AGENT } from './user-agent.js';
|
|
4
4
|
const UA_SNIFFING_HOSTS = new Set(['wttr.in']);
|
|
5
5
|
export function runNoRedirectFetch(request, url, init = {}) {
|
|
6
|
-
return new Promise((
|
|
6
|
+
return new Promise((outerResolve, outerReject) => {
|
|
7
|
+
let idle = null;
|
|
8
|
+
const stopIdle = () => {
|
|
9
|
+
if (idle) {
|
|
10
|
+
clearTimeout(idle);
|
|
11
|
+
}
|
|
12
|
+
idle = null;
|
|
13
|
+
};
|
|
14
|
+
const resolve = (response) => {
|
|
15
|
+
stopIdle();
|
|
16
|
+
outerResolve(response);
|
|
17
|
+
};
|
|
18
|
+
const reject = (err) => {
|
|
19
|
+
stopIdle();
|
|
20
|
+
outerReject(err);
|
|
21
|
+
};
|
|
7
22
|
const headers = { ...init.headers };
|
|
8
23
|
if (init.body !== undefined &&
|
|
9
24
|
!Object.keys(headers).some((h) => h.toLowerCase() === 'content-length')) {
|
|
@@ -16,6 +31,7 @@ export function runNoRedirectFetch(request, url, init = {}) {
|
|
|
16
31
|
}
|
|
17
32
|
const method = init.method ?? 'GET';
|
|
18
33
|
const req = request(url, { method, headers, validatedAddresses: init.validatedAddresses }, (res) => {
|
|
34
|
+
armIdle();
|
|
19
35
|
const chunks = [];
|
|
20
36
|
let received = 0;
|
|
21
37
|
let settled = false;
|
|
@@ -45,6 +61,7 @@ export function runNoRedirectFetch(request, url, init = {}) {
|
|
|
45
61
|
reject(err);
|
|
46
62
|
};
|
|
47
63
|
res.on('data', (chunk) => {
|
|
64
|
+
armIdle();
|
|
48
65
|
received += chunk.byteLength;
|
|
49
66
|
if (init.maxBytes !== undefined && received > init.maxBytes) {
|
|
50
67
|
if (init.truncate) {
|
|
@@ -67,6 +84,20 @@ export function runNoRedirectFetch(request, url, init = {}) {
|
|
|
67
84
|
res.on('end', respond);
|
|
68
85
|
});
|
|
69
86
|
req.on('error', reject);
|
|
87
|
+
function armIdle() {
|
|
88
|
+
const ms = init.idleTimeoutMs;
|
|
89
|
+
if (ms === undefined) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
stopIdle();
|
|
93
|
+
idle = setTimeout(() => {
|
|
94
|
+
const err = new Error(`no data received for ${ms} ms`);
|
|
95
|
+
err.name = 'TimeoutError';
|
|
96
|
+
req.destroy(err);
|
|
97
|
+
reject(err);
|
|
98
|
+
}, ms);
|
|
99
|
+
}
|
|
100
|
+
armIdle();
|
|
70
101
|
if (init.signal) {
|
|
71
102
|
const abort = () => {
|
|
72
103
|
const err = new Error('This operation was aborted');
|
package/dist-lib/lib/prompt.d.ts
CHANGED
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
export declare const RAG_CITATION_LINE = "After your answer, add one final line naming the files you used, written exactly as [Sources: file-a.pdf, file-b.md] - or [Sources: none] if the excerpts did not answer the question. This line is required, it is the only place square brackets belong, and it is removed before the user sees it.";
|
|
2
2
|
export declare function currentTimeAnnotation(now?: Date): string;
|
|
3
|
-
export declare function
|
|
3
|
+
export declare function annotateUserTimes<T extends {
|
|
4
4
|
role: string;
|
|
5
5
|
content: string;
|
|
6
|
+
sentAt?: number | undefined;
|
|
6
7
|
}>(turns: ReadonlyArray<T>, now?: Date): T[];
|
|
7
8
|
export interface SystemPromptInput {
|
|
8
9
|
bio?: string | null | undefined;
|
|
9
10
|
toolNames?: ReadonlyArray<string>;
|
|
10
11
|
skillsSection?: string | null;
|
|
12
|
+
platform?: string | null | undefined;
|
|
11
13
|
}
|
|
12
14
|
export interface SystemPromptParts {
|
|
13
15
|
text: string;
|
|
14
16
|
bioChars: number;
|
|
15
17
|
skillsChars: number;
|
|
16
18
|
}
|
|
17
|
-
export declare function systemPromptParts({ bio, toolNames, skillsSection }: SystemPromptInput): SystemPromptParts;
|
|
19
|
+
export declare function systemPromptParts({ bio, toolNames, skillsSection, platform }: SystemPromptInput): SystemPromptParts;
|
|
18
20
|
export declare function buildSystemPrompt(input: SystemPromptInput): string;
|
|
19
21
|
export interface PromptSkill {
|
|
20
22
|
readonly name: string;
|
|
21
23
|
readonly description: string;
|
|
24
|
+
readonly note?: string | undefined;
|
|
22
25
|
}
|
|
23
|
-
export declare function skillsPromptSection(
|
|
26
|
+
export declare function skillsPromptSection(skills: ReadonlyArray<PromptSkill>): string | null;
|
package/dist-lib/lib/prompt.js
CHANGED
|
@@ -22,25 +22,25 @@ export const RAG_CITATION_LINE = 'After your answer, add one final line naming t
|
|
|
22
22
|
const METADATA_SECTION = `## Message Metadata
|
|
23
23
|
|
|
24
24
|
User messages may include metadata such as [Current local time: ...]. This is contextual information provided by the system, not part of the user's query. Use it only when relevant and never repeat it unless the user asks about the current date or time.`;
|
|
25
|
+
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
25
26
|
export function currentTimeAnnotation(now = new Date()) {
|
|
26
27
|
const p = (n) => String(n).padStart(2, '0');
|
|
27
|
-
const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
|
|
28
|
+
const stamp = `${WEEKDAYS[now.getDay()]} ${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
|
|
28
29
|
const offset = -now.getTimezoneOffset();
|
|
29
30
|
const sign = offset < 0 ? '-' : '+';
|
|
30
31
|
const abs = Math.abs(offset);
|
|
31
32
|
return `[Current local time: ${stamp} (UTC${sign}${p(Math.floor(abs / 60))}:${p(abs % 60)})]`;
|
|
32
33
|
}
|
|
33
|
-
export function
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
return result;
|
|
34
|
+
export function annotateUserTimes(turns, now = new Date()) {
|
|
35
|
+
const lastUser = turns.findLastIndex((turn) => turn.role === 'user');
|
|
36
|
+
return turns.map((turn, i) => {
|
|
37
|
+
if (turn.role !== 'user')
|
|
38
|
+
return turn;
|
|
39
|
+
if (!turn.sentAt && i !== lastUser)
|
|
40
|
+
return turn;
|
|
41
|
+
const at = turn.sentAt ? new Date(turn.sentAt) : now;
|
|
42
|
+
return { ...turn, content: `${currentTimeAnnotation(at)}\n\n${turn.content}` };
|
|
43
|
+
});
|
|
44
44
|
}
|
|
45
45
|
function buildGuidelines(active) {
|
|
46
46
|
const lines = [...BASE_GUIDELINES];
|
|
@@ -58,14 +58,23 @@ function buildGuidelines(active) {
|
|
|
58
58
|
}
|
|
59
59
|
return `**Guidelines:**\n${lines.map((line) => `- ${line}`).join('\n')}`;
|
|
60
60
|
}
|
|
61
|
-
|
|
61
|
+
const PLATFORM_LABELS = {
|
|
62
|
+
darwin: 'macOS',
|
|
63
|
+
linux: 'Linux',
|
|
64
|
+
win32: 'Windows',
|
|
65
|
+
ios: 'iOS',
|
|
66
|
+
android: 'Android'
|
|
67
|
+
};
|
|
68
|
+
export function systemPromptParts({ bio, toolNames = [], skillsSection, platform }) {
|
|
62
69
|
const active = new Set(toolNames);
|
|
63
70
|
const header = active.size
|
|
64
71
|
? 'You are a helpful AI assistant with access to tools.'
|
|
65
72
|
: 'You are a helpful AI assistant.';
|
|
66
73
|
const preamble = `${header}\n\n${METADATA_SECTION}`;
|
|
74
|
+
const label = platform ? PLATFORM_LABELS[platform] : undefined;
|
|
75
|
+
const host = label ? `You run on ${label}.` : null;
|
|
67
76
|
const skills = active.has('skill') ? skillsSection : null;
|
|
68
|
-
const text = [preamble, bio, skills, buildGuidelines(active)]
|
|
77
|
+
const text = [preamble, host, bio, skills, buildGuidelines(active)]
|
|
69
78
|
.filter((part) => Boolean(part))
|
|
70
79
|
.join('\n\n');
|
|
71
80
|
return { text, bioChars: (bio ?? '').length, skillsChars: (skills ?? '').length };
|
|
@@ -73,9 +82,11 @@ export function systemPromptParts({ bio, toolNames = [], skillsSection }) {
|
|
|
73
82
|
export function buildSystemPrompt(input) {
|
|
74
83
|
return systemPromptParts(input).text;
|
|
75
84
|
}
|
|
76
|
-
export function skillsPromptSection(
|
|
77
|
-
if (!
|
|
85
|
+
export function skillsPromptSection(skills) {
|
|
86
|
+
if (!skills.length)
|
|
78
87
|
return null;
|
|
79
|
-
const lines =
|
|
88
|
+
const lines = skills
|
|
89
|
+
.map((skill) => `- ${skill.name}: ${skill.description}${skill.note ? ` [${skill.note}]` : ''}`)
|
|
90
|
+
.join('\n');
|
|
80
91
|
return `Skills available this turn. You MUST call the \`skill\` tool with its name BEFORE using the capability it describes — load the skill first, then act.\n${lines}`;
|
|
81
92
|
}
|
package/dist-lib/lib/serve.js
CHANGED
|
@@ -538,12 +538,13 @@ function completion(harness) {
|
|
|
538
538
|
typedText: isRecord(frame.payload) && typeof frame.payload.typedText === 'string'
|
|
539
539
|
? frame.payload.typedText
|
|
540
540
|
: undefined,
|
|
541
|
-
messages: (frame.messages ?? []).map(({ role, content, attachments }) => ({
|
|
541
|
+
messages: (frame.messages ?? []).map(({ role, content, attachments, sentAt }) => ({
|
|
542
542
|
role,
|
|
543
543
|
content,
|
|
544
544
|
attachments: attachments?.length
|
|
545
545
|
? attachments.map(({ path: file }) => ({ path: file }))
|
|
546
|
-
: undefined
|
|
546
|
+
: undefined,
|
|
547
|
+
sentAt: sentAt || undefined
|
|
547
548
|
})),
|
|
548
549
|
toolConfigs: frame.toolConfigs ?? undefined,
|
|
549
550
|
grantedDirs: frame.grantedDirs ?? undefined,
|
|
@@ -130,6 +130,7 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
|
|
|
130
130
|
required: ['prompt']
|
|
131
131
|
},
|
|
132
132
|
effect: () => 'write',
|
|
133
|
+
deliversMany: true,
|
|
133
134
|
resource: (args) => ({
|
|
134
135
|
kind: 'image-edit',
|
|
135
136
|
label: String(args.prompt ?? '').slice(0, 80)
|
|
@@ -264,13 +265,13 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
|
|
|
264
265
|
'Next time write the prompt with explicit @imageN tokens in source order');
|
|
265
266
|
}
|
|
266
267
|
return {
|
|
267
|
-
|
|
268
|
+
attachments: [
|
|
269
|
+
{ attachmentId: record.id, fileName: record.fileName, byteLength: record.byteLength }
|
|
270
|
+
],
|
|
268
271
|
...(sources.length === 1 && sources[0].id
|
|
269
272
|
? { sourceAttachmentId: sources[0].id }
|
|
270
273
|
: { sourceFileNames: sources.map((source) => source.fileName) }),
|
|
271
274
|
note: notes.length ? notes.join('; ') : undefined,
|
|
272
|
-
fileName: record.fileName,
|
|
273
|
-
byteLength: record.byteLength,
|
|
274
275
|
width,
|
|
275
276
|
height
|
|
276
277
|
};
|
|
@@ -19,6 +19,7 @@ export interface StageInputsOptions {
|
|
|
19
19
|
export interface StagedInputs {
|
|
20
20
|
files: readonly StagedInput[];
|
|
21
21
|
}
|
|
22
|
+
export declare function uploadsAvailable(fetchAttachment: FetchAttachmentFn, { turnImages, signal }?: StageInputsOptions): Promise<number | null>;
|
|
22
23
|
export declare function stageInputs(fetchAttachment: FetchAttachmentFn, inputs: readonly ExecInput[], opts?: StageInputsOptions): Promise<StagedInputs | ExecError>;
|
|
23
24
|
export interface AttachOutputsOptions {
|
|
24
25
|
readonly declared: readonly string[];
|
|
@@ -67,6 +67,17 @@ async function probeAttachment(fetchAttachment, id, { signal, deadline }) {
|
|
|
67
67
|
}
|
|
68
68
|
return { size: byteLengthOf(head), bytes: hasBytes(head) ? head.bytes : null };
|
|
69
69
|
}
|
|
70
|
+
export async function uploadsAvailable(fetchAttachment, { turnImages = [], signal } = {}) {
|
|
71
|
+
if (turnImages.length) {
|
|
72
|
+
return turnImages.length;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return (await bounded(fetchAttachment({ meta: true, signal }), STAGE_TIMEOUT_MS)) ? 1 : 0;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
70
81
|
export async function stageInputs(fetchAttachment, inputs, opts = {}) {
|
|
71
82
|
const { turnImages = [], signal } = opts;
|
|
72
83
|
const files = inputs.map(() => null);
|
|
@@ -313,6 +313,7 @@ export function createGenerateImageTool(runtime, clamps) {
|
|
|
313
313
|
required: ['prompt']
|
|
314
314
|
},
|
|
315
315
|
effect: () => 'read',
|
|
316
|
+
deliversMany: true,
|
|
316
317
|
resource: (args) => ({
|
|
317
318
|
kind: 'image-generation',
|
|
318
319
|
label: String(args.prompt ?? '').slice(0, 80)
|
|
@@ -359,9 +360,9 @@ export function createGenerateImageTool(runtime, clamps) {
|
|
|
359
360
|
raw: true
|
|
360
361
|
});
|
|
361
362
|
return {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
363
|
+
attachments: [
|
|
364
|
+
{ attachmentId: record.id, fileName: record.fileName, byteLength: record.byteLength }
|
|
365
|
+
],
|
|
365
366
|
width: parsed.width,
|
|
366
367
|
height: parsed.height
|
|
367
368
|
};
|