@qvac/harness 1.0.0-rc.6 → 1.0.0-rc.7

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 (85) hide show
  1. package/CHANGELOG.md +157 -10
  2. package/README.md +19 -7
  3. package/dist-lib/index.d.ts +2 -2
  4. package/dist-lib/index.js +1 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +2 -0
  6. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +31 -3
  7. package/dist-lib/lib/capabilities/completion-engine/driver.js +3 -0
  8. package/dist-lib/lib/capabilities/completion-engine/index.d.ts +1 -0
  9. package/dist-lib/lib/capabilities/completion-engine/index.js +1 -0
  10. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +1 -0
  11. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -2
  12. package/dist-lib/lib/capabilities/completion-engine/tool-sets.d.ts +24 -0
  13. package/dist-lib/lib/capabilities/completion-engine/tool-sets.js +15 -0
  14. package/dist-lib/lib/capabilities/detect-language.d.ts +2 -1
  15. package/dist-lib/lib/capabilities/detect-language.js +14 -2
  16. package/dist-lib/lib/connect.d.ts +2 -0
  17. package/dist-lib/lib/connect.js +73 -7
  18. package/dist-lib/lib/contract-types.d.ts +4 -0
  19. package/dist-lib/lib/helpers/require-peers.d.ts +3 -0
  20. package/dist-lib/lib/helpers/require-peers.js +23 -0
  21. package/dist-lib/lib/models/llm-presets.d.ts +1 -0
  22. package/dist-lib/lib/models/model-catalog.js +1 -1
  23. package/dist-lib/lib/models/opencl-cache.js +2 -2
  24. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  25. package/dist-lib/lib/plugins/registry.js +4 -0
  26. package/dist-lib/lib/round-host.d.ts +12 -0
  27. package/dist-lib/lib/round-host.js +57 -0
  28. package/dist-lib/lib/round-port.d.ts +24 -0
  29. package/dist-lib/lib/round-port.js +81 -0
  30. package/dist-lib/lib/sdk-loader.d.ts +1 -1
  31. package/dist-lib/lib/sdk-loader.js +30 -6
  32. package/dist-lib/lib/sdk-storage.d.ts +1 -0
  33. package/dist-lib/lib/sdk-storage.js +18 -2
  34. package/dist-lib/lib/serve.js +61 -1
  35. package/dist-lib/lib/sidecar/index.d.ts +10 -0
  36. package/dist-lib/lib/sidecar/index.js +35 -3
  37. package/dist-lib/lib/sidecar/user-plugins.d.ts +1 -0
  38. package/dist-lib/lib/sidecar/user-plugins.js +1 -1
  39. package/dist-lib/lib/tools/files/grep.js +113 -15
  40. package/dist-lib/lib/tools/fs/edit-match.js +75 -7
  41. package/dist-lib/lib/tools/fs/search.d.ts +1 -1
  42. package/dist-lib/lib/tools/fs/search.js +2 -1
  43. package/dist-lib/lib/tools/index.d.ts +2 -1
  44. package/dist-lib/lib/tools/index.js +2 -2
  45. package/dist-lib/lib/tools/skills/skill-state-constants.d.ts +1 -0
  46. package/dist-lib/lib/tools/skills/skill-state-constants.js +4 -0
  47. package/dist-lib/lib/wire.d.ts +13 -0
  48. package/dist-lib/lib/wire.js +44 -1
  49. package/dist-lib/plugins/coding/read-only.d.ts +1 -0
  50. package/dist-lib/plugins/coding/read-only.js +264 -0
  51. package/dist-lib/plugins/coding/session.d.ts +3 -1
  52. package/dist-lib/plugins/coding/session.js +19 -2
  53. package/dist-lib/plugins/egress-proxy/index.d.ts +2 -2
  54. package/dist-lib/plugins/egress-proxy/index.js +5 -3
  55. package/dist-lib/plugins/image/index.js +7 -2
  56. package/dist-lib/plugins/language-hint/index.js +4 -1
  57. package/dist-lib/plugins/music/index.js +6 -2
  58. package/dist-lib/plugins/python/index.js +1 -0
  59. package/dist-lib/plugins/python/loader.d.ts +1 -0
  60. package/dist-lib/plugins/python/loader.js +8 -0
  61. package/dist-lib/plugins/quickjs/index.js +4 -0
  62. package/dist-lib/plugins/quickjs/runtime.js +8 -3
  63. package/dist-lib/plugins/run-report/index.js +6 -2
  64. package/dist-lib/plugins/run-report/layout.js +1 -1
  65. package/dist-lib/plugins/sandbox-vm/index.js +3 -0
  66. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  67. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  68. package/dist-lib/plugins/speech/audio-resample.js +2 -1
  69. package/dist-lib/plugins/speech/index.d.ts +1 -0
  70. package/dist-lib/plugins/speech/index.js +8 -1
  71. package/dist-lib/plugins/speech/speech-runtime.js +3 -3
  72. package/dist-lib/plugins/translation/index.d.ts +1 -1
  73. package/dist-lib/plugins/translation/index.js +7 -3
  74. package/dist-lib/plugins/translation/translate.d.ts +2 -2
  75. package/dist-lib/plugins/translation/translate.js +7 -8
  76. package/dist-lib/plugins/walkie-talkie/index.d.ts +2 -2
  77. package/dist-lib/plugins/walkie-talkie/index.js +13 -5
  78. package/dist-lib/plugins/walkie-talkie/wire.d.ts +5 -0
  79. package/dist-lib/plugins/walkie-talkie/wire.js +6 -5
  80. package/dist-lib/schema/harness.js +13 -4
  81. package/dist-lib/spec/hrpc/messages.js +205 -151
  82. package/dist-lib/spec/hyperschema/index.js +205 -151
  83. package/dist-lib/spec/hyperschema/schema.json +125 -89
  84. package/dist-lib/spec/hyperschema/types.d.ts +4 -4
  85. package/package.json +149 -24
@@ -15,12 +15,13 @@ import { RunLog } from './run-log/index.js';
15
15
  import { errorMessage, isRecord } from './guards.js';
16
16
  import { HarnessLog } from './log.js';
17
17
  import { pushQueue } from './queue.js';
18
+ import { RoundPort } from './round-port.js';
18
19
  import { TextCoalescer } from './helpers/text-coalescer.js';
19
20
  import { prepareOpenclCache } from './models/opencl-cache.js';
20
21
  import { stageFile, sweepStaging } from './staging.js';
21
22
  import { sweepSpill } from './spill.js';
22
23
  import { readSetup, toWireSetup } from './tools/skills/manifest-parse.js';
23
- import { fromKnowledgeUpsertWire, packVectors, toDownloadWire, toKnowledgeUpsertResultWire, toWire } from './wire.js';
24
+ import { fromKnowledgeUpsertWire, roundFailureWire, roundRequestFrom, packVectors, toDownloadWire, toKnowledgeUpsertResultWire, toWire } from './wire.js';
24
25
  const MODEL_STATUSES = new Set([
25
26
  'loading',
26
27
  'downloading',
@@ -179,6 +180,12 @@ function startPayloadFrom(value) {
179
180
  if (value.replaysContext === true) {
180
181
  payload.replaysContext = true;
181
182
  }
183
+ if (value.modelRound === true) {
184
+ payload.modelRound = true;
185
+ }
186
+ if (value.roundCut === true) {
187
+ payload.roundCut = true;
188
+ }
182
189
  if (value.runLog === null) {
183
190
  payload.runLog = null;
184
191
  }
@@ -645,6 +652,7 @@ function completion(harness) {
645
652
  const pendingRunLog = new Map();
646
653
  const input = pushQueue();
647
654
  const controller = new AbortController();
655
+ const rounds = new RoundPort((event) => events.push(event));
648
656
  let calls = 0;
649
657
  let started = false;
650
658
  let clientGone = false;
@@ -679,6 +687,7 @@ function completion(harness) {
679
687
  reject(new HarnessError('CLIENT_GONE'));
680
688
  }
681
689
  pendingRunLog.clear();
690
+ rounds.close();
682
691
  input.end();
683
692
  events.end();
684
693
  };
@@ -686,6 +695,17 @@ function completion(harness) {
686
695
  duplex.on('end', gone);
687
696
  duplex.readStream?.on('close', gone);
688
697
  duplex.on('data', (frame) => {
698
+ if (rounds.frame(frame)) {
699
+ return;
700
+ }
701
+ if (frame.type === 'model-round-ask' && !started) {
702
+ started = true;
703
+ void serveRound(harness, frame.payload, {
704
+ signal: controller.signal,
705
+ events
706
+ });
707
+ return;
708
+ }
689
709
  if (frame.type === 'decision') {
690
710
  if (typeof frame.callId !== 'string') {
691
711
  return;
@@ -870,6 +890,8 @@ function completion(harness) {
870
890
  maxToolRounds: startPayload.maxToolRounds,
871
891
  typedText: startPayload.typedText,
872
892
  replaysContext: startPayload.replaysContext,
893
+ modelRound: startPayload.modelRound ? rounds.port : undefined,
894
+ roundCut: startPayload.roundCut ? rounds.roundCut : undefined,
873
895
  knowledge: startPayload.knowledge,
874
896
  planMode: startPayload.planMode,
875
897
  deferTools: startPayload.deferTools,
@@ -1073,6 +1095,44 @@ function completion(harness) {
1073
1095
  HarnessLog.info('wire handed off');
1074
1096
  };
1075
1097
  }
1098
+ async function serveRound(harness, request, { signal, events }) {
1099
+ let sent = Promise.resolve();
1100
+ const queue = (step) => {
1101
+ sent = sent.then(step).then(noop);
1102
+ };
1103
+ const text = new TextCoalescer((type, merged) => events.push({ type, text: merged }), {
1104
+ cap: TEXT_COALESCE_CAP,
1105
+ holdMs: TEXT_COALESCE_MS
1106
+ });
1107
+ const emit = (event) => queue(() => text.add(event.type, event.text));
1108
+ const retake = () => {
1109
+ queue(async () => {
1110
+ await text.flush();
1111
+ await events.push({ type: 'model-round-retake' });
1112
+ });
1113
+ return emit;
1114
+ };
1115
+ let settled;
1116
+ try {
1117
+ if (!harness.serveModelRound) {
1118
+ throw new HarnessError('CAPABILITY_UNSUPPORTED', ['serveModelRound']);
1119
+ }
1120
+ const result = await harness.serveModelRound(roundRequestFrom(request), {
1121
+ signal,
1122
+ emit,
1123
+ retake
1124
+ });
1125
+ settled = { type: 'model-round-result', result };
1126
+ }
1127
+ catch (err) {
1128
+ settled = { type: 'model-round-result', ...roundFailureWire(err) };
1129
+ }
1130
+ queue(() => text.flush());
1131
+ await sent;
1132
+ events.push(settled);
1133
+ events.push({ type: 'done' });
1134
+ events.end();
1135
+ }
1076
1136
  function encodableDownloadEvent(wire) {
1077
1137
  try {
1078
1138
  encode('@harness/download-event', wire);
@@ -1,4 +1,5 @@
1
1
  import '../hardware/gpu-probe-entry.ts';
2
+ import { Harness } from '../../index.ts';
2
3
  import type { HarnessPlugin } from '../plugins/index.ts';
3
4
  import type { Stream } from '../rpc-session.ts';
4
5
  import type { HarnessKnowledgeConfig, HarnessPluginOptions, MusicModelArg } from '../spawn.ts';
@@ -20,6 +21,12 @@ export interface SidecarContext {
20
21
  knowledge: HarnessKnowledgeConfig | undefined;
21
22
  }
22
23
  export type SidecarPlugins = (ctx: SidecarContext) => HarnessPlugin[];
24
+ interface Log {
25
+ info(...args: unknown[]): void;
26
+ debug(...args: unknown[]): void;
27
+ warn(...args: unknown[]): void;
28
+ error(...args: unknown[]): void;
29
+ }
23
30
  export declare class HarnessSidecar {
24
31
  private readonly _plugins;
25
32
  constructor(plugins: SidecarPlugins);
@@ -27,3 +34,6 @@ export declare class HarnessSidecar {
27
34
  static loadUserPlugins(dir: string, leftOut: LeftOut): Promise<HarnessPlugin[]>;
28
35
  start(ipc: Stream, ready: () => void): Promise<() => void>;
29
36
  }
37
+ export declare const HOST_MODULE_ENV = "QVAC_HARNESS_HOST_MODULE";
38
+ export declare function addHostModule(harness: Harness, log: Pick<Log, 'error'>, env?: Record<string, string | undefined>): Promise<void>;
39
+ export {};
@@ -1,11 +1,20 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
1
9
  import '../hardware/gpu-probe-entry.js';
2
10
  import FileLog from 'bare-file-logger';
3
11
  import fs from 'fs';
4
- import { dirname, join } from 'path';
12
+ import { dirname, isAbsolute, join } from 'path';
5
13
  import process from 'process';
14
+ import { pathToFileURL } from 'url';
6
15
  import { sealAddons } from '#addon-seal';
7
16
  import { Harness, serveHarness } from '../../index.js';
8
- import { errorMessage } from '../guards.js';
17
+ import { errorMessage, isRecord } from '../guards.js';
9
18
  import { HarnessLog } from '../log.js';
10
19
  import { configureSdkStorage } from '../sdk-storage.js';
11
20
  import { Tools } from '../tools/index.js';
@@ -80,6 +89,7 @@ export class HarnessSidecar {
80
89
  });
81
90
  await harness.ready().catch((err) => log.error(SCOPE, 'harness failed to open', err));
82
91
  await addUserPlugins(harness, log);
92
+ await addHostModule(harness, log);
83
93
  sealAddons();
84
94
  serveHarness(ipc, harness);
85
95
  ready();
@@ -140,6 +150,28 @@ async function addUserPlugins(harness, log) {
140
150
  }
141
151
  }
142
152
  }
153
+ export const HOST_MODULE_ENV = 'QVAC_HARNESS_HOST_MODULE';
154
+ export async function addHostModule(harness, log, env = process.env) {
155
+ const file = env[HOST_MODULE_ENV];
156
+ if (!file) {
157
+ return;
158
+ }
159
+ if (!isAbsolute(file)) {
160
+ throw new Error(`${HOST_MODULE_ENV} must be an absolute path, not ${file}`);
161
+ }
162
+ try {
163
+ const host = await import(__rewriteRelativeImportExtension(pathToFileURL(file).href));
164
+ const configure = isRecord(host) ? host.configureHarness : undefined;
165
+ if (typeof configure !== 'function') {
166
+ throw new Error('it exports no configureHarness(harness, log)');
167
+ }
168
+ await configure(harness, log);
169
+ }
170
+ catch (err) {
171
+ log.error(SCOPE, `host module ${file} failed, so the sidecar stops`, err);
172
+ throw err;
173
+ }
174
+ }
143
175
  function openHarnessLog(path) {
144
176
  try {
145
177
  fs.mkdirSync(dirname(path), { recursive: true });
@@ -157,7 +189,7 @@ function captureConsole(log) {
157
189
  }
158
190
  async function alignSdkConsoleWithHost(hostWantsLogs) {
159
191
  try {
160
- const logging = await import('@qvac/sdk/logging');
192
+ const logging = await import('#sdk-logging');
161
193
  logging.setGlobalConsoleOutput(hostWantsLogs);
162
194
  }
163
195
  catch {
@@ -6,3 +6,4 @@ import type { HarnessPlugin } from '../plugins/index.ts';
6
6
  export type LeftOut = (name: string, reason: string) => void;
7
7
  export declare function userConfigDir(env?: Record<string, string | undefined>): string;
8
8
  export declare function loadUserPlugins(dir: string, leftOut: LeftOut): Promise<HarnessPlugin[]>;
9
+ export declare function sharedImports(): Promise<Record<string, string>>;
@@ -89,7 +89,7 @@ async function userPlugin(pluginsDir, { name, options, read = [] }, imports) {
89
89
  return plugin;
90
90
  }
91
91
  const BUILTINS = ['fs', 'os', 'crypto', 'process', 'url', 'path', 'events'];
92
- async function sharedImports() {
92
+ export async function sharedImports() {
93
93
  const raceAbort = import.meta.resolve('../helpers/race-abort.ts');
94
94
  const targets = {
95
95
  ...Object.fromEntries(BUILTINS.map((name) => [name, import.meta.resolve(name)])),
@@ -7,13 +7,23 @@ import { anchorOf, shownPath, stringArg } from '../fs/tool-path.js';
7
7
  import { MAX_WALK_ENTRIES, MAX_WALK_MS } from '../fs/walk.js';
8
8
  import { folderArg, folderPaths } from './list-dir.js';
9
9
  const GREP_MATCHES = 100;
10
+ const MAX_LIMIT = 500;
10
11
  const MAX_LINE_CHARS = 300;
12
+ const TALLY_MATCHES = 5000;
13
+ const SPREAD_MATCHES = 1000;
14
+ const SPREAD_PER_FILE = 3;
15
+ const SPREAD_NAMED = 10;
16
+ const OUTPUTS = ['content', 'files', 'count'];
17
+ const isOutput = (value) => OUTPUTS.some((output) => output === value);
18
+ const ALTERNATIVE = /(?<![\\|])\|(?!\|)/;
19
+ const REGEX_LIKE = /\.\*|\\[a-z.(|]|^\^|\$$|\[[^\]]*\]|\(\?/i;
11
20
  export function createGrepTool({ realpath = defaultRealpath, deniedRoots, maxWalkEntries = MAX_WALK_ENTRIES } = {}) {
12
21
  return {
13
22
  name: 'grep',
14
23
  toolset: 'files',
15
- description: 'Search inside the files of the shared folder. The pattern is plain text, case-insensitive; set ' +
16
- 'regex for a regular expression. Returns "path:line: text". Narrow with include (e.g. "*.ts").',
24
+ description: 'Search inside the files of the shared folder. The pattern is plain text, case-insensitive; ' +
25
+ '"a|b" finds either; set regex for a regular expression. Returns "path:line: text"; output ' +
26
+ '"files" lists matching files with the first line and count, "count" counts per file. Narrow with include (e.g. "*.ts").',
17
27
  parameters: {
18
28
  type: 'object',
19
29
  properties: {
@@ -26,7 +36,14 @@ export function createGrepTool({ realpath = defaultRealpath, deniedRoots, maxWal
26
36
  type: 'string',
27
37
  description: 'Only files whose name matches this pattern (optional)'
28
38
  },
29
- regex: { type: 'boolean', description: 'Treat pattern as a regular expression' }
39
+ regex: { type: 'boolean', description: 'Treat pattern as a regular expression' },
40
+ output: {
41
+ type: 'string',
42
+ enum: [...OUTPUTS],
43
+ description: 'content (default): matching lines; files: matching paths; count: per file'
44
+ },
45
+ limit: { type: 'number', description: `Most rows to return (default ${GREP_MATCHES})` },
46
+ offset: { type: 'number', description: 'Rows to skip, to page past a cut-off answer' }
30
47
  },
31
48
  required: ['pattern']
32
49
  },
@@ -38,8 +55,17 @@ export function createGrepTool({ realpath = defaultRealpath, deniedRoots, maxWal
38
55
  validate(args) {
39
56
  if (!stringArg(args, 'pattern'))
40
57
  return 'pattern is required';
41
- if (args.regex !== true)
58
+ if (args.output !== undefined && !isOutput(args.output)) {
59
+ return `output is one of ${OUTPUTS.join(', ')}`;
60
+ }
61
+ for (const key of ['limit', 'offset']) {
62
+ if (args[key] !== undefined && !(Number.isInteger(args[key]) && Number(args[key]) >= 0)) {
63
+ return `${key} is a whole number`;
64
+ }
65
+ }
66
+ if (args.regex !== true) {
42
67
  return null;
68
+ }
43
69
  try {
44
70
  new RegExp(String(args.pattern), 'i');
45
71
  return null;
@@ -59,11 +85,17 @@ export function createGrepTool({ realpath = defaultRealpath, deniedRoots, maxWal
59
85
  }
60
86
  const pattern = String(args.pattern);
61
87
  const regex = args.regex === true;
88
+ const queries = regex ? [pattern] : alternatives(pattern);
89
+ const output = isOutput(args.output) ? args.output : 'content';
90
+ const limit = Math.min(Number(args.limit ?? GREP_MATCHES), MAX_LIMIT);
91
+ const offset = Number(args.offset ?? 0);
92
+ const spread = args.output === undefined && args.limit === undefined && offset === 0;
93
+ const wanted = spread ? SPREAD_MATCHES : reach(output, offset + limit);
62
94
  const query = {
63
- search: new DriveSearch([pattern], { regex }),
64
- pattern,
95
+ search: new DriveSearch(queries, { regex }),
96
+ queries,
65
97
  regex,
66
- include: stringArg(args, 'include') ? compileGlob(String(args.include)) : null,
98
+ include: stringArg(args, 'include') ? includes(String(args.include), anchorOf(ctx)) : null,
67
99
  deny,
68
100
  maxEntries: maxWalkEntries
69
101
  };
@@ -74,7 +106,7 @@ export function createGrepTool({ realpath = defaultRealpath, deniedRoots, maxWal
74
106
  try {
75
107
  found = await searchTarget(target, {
76
108
  ...query,
77
- maxMatches: GREP_MATCHES + 1 - hits.length
109
+ maxMatches: wanted + 1 - hits.length
78
110
  });
79
111
  }
80
112
  catch (err) {
@@ -87,21 +119,87 @@ export function createGrepTool({ realpath = defaultRealpath, deniedRoots, maxWal
87
119
  }
88
120
  }
89
121
  const anchor = anchorOf(ctx);
90
- const rows = hits
91
- .slice(0, GREP_MATCHES)
92
- .map((hit) => `${shownPath(hit.file, anchor)}:${hit.line}: ${hit.text.slice(0, MAX_LINE_CHARS)}`);
122
+ if (spread && hits.length > limit) {
123
+ return {
124
+ matches: spreadRows(hits.slice(0, wanted), limit, (file) => shownPath(file, anchor)),
125
+ truncated: true
126
+ };
127
+ }
128
+ const all = answerRows(hits.slice(0, wanted), output, (file) => shownPath(file, anchor));
129
+ const rows = all.slice(offset, offset + limit);
130
+ const more = all.length > offset + limit || hits.length > wanted;
93
131
  return {
94
- matches: rows.join('\n') || 'no matches',
95
- truncated: truncated || hits.length > GREP_MATCHES || undefined
132
+ matches: rows.join('\n') || noMatches(pattern, { regex, offset, found: all.length }),
133
+ truncated: truncated || more || undefined
96
134
  };
97
135
  }
98
136
  };
99
137
  }
100
- function searchTarget({ root, folder }, { search, pattern, regex, include, deny, maxEntries, maxMatches }) {
138
+ function includes(pattern, anchor) {
139
+ const glob = compileGlob(pattern.replace(/^\.\//, ''));
140
+ return pattern.includes('/') ? (_name, full) => glob(shownPath(full, anchor)) : glob;
141
+ }
142
+ const reach = (output, lines) => output === 'content' ? lines : TALLY_MATCHES;
143
+ function spreadRows(hits, limit, shown) {
144
+ const files = new Map();
145
+ for (const hit of hits) {
146
+ files.set(hit.file, [...(files.get(hit.file) ?? []), hit]);
147
+ }
148
+ const take = new Map();
149
+ let room = limit;
150
+ for (const [file, list] of files) {
151
+ const n = Math.min(list.length, SPREAD_PER_FILE, room);
152
+ take.set(file, n);
153
+ room -= n;
154
+ }
155
+ const bySize = [...files].sort(([, a], [, b]) => a.length - b.length);
156
+ for (const [file, list] of bySize) {
157
+ const n = Math.min(list.length - (take.get(file) ?? 0), room);
158
+ take.set(file, (take.get(file) ?? 0) + n);
159
+ room -= n;
160
+ }
161
+ const rows = [...files].flatMap(([file, list]) => list
162
+ .slice(0, take.get(file))
163
+ .map((hit) => `${shown(file)}:${hit.line}: ${hit.text.slice(0, MAX_LINE_CHARS)}`));
164
+ const left = [...files]
165
+ .map(([file, list]) => ({ file, n: list.length - (take.get(file) ?? 0) }))
166
+ .filter(({ n }) => n > 0);
167
+ const named = left.slice(0, SPREAD_NAMED).map(({ file, n }) => `${shown(file)} (${n})`);
168
+ const rest = left.length > SPREAD_NAMED ? `, and ${left.length - SPREAD_NAMED} more files` : '';
169
+ const more = left.reduce((sum, { n }) => sum + n, 0);
170
+ return [...rows, `… ${more} more matching lines: ${named.join(', ')}${rest}`].join('\n');
171
+ }
172
+ function alternatives(pattern) {
173
+ const parts = pattern
174
+ .split(ALTERNATIVE)
175
+ .map((part) => part.trim().replaceAll('\\|', '|'))
176
+ .filter(Boolean);
177
+ return parts.length ? parts : [pattern];
178
+ }
179
+ function answerRows(hits, output, shown) {
180
+ if (output === 'content') {
181
+ return hits.map((hit) => `${shown(hit.file)}:${hit.line}: ${hit.text.slice(0, MAX_LINE_CHARS)}`);
182
+ }
183
+ const files = new Map();
184
+ for (const hit of hits) {
185
+ const seen = files.get(hit.file);
186
+ files.set(hit.file, seen ? { ...seen, n: seen.n + 1 } : { first: hit.line, n: 1 });
187
+ }
188
+ return [...files].map(([file, { first, n }]) => output === 'files' ? `${shown(file)}:${first} (${n})` : `${shown(file)}: ${n}`);
189
+ }
190
+ function noMatches(pattern, { regex, offset, found }) {
191
+ if (found > 0)
192
+ return `no matches past offset ${offset} (${found} in all)`;
193
+ if (!regex && REGEX_LIKE.test(pattern)) {
194
+ return 'no matches (the pattern was searched as plain text; set regex: true for a regular expression)';
195
+ }
196
+ return 'no matches';
197
+ }
198
+ function searchTarget({ root, folder }, { search, queries, regex, include, deny, maxEntries, maxMatches }) {
101
199
  if (root.kind === 'hyper' && root.search && !include) {
102
200
  return root.search({
103
201
  folder,
104
- queries: [pattern],
202
+ queries: [...queries],
105
203
  regex,
106
204
  caseSensitive: false,
107
205
  includeIgnored: false,
@@ -62,21 +62,89 @@ function ambiguity(text, spans) {
62
62
  const lines = spans.map((span) => text.slice(0, span.from).split('\n').length).join(', ');
63
63
  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
64
  }
65
+ const NUMBERED = /^\s*\d+\| ?/;
66
+ function unnumbered(text) {
67
+ const lines = text.split('\n');
68
+ const filled = lines.filter((line) => line.trim());
69
+ return filled.length && filled.every((line) => NUMBERED.test(line))
70
+ ? lines.map((line) => line.replace(NUMBERED, '')).join('\n')
71
+ : text;
72
+ }
73
+ function closest(text, old) {
74
+ const lines = text.split('\n');
75
+ const file = lines.map((line) => pairsOf(line.trim()));
76
+ const wanted = old.split('\n');
77
+ const probe = wanted.slice(0, PROBE_LINES).map((line) => pairsOf(line.trim()));
78
+ let best = { at: -1, score: 0 };
79
+ for (let i = 0; i + wanted.length <= lines.length; i++) {
80
+ const sum = probe.reduce((total, pairs, k) => total + likeness(pairs, file[i + k] ?? NONE), 0);
81
+ if (sum / probe.length > best.score) {
82
+ best = { at: i, score: sum / probe.length };
83
+ }
84
+ }
85
+ if (best.at === -1 || best.score < CLOSE_ENOUGH) {
86
+ return null;
87
+ }
88
+ const from = Math.max(0, best.at - CONTEXT_LINES);
89
+ const to = Math.min(lines.length, best.at + wanted.length + CONTEXT_LINES);
90
+ return lines
91
+ .slice(from, to)
92
+ .map((line, i) => `${from + i + 1}| ${line}`)
93
+ .join('\n');
94
+ }
95
+ const NONE = { text: '', size: 0, counts: new Map() };
96
+ function pairsOf(text) {
97
+ const counts = new Map();
98
+ for (let i = 0; i < text.length - 1; i++) {
99
+ const pair = text.slice(i, i + 2);
100
+ counts.set(pair, (counts.get(pair) ?? 0) + 1);
101
+ }
102
+ return { text, size: Math.max(0, text.length - 1), counts };
103
+ }
104
+ function likeness(a, b) {
105
+ if (a.text === b.text) {
106
+ return 1;
107
+ }
108
+ if (a.size === 0 || b.size === 0) {
109
+ return 0;
110
+ }
111
+ let shared = 0;
112
+ for (const [pair, count] of a.counts) {
113
+ shared += Math.min(count, b.counts.get(pair) ?? 0);
114
+ }
115
+ return (2 * shared) / (a.size + b.size);
116
+ }
117
+ const CLOSE_ENOUGH = 0.6;
118
+ const CONTEXT_LINES = 2;
119
+ const PROBE_LINES = 8;
120
+ const DISTINCT_CHARS = 24;
121
+ function notFound(text, old, replacement) {
122
+ if (replacement.trim().length >= DISTINCT_CHARS && spansFor(text, replacement).length) {
123
+ 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
+ }
125
+ const near = closest(text, old);
126
+ return near
127
+ ? `old text not found. Did you mean these lines? Copy them exactly, indentation included, without the line numbers:\n${near}`
128
+ : 'old text not found. Read the file with read_file and copy the exact lines you want to change, including their indentation.';
129
+ }
65
130
  export function editMatch(content, request) {
66
131
  const crlf = content.includes('\r\n');
67
132
  const text = crlf ? content.replace(/\r\n/g, '\n') : content;
68
- const spans = spansFor(text, request.old.replace(/\r\n/g, '\n'));
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
+ }
69
142
  if (!spans.length) {
70
- return {
71
- content,
72
- count: 0,
73
- error: 'old text not found. Read the file with read_file and copy the exact lines you want to change, including their indentation.'
74
- };
143
+ return { content, count: 0, error: notFound(text, old, replacement) };
75
144
  }
76
145
  if (spans.length > 1 && !request.replaceAll) {
77
146
  return { content, count: 0, error: ambiguity(text, spans) };
78
147
  }
79
- const replacement = request.replacement.replace(/\r\n/g, '\n');
80
148
  let next = text;
81
149
  for (const span of [...spans].sort((a, b) => b.from - a.from)) {
82
150
  next = next.slice(0, span.from) + replacement + next.slice(span.to);
@@ -28,7 +28,7 @@ export interface FolderSearchOptions {
28
28
  maxEntries?: number;
29
29
  maxMs?: number;
30
30
  deny?: readonly string[];
31
- include?: ((name: string) => boolean) | null;
31
+ include?: ((name: string, path: string) => boolean) | null;
32
32
  }
33
33
  export interface FolderSearchResult extends SearchResult, WalkSummary {
34
34
  }
@@ -199,7 +199,8 @@ async function* gated(files, gate) {
199
199
  return;
200
200
  }
201
201
  const name = file.key.slice(file.key.lastIndexOf('/') + 1);
202
- if (!isDeniedPath(file.path, gate.deny) && (gate.include === null || gate.include(name))) {
202
+ if (!isDeniedPath(file.path, gate.deny) &&
203
+ (gate.include === null || gate.include(name, file.path))) {
203
204
  yield file;
204
205
  }
205
206
  }
@@ -11,11 +11,12 @@ export interface ProductToolsOptions {
11
11
  readonly skillsDir?: string | undefined;
12
12
  readonly skillCatalog?: readonly SkillCatalogEntry[] | undefined;
13
13
  readonly credentialStore?: CredentialStoreFn | undefined;
14
+ readonly files?: boolean | undefined;
14
15
  }
15
16
  export declare class Tools {
16
17
  static deniedRoots: typeof deniedRootsFor;
17
18
  static bundledSkillsDir: typeof ensureBundledSkillsDir;
18
19
  static stageInputs: typeof stageInputs;
19
20
  static operations: typeof compileOperationTools;
20
- static product({ sdkHome, skillsDir, skillCatalog, credentialStore }: ProductToolsOptions): ToolDefinition[];
21
+ static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files }: ProductToolsOptions): ToolDefinition[];
21
22
  }
@@ -14,7 +14,7 @@ export class Tools {
14
14
  static bundledSkillsDir = ensureBundledSkillsDir;
15
15
  static stageInputs = stageInputs;
16
16
  static operations = compileOperationTools;
17
- static product({ sdkHome, skillsDir, skillCatalog, credentialStore }) {
17
+ static product({ sdkHome, skillsDir, skillCatalog, credentialStore, files = true }) {
18
18
  const deniedRoots = deniedRootsFor(sdkHome);
19
19
  const credentialed = skillCatalog
20
20
  ? { credentialStore, credentialAllowList: credentialAllowListFor(skillCatalog) }
@@ -23,7 +23,7 @@ export class Tools {
23
23
  const tools = [
24
24
  httpRequestTool,
25
25
  createWebFetchTool(),
26
- ...createFileTools({ deniedRoots }),
26
+ ...(files ? createFileTools({ deniedRoots }) : []),
27
27
  createPdfTool(),
28
28
  ...createOfficeTools()
29
29
  ];
@@ -10,3 +10,4 @@ export declare const SKILL_STATE: {
10
10
  };
11
11
  export type SkillState = (typeof SKILL_STATE)[keyof typeof SKILL_STATE];
12
12
  export declare function isAvailableState(state: SkillState): boolean;
13
+ export declare function isDeviceSharedCredentialKey(key: string): boolean;
@@ -12,3 +12,7 @@ const AVAILABLE_STATES = new Set([SKILL_STATE.ready]);
12
12
  export function isAvailableState(state) {
13
13
  return AVAILABLE_STATES.has(state);
14
14
  }
15
+ const DEVICE_SHARED_CREDENTIAL_KEYS = new Set(['obsidian_vault_path']);
16
+ export function isDeviceSharedCredentialKey(key) {
17
+ return DEVICE_SHARED_CREDENTIAL_KEYS.has(key);
18
+ }
@@ -1,6 +1,7 @@
1
1
  import type { HarnessEvent } from './contract-types.ts';
2
2
  import type { KnowledgeArtifact, KnowledgeHit, KnowledgeStatus, KnowledgeUpsertResult } from './contract/knowledge.ts';
3
3
  import type { HarnessKnowledgeHit, HarnessKnowledgeStatusResponse, HarnessKnowledgeUpsertRequest, HarnessKnowledgeUpsertResponse } from '../spec/hyperschema/types.d.ts';
4
+ import type { ModelRoundEvent, ModelRoundRequest, ModelRoundResult } from './capabilities/completion-engine/index.ts';
4
5
  export interface WireEvent {
5
6
  runId?: string | null;
6
7
  round?: number | null;
@@ -38,6 +39,13 @@ export interface WireEvent {
38
39
  intent?: string | null;
39
40
  display?: unknown;
40
41
  }
42
+ export interface RoundFailureWire {
43
+ message: string;
44
+ payload: {
45
+ name: string;
46
+ code?: string | number | undefined;
47
+ };
48
+ }
41
49
  export interface WireDownloadEvent {
42
50
  type: string;
43
51
  downloaded?: boolean | null;
@@ -49,6 +57,11 @@ export declare function isPlainWireValue(value: unknown): boolean;
49
57
  export declare function redactedRecoveryFields(source: Record<string, unknown>): Record<string, unknown>;
50
58
  export declare function toWire(event: HarnessEvent): WireEvent;
51
59
  export declare function fromWire(event: WireEvent): HarnessEvent;
60
+ export declare function roundFailureWire(err: unknown): RoundFailureWire;
61
+ export declare function roundFailureFrom(wire: Pick<WireEvent, 'message' | 'payload'>): Error;
62
+ export declare function roundRequestFrom(payload: unknown): ModelRoundRequest;
63
+ export declare function roundResultFrom(wire: Pick<WireEvent, 'message' | 'payload' | 'result'>): ModelRoundResult;
64
+ export declare function roundChunkFrom(payload: unknown): ModelRoundEvent;
52
65
  export declare function toDownloadWire(event: HarnessEvent): WireDownloadEvent;
53
66
  export declare function fromDownloadWire(event: WireDownloadEvent): HarnessEvent;
54
67
  export interface PackedVectors {
@@ -1,5 +1,5 @@
1
1
  import b4a from 'b4a';
2
- import { isRecord } from './guards.js';
2
+ import { errorMessage, isRecord } from './guards.js';
3
3
  function stringField(value) {
4
4
  return typeof value === 'string' ? value : undefined;
5
5
  }
@@ -296,6 +296,49 @@ function fromWirePayload(event) {
296
296
  return { type: event.type };
297
297
  }
298
298
  }
299
+ export function roundFailureWire(err) {
300
+ const { name = 'Error', code } = isRecord(err) ? err : {};
301
+ return {
302
+ message: errorMessage(err),
303
+ payload: {
304
+ name: String(name),
305
+ code: typeof code === 'string' || typeof code === 'number' ? code : undefined
306
+ }
307
+ };
308
+ }
309
+ export function roundFailureFrom(wire) {
310
+ const { name, code } = objectField(wire.payload);
311
+ return Object.assign(new Error(wire.message ?? 'model round failed'), {
312
+ name: typeof name === 'string' ? name : 'Error',
313
+ code
314
+ });
315
+ }
316
+ function isRoundRequest(value) {
317
+ return (isRecord(value) &&
318
+ typeof value.runId === 'string' &&
319
+ typeof value.round === 'number' &&
320
+ typeof value.modelId === 'string' &&
321
+ Array.isArray(value.history));
322
+ }
323
+ export function roundRequestFrom(payload) {
324
+ if (!isRoundRequest(payload)) {
325
+ throw new TypeError('invalid model round request');
326
+ }
327
+ return payload;
328
+ }
329
+ function isRoundResult(value) {
330
+ return isRecord(value) && typeof value.contentText === 'string' && isRecord(value.final);
331
+ }
332
+ export function roundResultFrom(wire) {
333
+ if (isRoundResult(wire.result)) {
334
+ return wire.result;
335
+ }
336
+ throw roundFailureFrom(wire);
337
+ }
338
+ export function roundChunkFrom(payload) {
339
+ const { type, text } = objectField(payload);
340
+ return { type: type === 'thinking' ? 'thinking' : 'content', text: String(text ?? '') };
341
+ }
299
342
  export function toDownloadWire(event) {
300
343
  switch (event.type) {
301
344
  case 'progress': {