@qvac/harness 1.0.0-rc.5 → 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 (123) hide show
  1. package/CHANGELOG.md +245 -23
  2. package/README.md +19 -7
  3. package/dist-lib/index.d.ts +5 -3
  4. package/dist-lib/index.js +43 -2
  5. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.js +13 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +8 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +21 -19
  8. package/dist-lib/lib/capabilities/completion-engine/actors/resolving.js +11 -4
  9. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +10 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +9 -3
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +36 -19
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.d.ts +1 -1
  13. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +9 -11
  14. package/dist-lib/lib/capabilities/completion-engine/driver.js +3 -0
  15. package/dist-lib/lib/capabilities/completion-engine/index.d.ts +4 -1
  16. package/dist-lib/lib/capabilities/completion-engine/index.js +3 -0
  17. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +15 -1
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.js +52 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -3
  20. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -2
  21. package/dist-lib/lib/capabilities/completion-engine/tool-sets.d.ts +24 -0
  22. package/dist-lib/lib/capabilities/completion-engine/tool-sets.js +15 -0
  23. package/dist-lib/lib/capabilities/completion-engine/turns.js +14 -4
  24. package/dist-lib/lib/capabilities/detect-language.d.ts +2 -1
  25. package/dist-lib/lib/capabilities/detect-language.js +14 -2
  26. package/dist-lib/lib/capabilities/sdk-tool.d.ts +9 -1
  27. package/dist-lib/lib/capabilities/sdk-tool.js +21 -2
  28. package/dist-lib/lib/capabilities/tool-plan.d.ts +4 -0
  29. package/dist-lib/lib/capabilities/tool-plan.js +15 -0
  30. package/dist-lib/lib/connect.d.ts +2 -0
  31. package/dist-lib/lib/connect.js +79 -3
  32. package/dist-lib/lib/contract/run.d.ts +2 -0
  33. package/dist-lib/lib/contract-types.d.ts +5 -0
  34. package/dist-lib/lib/errors.d.ts +4 -0
  35. package/dist-lib/lib/errors.js +6 -0
  36. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  37. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  38. package/dist-lib/lib/helpers/goal-check.d.ts +2 -0
  39. package/dist-lib/lib/helpers/goal-check.js +18 -0
  40. package/dist-lib/lib/helpers/require-peers.d.ts +3 -0
  41. package/dist-lib/lib/helpers/require-peers.js +23 -0
  42. package/dist-lib/lib/machine/completion/actions/completion.js +30 -11
  43. package/dist-lib/lib/machine/completion/context.js +2 -1
  44. package/dist-lib/lib/machine/completion/rules.d.ts +1 -1
  45. package/dist-lib/lib/machine/completion/rules.js +7 -8
  46. package/dist-lib/lib/machine/completion/types.d.ts +1 -0
  47. package/dist-lib/lib/models/llm-presets.d.ts +1 -0
  48. package/dist-lib/lib/models/model-catalog.js +1 -1
  49. package/dist-lib/lib/models/model-pool.d.ts +4 -0
  50. package/dist-lib/lib/models/model-pool.js +4 -1
  51. package/dist-lib/lib/models/opencl-cache.js +2 -2
  52. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  53. package/dist-lib/lib/plugins/registry.js +4 -0
  54. package/dist-lib/lib/prompt.d.ts +2 -1
  55. package/dist-lib/lib/prompt.js +12 -12
  56. package/dist-lib/lib/residency/completion-runtime.d.ts +9 -1
  57. package/dist-lib/lib/residency/completion-runtime.js +29 -26
  58. package/dist-lib/lib/residency/index.d.ts +4 -0
  59. package/dist-lib/lib/residency/index.js +6 -1
  60. package/dist-lib/lib/round-host.d.ts +12 -0
  61. package/dist-lib/lib/round-host.js +57 -0
  62. package/dist-lib/lib/round-port.d.ts +24 -0
  63. package/dist-lib/lib/round-port.js +81 -0
  64. package/dist-lib/lib/sdk-loader.d.ts +1 -1
  65. package/dist-lib/lib/sdk-loader.js +30 -6
  66. package/dist-lib/lib/sdk-storage.d.ts +1 -0
  67. package/dist-lib/lib/sdk-storage.js +18 -2
  68. package/dist-lib/lib/serve.js +68 -6
  69. package/dist-lib/lib/sidecar/index.d.ts +10 -0
  70. package/dist-lib/lib/sidecar/index.js +35 -3
  71. package/dist-lib/lib/sidecar/user-plugins.d.ts +1 -0
  72. package/dist-lib/lib/sidecar/user-plugins.js +1 -1
  73. package/dist-lib/lib/tools/files/grep.js +113 -15
  74. package/dist-lib/lib/tools/fs/edit-match.js +75 -7
  75. package/dist-lib/lib/tools/fs/search.d.ts +1 -1
  76. package/dist-lib/lib/tools/fs/search.js +2 -1
  77. package/dist-lib/lib/tools/http-request.js +1 -0
  78. package/dist-lib/lib/tools/index.d.ts +2 -1
  79. package/dist-lib/lib/tools/index.js +2 -2
  80. package/dist-lib/lib/tools/skills/skill-state-constants.d.ts +1 -0
  81. package/dist-lib/lib/tools/skills/skill-state-constants.js +4 -0
  82. package/dist-lib/lib/wire.d.ts +13 -0
  83. package/dist-lib/lib/wire.js +44 -1
  84. package/dist-lib/plugins/coding/read-only.d.ts +1 -0
  85. package/dist-lib/plugins/coding/read-only.js +264 -0
  86. package/dist-lib/plugins/coding/session.d.ts +3 -1
  87. package/dist-lib/plugins/coding/session.js +19 -2
  88. package/dist-lib/plugins/egress-proxy/index.d.ts +2 -2
  89. package/dist-lib/plugins/egress-proxy/index.js +5 -3
  90. package/dist-lib/plugins/image/index.js +7 -2
  91. package/dist-lib/plugins/language-hint/index.js +4 -1
  92. package/dist-lib/plugins/mcp/server.js +1 -1
  93. package/dist-lib/plugins/music/index.js +6 -2
  94. package/dist-lib/plugins/obsidian/readiness.js +2 -2
  95. package/dist-lib/plugins/obsidian/vault-read.js +17 -16
  96. package/dist-lib/plugins/python/index.js +1 -0
  97. package/dist-lib/plugins/python/loader.d.ts +1 -0
  98. package/dist-lib/plugins/python/loader.js +8 -0
  99. package/dist-lib/plugins/quickjs/index.js +4 -0
  100. package/dist-lib/plugins/quickjs/runtime.js +8 -3
  101. package/dist-lib/plugins/run-report/index.js +6 -2
  102. package/dist-lib/plugins/run-report/layout.js +1 -1
  103. package/dist-lib/plugins/sandbox-vm/index.js +3 -0
  104. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  105. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  106. package/dist-lib/plugins/speech/audio-resample.js +2 -1
  107. package/dist-lib/plugins/speech/index.d.ts +1 -0
  108. package/dist-lib/plugins/speech/index.js +8 -1
  109. package/dist-lib/plugins/speech/speech-runtime.js +3 -3
  110. package/dist-lib/plugins/translation/index.d.ts +1 -1
  111. package/dist-lib/plugins/translation/index.js +7 -3
  112. package/dist-lib/plugins/translation/translate.d.ts +2 -2
  113. package/dist-lib/plugins/translation/translate.js +7 -8
  114. package/dist-lib/plugins/walkie-talkie/index.d.ts +2 -2
  115. package/dist-lib/plugins/walkie-talkie/index.js +13 -5
  116. package/dist-lib/plugins/walkie-talkie/wire.d.ts +5 -0
  117. package/dist-lib/plugins/walkie-talkie/wire.js +6 -5
  118. package/dist-lib/schema/harness.js +12 -2
  119. package/dist-lib/spec/hrpc/messages.js +208 -150
  120. package/dist-lib/spec/hyperschema/index.js +208 -150
  121. package/dist-lib/spec/hyperschema/schema.json +125 -84
  122. package/dist-lib/spec/hyperschema/types.d.ts +4 -3
  123. package/package.json +150 -25
@@ -1,18 +1,24 @@
1
- import { mkdirSync, writeFileSync } from 'fs';
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  import process from 'process';
4
4
  import { isBareKit } from 'which-runtime';
5
5
  import { installSdkConfigLoader } from '#sdk-config-loader';
6
+ import { isRecord } from './guards.js';
6
7
  import { SDK_HOME_ENV } from './storage.js';
7
8
  export const SDK_CONFIG_PATH_ENV = 'QVAC_CONFIG_PATH';
8
9
  export const OPENCL_CACHE_DIR_ENV = 'QVAC_OPENCL_CACHE_DIR';
10
+ export const SDK_OPTIONS_ENV = 'QVAC_SDK_OPTIONS';
9
11
  const FIT_STUB_BUDGET_MS = 10_000;
10
12
  export function configureSdkStorage(storage, channels = {}) {
11
13
  const { env = process.env, argv = isBareKit ? Bare.argv : null } = channels;
12
14
  installSdkConfigLoader();
13
15
  mkdirSync(storage.home, { recursive: true });
14
16
  const configPath = join(storage.home, 'qvac.config.json');
15
- const config = { cacheDirectory: storage.models, fitStubBudgetMs: FIT_STUB_BUDGET_MS };
17
+ const config = {
18
+ ...hostOptions(env[SDK_OPTIONS_ENV]),
19
+ cacheDirectory: storage.models,
20
+ fitStubBudgetMs: FIT_STUB_BUDGET_MS
21
+ };
16
22
  writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
17
23
  const openclCacheDir = join(storage.home, 'opencl-cache');
18
24
  mkdirSync(openclCacheDir, { recursive: true });
@@ -26,3 +32,13 @@ export function configureSdkStorage(storage, channels = {}) {
26
32
  env[OPENCL_CACHE_DIR_ENV] = openclCacheDir;
27
33
  return configPath;
28
34
  }
35
+ function hostOptions(file) {
36
+ if (!file) {
37
+ return {};
38
+ }
39
+ const options = JSON.parse(readFileSync(file, 'utf8'));
40
+ if (!isRecord(options) || Array.isArray(options)) {
41
+ throw new Error(`${SDK_OPTIONS_ENV} must name a JSON object: ${file}`);
42
+ }
43
+ return options;
44
+ }
@@ -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',
@@ -91,16 +92,17 @@ function optionalNumber(value) {
91
92
  return value === undefined || typeof value === 'number';
92
93
  }
93
94
  function goalFrom(value) {
94
- const { objective, rounds, ms, tokens, checks } = value;
95
+ const { objective, rounds, ms, tokens, checks, checksProve } = value;
95
96
  if (typeof objective !== 'string' ||
96
97
  !optionalNumber(rounds) ||
97
98
  !optionalNumber(ms) ||
98
99
  !optionalNumber(tokens) ||
99
100
  (checks !== undefined &&
100
- (!Array.isArray(checks) || !checks.every((check) => typeof check === 'string')))) {
101
+ (!Array.isArray(checks) || !checks.every((check) => typeof check === 'string'))) ||
102
+ (checksProve !== undefined && typeof checksProve !== 'boolean')) {
101
103
  throw new TypeError('Invalid goal');
102
104
  }
103
- return { objective, rounds, ms, tokens, checks };
105
+ return { objective, rounds, ms, tokens, checks, checksProve };
104
106
  }
105
107
  function startPayloadFrom(value) {
106
108
  if (!isRecord(value)) {
@@ -178,6 +180,12 @@ function startPayloadFrom(value) {
178
180
  if (value.replaysContext === true) {
179
181
  payload.replaysContext = true;
180
182
  }
183
+ if (value.modelRound === true) {
184
+ payload.modelRound = true;
185
+ }
186
+ if (value.roundCut === true) {
187
+ payload.roundCut = true;
188
+ }
181
189
  if (value.runLog === null) {
182
190
  payload.runLog = null;
183
191
  }
@@ -644,6 +652,7 @@ function completion(harness) {
644
652
  const pendingRunLog = new Map();
645
653
  const input = pushQueue();
646
654
  const controller = new AbortController();
655
+ const rounds = new RoundPort((event) => events.push(event));
647
656
  let calls = 0;
648
657
  let started = false;
649
658
  let clientGone = false;
@@ -678,6 +687,7 @@ function completion(harness) {
678
687
  reject(new HarnessError('CLIENT_GONE'));
679
688
  }
680
689
  pendingRunLog.clear();
690
+ rounds.close();
681
691
  input.end();
682
692
  events.end();
683
693
  };
@@ -685,6 +695,17 @@ function completion(harness) {
685
695
  duplex.on('end', gone);
686
696
  duplex.readStream?.on('close', gone);
687
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
+ }
688
709
  if (frame.type === 'decision') {
689
710
  if (typeof frame.callId !== 'string') {
690
711
  return;
@@ -869,12 +890,14 @@ function completion(harness) {
869
890
  maxToolRounds: startPayload.maxToolRounds,
870
891
  typedText: startPayload.typedText,
871
892
  replaysContext: startPayload.replaysContext,
893
+ modelRound: startPayload.modelRound ? rounds.port : undefined,
894
+ roundCut: startPayload.roundCut ? rounds.roundCut : undefined,
872
895
  knowledge: startPayload.knowledge,
873
896
  planMode: startPayload.planMode,
874
897
  deferTools: startPayload.deferTools,
875
898
  parentRunId: startPayload.parentRunId,
876
899
  goal: startPayload.goal,
877
- messages: (frame.messages ?? []).map(({ role, content, attachments, toolCalls, toolCallId, name, id, context: added }) => ({
900
+ messages: (frame.messages ?? []).map(({ role, content, attachments, toolCalls, toolCallId, name, id, context: added, sentAt }) => ({
878
901
  role,
879
902
  content,
880
903
  attachments: attachments?.length
@@ -884,7 +907,8 @@ function completion(harness) {
884
907
  toolCallId: toolCallId ?? undefined,
885
908
  name: name ?? undefined,
886
909
  id: id || undefined,
887
- context: added ?? undefined
910
+ context: added ?? undefined,
911
+ sentAt: sentAt || undefined
888
912
  })),
889
913
  toolConfigs: frame.toolConfigs ?? undefined,
890
914
  grantedDirs: frame.grantedDirs ?? undefined,
@@ -1071,6 +1095,44 @@ function completion(harness) {
1071
1095
  HarnessLog.info('wire handed off');
1072
1096
  };
1073
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
+ }
1074
1136
  function encodableDownloadEvent(wire) {
1075
1137
  try {
1076
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
  }
@@ -16,6 +16,7 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
16
16
  name: 'http_request',
17
17
  policyVersion,
18
18
  toolset: 'http-request',
19
+ defer: true,
19
20
  description: 'Make an outbound HTTP or HTTPS request and return the response status and body (truncated) as text. Authorization/Cookie headers are stripped before sending. Stored skill credentials are attached automatically for their allow-listed hosts; `auth` is only needed to force a specific credential key. For APIs and text responses only: a URL that serves a file — PDF, .docx, .xlsx, an image, any binary — comes back as truncated garbage here. Use web_fetch for those; it downloads and attaches the file.',
20
21
  parameters: {
21
22
  type: 'object',
@@ -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
+ }