@qvac/harness 1.0.0-rc.12 → 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/CHANGELOG.md +29 -0
- package/README.md +3 -1
- package/dist-lib/index.js +0 -1
- package/dist-lib/lib/agent/follow.js +9 -2
- package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +13 -3
- package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +1 -1
- package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +21 -12
- package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
- package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
- 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 +11 -0
- package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +16 -4
- package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +8 -2
- package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
- package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
- package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
- package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
- package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
- package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +2 -0
- package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
- package/dist-lib/lib/capabilities/completion-engine/ports.js +1 -1
- package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -0
- package/dist-lib/lib/capabilities/completion-engine/round.js +40 -20
- package/dist-lib/lib/capabilities/completion-engine/session.d.ts +3 -3
- package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
- package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
- 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/tool-turns.d.ts +1 -0
- package/dist-lib/lib/capabilities/tool-turns.js +1 -0
- package/dist-lib/lib/capabilities/usage-breakdown.d.ts +1 -0
- package/dist-lib/lib/capabilities/usage-breakdown.js +4 -1
- package/dist-lib/lib/connect.js +4 -2
- package/dist-lib/lib/contract/completion.d.ts +2 -1
- package/dist-lib/lib/contract/knowledge.d.ts +10 -0
- package/dist-lib/lib/fold/index.d.ts +3 -2
- package/dist-lib/lib/fold/index.js +7 -6
- package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
- package/dist-lib/lib/helpers/goal-check.js +89 -7
- package/dist-lib/lib/helpers/html-helpers.js +9 -6
- package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
- package/dist-lib/lib/helpers/input-budget.js +9 -0
- package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
- package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
- package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
- package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
- package/dist-lib/lib/machine/completion/rules.js +14 -5
- package/dist-lib/lib/machine/completion/types.d.ts +3 -0
- package/dist-lib/lib/plugins/registry.d.ts +1 -0
- package/dist-lib/lib/plugins/registry.js +49 -10
- package/dist-lib/lib/residency/index.js +2 -0
- package/dist-lib/lib/serve.js +56 -15
- package/dist-lib/lib/tools/files/glob.js +2 -2
- package/dist-lib/lib/tools/files/read-file.js +134 -15
- package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
- package/dist-lib/lib/tools/fs/walk.js +2 -1
- package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
- package/dist-lib/lib/tools/http-request.js +28 -11
- package/dist-lib/lib/tools/office.d.ts +1 -1
- package/dist-lib/lib/tools/office.js +34 -12
- package/dist-lib/lib/wire.js +23 -3
- package/dist-lib/plugins/knowledge/index.d.ts +3 -0
- package/dist-lib/plugins/knowledge/index.js +5 -0
- package/dist-lib/plugins/knowledge/manifest.d.ts +53 -0
- package/dist-lib/plugins/knowledge/manifest.js +86 -0
- package/dist-lib/plugins/knowledge/search-tool.js +8 -8
- package/dist-lib/plugins/knowledge/store.d.ts +45 -8
- package/dist-lib/plugins/knowledge/store.js +428 -166
- package/dist-lib/plugins/mcp/call.js +10 -3
- package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
- package/dist-lib/plugins/mcp/protocol.js +11 -10
- package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
- package/dist-lib/plugins/mcp/tool-listing.js +97 -0
- package/dist-lib/plugins/music/generate-music.js +2 -2
- 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/language.js +2 -2
- 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/dist-lib/schema/harness.js +4 -2
- package/dist-lib/spec/hrpc/messages.js +19 -4
- package/dist-lib/spec/hyperschema/index.js +19 -4
- package/dist-lib/spec/hyperschema/schema.json +12 -1
- package/dist-lib/spec/hyperschema/types.d.ts +2 -0
- package/package.json +28 -19
- package/scripts/addon-externals.cjs +4 -1
|
@@ -9,6 +9,8 @@ import { createCompletionActors, createInvokeTracker } from './actors.js';
|
|
|
9
9
|
import { replayFinalRound, replaySuccessOutput } from './replay-output.js';
|
|
10
10
|
import { AbortedError, rehydrateError, tagError } from '../../helpers/engine-error.js';
|
|
11
11
|
import { turnText } from './turns.js';
|
|
12
|
+
import { EventMailbox } from './event-mailbox.js';
|
|
13
|
+
import { acceptsInput, inputBytes } from '../../helpers/input-budget.js';
|
|
12
14
|
import { CompletionMachine } from '../../machine/index.js';
|
|
13
15
|
function readRestoredSnapshot(value) {
|
|
14
16
|
if (!isRecord(value) || Array.isArray(value))
|
|
@@ -113,7 +115,7 @@ export async function* runEngine(run, options = {}) {
|
|
|
113
115
|
yield started(run);
|
|
114
116
|
const invokes = createInvokeTracker();
|
|
115
117
|
const boot = RunLog.boundaryBoot(journal);
|
|
116
|
-
const mailbox =
|
|
118
|
+
const mailbox = new EventMailbox();
|
|
117
119
|
const { ports, context } = await run.start({
|
|
118
120
|
operations: createOperationPort(journal),
|
|
119
121
|
invokes,
|
|
@@ -149,7 +151,6 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
149
151
|
const pausedMs = run.resume && journal.snapshotSavedAt !== undefined
|
|
150
152
|
? Math.max(0, now() - journal.snapshotSavedAt)
|
|
151
153
|
: 0;
|
|
152
|
-
const { queue } = mailbox;
|
|
153
154
|
let detached = false;
|
|
154
155
|
const detach = () => {
|
|
155
156
|
detached = true;
|
|
@@ -164,14 +165,17 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
164
165
|
wakeVersion++;
|
|
165
166
|
wake();
|
|
166
167
|
};
|
|
168
|
+
let pause = () => { };
|
|
169
|
+
let inputLimitNotified = false;
|
|
167
170
|
mailbox.notify = notify;
|
|
171
|
+
mailbox.onOverflow = () => queueMicrotask(pause);
|
|
168
172
|
const { actor, persistence } = await RunLog.createPersistedActor(journal, machine, notify, now);
|
|
169
173
|
actor.on('*', (event) => {
|
|
170
|
-
|
|
174
|
+
mailbox.push(event);
|
|
171
175
|
notify();
|
|
172
176
|
});
|
|
173
177
|
actor.subscribe({ next: notify, error: notify });
|
|
174
|
-
|
|
178
|
+
pause = () => {
|
|
175
179
|
if (actor.getSnapshot().status === 'active') {
|
|
176
180
|
actor.send({ type: 'PAUSE' });
|
|
177
181
|
}
|
|
@@ -189,11 +193,30 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
189
193
|
return pumping;
|
|
190
194
|
}
|
|
191
195
|
if ('reason' in item) {
|
|
192
|
-
|
|
196
|
+
mailbox.push({ type: 'input-rejected', runId, reason: item.reason });
|
|
193
197
|
notify();
|
|
194
198
|
}
|
|
195
199
|
else {
|
|
196
|
-
|
|
200
|
+
const pending = [
|
|
201
|
+
...actor.getSnapshot().context.steering,
|
|
202
|
+
...actor.getSnapshot().context.followUps
|
|
203
|
+
];
|
|
204
|
+
const bytes = pending.reduce((total, queued) => total + inputBytes(queued), 0);
|
|
205
|
+
if (!acceptsInput(pending.length, bytes, item)) {
|
|
206
|
+
if (!inputLimitNotified) {
|
|
207
|
+
inputLimitNotified = true;
|
|
208
|
+
mailbox.push({
|
|
209
|
+
type: 'input-rejected',
|
|
210
|
+
runId,
|
|
211
|
+
reason: 'Pending input limit exceeded; one or more inputs were rejected'
|
|
212
|
+
});
|
|
213
|
+
notify();
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
inputLimitNotified = false;
|
|
218
|
+
actor.send(inputMessage(item));
|
|
219
|
+
}
|
|
197
220
|
}
|
|
198
221
|
return pumping;
|
|
199
222
|
}).catch(noop);
|
|
@@ -225,7 +248,11 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
225
248
|
if (journal.hasPendingFlush()) {
|
|
226
249
|
await persistence.flush();
|
|
227
250
|
}
|
|
228
|
-
yield* drainQueue(
|
|
251
|
+
yield* drainQueue(mailbox);
|
|
252
|
+
if (mailbox.failure) {
|
|
253
|
+
const snapshot = actor.getSnapshot();
|
|
254
|
+
return { status: 'error', snapshot, error: mailbox.failure };
|
|
255
|
+
}
|
|
229
256
|
if (isActiveIdle(actor.getSnapshot()) && !signal?.aborted) {
|
|
230
257
|
actor.send({ type: 'START' });
|
|
231
258
|
}
|
|
@@ -241,7 +268,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
241
268
|
? await drainSettling({ actor, persistence, durable, detach })
|
|
242
269
|
: undefined;
|
|
243
270
|
if (settlingResult) {
|
|
244
|
-
yield* drainQueue(
|
|
271
|
+
yield* drainQueue(mailbox);
|
|
245
272
|
return settlingResult;
|
|
246
273
|
}
|
|
247
274
|
if (isSettling) {
|
|
@@ -255,12 +282,12 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
255
282
|
durable,
|
|
256
283
|
detach,
|
|
257
284
|
journal,
|
|
258
|
-
queue,
|
|
285
|
+
queue: mailbox,
|
|
259
286
|
runId
|
|
260
287
|
});
|
|
261
288
|
}
|
|
262
289
|
const observedWakeVersion = wakeVersion;
|
|
263
|
-
if (
|
|
290
|
+
if (mailbox.size) {
|
|
264
291
|
continue;
|
|
265
292
|
}
|
|
266
293
|
await new Promise((resolve) => {
|
|
@@ -271,7 +298,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
|
|
|
271
298
|
});
|
|
272
299
|
}
|
|
273
300
|
await persistence.flush();
|
|
274
|
-
yield* drainQueue(
|
|
301
|
+
yield* drainQueue(mailbox);
|
|
275
302
|
return { status: 'done', snapshot: actor.getSnapshot() };
|
|
276
303
|
}
|
|
277
304
|
finally {
|
|
@@ -392,24 +419,13 @@ function settling(snapshot) {
|
|
|
392
419
|
return value === 'pausing';
|
|
393
420
|
}
|
|
394
421
|
function* drainQueue(queue) {
|
|
395
|
-
while (queue.
|
|
422
|
+
while (queue.size) {
|
|
396
423
|
const event = queue.shift();
|
|
397
424
|
if (event) {
|
|
398
425
|
yield event;
|
|
399
426
|
}
|
|
400
427
|
}
|
|
401
428
|
}
|
|
402
|
-
function createEventMailbox() {
|
|
403
|
-
const mailbox = {
|
|
404
|
-
queue: [],
|
|
405
|
-
notify() { },
|
|
406
|
-
emit(event) {
|
|
407
|
-
mailbox.queue.push(event);
|
|
408
|
-
mailbox.notify();
|
|
409
|
-
}
|
|
410
|
-
};
|
|
411
|
-
return mailbox;
|
|
412
|
-
}
|
|
413
429
|
function createOperationPort(journal) {
|
|
414
430
|
return Object.freeze({
|
|
415
431
|
flush: () => journal.flush(),
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { EngineEvent } from '../../machine/index.ts';
|
|
2
|
+
export declare const EVENT_MAILBOX_MAX_EVENTS = 512;
|
|
3
|
+
export declare const EVENT_MAILBOX_MAX_BYTES: number;
|
|
4
|
+
export declare const EVENT_MAILBOX_TEXT_CHUNK = 8192;
|
|
5
|
+
export declare class EventMailbox {
|
|
6
|
+
notify(): void;
|
|
7
|
+
onOverflow(): void;
|
|
8
|
+
private readonly _events;
|
|
9
|
+
private _head;
|
|
10
|
+
private _bytes;
|
|
11
|
+
private _failure;
|
|
12
|
+
get size(): number;
|
|
13
|
+
get failure(): Error | null;
|
|
14
|
+
get bytes(): number;
|
|
15
|
+
push(event: EngineEvent): boolean;
|
|
16
|
+
private pushText;
|
|
17
|
+
private pushEvent;
|
|
18
|
+
emit(event: EngineEvent): void;
|
|
19
|
+
shift(): EngineEvent | undefined;
|
|
20
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import b4a from 'b4a';
|
|
2
|
+
export const EVENT_MAILBOX_MAX_EVENTS = 512;
|
|
3
|
+
export const EVENT_MAILBOX_MAX_BYTES = 1024 * 1024;
|
|
4
|
+
export const EVENT_MAILBOX_TEXT_CHUNK = 8192;
|
|
5
|
+
export class EventMailbox {
|
|
6
|
+
notify() { }
|
|
7
|
+
onOverflow() { }
|
|
8
|
+
_events = [];
|
|
9
|
+
_head = 0;
|
|
10
|
+
_bytes = 0;
|
|
11
|
+
_failure = null;
|
|
12
|
+
get size() {
|
|
13
|
+
return this._events.length - this._head;
|
|
14
|
+
}
|
|
15
|
+
get failure() {
|
|
16
|
+
return this._failure;
|
|
17
|
+
}
|
|
18
|
+
get bytes() {
|
|
19
|
+
return this._bytes;
|
|
20
|
+
}
|
|
21
|
+
push(event) {
|
|
22
|
+
if (this._failure) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
if (isLongText(event)) {
|
|
26
|
+
return this.pushText(event);
|
|
27
|
+
}
|
|
28
|
+
return this.pushEvent(event);
|
|
29
|
+
}
|
|
30
|
+
pushText(event) {
|
|
31
|
+
let offset = 0;
|
|
32
|
+
while (offset < event.text.length) {
|
|
33
|
+
let end = Math.min(offset + EVENT_MAILBOX_TEXT_CHUNK, event.text.length);
|
|
34
|
+
if (end < event.text.length && isHighSurrogate(event.text.charCodeAt(end - 1))) {
|
|
35
|
+
end--;
|
|
36
|
+
}
|
|
37
|
+
if (!this.pushEvent({ ...event, text: event.text.slice(offset, end) })) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
offset = end;
|
|
41
|
+
}
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
pushEvent(event) {
|
|
45
|
+
if (this._failure) {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
const tail = this.size ? this._events[this._events.length - 1] : undefined;
|
|
49
|
+
if (tail && canCoalesce(tail, event)) {
|
|
50
|
+
const joined = `${tail.text ?? ''}${event.text ?? ''}`;
|
|
51
|
+
if (joined.length <= EVENT_MAILBOX_TEXT_CHUNK) {
|
|
52
|
+
const nextBytes = this._bytes - eventBytes(tail) + eventBytes({ ...tail, text: joined });
|
|
53
|
+
if (nextBytes <= EVENT_MAILBOX_MAX_BYTES) {
|
|
54
|
+
this._events[this._events.length - 1] = { ...tail, text: joined };
|
|
55
|
+
this._bytes = nextBytes;
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const bytes = eventBytes(event);
|
|
61
|
+
if (this.size >= EVENT_MAILBOX_MAX_EVENTS || this._bytes + bytes > EVENT_MAILBOX_MAX_BYTES) {
|
|
62
|
+
this._failure = new Error('Completion output buffer limit exceeded');
|
|
63
|
+
this.onOverflow();
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
this._events.push(event);
|
|
67
|
+
this._bytes += bytes;
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
emit(event) {
|
|
71
|
+
this.push(event);
|
|
72
|
+
this.notify();
|
|
73
|
+
}
|
|
74
|
+
shift() {
|
|
75
|
+
if (this._head === this._events.length) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
const event = this._events[this._head++];
|
|
79
|
+
this._bytes -= eventBytes(event);
|
|
80
|
+
if (this._head === this._events.length) {
|
|
81
|
+
this._events.length = 0;
|
|
82
|
+
this._head = 0;
|
|
83
|
+
return event;
|
|
84
|
+
}
|
|
85
|
+
if (this._head >= 128 && this._head * 2 >= this._events.length) {
|
|
86
|
+
this._events.splice(0, this._head);
|
|
87
|
+
this._head = 0;
|
|
88
|
+
}
|
|
89
|
+
return event;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function isLongText(event) {
|
|
93
|
+
return ((event.type === 'content' || event.type === 'thinking') &&
|
|
94
|
+
typeof event.text === 'string' &&
|
|
95
|
+
event.text.length > EVENT_MAILBOX_TEXT_CHUNK);
|
|
96
|
+
}
|
|
97
|
+
function isHighSurrogate(code) {
|
|
98
|
+
return code >= 0xd800 && code <= 0xdbff;
|
|
99
|
+
}
|
|
100
|
+
function canCoalesce(left, right) {
|
|
101
|
+
return ((left.type === 'content' || left.type === 'thinking') &&
|
|
102
|
+
left.type === right.type &&
|
|
103
|
+
left.runId === right.runId &&
|
|
104
|
+
left.round === right.round &&
|
|
105
|
+
typeof left.text === 'string' &&
|
|
106
|
+
typeof right.text === 'string');
|
|
107
|
+
}
|
|
108
|
+
function eventBytes(event) {
|
|
109
|
+
return b4a.byteLength(JSON.stringify(event), 'utf8');
|
|
110
|
+
}
|
|
@@ -19,6 +19,8 @@ export interface ModelRoundRequest {
|
|
|
19
19
|
promptPrefix: string;
|
|
20
20
|
continuationNudge: string;
|
|
21
21
|
deliveredNudge: string;
|
|
22
|
+
goalNudge?: string | undefined;
|
|
23
|
+
wrapUpNudge?: string | undefined;
|
|
22
24
|
unforced?: {
|
|
23
25
|
generationParams?: Partial<LlmGenerationParams> | undefined;
|
|
24
26
|
} | undefined;
|
|
@@ -67,6 +67,8 @@ function servedArgs(request, signal, acquireRound) {
|
|
|
67
67
|
failureResults: {},
|
|
68
68
|
continuationNudge: request.continuationNudge,
|
|
69
69
|
deliveredNudge: request.deliveredNudge,
|
|
70
|
+
goalNudge: request.goalNudge,
|
|
71
|
+
wrapUpNudge: request.wrapUpNudge,
|
|
70
72
|
tools: request.tools,
|
|
71
73
|
generationParams: request.generationParams,
|
|
72
74
|
responseFormat: request.responseFormat,
|
|
@@ -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) => {
|
|
@@ -15,6 +15,7 @@ export interface RecoveredRound {
|
|
|
15
15
|
final: CompletionFinal;
|
|
16
16
|
history: CompletionHistoryEntry[];
|
|
17
17
|
cacheable: boolean;
|
|
18
|
+
keyed: boolean;
|
|
18
19
|
unproven: string | null;
|
|
19
20
|
replay: string | null;
|
|
20
21
|
reasoningDeltas?: number | undefined;
|
|
@@ -30,6 +31,8 @@ export interface RoundArgs {
|
|
|
30
31
|
failureResults: Readonly<Record<string, FailureResultValue>>;
|
|
31
32
|
continuationNudge: string;
|
|
32
33
|
deliveredNudge: string;
|
|
34
|
+
goalNudge?: string | undefined;
|
|
35
|
+
wrapUpNudge?: string | undefined;
|
|
33
36
|
tools?: SdkTool[] | undefined;
|
|
34
37
|
generationParams?: Partial<LlmGenerationParams> | undefined;
|
|
35
38
|
responseFormat?: ResponseFormat | undefined;
|
|
@@ -17,7 +17,9 @@ 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';
|
|
22
|
+
import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
|
|
21
23
|
import { Fold } from '../../fold/index.js';
|
|
22
24
|
import { CompletionMachine } from '../../machine/index.js';
|
|
23
25
|
import { modelTurns } from './turns.js';
|
|
@@ -75,7 +77,9 @@ async function* runRoundTokens({ result, state, cancelThisRound, unsettled, sign
|
|
|
75
77
|
const events = splitThinking(bufferBurst(countGenerated(counted, state), BURST_WINDOW_MS), {
|
|
76
78
|
startInThink
|
|
77
79
|
});
|
|
78
|
-
const thinkingFilter = createMarkupStreamFilter(
|
|
80
|
+
const thinkingFilter = createMarkupStreamFilter({
|
|
81
|
+
onToolCall: watchMarkupCalls(state, knownTools, cancelThisRound)
|
|
82
|
+
});
|
|
79
83
|
const contentFilter = createMarkupStreamFilter({
|
|
80
84
|
onToolCall: watchMarkupCalls(state, knownTools, cancelThisRound)
|
|
81
85
|
});
|
|
@@ -312,7 +316,7 @@ function releaseLease(lease) {
|
|
|
312
316
|
export async function recordWholeRound(args) {
|
|
313
317
|
const history = materializeCompletionHistory(args.history, args.failureResults);
|
|
314
318
|
const origins = historyOrigins(args.history, history);
|
|
315
|
-
const params = inferenceParams({ args, modelId: args.modelId, history
|
|
319
|
+
const params = inferenceParams({ args, modelId: args.modelId, history });
|
|
316
320
|
await args.recordRequest?.({ round: args.round, attempt: 0, droppedTurns: 0, params }, failureTurns(args, origins, history));
|
|
317
321
|
if (args.signal?.aborted) {
|
|
318
322
|
throw new AbortedError();
|
|
@@ -342,10 +346,12 @@ async function* runRecoveredRoundWith(send) {
|
|
|
342
346
|
}
|
|
343
347
|
async function* runLadder({ send, history, origins, fold }) {
|
|
344
348
|
let lastOverflow = null;
|
|
345
|
-
|
|
349
|
+
const candidates = contextCandidates(history, ...harnessTurns(send.args, history));
|
|
350
|
+
for (const candidate of candidates) {
|
|
346
351
|
const outcome = yield* runCandidateAttempts({ ...send, candidate, history, origins });
|
|
347
352
|
if ('round' in outcome) {
|
|
348
|
-
|
|
353
|
+
const cacheable = !send.attempts.uncached;
|
|
354
|
+
return { round: recoveredRound({ candidate, attempt: outcome.round, origins, cacheable }) };
|
|
349
355
|
}
|
|
350
356
|
lastOverflow = outcome.overflow;
|
|
351
357
|
send.attempts.overflows++;
|
|
@@ -354,6 +360,9 @@ async function* runLadder({ send, history, origins, fold }) {
|
|
|
354
360
|
if (folded) {
|
|
355
361
|
return { folded };
|
|
356
362
|
}
|
|
363
|
+
if (candidates.length > 1) {
|
|
364
|
+
await dropShrunkKey(send);
|
|
365
|
+
}
|
|
357
366
|
}
|
|
358
367
|
}
|
|
359
368
|
if (!lastOverflow) {
|
|
@@ -375,15 +384,21 @@ async function* foldHistory(send, history, tries) {
|
|
|
375
384
|
tries.rounds = true;
|
|
376
385
|
return foldRounds(send, history);
|
|
377
386
|
}
|
|
378
|
-
function
|
|
387
|
+
function harnessTurns(args, history) {
|
|
379
388
|
const mentions = history.flatMap((message) => message.role === 'user' && isSkillMentionNudge(message.content) ? [message.content] : []);
|
|
380
|
-
|
|
389
|
+
const wrapUp = args.wrapUpNudge === undefined ? [] : [args.wrapUpNudge];
|
|
390
|
+
return [args.continuationNudge, args.deliveredNudge, ...wrapUp, ...goalTurns(args), ...mentions];
|
|
391
|
+
}
|
|
392
|
+
function goalTurns(args) {
|
|
393
|
+
const goal = args.goalNudge === undefined ? [] : [args.goalNudge];
|
|
394
|
+
return [...goal, GOAL_CHECKS_ASK, GOAL_PROOF_ASK];
|
|
381
395
|
}
|
|
382
396
|
async function foldRounds(send, history) {
|
|
383
397
|
const { sdk, args, ctxSize } = send;
|
|
384
398
|
const spec = args.fold;
|
|
385
|
-
const nudges =
|
|
386
|
-
|
|
399
|
+
const nudges = harnessTurns(args, history);
|
|
400
|
+
const goals = goalTurns(args);
|
|
401
|
+
if (!spec || !Fold.roundBoundary(history, { nudges, goals, keeps: keepsLoad })?.foldedRounds) {
|
|
387
402
|
return null;
|
|
388
403
|
}
|
|
389
404
|
const instructions = await spec.instructions?.(history);
|
|
@@ -391,6 +406,7 @@ async function foldRounds(send, history) {
|
|
|
391
406
|
ctxSize,
|
|
392
407
|
instructions,
|
|
393
408
|
nudges,
|
|
409
|
+
goals,
|
|
394
410
|
keeps: keepsLoad
|
|
395
411
|
});
|
|
396
412
|
if (args.signal?.aborted) {
|
|
@@ -453,6 +469,11 @@ async function* foldChat(send, history) {
|
|
|
453
469
|
};
|
|
454
470
|
return folded;
|
|
455
471
|
}
|
|
472
|
+
async function dropShrunkKey({ sdk, args, attempts }) {
|
|
473
|
+
if (args.cacheKey && !attempts.uncached) {
|
|
474
|
+
await dropFoldedKey(sdk, args.cacheKey);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
456
477
|
async function dropFoldedKey(sdk, cacheKey) {
|
|
457
478
|
Fold.forget(cacheKey);
|
|
458
479
|
try {
|
|
@@ -543,10 +564,9 @@ async function* runCandidateAttempts(input) {
|
|
|
543
564
|
modelId,
|
|
544
565
|
candidate,
|
|
545
566
|
progress,
|
|
546
|
-
baseHistory: history,
|
|
547
567
|
origins
|
|
548
568
|
});
|
|
549
|
-
return { round
|
|
569
|
+
return { round };
|
|
550
570
|
}
|
|
551
571
|
catch (err) {
|
|
552
572
|
if (err instanceof AbortedError || args.signal?.aborted) {
|
|
@@ -628,14 +648,15 @@ async function flushCandidate(args, progress) {
|
|
|
628
648
|
}
|
|
629
649
|
await raceTimeout(progress.cancel.flush(), { ms: TRUNCATED_FINAL_MS, fallback: undefined });
|
|
630
650
|
}
|
|
631
|
-
function recoveredRound({ candidate, attempt, origins }) {
|
|
651
|
+
function recoveredRound({ candidate, attempt, origins, cacheable }) {
|
|
632
652
|
const replay = unprovenReplay(attempt.state, attempt.final);
|
|
633
653
|
logCandidateFinal(attempt, replay);
|
|
634
654
|
return {
|
|
635
655
|
contentText: attempt.contentText,
|
|
636
656
|
final: attempt.final,
|
|
637
657
|
history: restoreHistory(candidate.history, origins),
|
|
638
|
-
cacheable
|
|
658
|
+
cacheable,
|
|
659
|
+
keyed: attempt.keyed,
|
|
639
660
|
unproven: attempt.state.unproven,
|
|
640
661
|
replay,
|
|
641
662
|
reasoningDeltas: attempt.state.reasoningDeltas || undefined,
|
|
@@ -655,16 +676,15 @@ function historyOrigins(entries, messages) {
|
|
|
655
676
|
});
|
|
656
677
|
return origins;
|
|
657
678
|
}
|
|
658
|
-
async function* runCandidate({ sdk, args, modelId, candidate, progress,
|
|
659
|
-
const
|
|
660
|
-
const params = inferenceParams({ args, modelId, history: candidate.history, cacheable });
|
|
679
|
+
async function* runCandidate({ sdk, args, modelId, candidate, progress, origins }) {
|
|
680
|
+
const params = inferenceParams({ args, modelId, history: candidate.history });
|
|
661
681
|
if (args.capture) {
|
|
662
682
|
yield inferenceCall({
|
|
663
683
|
args,
|
|
664
684
|
droppedTurns: candidate.droppedTurns,
|
|
665
685
|
modelId,
|
|
666
686
|
params,
|
|
667
|
-
cacheKey:
|
|
687
|
+
cacheKey: args.cacheKey
|
|
668
688
|
});
|
|
669
689
|
}
|
|
670
690
|
await args.recordRequest?.({
|
|
@@ -704,9 +724,9 @@ async function* runCandidate({ sdk, args, modelId, candidate, progress, baseHist
|
|
|
704
724
|
if (args.capture) {
|
|
705
725
|
yield inferenceSent({ args, candidate, final: detachedFinal });
|
|
706
726
|
}
|
|
707
|
-
return { contentText, final: detachedFinal, state,
|
|
727
|
+
return { contentText, final: detachedFinal, state, keyed: args.cacheKey !== undefined };
|
|
708
728
|
}
|
|
709
|
-
function inferenceParams({ args, modelId, history
|
|
729
|
+
function inferenceParams({ args, modelId, history }) {
|
|
710
730
|
return completionParams({
|
|
711
731
|
modelId,
|
|
712
732
|
history: detachJson(history),
|
|
@@ -714,7 +734,7 @@ function inferenceParams({ args, modelId, history, cacheable }) {
|
|
|
714
734
|
generationParams: generationParams(args),
|
|
715
735
|
responseFormat: args.responseFormat ? detachJson(args.responseFormat) : undefined,
|
|
716
736
|
toolDialect: args.toolDialect,
|
|
717
|
-
kvCache:
|
|
737
|
+
kvCache: args.cacheKey
|
|
718
738
|
});
|
|
719
739
|
}
|
|
720
740
|
function generationParams(args) {
|
|
@@ -737,7 +757,7 @@ export function inferenceCall({ args, droppedTurns, modelId, params, cacheKey })
|
|
|
737
757
|
responseFormat: params.responseFormat,
|
|
738
758
|
toolDialect: params.toolDialect,
|
|
739
759
|
cacheKey,
|
|
740
|
-
promptPrefix:
|
|
760
|
+
promptPrefix: requestPromptPrefix(params.history, params.tools)
|
|
741
761
|
}
|
|
742
762
|
};
|
|
743
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,3 +1,4 @@
|
|
|
1
|
+
import type { KnowledgeHit, KnowledgeSource } from '../../contract/knowledge.ts';
|
|
1
2
|
import type { CompletionHistoryEntry, Message, ToolDefinition, TrustedSource, TurnContext } from '../../contract/index.ts';
|
|
2
3
|
export declare function trustedSourcesFrom(history: readonly Message[]): TrustedSource[];
|
|
3
4
|
export declare function sanitizeTurn(turn: Message, answered?: boolean): Message;
|
|
@@ -26,6 +27,8 @@ interface AssistantToolCall {
|
|
|
26
27
|
export declare function assistantToolTurn(contentText: string, calls: ReadonlyArray<AssistantToolCall>): string;
|
|
27
28
|
export declare function withLastUserNote(messages: readonly CompletionHistoryEntry[], note: string): CompletionHistoryEntry[];
|
|
28
29
|
export declare function turnText(text: string, { time, excerpts, notes }: TurnContext): string;
|
|
30
|
+
export declare function knowledgeExcerpt({ text, metadata }: KnowledgeHit): string;
|
|
31
|
+
export declare function knowledgeSources(hits: readonly KnowledgeHit[]): KnowledgeSource[];
|
|
29
32
|
export declare function withTurnContext(messages: readonly Message[], context: TurnContext): Message[];
|
|
30
33
|
export declare function carriesRunOnlyText(history: readonly CompletionHistoryEntry[]): boolean;
|
|
31
34
|
export declare function annotateCompletionHistoryLastUserTime(history: readonly CompletionHistoryEntry[], now?: Date): CompletionHistoryEntry[];
|
|
@@ -186,6 +186,22 @@ export function turnText(text, { time, excerpts, notes }) {
|
|
|
186
186
|
const body = notes === undefined ? `${found}${text}` : `${found}${text}${NOTES_HEAD}${notes}`;
|
|
187
187
|
return time === undefined ? body : `${time}\n\n${body}`;
|
|
188
188
|
}
|
|
189
|
+
export function knowledgeExcerpt({ text, metadata }) {
|
|
190
|
+
const title = metadata?.title;
|
|
191
|
+
if (typeof title !== 'string' || !title) {
|
|
192
|
+
return text;
|
|
193
|
+
}
|
|
194
|
+
const page = typeof metadata?.page === 'number' ? `, page ${metadata.page}` : '';
|
|
195
|
+
return `${title}${page}:\n${text}`;
|
|
196
|
+
}
|
|
197
|
+
export function knowledgeSources(hits) {
|
|
198
|
+
return hits.map(({ artifactId, chunkId, score, metadata }) => ({
|
|
199
|
+
artifactId,
|
|
200
|
+
chunkId,
|
|
201
|
+
score,
|
|
202
|
+
metadata
|
|
203
|
+
}));
|
|
204
|
+
}
|
|
189
205
|
export function withTurnContext(messages, context) {
|
|
190
206
|
const at = messages.findLastIndex((turn) => turn.role === 'user');
|
|
191
207
|
const user = messages[at];
|
|
@@ -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)));
|
|
@@ -7,6 +7,7 @@ export declare const MAX_TOOL_ROUNDS = 10;
|
|
|
7
7
|
export declare const GOAL_ROUNDS = 40;
|
|
8
8
|
export declare const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
|
|
9
9
|
export declare 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.]";
|
|
10
|
+
export declare const WRAP_UP_NUDGE = "[Tool results above. No tool can be called for this reply. Answer the user's request now, in plain text.]";
|
|
10
11
|
export declare function skillMentionNudge(handle: string): string;
|
|
11
12
|
export declare function isSkillMentionNudge(content: string): boolean;
|
|
12
13
|
export { TOOL_FAILED_NOTE };
|
|
@@ -13,6 +13,7 @@ export const MAX_TOOL_ROUNDS = 10;
|
|
|
13
13
|
export const GOAL_ROUNDS = 40;
|
|
14
14
|
export const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
|
|
15
15
|
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.]';
|
|
16
|
+
export const WRAP_UP_NUDGE = "[Tool results above. No tool can be called for this reply. Answer the user's request now, in plain text.]";
|
|
16
17
|
const MENTION_NUDGE_PREFIX = '[Tool results above. The user picked @';
|
|
17
18
|
export function skillMentionNudge(handle) {
|
|
18
19
|
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.]`;
|