@qvac/harness 1.0.0-rc.13 → 1.0.0-rc.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/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +1 -1
- package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +10 -6
- package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
- package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +1 -1
- package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +8 -0
- package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +6 -2
- package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +5 -2
- package/dist-lib/lib/capabilities/completion-engine/ports.js +1 -1
- package/dist-lib/lib/capabilities/completion-engine/round.js +2 -1
- package/dist-lib/lib/capabilities/completion-engine/session.d.ts +3 -3
- package/dist-lib/lib/capabilities/prompt-prefix.d.ts +2 -0
- package/dist-lib/lib/capabilities/prompt-prefix.js +8 -0
- package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
- package/dist-lib/lib/capabilities/sdk-tool.js +17 -2
- package/dist-lib/lib/capabilities/usage-breakdown.d.ts +1 -0
- package/dist-lib/lib/capabilities/usage-breakdown.js +4 -1
- package/dist-lib/plugins/knowledge/index.d.ts +3 -0
- package/dist-lib/plugins/knowledge/index.js +4 -0
- package/dist-lib/plugins/knowledge/manifest.d.ts +28 -4
- package/dist-lib/plugins/knowledge/manifest.js +49 -4
- package/dist-lib/plugins/knowledge/store.d.ts +10 -1
- package/dist-lib/plugins/knowledge/store.js +127 -57
- package/dist-lib/plugins/obsidian/index.js +14 -4
- package/dist-lib/plugins/python/index.d.ts +3 -1
- package/dist-lib/plugins/python/index.js +4 -1
- package/dist-lib/plugins/python/python-adapter.d.ts +2 -1
- package/dist-lib/plugins/python/python-adapter.js +8 -1
- package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
- package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
- package/package.json +24 -19
- package/scripts/addon-externals.cjs +4 -1
|
@@ -82,7 +82,7 @@ export async function loadSkill({ emit, input: deps, context }, plan) {
|
|
|
82
82
|
else {
|
|
83
83
|
session.loadedFilesThisTurn.add(fileKey);
|
|
84
84
|
}
|
|
85
|
-
session.reselectTools?.(new Set([...loadedSkills(context, session), skillName]));
|
|
85
|
+
session.reselectTools?.(new Set([...loadedSkills(context, session), skillName]), context.history);
|
|
86
86
|
const skill = session.inContextSkills.find(({ name }) => name === skillName);
|
|
87
87
|
const loads = skillLoadTurns(skill, {
|
|
88
88
|
sent: session.sdkTools,
|
|
@@ -116,8 +116,6 @@ async function prepare({ input, context, reconstruct, source, emit }) {
|
|
|
116
116
|
const { skillsSelected } = activation;
|
|
117
117
|
const sent = reconstruct ? context.history[0] : undefined;
|
|
118
118
|
let systemContent = sent && 'role' in sent && sent.role === 'system' ? sent.content : system.text;
|
|
119
|
-
const promptPrefix = promptPrefixHash({ system: systemContent, tools: renderedTools(sdkTools) });
|
|
120
|
-
const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools) });
|
|
121
119
|
const logSelection = (prefix) => {
|
|
122
120
|
logToolPrompt({
|
|
123
121
|
promptPrefix: prefix,
|
|
@@ -136,25 +134,26 @@ async function prepare({ input, context, reconstruct, source, emit }) {
|
|
|
136
134
|
toolOps: session.grantedOps
|
|
137
135
|
});
|
|
138
136
|
};
|
|
139
|
-
session.reselectTools = (loaded) => {
|
|
137
|
+
session.reselectTools = (loaded, history) => {
|
|
140
138
|
const reselected = callable(loaded);
|
|
141
139
|
const names = reselected.map((tool) => tool.name).join();
|
|
142
140
|
const changed = names !== session.enabled.map((tool) => tool.name).join();
|
|
143
141
|
if (changed) {
|
|
144
142
|
session.enabled = reselected;
|
|
145
143
|
}
|
|
146
|
-
const
|
|
144
|
+
const tools = renderedTools(sdkTools, history);
|
|
145
|
+
const prefix = promptPrefixHash({ system: systemContent, tools });
|
|
147
146
|
if (changed) {
|
|
148
147
|
logSelection(prefix);
|
|
149
148
|
}
|
|
150
149
|
return prefix;
|
|
151
150
|
};
|
|
152
|
-
session.preloadSystem = (skill) => {
|
|
151
|
+
session.preloadSystem = (skill, history) => {
|
|
153
152
|
const systemParts = resolved.systemFor(new Set([...loadedSkills, skill]));
|
|
154
153
|
systemContent = systemParts.text;
|
|
155
154
|
session.promptParts = promptUsageParts({
|
|
156
155
|
system: systemParts,
|
|
157
|
-
toolSchemas: renderedTools(sdkTools)
|
|
156
|
+
toolSchemas: renderedTools(sdkTools, history)
|
|
158
157
|
});
|
|
159
158
|
return systemContent;
|
|
160
159
|
};
|
|
@@ -168,6 +167,11 @@ async function prepare({ input, context, reconstruct, source, emit }) {
|
|
|
168
167
|
const history = firstTurn
|
|
169
168
|
? withSystem([...withTurnContext(messages, { time, ...added }), ...checks])
|
|
170
169
|
: [...context.history];
|
|
170
|
+
const promptPrefix = promptPrefixHash({
|
|
171
|
+
system: systemContent,
|
|
172
|
+
tools: renderedTools(sdkTools, history)
|
|
173
|
+
});
|
|
174
|
+
const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools, history) });
|
|
171
175
|
if (firstTurn && !reconstruct && messages.some((turn) => turn.role === 'user')) {
|
|
172
176
|
const sources = hits.length ? knowledgeSources(hits) : undefined;
|
|
173
177
|
emit({ type: 'context', context: { time, ...added }, sources, round: context.round });
|
|
@@ -60,8 +60,8 @@ export const skillStep = {
|
|
|
60
60
|
const content = String(result.content);
|
|
61
61
|
session.loadedThisTurn.add(name);
|
|
62
62
|
session.skillIcon = skillEmojiFrom(session.inContextSkills, name) ?? session.skillIcon;
|
|
63
|
-
const typed = withSystem(annotateCompletionHistoryLastUserTime(context.history, new Date(session.startedAt)), session.preloadSystem?.(name));
|
|
64
|
-
session.reselectTools?.(new Set([...loadedSkills(context, session), name]));
|
|
63
|
+
const typed = withSystem(annotateCompletionHistoryLastUserTime(context.history, new Date(session.startedAt)), session.preloadSystem?.(name, context.history));
|
|
64
|
+
session.reselectTools?.(new Set([...loadedSkills(context, session), name]), context.history);
|
|
65
65
|
const called = directToolHistory(typed, {
|
|
66
66
|
tool: step.tool,
|
|
67
67
|
id: step.id,
|
|
@@ -12,7 +12,7 @@ interface RunRoundOptions {
|
|
|
12
12
|
agent?: AgentConfig | undefined;
|
|
13
13
|
kind: RoundKind;
|
|
14
14
|
args: Omit<RoundArgs, 'live' | 'knownTools'>;
|
|
15
|
-
session: Pick<Session, 'liveRound' | 'enabled' | 'runId'>;
|
|
15
|
+
session: Pick<Session, 'liveRound' | 'enabled' | 'runId' | 'promptParts'>;
|
|
16
16
|
emit: (event: CompletionEvent) => void;
|
|
17
17
|
}
|
|
18
18
|
export interface AssembleAnswerOptions {
|
|
@@ -3,6 +3,8 @@ import { inferenceCall, recordWholeRound, runRecoveredRound } from '../round.js'
|
|
|
3
3
|
import { ModelRound } from '../model-round.js';
|
|
4
4
|
import { ToolSets } from '../tool-sets.js';
|
|
5
5
|
import { AbortedError } from '../../../helpers/race-abort.js';
|
|
6
|
+
import { renderedTools } from '../../sdk-tool.js';
|
|
7
|
+
import { toolSchemaChars } from '../../usage-breakdown.js';
|
|
6
8
|
export async function forwardStream({ stream, emit }) {
|
|
7
9
|
try {
|
|
8
10
|
while (true) {
|
|
@@ -37,6 +39,12 @@ export async function runRound({ sdk, modelRound, agent, kind, args, session, em
|
|
|
37
39
|
emit
|
|
38
40
|
});
|
|
39
41
|
session.liveRound = null;
|
|
42
|
+
if (session.promptParts) {
|
|
43
|
+
session.promptParts = {
|
|
44
|
+
...session.promptParts,
|
|
45
|
+
toolSchemas: toolSchemaChars(renderedTools(args.tools, round.history))
|
|
46
|
+
};
|
|
47
|
+
}
|
|
40
48
|
return round;
|
|
41
49
|
}
|
|
42
50
|
catch (error) {
|
|
@@ -7,6 +7,7 @@ import { clipRawCall, recoverMarkupToolCalls, recoverPrintedSkillLoad, recoverSk
|
|
|
7
7
|
import { unquoteArg } from '../../../helpers/model-args.js';
|
|
8
8
|
import { Agent } from '../../../agent/index.js';
|
|
9
9
|
import { loadedTools } from '../../sdk-tool.js';
|
|
10
|
+
import { requestPromptPrefix } from '../../prompt-prefix.js';
|
|
10
11
|
import { FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, TOOL_CONTINUATION_NUDGE, WRAP_UP_NUDGE } from '../../tool-turns.js';
|
|
11
12
|
import { HarnessLog } from '../../../log.js';
|
|
12
13
|
import { toolDialectFor } from '../../../models/model-catalog.js';
|
|
@@ -94,7 +95,10 @@ async function generateStreamingRound({ sdk, args, session, operations, context,
|
|
|
94
95
|
session.runBudget.responseRoomChars = responseRoomChars(recovered.ctxSize ?? args.ctxSize, recovered.final.stats?.cacheTokens);
|
|
95
96
|
const durationMs = Date.now() - prepared.startedAt;
|
|
96
97
|
logRoundStats({ round: context.round, durationMs, recovered });
|
|
97
|
-
|
|
98
|
+
const promptPrefix = recovered.history
|
|
99
|
+
? requestPromptPrefix(recovered.history, session.sdkTools)
|
|
100
|
+
: prepared.promptPrefix;
|
|
101
|
+
return { recovered, promptPrefix, thinkingText, durationMs };
|
|
98
102
|
}
|
|
99
103
|
function logRoundStats({ round, durationMs, recovered }) {
|
|
100
104
|
HarnessLog.debug('round stats', Object.assign({ round, wallMs: durationMs }, recovered.final.stats));
|
|
@@ -106,7 +110,7 @@ function prepareStreamingRound({ args, session, operations, context }) {
|
|
|
106
110
|
: (context.cacheKey ?? undefined);
|
|
107
111
|
const model = args.model;
|
|
108
112
|
const toolDialect = model ? toolDialectFor(model) : undefined;
|
|
109
|
-
const promptPrefix = session.reselectTools?.(loadedSkills(context, session)) ?? context.promptPrefix;
|
|
113
|
+
const promptPrefix = session.reselectTools?.(loadedSkills(context, session), context.history) ?? context.promptPrefix;
|
|
110
114
|
HarnessLog.debug('round start', {
|
|
111
115
|
round: context.round,
|
|
112
116
|
turns: context.history.length,
|
|
@@ -5,6 +5,7 @@ import { roundFold } from './streaming.js';
|
|
|
5
5
|
import { degenerateAnswer } from '../../../helpers/run-outcome.js';
|
|
6
6
|
import { stripToolCallMarkup } from '../../../helpers/tool-call-markup.js';
|
|
7
7
|
import { materializeCompletionHistory } from '../../tool-turns.js';
|
|
8
|
+
import { requestPromptPrefix } from '../../prompt-prefix.js';
|
|
8
9
|
import { toolDialectFor } from '../../../models/model-catalog.js';
|
|
9
10
|
import { loadedSkills } from '../session.js';
|
|
10
11
|
import { CompletionMachine } from '../../../machine/index.js';
|
|
@@ -14,7 +15,7 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
|
|
|
14
15
|
const cacheKey = !args.replaysContext && carriesRunOnlyText(context.history)
|
|
15
16
|
? undefined
|
|
16
17
|
: (context.cacheKey ?? undefined);
|
|
17
|
-
const promptPrefix = session.reselectTools?.(loadedSkills(context, session)) ?? context.promptPrefix;
|
|
18
|
+
const promptPrefix = session.reselectTools?.(loadedSkills(context, session), context.history) ?? context.promptPrefix;
|
|
18
19
|
const startedAt = Date.now();
|
|
19
20
|
const recovered = await runRound({
|
|
20
21
|
sdk,
|
|
@@ -60,7 +61,9 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
|
|
|
60
61
|
return {
|
|
61
62
|
contentText,
|
|
62
63
|
thinkingText: '',
|
|
63
|
-
promptPrefix
|
|
64
|
+
promptPrefix: recovered.history
|
|
65
|
+
? requestPromptPrefix(recovered.history, session.sdkTools)
|
|
66
|
+
: promptPrefix,
|
|
64
67
|
toolCalls: [],
|
|
65
68
|
stats: recovered.final.stats,
|
|
66
69
|
stopReason: recovered.final.stopReason,
|
|
@@ -226,7 +226,7 @@ async function rebuildSession(deps, cx) {
|
|
|
226
226
|
restoreFacts(invocation.input, durable);
|
|
227
227
|
}
|
|
228
228
|
const session = deps.session;
|
|
229
|
-
session.reselectTools?.(loadedSkills(context, session));
|
|
229
|
+
session.reselectTools?.(loadedSkills(context, session), context.history);
|
|
230
230
|
const missing = context.availableTools.filter((name) => !session.enabled.some((tool) => tool.name === name));
|
|
231
231
|
const changed = durable?.tools
|
|
232
232
|
.filter((saved) => {
|
|
@@ -17,6 +17,7 @@ import { stableStringify } from '../../helpers/stable-stringify.js';
|
|
|
17
17
|
import { detachJson } from '../../helpers/detach-json.js';
|
|
18
18
|
import { isSkillMentionNudge, materializeCompletionHistory } from '../tool-turns.js';
|
|
19
19
|
import { completionParams } from '../../helpers/completion-params.js';
|
|
20
|
+
import { requestPromptPrefix } from '../prompt-prefix.js';
|
|
20
21
|
import { isFailureResultReference } from '../../helpers/failure-result.js';
|
|
21
22
|
import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
|
|
22
23
|
import { Fold } from '../../fold/index.js';
|
|
@@ -756,7 +757,7 @@ export function inferenceCall({ args, droppedTurns, modelId, params, cacheKey })
|
|
|
756
757
|
responseFormat: params.responseFormat,
|
|
757
758
|
toolDialect: params.toolDialect,
|
|
758
759
|
cacheKey,
|
|
759
|
-
promptPrefix:
|
|
760
|
+
promptPrefix: requestPromptPrefix(params.history, params.tools)
|
|
760
761
|
}
|
|
761
762
|
};
|
|
762
763
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Tool as SdkTool } from '@qvac/inference';
|
|
2
2
|
import type { HookPipeline } from '../../hooks/index.ts';
|
|
3
3
|
import { type RunOutcomeTracker } from '../../helpers/run-outcome.ts';
|
|
4
|
-
import type { AgentPolicy, AgentPorts, CompletionEvent, CliValidator, CompiledPolicy, CompletionSdk, DriveRoot, LlmGenerationParams, OutboundGuard, RunBackendUse, RunBudget, SkillActivation, ToolDefinition } from '../../contract/index.ts';
|
|
4
|
+
import type { AgentPolicy, AgentPorts, CompletionEvent, CliValidator, CompiledPolicy, CompletionHistoryEntry, CompletionSdk, DriveRoot, LlmGenerationParams, OutboundGuard, RunBackendUse, RunBudget, SkillActivation, ToolDefinition } from '../../contract/index.ts';
|
|
5
5
|
import type { CompletionArgs, ToolContextFactory } from './loop.ts';
|
|
6
6
|
import type { CompletionSkillEntry } from '../skill-entry.ts';
|
|
7
7
|
import type { PromptUsageChars } from '../usage-breakdown.ts';
|
|
@@ -49,8 +49,8 @@ export interface Session extends InvokeTracker {
|
|
|
49
49
|
startedAt: number;
|
|
50
50
|
now: () => number;
|
|
51
51
|
wallStart: number;
|
|
52
|
-
reselectTools: ((loadedSkills: ReadonlySet<string
|
|
53
|
-
preloadSystem: ((skill: string) => string) | null;
|
|
52
|
+
reselectTools: ((loadedSkills: ReadonlySet<string>, history: readonly CompletionHistoryEntry[]) => string) | null;
|
|
53
|
+
preloadSystem: ((skill: string, history: readonly CompletionHistoryEntry[]) => string) | null;
|
|
54
54
|
liveRound: LiveRound | null;
|
|
55
55
|
}
|
|
56
56
|
export interface CompletionDeps {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Tool as SdkTool } from '@qvac/inference';
|
|
2
|
+
import type { CompletionHistoryEntry } from '../contract/index.ts';
|
|
2
3
|
export interface PromptPrefix {
|
|
3
4
|
system: string | null;
|
|
4
5
|
tools: ReadonlyArray<SdkTool> | undefined;
|
|
5
6
|
}
|
|
6
7
|
export declare function promptPrefixHash({ system, tools }: PromptPrefix): string;
|
|
8
|
+
export declare function requestPromptPrefix(history: readonly CompletionHistoryEntry[], tools: SdkTool[] | undefined): string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
|
+
import { renderedTools } from './sdk-tool.js';
|
|
2
3
|
export function promptPrefixHash({ system, tools }) {
|
|
3
4
|
const hash = crypto.createHash('sha256');
|
|
4
5
|
hash.update(system ?? '');
|
|
@@ -8,3 +9,10 @@ export function promptPrefixHash({ system, tools }) {
|
|
|
8
9
|
}
|
|
9
10
|
return hash.digest('hex').slice(0, 12);
|
|
10
11
|
}
|
|
12
|
+
export function requestPromptPrefix(history, tools) {
|
|
13
|
+
const system = history.find((entry) => 'role' in entry && entry.role === 'system');
|
|
14
|
+
return promptPrefixHash({
|
|
15
|
+
system: system && 'content' in system ? system.content : null,
|
|
16
|
+
tools: renderedTools(tools, history)
|
|
17
|
+
});
|
|
18
|
+
}
|
|
@@ -5,7 +5,7 @@ export declare function defers(tool: ToolDefinition): boolean;
|
|
|
5
5
|
export declare function deferredForRun(tool: ToolDefinition): ToolDefinition;
|
|
6
6
|
export declare function toSdkTool(tool: ToolDefinition): SdkTool;
|
|
7
7
|
export declare function toSdkTools(tools: readonly ToolDefinition[]): SdkTool[] | undefined;
|
|
8
|
-
export declare function renderedTools(tools: SdkTool[] | undefined): SdkTool[] | undefined;
|
|
8
|
+
export declare function renderedTools(tools: SdkTool[] | undefined, history: readonly CompletionHistoryEntry[]): SdkTool[] | undefined;
|
|
9
9
|
export declare function loadedTools(history: readonly CompletionHistoryEntry[]): Set<string>;
|
|
10
10
|
export declare function loadTurns(sent: readonly SdkTool[] | undefined, names: Iterable<string>, history: readonly CompletionHistoryEntry[]): Message[];
|
|
11
11
|
interface SkillLoad {
|
|
@@ -102,12 +102,27 @@ export function toSdkTools(tools) {
|
|
|
102
102
|
const sent = tools.filter((tool) => !searching || tool.name !== TOOL_SEARCH_NAME);
|
|
103
103
|
return sent.length ? sent.map((tool) => toSdkTool(tool)) : undefined;
|
|
104
104
|
}
|
|
105
|
-
export function renderedTools(tools) {
|
|
105
|
+
export function renderedTools(tools, history) {
|
|
106
106
|
const deferred = tools?.filter((tool) => tool.deferLoading === true) ?? [];
|
|
107
107
|
if (!tools || !deferred.length) {
|
|
108
108
|
return tools;
|
|
109
109
|
}
|
|
110
|
-
|
|
110
|
+
const whole = tools.filter((tool) => tool.deferLoading !== true);
|
|
111
|
+
const ruleName = (name) => name.replace(/[^A-Za-z0-9-]+/g, '-');
|
|
112
|
+
const taken = new Set([...whole.map(({ name }) => name), TOOL_SEARCH_NAME].map(ruleName));
|
|
113
|
+
const selectable = deferred.filter(({ name }) => {
|
|
114
|
+
const rule = ruleName(name);
|
|
115
|
+
if (['', 'auto', 'none', 'required'].includes(name) || taken.has(rule)) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
taken.add(rule);
|
|
119
|
+
return true;
|
|
120
|
+
});
|
|
121
|
+
const loaded = loadedTools(history);
|
|
122
|
+
const declared = selectable
|
|
123
|
+
.filter(({ name }) => loaded.has(name))
|
|
124
|
+
.map(({ deferLoading: _deferLoading, group: _group, ...wire }) => wire);
|
|
125
|
+
return [...whole, buildToolSearchTool(selectable), ...declared];
|
|
111
126
|
}
|
|
112
127
|
export function loadedTools(history) {
|
|
113
128
|
return loadedToolNames(history.filter((entry) => !isFailureResultReference(entry)));
|
|
@@ -24,4 +24,5 @@ export interface PromptUsagePartsInput {
|
|
|
24
24
|
toolSchemas?: ReadonlyArray<unknown> | undefined;
|
|
25
25
|
}
|
|
26
26
|
export declare function promptUsageParts({ system, toolSchemas }: PromptUsagePartsInput): PromptUsageChars;
|
|
27
|
+
export declare function toolSchemaChars(toolSchemas?: ReadonlyArray<unknown>): number;
|
|
27
28
|
export declare function usageBreakdown(chars: PromptUsageChars, totalTokens?: number | null, modelName?: string | null): UsageBreakdown | null;
|
|
@@ -13,9 +13,12 @@ export function promptUsageParts({ system, toolSchemas }) {
|
|
|
13
13
|
systemPrompt: system.text.length - system.bioChars - system.skillsChars,
|
|
14
14
|
agentInstructions: system.bioChars,
|
|
15
15
|
activeSkills: system.skillsChars,
|
|
16
|
-
toolSchemas: (toolSchemas
|
|
16
|
+
toolSchemas: toolSchemaChars(toolSchemas)
|
|
17
17
|
};
|
|
18
18
|
}
|
|
19
|
+
export function toolSchemaChars(toolSchemas) {
|
|
20
|
+
return (toolSchemas ?? []).reduce((total, schema) => total + JSON.stringify(schema).length, 0);
|
|
21
|
+
}
|
|
19
22
|
export function usageBreakdown(chars, totalTokens, modelName) {
|
|
20
23
|
if (!totalTokens || totalTokens <= 0)
|
|
21
24
|
return null;
|
|
@@ -13,6 +13,9 @@ export declare class Knowledge implements HarnessPlugin {
|
|
|
13
13
|
readonly api = 1;
|
|
14
14
|
readonly provides: string[];
|
|
15
15
|
readonly needs: string[];
|
|
16
|
+
readonly addons: {
|
|
17
|
+
'turbovec-ggml': () => Promise<any>;
|
|
18
|
+
};
|
|
16
19
|
readonly read: readonly string[] | undefined;
|
|
17
20
|
private readonly _options;
|
|
18
21
|
constructor(options: KnowledgeOptions);
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { PluginRegistry } from '../../lib/plugins/index.js';
|
|
2
2
|
import { knowledgeSearchTool } from './search-tool.js';
|
|
3
3
|
import { KnowledgeStore } from './store.js';
|
|
4
|
+
PluginRegistry.requirePeers('knowledge', {
|
|
5
|
+
'@qvac/turbovec-ggml': () => import.meta.resolve('@qvac/turbovec-ggml')
|
|
6
|
+
});
|
|
4
7
|
export { KNOWLEDGE_SEARCH_TOOL } from './search-tool.js';
|
|
5
8
|
function invalid(config) {
|
|
6
9
|
if (!config?.dir || !config.model) {
|
|
@@ -20,6 +23,7 @@ export class Knowledge {
|
|
|
20
23
|
api = PluginRegistry.API_VERSION;
|
|
21
24
|
provides = ['knowledge'];
|
|
22
25
|
needs = ['embed'];
|
|
26
|
+
addons = { 'turbovec-ggml': () => import('@qvac/turbovec-ggml/binding.js') };
|
|
23
27
|
read;
|
|
24
28
|
_options;
|
|
25
29
|
constructor(options) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const MANIFEST_FILE = "knowledge.json";
|
|
2
|
+
export declare const CHUNKS_DIR = "chunks";
|
|
3
|
+
declare const FORMAT = 2;
|
|
2
4
|
export interface StoredChunk {
|
|
3
|
-
id: string;
|
|
4
5
|
chunkId: string;
|
|
5
6
|
text: string;
|
|
6
7
|
metadata?: Record<string, unknown>;
|
|
@@ -10,9 +11,10 @@ export interface StoredArtifact {
|
|
|
10
11
|
scope: string;
|
|
11
12
|
seq: number;
|
|
12
13
|
pending?: boolean;
|
|
13
|
-
|
|
14
|
+
ids: string[];
|
|
14
15
|
}
|
|
15
16
|
export interface Manifest {
|
|
17
|
+
format: typeof FORMAT;
|
|
16
18
|
model: string;
|
|
17
19
|
dimensions: number;
|
|
18
20
|
nextId: number;
|
|
@@ -20,10 +22,32 @@ export interface Manifest {
|
|
|
20
22
|
generation?: number;
|
|
21
23
|
artifacts: Record<string, StoredArtifact>;
|
|
22
24
|
}
|
|
25
|
+
interface LegacyChunk extends StoredChunk {
|
|
26
|
+
id: string;
|
|
27
|
+
}
|
|
28
|
+
interface LegacyArtifact extends Omit<StoredArtifact, 'ids'> {
|
|
29
|
+
chunks: LegacyChunk[];
|
|
30
|
+
}
|
|
31
|
+
export interface LegacyManifest extends Omit<Manifest, 'format' | 'artifacts'> {
|
|
32
|
+
artifacts: Record<string, LegacyArtifact>;
|
|
33
|
+
}
|
|
23
34
|
export declare function emptyManifest(model: string): Manifest;
|
|
24
35
|
export declare function snapshotFile(generation: number | undefined): string;
|
|
25
36
|
export declare function isSnapshotFile(file: string): boolean;
|
|
26
|
-
export declare function
|
|
37
|
+
export declare function chunksFile(ids: readonly string[]): string | null;
|
|
27
38
|
export declare function indexedChunks(manifest: Manifest): number;
|
|
28
|
-
export declare function
|
|
39
|
+
export declare function isLegacy(manifest: Manifest | LegacyManifest): manifest is LegacyManifest;
|
|
40
|
+
export interface ChunkFile {
|
|
41
|
+
ids: string[];
|
|
42
|
+
chunks: StoredChunk[];
|
|
43
|
+
}
|
|
44
|
+
export interface Split {
|
|
45
|
+
manifest: Manifest;
|
|
46
|
+
files: ChunkFile[];
|
|
47
|
+
}
|
|
48
|
+
export declare function splitLegacy(legacy: LegacyManifest): Split;
|
|
49
|
+
export declare function readManifest(file: string): Promise<Manifest | LegacyManifest | null>;
|
|
29
50
|
export declare function writeManifest(file: string, manifest: Manifest): Promise<void>;
|
|
51
|
+
export declare function readChunks(dir: string, ids: readonly string[]): Promise<StoredChunk[]>;
|
|
52
|
+
export declare function writeChunks(dir: string, ids: readonly string[], chunks: StoredChunk[]): Promise<void>;
|
|
53
|
+
export {};
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
2
3
|
import { isRecord } from '../../lib/guards.js';
|
|
3
4
|
export const MANIFEST_FILE = 'knowledge.json';
|
|
5
|
+
export const CHUNKS_DIR = 'chunks';
|
|
4
6
|
const SNAPSHOT = /^knowledge(\.\d+)?\.qvi$/;
|
|
7
|
+
const FORMAT = 2;
|
|
5
8
|
export function emptyManifest(model) {
|
|
6
|
-
return { model, dimensions: 0, nextId: 1, seq: 0, artifacts: {} };
|
|
9
|
+
return { format: FORMAT, model, dimensions: 0, nextId: 1, seq: 0, artifacts: {} };
|
|
7
10
|
}
|
|
8
11
|
export function snapshotFile(generation) {
|
|
9
12
|
return generation === undefined ? 'knowledge.qvi' : `knowledge.${generation}.qvi`;
|
|
@@ -11,11 +14,27 @@ export function snapshotFile(generation) {
|
|
|
11
14
|
export function isSnapshotFile(file) {
|
|
12
15
|
return SNAPSHOT.test(file);
|
|
13
16
|
}
|
|
14
|
-
export function
|
|
15
|
-
return
|
|
17
|
+
export function chunksFile(ids) {
|
|
18
|
+
return ids.length ? `${ids[0]}.json` : null;
|
|
16
19
|
}
|
|
17
20
|
export function indexedChunks(manifest) {
|
|
18
|
-
return Object.values(manifest.artifacts).reduce((sum, stored) => sum + (stored.pending ? 0 : stored.
|
|
21
|
+
return Object.values(manifest.artifacts).reduce((sum, stored) => sum + (stored.pending ? 0 : stored.ids.length), 0);
|
|
22
|
+
}
|
|
23
|
+
export function isLegacy(manifest) {
|
|
24
|
+
return !('format' in manifest);
|
|
25
|
+
}
|
|
26
|
+
export function splitLegacy(legacy) {
|
|
27
|
+
const files = [];
|
|
28
|
+
const artifacts = {};
|
|
29
|
+
for (const [artifactId, { chunks, ...header }] of Object.entries(legacy.artifacts)) {
|
|
30
|
+
const ids = chunks.map((chunk) => chunk.id);
|
|
31
|
+
files.push({
|
|
32
|
+
ids,
|
|
33
|
+
chunks: chunks.map(({ chunkId, text, metadata }) => ({ chunkId, text, metadata }))
|
|
34
|
+
});
|
|
35
|
+
artifacts[artifactId] = { ...header, ids };
|
|
36
|
+
}
|
|
37
|
+
return { manifest: { ...legacy, format: FORMAT, artifacts }, files };
|
|
19
38
|
}
|
|
20
39
|
export async function readManifest(file) {
|
|
21
40
|
try {
|
|
@@ -30,8 +49,34 @@ export async function writeManifest(file, manifest) {
|
|
|
30
49
|
await fs.promises.writeFile(`${file}.tmp`, JSON.stringify(manifest));
|
|
31
50
|
await fs.promises.rename(`${file}.tmp`, file);
|
|
32
51
|
}
|
|
52
|
+
export async function readChunks(dir, ids) {
|
|
53
|
+
const file = chunksFile(ids);
|
|
54
|
+
if (!file) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
const chunks = JSON.parse(await fs.promises.readFile(path.join(dir, file), 'utf8'));
|
|
58
|
+
if (!Array.isArray(chunks) || chunks.length !== ids.length || !chunks.every(isStoredChunk)) {
|
|
59
|
+
throw new Error(`${file} does not hold the artifact's ${ids.length} chunks`);
|
|
60
|
+
}
|
|
61
|
+
return chunks;
|
|
62
|
+
}
|
|
63
|
+
export async function writeChunks(dir, ids, chunks) {
|
|
64
|
+
const file = chunksFile(ids);
|
|
65
|
+
if (!file) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
await fs.promises.mkdir(dir, { recursive: true });
|
|
69
|
+
await fs.promises.writeFile(path.join(dir, file), JSON.stringify(chunks));
|
|
70
|
+
}
|
|
71
|
+
function isStoredChunk(value) {
|
|
72
|
+
return (isRecord(value) &&
|
|
73
|
+
typeof value.chunkId === 'string' &&
|
|
74
|
+
typeof value.text === 'string' &&
|
|
75
|
+
(value.metadata === undefined || isRecord(value.metadata)));
|
|
76
|
+
}
|
|
33
77
|
function isManifest(value) {
|
|
34
78
|
return (isRecord(value) &&
|
|
79
|
+
(value.format === undefined || value.format === FORMAT) &&
|
|
35
80
|
typeof value.model === 'string' &&
|
|
36
81
|
typeof value.dimensions === 'number' &&
|
|
37
82
|
typeof value.nextId === 'number' &&
|
|
@@ -14,6 +14,8 @@ export declare class KnowledgeStore implements KnowledgeService {
|
|
|
14
14
|
private readonly _minScore;
|
|
15
15
|
private readonly _embed;
|
|
16
16
|
private _manifest;
|
|
17
|
+
private readonly _located;
|
|
18
|
+
private _freed;
|
|
17
19
|
private _index;
|
|
18
20
|
private _opened;
|
|
19
21
|
private _writes;
|
|
@@ -39,6 +41,7 @@ export declare class KnowledgeStore implements KnowledgeService {
|
|
|
39
41
|
private _ready;
|
|
40
42
|
private _recovering;
|
|
41
43
|
private _open;
|
|
44
|
+
private _split;
|
|
42
45
|
private _load;
|
|
43
46
|
private _reload;
|
|
44
47
|
private _loadCurrent;
|
|
@@ -49,6 +52,7 @@ export declare class KnowledgeStore implements KnowledgeService {
|
|
|
49
52
|
private _apply;
|
|
50
53
|
private _indexFor;
|
|
51
54
|
private _drop;
|
|
55
|
+
private _locate;
|
|
52
56
|
private _evict;
|
|
53
57
|
private _release;
|
|
54
58
|
private _refill;
|
|
@@ -59,7 +63,10 @@ export declare class KnowledgeStore implements KnowledgeService {
|
|
|
59
63
|
private _searchable;
|
|
60
64
|
private _search;
|
|
61
65
|
private _ranked;
|
|
62
|
-
private
|
|
66
|
+
private _granted;
|
|
67
|
+
private _withText;
|
|
68
|
+
private _chunks;
|
|
69
|
+
private _lose;
|
|
63
70
|
private _warm;
|
|
64
71
|
private _chunkCount;
|
|
65
72
|
private _file;
|
|
@@ -67,4 +74,6 @@ export declare class KnowledgeStore implements KnowledgeService {
|
|
|
67
74
|
private _writeOut;
|
|
68
75
|
private _persist;
|
|
69
76
|
private _sweep;
|
|
77
|
+
private _sweepChunks;
|
|
78
|
+
private _remove;
|
|
70
79
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
3
|
import { isRecord } from '../../lib/guards.js';
|
|
4
|
-
import { MANIFEST_FILE,
|
|
4
|
+
import { CHUNKS_DIR, MANIFEST_FILE, chunksFile, emptyManifest, indexedChunks, isLegacy, isSnapshotFile, readChunks, readManifest, snapshotFile, splitLegacy, writeChunks, writeManifest } from './manifest.js';
|
|
5
5
|
const DEFAULT_K = 5;
|
|
6
6
|
const DEFAULT_MIN_SCORE = 0.4;
|
|
7
7
|
const VECTOR_INDEX_NOT_FOUND = 52851;
|
|
@@ -21,9 +21,11 @@ function matches(embedding, want) {
|
|
|
21
21
|
embedding.vectors.length === want.chunks &&
|
|
22
22
|
embedding.vectors.every((row) => row.length === embedding.dimensions));
|
|
23
23
|
}
|
|
24
|
+
function storedChunk({ id, text, metadata }) {
|
|
25
|
+
return { chunkId: id, text, metadata };
|
|
26
|
+
}
|
|
24
27
|
function sameChunks(a, b) {
|
|
25
|
-
return
|
|
26
|
-
a.chunks.every((chunk, at) => chunk.id === b.chunks[at]?.id));
|
|
28
|
+
return a.ids.length === b.ids.length && a.ids.every((id, at) => id === b.ids[at]);
|
|
27
29
|
}
|
|
28
30
|
function turn() {
|
|
29
31
|
return new Promise((resolve) => setImmediate(resolve));
|
|
@@ -38,6 +40,8 @@ export class KnowledgeStore {
|
|
|
38
40
|
_minScore;
|
|
39
41
|
_embed;
|
|
40
42
|
_manifest;
|
|
43
|
+
_located;
|
|
44
|
+
_freed;
|
|
41
45
|
_index;
|
|
42
46
|
_opened;
|
|
43
47
|
_writes;
|
|
@@ -55,6 +59,8 @@ export class KnowledgeStore {
|
|
|
55
59
|
this._minScore = minScore;
|
|
56
60
|
this._embed = embed;
|
|
57
61
|
this._manifest = emptyManifest(model);
|
|
62
|
+
this._located = new Map();
|
|
63
|
+
this._freed = [];
|
|
58
64
|
this._index = null;
|
|
59
65
|
this._opened = null;
|
|
60
66
|
this._writes = Promise.resolve();
|
|
@@ -121,7 +127,7 @@ export class KnowledgeStore {
|
|
|
121
127
|
artifactId,
|
|
122
128
|
version: stored.version,
|
|
123
129
|
scope: stored.scope,
|
|
124
|
-
chunks: stored.
|
|
130
|
+
chunks: stored.ids.length
|
|
125
131
|
}));
|
|
126
132
|
const chunks = entries.reduce((sum, entry) => sum + entry.chunks, 0);
|
|
127
133
|
return {
|
|
@@ -196,8 +202,10 @@ export class KnowledgeStore {
|
|
|
196
202
|
}
|
|
197
203
|
}
|
|
198
204
|
async _open() {
|
|
199
|
-
const
|
|
200
|
-
await this._sweep(snapshotFile(
|
|
205
|
+
const read = await readManifest(this._file(MANIFEST_FILE));
|
|
206
|
+
await this._sweep(snapshotFile(read?.generation));
|
|
207
|
+
const saved = read && isLegacy(read) ? await this._split(read) : read;
|
|
208
|
+
const written = await this._sweepChunks(saved);
|
|
201
209
|
if (!saved) {
|
|
202
210
|
return;
|
|
203
211
|
}
|
|
@@ -212,8 +220,25 @@ export class KnowledgeStore {
|
|
|
212
220
|
this._markPending();
|
|
213
221
|
}
|
|
214
222
|
}
|
|
223
|
+
for (const [artifactId, stored] of Object.entries(this._manifest.artifacts)) {
|
|
224
|
+
const file = chunksFile(stored.ids);
|
|
225
|
+
if (file && !written.has(file)) {
|
|
226
|
+
await this._lose(artifactId, stored);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
this._locate(artifactId, stored);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
215
232
|
this._refill();
|
|
216
233
|
}
|
|
234
|
+
async _split(legacy) {
|
|
235
|
+
const { manifest, files } = splitLegacy(legacy);
|
|
236
|
+
for (const { ids, chunks } of files) {
|
|
237
|
+
await writeChunks(this._file(CHUNKS_DIR), ids, chunks);
|
|
238
|
+
}
|
|
239
|
+
await writeManifest(this._file(MANIFEST_FILE), manifest);
|
|
240
|
+
return manifest;
|
|
241
|
+
}
|
|
217
242
|
async _load(saved) {
|
|
218
243
|
const chunks = indexedChunks(saved);
|
|
219
244
|
if (chunks === 0) {
|
|
@@ -233,7 +258,8 @@ export class KnowledgeStore {
|
|
|
233
258
|
}
|
|
234
259
|
async _reload() {
|
|
235
260
|
this._index = null;
|
|
236
|
-
const
|
|
261
|
+
const read = await readManifest(this._file(MANIFEST_FILE));
|
|
262
|
+
const saved = read && !isLegacy(read) ? read : null;
|
|
237
263
|
const index = await this._loadCurrent(saved);
|
|
238
264
|
const written = new Map(Object.entries(index && saved ? saved.artifacts : {}).filter(([, stored]) => !stored.pending));
|
|
239
265
|
const stale = [];
|
|
@@ -243,11 +269,11 @@ export class KnowledgeStore {
|
|
|
243
269
|
if (before && !stored.pending && sameChunks(before, stored)) {
|
|
244
270
|
continue;
|
|
245
271
|
}
|
|
246
|
-
stale.push(...(before
|
|
247
|
-
stored.pending = stored.
|
|
272
|
+
stale.push(...(before?.ids ?? []));
|
|
273
|
+
stored.pending = stored.ids.length > 0 || undefined;
|
|
248
274
|
}
|
|
249
275
|
for (const before of written.values()) {
|
|
250
|
-
stale.push(...
|
|
276
|
+
stale.push(...before.ids);
|
|
251
277
|
}
|
|
252
278
|
if (index && stale.length) {
|
|
253
279
|
await index.remove({ ids: stale });
|
|
@@ -266,7 +292,7 @@ export class KnowledgeStore {
|
|
|
266
292
|
}
|
|
267
293
|
_markPending() {
|
|
268
294
|
for (const stored of Object.values(this._manifest.artifacts)) {
|
|
269
|
-
stored.pending = stored.
|
|
295
|
+
stored.pending = stored.ids.length > 0 || undefined;
|
|
270
296
|
}
|
|
271
297
|
}
|
|
272
298
|
async _reset(dimensions) {
|
|
@@ -310,27 +336,22 @@ export class KnowledgeStore {
|
|
|
310
336
|
await this._reset(dim);
|
|
311
337
|
}
|
|
312
338
|
const fits = vectors.length > 0 && (manifest.dimensions === 0 || dim === manifest.dimensions);
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
chunkId: chunk.id,
|
|
316
|
-
text: chunk.text,
|
|
317
|
-
metadata: chunk.metadata
|
|
318
|
-
}));
|
|
339
|
+
const ids = chunks.map(() => String(manifest.nextId++));
|
|
340
|
+
await writeChunks(this._file(CHUNKS_DIR), ids, chunks.map(storedChunk));
|
|
319
341
|
if (fits) {
|
|
320
342
|
const index = await this._indexFor(dim);
|
|
321
|
-
await index.add({ ids
|
|
343
|
+
await index.add({ ids, vectors: vectors.map(unit) });
|
|
322
344
|
}
|
|
323
345
|
await this._drop(artifactId);
|
|
324
|
-
const pending =
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
}
|
|
346
|
+
const pending = (ids.length > 0 && !fits) || undefined;
|
|
347
|
+
const stored = { version, scope, seq: ++manifest.seq, pending, ids };
|
|
348
|
+
manifest.artifacts[artifactId] = stored;
|
|
349
|
+
this._locate(artifactId, stored);
|
|
329
350
|
await this._evict(artifactId);
|
|
330
351
|
await this._release();
|
|
331
352
|
this._changed();
|
|
332
353
|
this._refill();
|
|
333
|
-
return { added:
|
|
354
|
+
return { added: ids.length, embedded };
|
|
334
355
|
}
|
|
335
356
|
async _indexFor(dim) {
|
|
336
357
|
if (this._index) {
|
|
@@ -349,12 +370,22 @@ export class KnowledgeStore {
|
|
|
349
370
|
if (!stored) {
|
|
350
371
|
return 0;
|
|
351
372
|
}
|
|
352
|
-
if (this._index && !stored.pending && stored.
|
|
353
|
-
await this._index.remove({ ids:
|
|
373
|
+
if (this._index && !stored.pending && stored.ids.length) {
|
|
374
|
+
await this._index.remove({ ids: stored.ids });
|
|
354
375
|
}
|
|
355
376
|
delete this._manifest.artifacts[artifactId];
|
|
377
|
+
for (const id of stored.ids) {
|
|
378
|
+
this._located.delete(id);
|
|
379
|
+
}
|
|
380
|
+
const file = chunksFile(stored.ids);
|
|
381
|
+
if (file) {
|
|
382
|
+
this._freed.push(file);
|
|
383
|
+
}
|
|
356
384
|
this._changed();
|
|
357
|
-
return stored.
|
|
385
|
+
return stored.ids.length;
|
|
386
|
+
}
|
|
387
|
+
_locate(artifactId, stored) {
|
|
388
|
+
stored.ids.forEach((id, at) => this._located.set(id, { artifactId, at }));
|
|
358
389
|
}
|
|
359
390
|
async _evict(keep) {
|
|
360
391
|
const oldest = Object.entries(this._manifest.artifacts)
|
|
@@ -396,7 +427,12 @@ export class KnowledgeStore {
|
|
|
396
427
|
if (this._manifest.artifacts[artifactId] !== stored || !stored.pending) {
|
|
397
428
|
return;
|
|
398
429
|
}
|
|
399
|
-
const
|
|
430
|
+
const chunks = await this._chunks(stored.ids);
|
|
431
|
+
if (!chunks) {
|
|
432
|
+
await this._locked(() => this._lose(artifactId, stored));
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const embedded = await this._embedTexts(chunks.map((chunk) => chunk.text), { stopped: () => this._closed });
|
|
400
436
|
await this._locked(() => this._fill(artifactId, stored, embedded));
|
|
401
437
|
}
|
|
402
438
|
_nextPending() {
|
|
@@ -412,17 +448,17 @@ export class KnowledgeStore {
|
|
|
412
448
|
await this._reset(dimensions);
|
|
413
449
|
}
|
|
414
450
|
const index = await this._indexFor(dimensions);
|
|
415
|
-
await index.add({ ids:
|
|
451
|
+
await index.add({ ids: stored.ids, vectors: vectors.map(unit) });
|
|
416
452
|
delete stored.pending;
|
|
417
453
|
this._changed();
|
|
418
454
|
}
|
|
419
455
|
_searchable(granted) {
|
|
420
|
-
return
|
|
456
|
+
return this._granted(granted).size > 0;
|
|
421
457
|
}
|
|
422
458
|
async _search({ scopes, focus, k = DEFAULT_K }, query) {
|
|
423
|
-
const
|
|
459
|
+
const granted = this._granted(new Set(scopes));
|
|
424
460
|
const index = this._index;
|
|
425
|
-
if (!index ||
|
|
461
|
+
if (!index || granted.size === 0) {
|
|
426
462
|
return [];
|
|
427
463
|
}
|
|
428
464
|
if (query.length !== index.dim) {
|
|
@@ -430,18 +466,24 @@ export class KnowledgeStore {
|
|
|
430
466
|
return [];
|
|
431
467
|
}
|
|
432
468
|
const named = new Set(focus);
|
|
433
|
-
const focused = new Map([...
|
|
434
|
-
const hits = focused.size ? await this._ranked(index, { query,
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
469
|
+
const focused = new Map([...granted].filter(([artifactId]) => named.has(artifactId)));
|
|
470
|
+
const hits = focused.size ? await this._ranked(index, { query, among: focused, k }) : [];
|
|
471
|
+
const found = hits.length
|
|
472
|
+
? hits
|
|
473
|
+
: await this._ranked(index, { query, among: granted, k, floor: this._minScore });
|
|
474
|
+
return this._withText(found);
|
|
475
|
+
}
|
|
476
|
+
async _ranked(index, { query, among, k, floor = -Infinity }) {
|
|
477
|
+
const chunks = [...among.values()].reduce((sum, stored) => sum + stored.ids.length, 0);
|
|
478
|
+
const want = Math.min(k, chunks);
|
|
439
479
|
let fetch = Math.min(index.length, want * 4);
|
|
440
480
|
for (;;) {
|
|
441
481
|
const hits = await index.search({ query: unit(query), k: fetch });
|
|
442
482
|
const found = hits.flatMap((hit) => {
|
|
443
|
-
const
|
|
444
|
-
return
|
|
483
|
+
const located = this._located.get(hit.id);
|
|
484
|
+
return located && among.has(located.artifactId) && hit.score >= floor
|
|
485
|
+
? [{ ...located, score: hit.score }]
|
|
486
|
+
: [];
|
|
445
487
|
});
|
|
446
488
|
const floored = (hits.at(-1)?.score ?? -Infinity) < floor;
|
|
447
489
|
if (found.length >= want || floored || fetch >= index.length) {
|
|
@@ -450,22 +492,41 @@ export class KnowledgeStore {
|
|
|
450
492
|
fetch = Math.min(index.length, fetch * 4);
|
|
451
493
|
}
|
|
452
494
|
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
495
|
+
_granted(scopes) {
|
|
496
|
+
return new Map(Object.entries(this._manifest.artifacts).filter(([, stored]) => !stored.pending && stored.ids.length > 0 && scopes.has(stored.scope)));
|
|
497
|
+
}
|
|
498
|
+
async _withText(found) {
|
|
499
|
+
const files = new Map();
|
|
500
|
+
const read = (artifactId, ids) => {
|
|
501
|
+
const chunks = files.get(artifactId) ?? this._chunks(ids);
|
|
502
|
+
files.set(artifactId, chunks);
|
|
503
|
+
return chunks;
|
|
504
|
+
};
|
|
505
|
+
const hits = await Promise.all(found.map(async ({ artifactId, at, score }) => {
|
|
506
|
+
const { scope, ids } = this._manifest.artifacts[artifactId];
|
|
507
|
+
const chunks = await read(artifactId, ids);
|
|
508
|
+
if (!chunks) {
|
|
509
|
+
return [];
|
|
466
510
|
}
|
|
511
|
+
const { chunkId, text, metadata } = chunks[at];
|
|
512
|
+
return [{ artifactId, chunkId, scope, text, metadata, score }];
|
|
513
|
+
}));
|
|
514
|
+
for (const [artifactId, chunks] of files) {
|
|
515
|
+
if (!(await chunks)) {
|
|
516
|
+
await this._lose(artifactId, this._manifest.artifacts[artifactId]);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return hits.flat();
|
|
520
|
+
}
|
|
521
|
+
_chunks(ids) {
|
|
522
|
+
return readChunks(this._file(CHUNKS_DIR), ids).catch(() => null);
|
|
523
|
+
}
|
|
524
|
+
async _lose(artifactId, stored) {
|
|
525
|
+
if (this._manifest.artifacts[artifactId] !== stored) {
|
|
526
|
+
return;
|
|
467
527
|
}
|
|
468
|
-
|
|
528
|
+
await this._drop(artifactId);
|
|
529
|
+
await this._release();
|
|
469
530
|
}
|
|
470
531
|
async _warm() {
|
|
471
532
|
const index = this._index;
|
|
@@ -476,7 +537,7 @@ export class KnowledgeStore {
|
|
|
476
537
|
await index.search({ query: probe, k: 1 });
|
|
477
538
|
}
|
|
478
539
|
_chunkCount() {
|
|
479
|
-
return Object.values(this._manifest.artifacts).reduce((sum, stored) => sum + stored.
|
|
540
|
+
return Object.values(this._manifest.artifacts).reduce((sum, stored) => sum + stored.ids.length, 0);
|
|
480
541
|
}
|
|
481
542
|
_file(name) {
|
|
482
543
|
return path.join(this._dir, name);
|
|
@@ -514,11 +575,20 @@ export class KnowledgeStore {
|
|
|
514
575
|
await writeManifest(this._file(MANIFEST_FILE), { ...this._manifest, generation });
|
|
515
576
|
this._manifest.generation = generation;
|
|
516
577
|
await fs.promises.rm(this._file(snapshotFile(replaced)), { force: true });
|
|
578
|
+
await this._remove(CHUNKS_DIR, this._freed.splice(0));
|
|
517
579
|
}
|
|
518
580
|
async _sweep(kept) {
|
|
519
581
|
const files = await fs.promises.readdir(this._dir).catch(() => []);
|
|
520
|
-
|
|
521
|
-
|
|
582
|
+
await this._remove('.', files.filter((file) => isSnapshotFile(file) && file !== kept));
|
|
583
|
+
}
|
|
584
|
+
async _sweepChunks(saved) {
|
|
585
|
+
const named = new Set(Object.values(saved?.artifacts ?? {}).map((stored) => chunksFile(stored.ids)));
|
|
586
|
+
const files = await fs.promises.readdir(this._file(CHUNKS_DIR)).catch(() => []);
|
|
587
|
+
await this._remove(CHUNKS_DIR, files.filter((file) => !named.has(file)));
|
|
588
|
+
return new Set(files.filter((file) => named.has(file)));
|
|
589
|
+
}
|
|
590
|
+
async _remove(dir, files) {
|
|
591
|
+
await Promise.all(files.map((file) => fs.promises.rm(path.join(this._dir, dir, file), { force: true })));
|
|
522
592
|
}
|
|
523
593
|
}
|
|
524
594
|
function noop() { }
|
|
@@ -4,11 +4,15 @@ import { PluginRegistry } from '../../lib/plugins/index.js';
|
|
|
4
4
|
import { SKILL_STATE } from '../../lib/tools/skills/skill-state-constants.js';
|
|
5
5
|
import { isObsidianVaultPath, isSandboxedWorkbenchInstall, OBSIDIAN_SKILL_NAME, OBSIDIAN_VAULT_MODE_NOTE, OBSIDIAN_VAULT_PATH_CREDENTIAL_KEY, obsidianCliState, obsidianInstallState } from './readiness.js';
|
|
6
6
|
import { capOutput, MAX_OUTPUT_CHARS } from '../../lib/tools/exec/runner.js';
|
|
7
|
-
import { runObsidianCli } from './cli.js';
|
|
8
7
|
import { normalizeObsidianCommand, parseObsidianCommand } from './command.js';
|
|
9
8
|
import { OBSIDIAN_DESKTOP_AGENT_REQUIRED, OBSIDIAN_NO_SHELL_FALLBACK, OBSIDIAN_VAULT_SETUP_REQUIRED } from './guidance.js';
|
|
10
|
-
import {
|
|
9
|
+
import { retryMemo } from '../../lib/helpers/retry-memo.js';
|
|
11
10
|
const DESKTOP_PLATFORMS = new Set(['darwin', 'linux', 'win32']);
|
|
11
|
+
const backends = retryMemo(() => Promise.all([import('./vault-fs.js'), import('./cli.js')]).catch((err) => {
|
|
12
|
+
throw new Error(`plugin 'obsidian' could not load its implementation: ${errorMessage(err)}`, {
|
|
13
|
+
cause: err
|
|
14
|
+
});
|
|
15
|
+
}));
|
|
12
16
|
function credentialRecord(value) {
|
|
13
17
|
if (typeof value === 'string') {
|
|
14
18
|
return value ? { token: value } : null;
|
|
@@ -27,7 +31,7 @@ function vaultFsResult(stdout, exitCode) {
|
|
|
27
31
|
? { stdout, stderr: '', exitCode: 0 }
|
|
28
32
|
: { stdout: '', stderr: `${stdout}\n\n${OBSIDIAN_NO_SHELL_FALLBACK}`, exitCode };
|
|
29
33
|
}
|
|
30
|
-
function runVaultFs(vaultPath, { action, args, maxOutputChars }) {
|
|
34
|
+
function runVaultFs(executeVaultFsAction, vaultPath, { action, args, maxOutputChars }) {
|
|
31
35
|
try {
|
|
32
36
|
return limitResult(vaultFsResult(executeVaultFsAction(vaultPath, action, args), 0), maxOutputChars);
|
|
33
37
|
}
|
|
@@ -124,11 +128,17 @@ export class ObsidianRoute {
|
|
|
124
128
|
}
|
|
125
129
|
const vaultPath = await resolveVaultPath(this._options.credentialStore, ctx);
|
|
126
130
|
if (vaultPath) {
|
|
127
|
-
|
|
131
|
+
const [{ executeVaultFsAction }] = await backends();
|
|
132
|
+
return runVaultFs(executeVaultFsAction, vaultPath, {
|
|
133
|
+
action: parsed.action,
|
|
134
|
+
args: parsed.args,
|
|
135
|
+
maxOutputChars
|
|
136
|
+
});
|
|
128
137
|
}
|
|
129
138
|
if (isSandboxedWorkbenchInstall(this._options.env ?? process.env)) {
|
|
130
139
|
return { stdout: '', stderr: OBSIDIAN_VAULT_SETUP_REQUIRED, exitCode: 1 };
|
|
131
140
|
}
|
|
141
|
+
const [, { runObsidianCli }] = await backends();
|
|
132
142
|
return runObsidianCli(normalizeObsidianCommand(command), await runtime(), {
|
|
133
143
|
timeoutMs,
|
|
134
144
|
maxOutputChars,
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type { HarnessPlugin, PluginSetup } from '../../lib/plugins/index.ts';
|
|
2
2
|
import { type PythonLanguageOptions } from './language.ts';
|
|
3
|
+
import type { PythonRunResult } from './pyodide.ts';
|
|
3
4
|
import { closePythonWorker } from './worker/active.ts';
|
|
4
5
|
import { preloadPythonAddons } from './worker/client.ts';
|
|
5
6
|
export type { PythonLanguageOptions };
|
|
6
|
-
export {
|
|
7
|
+
export type { LoadPyodideFn, PythonRunResult } from './pyodide.ts';
|
|
7
8
|
export { planVendoredInstall, vendoredManifest, wheelsDir } from './wheels.ts';
|
|
8
9
|
export { closePythonWorker };
|
|
10
|
+
export declare function runPython(...args: Parameters<typeof import('./pyodide.ts').runPython>): Promise<PythonRunResult>;
|
|
9
11
|
export declare class Python implements HarnessPlugin {
|
|
10
12
|
readonly name = "python";
|
|
11
13
|
readonly api = 1;
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { PluginRegistry } from '../../lib/plugins/index.js';
|
|
2
2
|
import { createPythonLanguage } from './language.js';
|
|
3
|
+
import { pyodideModule } from './python-adapter.js';
|
|
3
4
|
import { closePythonWorker } from './worker/active.js';
|
|
4
5
|
import { preloadPythonAddons } from './worker/client.js';
|
|
5
6
|
PluginRegistry.requirePeers('python', { pyodide: () => import.meta.resolve('pyodide') });
|
|
6
|
-
export { runPython } from './pyodide.js';
|
|
7
7
|
export { planVendoredInstall, vendoredManifest, wheelsDir } from './wheels.js';
|
|
8
8
|
export { closePythonWorker };
|
|
9
|
+
export async function runPython(...args) {
|
|
10
|
+
return (await pyodideModule()).runPython(...args);
|
|
11
|
+
}
|
|
9
12
|
export class Python {
|
|
10
13
|
name = 'python';
|
|
11
14
|
api = PluginRegistry.API_VERSION;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { ExecutionAdapter } from '../../lib/contract/exec.ts';
|
|
2
2
|
import { type ExecInput } from '../../lib/tools/attachments/staging.ts';
|
|
3
3
|
import { type ExecError } from '../../lib/tools/attachments/output-policy.ts';
|
|
4
|
-
import {
|
|
4
|
+
import type { LoadPyodideFn } from './pyodide.ts';
|
|
5
|
+
export declare const pyodideModule: import("../../lib/helpers/retry-memo.ts").RetryMemo<typeof import("./pyodide.ts")>;
|
|
5
6
|
export declare function pinned(spec: string): string;
|
|
6
7
|
export declare function pipMessage(targets: readonly string[] | null, { sandbox }?: {
|
|
7
8
|
sandbox?: boolean | undefined;
|
|
@@ -2,12 +2,18 @@ import b4a from 'b4a';
|
|
|
2
2
|
import { Policy } from '../../lib/policy/index.js';
|
|
3
3
|
import { attachOutputs, stageInputs } from '../../lib/tools/attachments/staging.js';
|
|
4
4
|
import { checkFileName, checkOutputName, MAX_INPUTS, MAX_OUTPUTS } from '../../lib/tools/attachments/output-policy.js';
|
|
5
|
-
import {
|
|
5
|
+
import { errorMessage } from '../../lib/guards.js';
|
|
6
|
+
import { retryMemo } from '../../lib/helpers/retry-memo.js';
|
|
6
7
|
import { isTranscoder, TRANSCODE_ERROR, VIDEO_TOOLS_ERROR, videoTool } from '../../lib/tools/exec/video-tools.js';
|
|
7
8
|
import { moduleDistribution } from './distributions.js';
|
|
8
9
|
import { namedHosts } from './named-hosts.js';
|
|
9
10
|
import { normalizeDistribution, planVendoredInstall, vendoredSpec } from './wheels.js';
|
|
10
11
|
import { isPythonLanguage, pipInstallTargets, unwrapPythonSource } from '../../lib/tools/exec/python-source.js';
|
|
12
|
+
export const pyodideModule = retryMemo(() => import('./pyodide.js').catch((err) => {
|
|
13
|
+
throw new Error(`plugin 'python' could not load its implementation: ${errorMessage(err)}`, {
|
|
14
|
+
cause: err
|
|
15
|
+
});
|
|
16
|
+
}));
|
|
11
17
|
const SHELL_WRAPPER = /^(python3?|py|pip3?)(\s*$|\s+(-[A-Za-z]|['"]|[\w./]))/;
|
|
12
18
|
const SANDBOX_NO_INSTALL = 'and sandbox mode installs only the packages bundled with this app, which do not include it. Use only what is already installed, or tell the user it is unavailable while sandbox mode is on.';
|
|
13
19
|
const specName = (spec) => normalizeDistribution(spec.split(/[=<>!~[]/)[0] ?? '');
|
|
@@ -462,6 +468,7 @@ export function createPythonAdapter(loadPyodide, network = false) {
|
|
|
462
468
|
if (refusal) {
|
|
463
469
|
return fail(refusal);
|
|
464
470
|
}
|
|
471
|
+
const { runPython } = await pyodideModule();
|
|
465
472
|
const result = await runPython(install ? 'pass' : source, {
|
|
466
473
|
timeoutMs: options.timeoutMs,
|
|
467
474
|
maxOutputChars: options.maxOutputChars,
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qvac/harness",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.14",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"bare": ">=1.34.0",
|
|
@@ -575,9 +575,9 @@
|
|
|
575
575
|
},
|
|
576
576
|
"dependencies": {
|
|
577
577
|
"@qvac/error": "^0.1.1",
|
|
578
|
-
"@qvac/inference": "^0.
|
|
578
|
+
"@qvac/inference": "^0.23.0",
|
|
579
579
|
"@qvac/logging": "0.1.1",
|
|
580
|
-
"@qvac/skills": "^0.1.
|
|
580
|
+
"@qvac/skills": "^0.1.19",
|
|
581
581
|
"@xmldom/xmldom": "^0.9.12",
|
|
582
582
|
"asenion": "^0.1.0",
|
|
583
583
|
"b4a": "^1.9.0",
|
|
@@ -628,16 +628,17 @@
|
|
|
628
628
|
},
|
|
629
629
|
"peerDependencies": {
|
|
630
630
|
"@jitl/quickjs-singlefile-mjs-release-sync": "0.32.0",
|
|
631
|
-
"@qvac/asr-ggml": "^0.
|
|
632
|
-
"@qvac/audiogen-ggml": "^0.
|
|
631
|
+
"@qvac/asr-ggml": "^0.11.1",
|
|
632
|
+
"@qvac/audiogen-ggml": "^0.9.0",
|
|
633
633
|
"@qvac/decoder-audio": "^0.8.1",
|
|
634
|
-
"@qvac/diffusion-cpp": "^0.
|
|
635
|
-
"@qvac/embed-llamacpp": "0.
|
|
634
|
+
"@qvac/diffusion-cpp": "^0.31.0",
|
|
635
|
+
"@qvac/embed-llamacpp": "^0.53.0",
|
|
636
636
|
"@qvac/langdetect-text": "^0.1.2",
|
|
637
|
-
"@qvac/llm-llamacpp": "^0.
|
|
638
|
-
"@qvac/sdk": "^0.
|
|
639
|
-
"@qvac/translation-nmtcpp": "^0.
|
|
640
|
-
"@qvac/tts-ggml": "^0.
|
|
637
|
+
"@qvac/llm-llamacpp": "^0.65.0",
|
|
638
|
+
"@qvac/sdk": "^0.23.0",
|
|
639
|
+
"@qvac/translation-nmtcpp": "^0.23.0",
|
|
640
|
+
"@qvac/tts-ggml": "^0.14.0",
|
|
641
|
+
"@qvac/turbovec-ggml": "^0.3.0",
|
|
641
642
|
"bare-ffmpeg": "^1.2.3",
|
|
642
643
|
"bare-image-resample": "^1.0.2",
|
|
643
644
|
"bare-media": "^2.10.0",
|
|
@@ -683,6 +684,9 @@
|
|
|
683
684
|
"@qvac/tts-ggml": {
|
|
684
685
|
"optional": true
|
|
685
686
|
},
|
|
687
|
+
"@qvac/turbovec-ggml": {
|
|
688
|
+
"optional": true
|
|
689
|
+
},
|
|
686
690
|
"bare-ffmpeg": {
|
|
687
691
|
"optional": true
|
|
688
692
|
},
|
|
@@ -716,16 +720,17 @@
|
|
|
716
720
|
},
|
|
717
721
|
"devDependencies": {
|
|
718
722
|
"@jitl/quickjs-singlefile-mjs-release-sync": "0.32.0",
|
|
719
|
-
"@qvac/asr-ggml": "^0.
|
|
720
|
-
"@qvac/audiogen-ggml": "^0.
|
|
723
|
+
"@qvac/asr-ggml": "^0.11.1",
|
|
724
|
+
"@qvac/audiogen-ggml": "^0.9.0",
|
|
721
725
|
"@qvac/decoder-audio": "^0.8.1",
|
|
722
|
-
"@qvac/diffusion-cpp": "^0.
|
|
723
|
-
"@qvac/embed-llamacpp": "0.
|
|
726
|
+
"@qvac/diffusion-cpp": "^0.31.0",
|
|
727
|
+
"@qvac/embed-llamacpp": "^0.53.0",
|
|
724
728
|
"@qvac/langdetect-text": "^0.1.2",
|
|
725
|
-
"@qvac/llm-llamacpp": "^0.
|
|
726
|
-
"@qvac/sdk": "^0.
|
|
727
|
-
"@qvac/translation-nmtcpp": "^0.
|
|
728
|
-
"@qvac/tts-ggml": "^0.
|
|
729
|
+
"@qvac/llm-llamacpp": "^0.65.0",
|
|
730
|
+
"@qvac/sdk": "^0.23.0",
|
|
731
|
+
"@qvac/translation-nmtcpp": "^0.23.0",
|
|
732
|
+
"@qvac/tts-ggml": "^0.14.0",
|
|
733
|
+
"@qvac/turbovec-ggml": "^0.3.0",
|
|
729
734
|
"bare-bundle": "^1.10.0",
|
|
730
735
|
"bare-ffmpeg": "^1.2.3",
|
|
731
736
|
"bare-image-resample": "^1.0.2",
|
|
@@ -14,6 +14,7 @@ const QVAC_ADDON_PACKAGES = [
|
|
|
14
14
|
'@qvac/asr-ggml',
|
|
15
15
|
'@qvac/audiogen-ggml',
|
|
16
16
|
'@qvac/translation-nmtcpp',
|
|
17
|
+
'@qvac/turbovec-ggml',
|
|
17
18
|
// fabric is the shared ggml module
|
|
18
19
|
'@qvac/fabric'
|
|
19
20
|
]
|
|
@@ -28,6 +29,7 @@ const NATIVE_ADDON_PACKAGES = [
|
|
|
28
29
|
'@qvac/llm-llamacpp',
|
|
29
30
|
'@qvac/translation-nmtcpp',
|
|
30
31
|
'@qvac/tts-ggml',
|
|
32
|
+
'@qvac/turbovec-ggml',
|
|
31
33
|
'bare-abort',
|
|
32
34
|
'bare-bmp',
|
|
33
35
|
'bare-broadcast-channel',
|
|
@@ -85,7 +87,8 @@ const NATIVE_ADDON_PACKAGES = [
|
|
|
85
87
|
// defer matches specifiers exactly, so list every subpath the SDK or a plugin imports, as written
|
|
86
88
|
const EXTRA_ADDON_SUBPATHS = {
|
|
87
89
|
'@qvac/audiogen-ggml': ['binding.js'],
|
|
88
|
-
'@qvac/diffusion-cpp': ['world', 'world.js']
|
|
90
|
+
'@qvac/diffusion-cpp': ['world', 'world.js'],
|
|
91
|
+
'@qvac/turbovec-ggml': ['binding.js']
|
|
89
92
|
}
|
|
90
93
|
|
|
91
94
|
function deferSpecifiers() {
|