@qvac/harness 1.0.0-rc.19 → 1.0.0-rc.20

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +106 -2
  2. package/README.md +7 -0
  3. package/dist-lib/lib/capabilities/agent-ports.js +4 -3
  4. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +1 -0
  5. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +3 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/rejecting.js +5 -4
  7. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +5 -1
  8. package/dist-lib/lib/capabilities/completion-engine/driver.js +9 -2
  9. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +3 -1
  10. package/dist-lib/lib/capabilities/sdk-tool.d.ts +2 -2
  11. package/dist-lib/lib/capabilities/sdk-tool.js +2 -2
  12. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  13. package/dist-lib/lib/capabilities/tool-turns.js +2 -0
  14. package/dist-lib/lib/contract/agent.d.ts +2 -0
  15. package/dist-lib/lib/contract/media.d.ts +7 -0
  16. package/dist-lib/lib/helpers/run-outcome.d.ts +2 -0
  17. package/dist-lib/lib/helpers/run-outcome.js +6 -2
  18. package/dist-lib/lib/machine/completion/types.d.ts +1 -0
  19. package/dist-lib/lib/machine/index.d.ts +2 -0
  20. package/dist-lib/lib/machine/index.js +2 -0
  21. package/dist-lib/lib/media-wire.js +16 -1
  22. package/dist-lib/lib/models/context-choice.js +8 -1
  23. package/dist-lib/lib/models/llm-presets.js +27 -1
  24. package/dist-lib/lib/models/model-catalog-constants.d.ts +2 -2
  25. package/dist-lib/lib/models/model-catalog-constants.js +3 -4
  26. package/dist-lib/lib/models/model-catalog.d.ts +4 -2
  27. package/dist-lib/lib/models/model-catalog.js +29 -11
  28. package/dist-lib/lib/models/tts-model-default.d.ts +2 -1
  29. package/dist-lib/lib/models/tts-model-default.js +8 -6
  30. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  31. package/dist-lib/lib/plugins/registry.js +7 -4
  32. package/dist-lib/lib/prompt.d.ts +5 -4
  33. package/dist-lib/lib/prompt.js +68 -22
  34. package/dist-lib/lib/residency/completion-runtime.js +6 -1
  35. package/dist-lib/lib/residency/index.js +1 -0
  36. package/dist-lib/lib/tools/files/edit-file.d.ts +4 -1
  37. package/dist-lib/lib/tools/files/edit-file.js +220 -28
  38. package/dist-lib/lib/tools/files/index.js +3 -1
  39. package/dist-lib/lib/tools/fs/edit-match.d.ts +22 -0
  40. package/dist-lib/lib/tools/fs/edit-match.js +337 -45
  41. package/dist-lib/plugins/coding-guards/index.d.ts +25 -0
  42. package/dist-lib/plugins/coding-guards/index.js +126 -0
  43. package/dist-lib/plugins/image/edit-image.d.ts +3 -22
  44. package/dist-lib/plugins/image/edit-image.js +13 -32
  45. package/dist-lib/plugins/image/fit.d.ts +31 -0
  46. package/dist-lib/plugins/image/fit.js +28 -0
  47. package/dist-lib/plugins/image/generate-image.d.ts +9 -2
  48. package/dist-lib/plugins/image/generate-image.js +23 -6
  49. package/dist-lib/plugins/image/index.js +4 -1
  50. package/dist-lib/plugins/ocr/index.d.ts +1 -1
  51. package/dist-lib/plugins/ocr/index.js +3 -1
  52. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  53. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  54. package/dist-lib/plugins/speech/speech-engine.d.ts +1 -1
  55. package/dist-lib/plugins/speech/speech-engine.js +10 -5
  56. package/dist-lib/plugins/speech/speech-text.d.ts +1 -0
  57. package/dist-lib/plugins/speech/speech-text.js +9 -4
  58. package/dist-lib/plugins/speech/voice.js +7 -2
  59. package/package.json +5 -1
@@ -28,41 +28,74 @@ function lineStarts(lines) {
28
28
  }
29
29
  return starts;
30
30
  }
31
- function trimmedLineSpans(content, old) {
32
- const lines = content.split('\n');
33
- const wanted = old.split('\n').map((line) => line.trimEnd());
34
- const ownsNewline = wanted.length > 1 && wanted[wanted.length - 1] === '';
35
- if (ownsNewline) {
36
- wanted.pop();
37
- }
38
- const starts = lineStarts(lines);
39
- const spans = [];
40
- for (let i = 0; i + wanted.length <= lines.length; i++) {
41
- const block = lines.slice(i, i + wanted.length);
42
- if (block.every((line, k) => line.trimEnd() === wanted[k])) {
43
- const last = i + wanted.length - 1;
44
- const end = starts[last] + lines[last].length;
45
- spans.push({ from: starts[i], to: ownsNewline && last < lines.length - 1 ? end + 1 : end });
31
+ class MatchView {
32
+ text;
33
+ #plain;
34
+ #lines;
35
+ #trimmed;
36
+ #starts;
37
+ #rows;
38
+ constructor(text) {
39
+ this.text = text;
40
+ }
41
+ rows() {
42
+ if (!this.#rows) {
43
+ const lines = fileLines(this.text);
44
+ this.#rows = { lines, starts: lineStarts(lines) };
46
45
  }
46
+ return this.#rows;
47
47
  }
48
- return spans;
49
- }
50
- function spansFor(content, old) {
51
- const exact = occurrences(content, old);
52
- if (exact.length) {
53
- return exact;
48
+ spans(old) {
49
+ if (!old) {
50
+ return [];
51
+ }
52
+ const exact = occurrences(this.text, old);
53
+ if (exact.length) {
54
+ return exact;
55
+ }
56
+ const wanted = plain(old);
57
+ const typographic = occurrences(this.#normalized(), wanted);
58
+ if (typographic.length) {
59
+ return typographic;
60
+ }
61
+ return this.#lineSpans(wanted);
62
+ }
63
+ #normalized() {
64
+ return (this.#plain ??= plain(this.text));
54
65
  }
55
- const typographic = occurrences(plain(content), plain(old));
56
- if (typographic.length) {
57
- return typographic;
66
+ #lineSpans(old) {
67
+ const lines = (this.#lines ??= this.#normalized().split('\n'));
68
+ const trimmed = (this.#trimmed ??= lines.map((line) => line.trimEnd()));
69
+ const starts = (this.#starts ??= lineStarts(lines));
70
+ const wanted = old.split('\n').map((line) => line.trimEnd());
71
+ const ownsNewline = wanted.length > 1 && wanted[wanted.length - 1] === '';
72
+ if (ownsNewline) {
73
+ wanted.pop();
74
+ }
75
+ const spans = [];
76
+ for (let i = 0; i + wanted.length <= lines.length; i++) {
77
+ let matched = true;
78
+ for (let k = 0; k < wanted.length; k++) {
79
+ if (trimmed[i + k] !== wanted[k]) {
80
+ matched = false;
81
+ break;
82
+ }
83
+ }
84
+ if (matched) {
85
+ const last = i + wanted.length - 1;
86
+ const end = starts[last] + lines[last].length;
87
+ spans.push({ from: starts[i], to: ownsNewline && last < lines.length - 1 ? end + 1 : end });
88
+ }
89
+ }
90
+ return spans;
58
91
  }
59
- return trimmedLineSpans(plain(content), plain(old));
60
92
  }
61
93
  function ambiguity(text, spans) {
62
- const lines = spans.map((span) => text.slice(0, span.from).split('\n').length).join(', ');
94
+ const lineAt = lineCounter(text);
95
+ const lines = spans.map((span) => lineAt(span.from)).join(', ');
63
96
  return `old text matches ${spans.length} places (lines ${lines}). Include a neighbouring line so it matches once, or set replaceAll to change every one.`;
64
97
  }
65
- const NUMBERED = /^\s*\d+\| ?/;
98
+ const NUMBERED = /^\s*(\d+)\| ?/;
66
99
  function unnumbered(text) {
67
100
  const lines = text.split('\n');
68
101
  const filled = lines.filter((line) => line.trim());
@@ -70,6 +103,67 @@ function unnumbered(text) {
70
103
  ? lines.map((line) => line.replace(NUMBERED, '')).join('\n')
71
104
  : text;
72
105
  }
106
+ function rows(text) {
107
+ return text
108
+ .split('\n')
109
+ .filter((line) => line.trim())
110
+ .map((line) => Number(line.match(NUMBERED)?.[1]));
111
+ }
112
+ function matched(view, request) {
113
+ const asked = request.old.replace(/\r\n/g, '\n');
114
+ const replacement = request.replacement.replace(/\r\n/g, '\n');
115
+ const spans = view.spans(asked);
116
+ if (spans.length) {
117
+ return { old: asked, replacement, spans };
118
+ }
119
+ const old = unnumbered(asked);
120
+ if (old === asked) {
121
+ return { old: asked, replacement, spans };
122
+ }
123
+ const from = rows(asked);
124
+ const copied = rows(replacement).every((row) => row >= from[0] && row <= from[from.length - 1]);
125
+ return {
126
+ old,
127
+ replacement: copied ? unnumbered(replacement) : replacement,
128
+ spans: view.spans(old)
129
+ };
130
+ }
131
+ function viewOf(content) {
132
+ const bom = content.startsWith('\uFEFF') ? 1 : 0;
133
+ const parts = content.slice(bom).split('\r\n');
134
+ const breaks = [];
135
+ let offset = 0;
136
+ for (const part of parts.slice(0, -1)) {
137
+ offset += part.length;
138
+ breaks.push(offset);
139
+ offset++;
140
+ }
141
+ return { text: parts.join('\n'), bom, crlf: breaks.length > 0, breaks };
142
+ }
143
+ function original(view, offset) {
144
+ let lo = 0;
145
+ let hi = view.breaks.length;
146
+ while (lo < hi) {
147
+ const mid = (lo + hi) >> 1;
148
+ if (view.breaks[mid] < offset) {
149
+ lo = mid + 1;
150
+ }
151
+ else {
152
+ hi = mid;
153
+ }
154
+ }
155
+ return view.bom + offset + lo;
156
+ }
157
+ function written(content, view, changes) {
158
+ let out = '';
159
+ let cursor = 0;
160
+ for (const change of changes) {
161
+ const text = view.crlf ? change.text.replace(/\n/g, '\r\n') : change.text;
162
+ out += content.slice(cursor, original(view, change.from)) + text;
163
+ cursor = original(view, change.to);
164
+ }
165
+ return out + content.slice(cursor);
166
+ }
73
167
  function closest(text, old) {
74
168
  const lines = text.split('\n');
75
169
  const file = lines.map((line) => pairsOf(line.trim()));
@@ -118,8 +212,9 @@ const CLOSE_ENOUGH = 0.6;
118
212
  const CONTEXT_LINES = 2;
119
213
  const PROBE_LINES = 8;
120
214
  const DISTINCT_CHARS = 24;
121
- function notFound(text, old, replacement) {
122
- if (replacement.trim().length >= DISTINCT_CHARS && spansFor(text, replacement).length) {
215
+ function notFound(matcher, old, replacement) {
216
+ const { text } = matcher;
217
+ if (replacement.trim().length >= DISTINCT_CHARS && matcher.spans(replacement).length) {
123
218
  return 'old text not found, and the new text is already in the file: this edit looks done. Read the file to check before changing it again.';
124
219
  }
125
220
  const near = closest(text, old);
@@ -128,26 +223,223 @@ function notFound(text, old, replacement) {
128
223
  : 'old text not found. Read the file with read_file and copy the exact lines you want to change, including their indentation.';
129
224
  }
130
225
  export function editMatch(content, request) {
131
- const crlf = content.includes('\r\n');
132
- const text = crlf ? content.replace(/\r\n/g, '\n') : content;
133
- const asked = request.old.replace(/\r\n/g, '\n');
134
- let old = asked;
135
- let replacement = request.replacement.replace(/\r\n/g, '\n');
136
- let spans = spansFor(text, old);
137
- if (!spans.length && unnumbered(asked) !== asked) {
138
- old = unnumbered(asked);
139
- replacement = unnumbered(replacement);
140
- spans = spansFor(text, old);
141
- }
226
+ const view = viewOf(content);
227
+ const { text } = view;
228
+ const matcher = new MatchView(text);
229
+ const { old, replacement, spans } = matched(matcher, request);
142
230
  if (!spans.length) {
143
- return { content, count: 0, error: notFound(text, old, replacement) };
231
+ return { content, count: 0, error: notFound(matcher, old, replacement) };
144
232
  }
145
233
  if (spans.length > 1 && !request.replaceAll) {
146
234
  return { content, count: 0, error: ambiguity(text, spans) };
147
235
  }
148
- let next = text;
149
- for (const span of [...spans].sort((a, b) => b.from - a.from)) {
150
- next = next.slice(0, span.from) + replacement + next.slice(span.to);
236
+ const changes = spans.map((span) => ({ ...span, text: replacement }));
237
+ return { content: written(content, view, changes), count: spans.length, error: null };
238
+ }
239
+ const AROUND_LINES = 3;
240
+ function fileLines(text) {
241
+ const lines = text.split('\n');
242
+ if (lines[lines.length - 1] === '') {
243
+ lines.pop();
244
+ }
245
+ return lines;
246
+ }
247
+ function block(text) {
248
+ const lf = text.replace(/\r\n/g, '\n');
249
+ return lf.endsWith('\n') ? lf : `${lf}\n`;
250
+ }
251
+ function appended(text, insert) {
252
+ return text === '' || text.endsWith('\n') ? block(insert) : `\n${block(insert).slice(0, -1)}`;
253
+ }
254
+ function edgeSplice(text, edit) {
255
+ if (edit.at === 'start') {
256
+ return { from: 0, to: 0, text: block(edit.text) };
257
+ }
258
+ return { from: text.length, to: text.length, text: appended(text, edit.text) };
259
+ }
260
+ function sameLine(actual, expect, line) {
261
+ const wanted = expect.replace(/\r\n/g, '\n');
262
+ const prefix = new RegExp(`^${line}\\| ?`);
263
+ const candidates = prefix.test(wanted) ? [wanted, wanted.replace(prefix, '')] : [wanted];
264
+ return candidates.some((each) => plain(each).trimEnd() === plain(actual).trimEnd());
265
+ }
266
+ function around(lines, line) {
267
+ if (!lines.length) {
268
+ return '(the file is empty)';
269
+ }
270
+ const first = Math.max(1, line - AROUND_LINES);
271
+ const last = Math.min(lines.length, line + AROUND_LINES);
272
+ const rows = [];
273
+ for (let n = first; n <= last; n++) {
274
+ rows.push(`${n}| ${lines[n - 1]}`);
275
+ }
276
+ return rows.join('\n');
277
+ }
278
+ function lineSplice(matcher, edit) {
279
+ const { text } = matcher;
280
+ const { lines, starts } = matcher.rows();
281
+ const { line } = edit;
282
+ if (text === '' && line === 1 && sameLine('', edit.expect, 1)) {
283
+ return { from: 0, to: 0, text: block(edit.text) };
284
+ }
285
+ if (line < 1 || line > lines.length) {
286
+ return (`there is no line ${line}: the file has ${lines.length} lines. ` +
287
+ `Use after "end" to add to the end, or read the file with read_file for its line numbers.`);
288
+ }
289
+ if (!sameLine(lines[line - 1], edit.expect, line)) {
290
+ return (`line ${line} is not ${JSON.stringify(edit.expect)}. The file reads:\n${around(lines, line)}\n` +
291
+ `Use the line number and the exact text of the line you mean, or read the file again with read_file.`);
292
+ }
293
+ if (line < lines.length) {
294
+ return { from: starts[line], to: starts[line], text: block(edit.text) };
295
+ }
296
+ return { from: text.length, to: text.length, text: appended(text, edit.text) };
297
+ }
298
+ function replaceSplices(matcher, edit) {
299
+ const { text } = matcher;
300
+ const { old, replacement, spans } = matched(matcher, edit);
301
+ if (!spans.length) {
302
+ return notFound(matcher, old, replacement);
303
+ }
304
+ if (spans.length > 1 && !edit.replaceAll) {
305
+ return ambiguity(text, spans);
306
+ }
307
+ return spans.map((span) => ({ ...span, text: replacement }));
308
+ }
309
+ function splicesOf(matcher, edit) {
310
+ const { text } = matcher;
311
+ if (edit.kind === 'replace') {
312
+ return replaceSplices(matcher, edit);
313
+ }
314
+ const splice = edit.kind === 'edge' ? edgeSplice(text, edit) : lineSplice(matcher, edit);
315
+ return typeof splice === 'string' ? splice : [splice];
316
+ }
317
+ function lineCounter(text) {
318
+ let line = 1;
319
+ let next = text.indexOf('\n');
320
+ let last = 0;
321
+ return (offset) => {
322
+ if (offset < last) {
323
+ line = 1;
324
+ next = text.indexOf('\n');
325
+ }
326
+ last = offset;
327
+ while (next !== -1 && next < offset) {
328
+ line++;
329
+ next = text.indexOf('\n', next + 1);
330
+ }
331
+ return line;
332
+ };
333
+ }
334
+ function lineOf(text, offset) {
335
+ return lineCounter(text)(offset);
336
+ }
337
+ function overlap(text, splices) {
338
+ let reach = null;
339
+ for (const splice of splices) {
340
+ if (reach && reach.to > splice.from) {
341
+ return (`edits ${reach.edit + 1} and ${splice.edit + 1} change the same text ` +
342
+ `(line ${lineOf(text, splice.from)}). Merge them into one edit.`);
343
+ }
344
+ if (!reach || splice.to > reach.to) {
345
+ reach = splice;
346
+ }
347
+ }
348
+ return null;
349
+ }
350
+ function spliced(text, splices) {
351
+ let out = '';
352
+ let cursor = 0;
353
+ for (const splice of splices) {
354
+ out += text.slice(cursor, splice.from) + splice.text;
355
+ cursor = splice.to;
356
+ }
357
+ return out + text.slice(cursor);
358
+ }
359
+ export function applyEdits(content, edits) {
360
+ const view = viewOf(content);
361
+ const { text } = view;
362
+ const matcher = new MatchView(text);
363
+ const splices = [];
364
+ for (const [index, edit] of edits.entries()) {
365
+ const found = splicesOf(matcher, edit);
366
+ if (typeof found === 'string') {
367
+ const error = edits.length > 1 ? `edit ${index + 1}: ${found}` : found;
368
+ return { content, changes: 0, diff: '', error };
369
+ }
370
+ splices.push(...found.map((splice) => ({ ...splice, edit: index })));
371
+ }
372
+ splices.sort((a, b) => a.from - b.from || a.to - b.to || a.edit - b.edit);
373
+ const crossed = overlap(text, splices);
374
+ if (crossed) {
375
+ return { content, changes: 0, diff: '', error: crossed };
376
+ }
377
+ return {
378
+ content: written(content, view, splices),
379
+ changes: splices.length,
380
+ diff: unifiedHunks(text, splices),
381
+ error: null
382
+ };
383
+ }
384
+ const NO_NEWLINE = '\n\';
385
+ function diffLines(text) {
386
+ const lines = fileLines(text);
387
+ if (text && !text.endsWith('\n')) {
388
+ lines[lines.length - 1] += NO_NEWLINE;
389
+ }
390
+ return lines;
391
+ }
392
+ function hunksOf(text, splices) {
393
+ const hunks = [];
394
+ for (const splice of splices) {
395
+ const from = splice.from && text.lastIndexOf('\n', splice.from - 1) + 1;
396
+ const end = text.indexOf('\n', Math.max(splice.to, from));
397
+ const to = end === -1 ? text.length : end + 1;
398
+ const last = hunks[hunks.length - 1];
399
+ if (last && from < last.to) {
400
+ last.to = Math.max(last.to, to);
401
+ last.splices.push(splice);
402
+ }
403
+ else {
404
+ hunks.push({ from, to, splices: [splice] });
405
+ }
406
+ }
407
+ return hunks;
408
+ }
409
+ function sharedEdges(before, after) {
410
+ let head = 0;
411
+ while (head < before.length && head < after.length && before[head] === after[head]) {
412
+ head++;
413
+ }
414
+ let tail = 0;
415
+ while (tail < before.length - head &&
416
+ tail < after.length - head &&
417
+ before[before.length - 1 - tail] === after[after.length - 1 - tail]) {
418
+ tail++;
419
+ }
420
+ return [head, tail];
421
+ }
422
+ function range(start, count) {
423
+ return `${count ? start : start - 1},${count}`;
424
+ }
425
+ function unifiedHunks(text, splices) {
426
+ const out = [];
427
+ let shift = 0;
428
+ const lineAt = lineCounter(text);
429
+ for (const hunk of hunksOf(text, splices)) {
430
+ const shifted = hunk.splices.map((splice) => ({
431
+ ...splice,
432
+ from: splice.from - hunk.from,
433
+ to: splice.to - hunk.from
434
+ }));
435
+ const before = diffLines(text.slice(hunk.from, hunk.to));
436
+ const after = diffLines(spliced(text.slice(hunk.from, hunk.to), shifted));
437
+ const [head, tail] = sharedEdges(before, after);
438
+ const removed = before.slice(head, before.length - tail);
439
+ const added = after.slice(head, after.length - tail);
440
+ const start = lineAt(hunk.from) + head;
441
+ out.push(`@@ -${range(start, removed.length)} +${range(start + shift, added.length)} @@`, ...removed.map((line) => `-${line}`), ...added.map((line) => `+${line}`));
442
+ shift += added.length - removed.length;
151
443
  }
152
- return { content: crlf ? next.replace(/\n/g, '\r\n') : next, count: spans.length, error: null };
444
+ return out.join('\n');
153
445
  }
@@ -0,0 +1,25 @@
1
+ import type { HarnessPlugin, PluginSetup } from '../../lib/plugins/index.ts';
2
+ export interface CodingGuardsOptions {
3
+ sameWrite?: boolean | string;
4
+ promptNote?: boolean | string;
5
+ noRunner?: boolean | string;
6
+ }
7
+ export declare const SAME_WRITE: string;
8
+ export declare const PROMPT_NOTE: string;
9
+ export declare const NO_RUNNER: string;
10
+ export declare class CodingGuards implements HarnessPlugin {
11
+ readonly name = "coding-guards";
12
+ readonly api = 1;
13
+ private readonly _sameWrite;
14
+ private readonly _promptNote;
15
+ private readonly _noRunner;
16
+ private readonly _written;
17
+ constructor(options?: CodingGuardsOptions);
18
+ setup(): PluginSetup;
19
+ private readonly _prompt;
20
+ private _run;
21
+ private _pre;
22
+ private readonly _post;
23
+ private readonly _failure;
24
+ private readonly _end;
25
+ }
@@ -0,0 +1,126 @@
1
+ import path from 'path';
2
+ import { isRecord } from '../../lib/guards.js';
3
+ import { PluginRegistry } from '../../lib/plugins/index.js';
4
+ export const SAME_WRITE = 'This run already wrote exactly this content to {path}, so this call would repeat that write. ' +
5
+ 'Work out what is still wrong from the task or the errors, then change that.';
6
+ export const PROMPT_NOTE = 'If this message reports failing tests or errors, first write one line per failure: the ' +
7
+ 'test, what it expected, what the code did, and why. Then fix the causes, not each symptom.';
8
+ export const NO_RUNNER = 'Nothing can be built, compiled, run or tested in this session. Check your work by reasoning ' +
9
+ 'from the code and the task.';
10
+ const CHANGES = new Set([
11
+ 'edit_file',
12
+ 'insert_text',
13
+ 'edit_many',
14
+ 'move_file',
15
+ 'trash_file',
16
+ 'copy_file',
17
+ 'shell',
18
+ 'exec'
19
+ ]);
20
+ export class CodingGuards {
21
+ name = 'coding-guards';
22
+ api = PluginRegistry.API_VERSION;
23
+ _sameWrite;
24
+ _promptNote;
25
+ _noRunner;
26
+ _written = new Map();
27
+ constructor(options = {}) {
28
+ this._sameWrite = wording(options.sameWrite, SAME_WRITE);
29
+ this._promptNote = wording(options.promptNote, PROMPT_NOTE);
30
+ this._noRunner = wording(options.noRunner, NO_RUNNER);
31
+ }
32
+ setup() {
33
+ const hooks = [];
34
+ if (this._sameWrite) {
35
+ const refusal = this._sameWrite;
36
+ hooks.push({
37
+ name: 'coding-guards',
38
+ phase: 'preToolCall',
39
+ matcher: 'write_file',
40
+ run: (ctx) => this._pre(ctx, refusal)
41
+ }, { name: 'coding-guards', phase: 'postToolCall', run: this._post }, { name: 'coding-guards', phase: 'toolFailure', run: this._failure }, { name: 'coding-guards', phase: 'runEnd', run: this._end });
42
+ }
43
+ if (this._promptNote || this._noRunner) {
44
+ hooks.push({ name: 'coding-guards', phase: 'promptSubmit', run: this._prompt });
45
+ }
46
+ return { hooks };
47
+ }
48
+ _prompt = (ctx) => {
49
+ if (ctx.phase !== 'promptSubmit' || ctx.mode !== 'prompt')
50
+ return;
51
+ const notes = [this._noRunner, this._promptNote].filter((note) => note !== null);
52
+ return { context: notes.join('\n\n') };
53
+ };
54
+ _run(runId) {
55
+ let written = this._written.get(runId);
56
+ if (!written) {
57
+ written = new Map();
58
+ this._written.set(runId, written);
59
+ }
60
+ return written;
61
+ }
62
+ _pre(ctx, refusal) {
63
+ if (ctx.phase !== 'preToolCall')
64
+ return;
65
+ const { path, content } = writeArgs(ctx);
66
+ if (path !== null && this._run(ctx.runId).get(clean(path)) === content) {
67
+ return refuse(refusal, path);
68
+ }
69
+ }
70
+ _post = (ctx) => {
71
+ if (ctx.phase !== 'postToolCall')
72
+ return;
73
+ const written = this._run(ctx.runId);
74
+ if (!succeeded(ctx)) {
75
+ if (ctx.toolName === 'write_file' || CHANGES.has(ctx.toolName)) {
76
+ written.clear();
77
+ }
78
+ return;
79
+ }
80
+ if (ctx.toolName === 'write_file') {
81
+ const { path, content } = writeArgs(ctx);
82
+ if (path !== null) {
83
+ written.set(clean(path), content);
84
+ }
85
+ }
86
+ else if (CHANGES.has(ctx.toolName)) {
87
+ written.clear();
88
+ }
89
+ };
90
+ _failure = (ctx) => {
91
+ if (ctx.phase !== 'toolFailure' || !ctx.executed)
92
+ return;
93
+ if (ctx.toolName === 'write_file' || CHANGES.has(ctx.toolName)) {
94
+ this._run(ctx.runId).clear();
95
+ }
96
+ };
97
+ _end = (ctx) => {
98
+ this._written.delete(ctx.runId);
99
+ };
100
+ }
101
+ function clean(requested) {
102
+ if (requested.startsWith('hyper://')) {
103
+ return `hyper:${requested}`;
104
+ }
105
+ const normalized = path.normalize(requested);
106
+ return `${path.isAbsolute(requested) ? 'absolute' : 'relative'}:${normalized}`;
107
+ }
108
+ function wording(option, text) {
109
+ if (!option)
110
+ return null;
111
+ return option === true ? text : option;
112
+ }
113
+ function refuse(text, path) {
114
+ return { kind: 'hook-rejection', error: text.replaceAll('{path}', path), guidance: true };
115
+ }
116
+ function writeArgs(ctx) {
117
+ const { path, content } = ctx.args;
118
+ return typeof path === 'string' && typeof content === 'string'
119
+ ? { path, content }
120
+ : { path: null, content: '' };
121
+ }
122
+ function succeeded(ctx) {
123
+ return (ctx.executed &&
124
+ ctx.outcome?.kind === 'success' &&
125
+ !(isRecord(ctx.result) && 'error' in ctx.result));
126
+ }
@@ -1,26 +1,7 @@
1
1
  import type { ToolDefinition } from '../../lib/contract/index.ts';
2
2
  import type { ImageClamps } from '../../lib/models/model-catalog.ts';
3
3
  import { type DiffusionRuntime } from './generate-image.ts';
4
- interface Rgba {
5
- width: number;
6
- height: number;
7
- data: Uint8Array;
8
- frames?: Rgba[];
9
- }
10
- interface Media {
11
- image: {
12
- decode(input: Uint8Array, opts?: {
13
- maxFrames?: number;
14
- }): Promise<Rgba>;
15
- encode(rgba: Rgba, opts: {
16
- mimetype: string;
17
- }): Promise<Uint8Array>;
18
- };
19
- }
20
- export interface EditImageDeps {
21
- loadMedia?: () => Promise<Media | null>;
22
- resample?: (rgba: Rgba, width: number, height: number) => Rgba | Promise<Rgba>;
23
- }
4
+ import { type FitDeps } from './fit.ts';
5
+ export type EditImageDeps = FitDeps;
24
6
  export declare function loadMediaCodecs(): Promise<void>;
25
- export declare function createEditImageTool(runtime: DiffusionRuntime, { loadMedia, resample }?: EditImageDeps, clamps?: ImageClamps): ToolDefinition;
26
- export {};
7
+ export declare function createEditImageTool(runtime: DiffusionRuntime, deps?: EditImageDeps, clamps?: ImageClamps): ToolDefinition;