@kingsoftcloud/agentkit-harness-node 0.0.31 → 0.0.33

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.
@@ -0,0 +1,121 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
3
+ import { basename, join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
6
+ import { splitlines } from './workspace-editing.mjs';
7
+ import { escapeRegex, fnmatch, isInside, workspaceRelative } from './workspace-paths.mjs';
8
+
9
+ const skippedDirectories = new Set(['.git', 'node_modules', '.venv', 'venv', '__pycache__']);
10
+ const maxFileBytes = 1024 * 1024;
11
+ const timedOut = Symbol('timed out');
12
+
13
+ async function readText(file, root, signal) {
14
+ if (!isInside(await realpath(file), root) || signal.aborted) return;
15
+ const fd = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
16
+ try {
17
+ if (signal.aborted) return;
18
+ const info = await fd.stat();
19
+ if (!info.isFile() || info.size > maxFileBytes || signal.aborted) return;
20
+ const buffer = Buffer.allocUnsafe(info.size + 1);
21
+ let offset = 0;
22
+ while (offset < buffer.length && !signal.aborted) {
23
+ const { bytesRead } = await fd.read(buffer, offset, buffer.length - offset, offset);
24
+ if (bytesRead === 0) return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));
25
+ offset += bytesRead;
26
+ }
27
+ } finally {
28
+ await fd.close();
29
+ }
30
+ }
31
+
32
+ export async function searchWorkspace({ args, root, base }, { read = readText, fileTimeoutMs = 1000 } = {}) {
33
+ const { query, path, glob } = args;
34
+ let pattern;
35
+ try {
36
+ pattern = new RegExp(args.is_regex ? query.trim() : escapeRegex(query.trim()), args.case_sensitive ? '' : 'i');
37
+ } catch (error) {
38
+ return { ok: false, error_code: 'invalid_search_pattern', error_message: publicErrorMessage(error) };
39
+ }
40
+ const limit = Math.max(1, Math.min(Number(args.max_results) || 100, 5000));
41
+ const context = Math.max(0, Math.min(Number(args.context_lines) || 0, 20));
42
+ const results = [];
43
+ const deadline = performance.now() + 27_000;
44
+ let skippedSlow = 0;
45
+ let stalledIo = 0;
46
+ let truncated = false;
47
+
48
+ async function bounded(action) {
49
+ const controller = new AbortController();
50
+ let timer;
51
+ const result = action(controller.signal).catch(() => undefined).finally(() => {
52
+ if (controller.signal.aborted) stalledIo--;
53
+ });
54
+ const timeout = new Promise(resolve => {
55
+ timer = setTimeout(() => {
56
+ skippedSlow++;
57
+ stalledIo++;
58
+ controller.abort();
59
+ resolve(timedOut);
60
+ }, fileTimeoutMs);
61
+ });
62
+ try {
63
+ return await Promise.race([result, timeout]);
64
+ } finally {
65
+ clearTimeout(timer);
66
+ }
67
+ }
68
+
69
+ async function inspect(file) {
70
+ const path = workspaceRelative(root, file);
71
+ if (glob && !fnmatch(path, glob) && !fnmatch(basename(file), glob)) return false;
72
+ const text = await bounded(signal => read(file, root, signal));
73
+ if (typeof text !== 'string') return false;
74
+ const lines = splitlines(text);
75
+ for (let i = 0; i < lines.length; i++) {
76
+ const line = lines[i];
77
+ if (!pattern.test(line)) continue;
78
+ if (results.length >= limit) return true;
79
+ results.push({ path, line: i + 1, text: line, snippet: line,
80
+ context_before: lines.slice(Math.max(0, i - context), i),
81
+ context_after: lines.slice(i + 1, i + 1 + context) });
82
+ }
83
+ return false;
84
+ }
85
+
86
+ const info = await bounded(() => lstat(base));
87
+ if (!info) return { ok: false, error_code: 'workspace_path_not_found', error_message: `workspace path not found: ${path}` };
88
+ if (info === timedOut) return { ok: false, error_code: 'workspace_search_timeout', error_message: 'workspace search path did not respond' };
89
+ // Stop before slow operations can fill the separate process's default
90
+ // four-thread I/O pool. The parent reaps outstanding reads when we return.
91
+ const budgetUsed = () => stalledIo >= 3 || performance.now() >= deadline;
92
+ if (info.isFile()) truncated = await inspect(base);
93
+ else if (info.isDirectory()) {
94
+ const dirs = [base];
95
+ search: while (dirs.length) {
96
+ if (budgetUsed()) { truncated = true; break; }
97
+ const dir = dirs.pop();
98
+ const entries = await bounded(async signal => {
99
+ if (await realpath(dir) !== dir || signal.aborted) return;
100
+ return readdir(dir, { withFileTypes: true });
101
+ });
102
+ if (!Array.isArray(entries)) continue;
103
+ for (const entry of entries) {
104
+ if (budgetUsed()) { truncated = true; break search; }
105
+ const name = entry.name;
106
+ const child = join(dir, name);
107
+ if (entry.isDirectory() && !skippedDirectories.has(name.toLowerCase())) dirs.push(child);
108
+ else if (entry.isFile() && await inspect(child)) { truncated = true; break search; }
109
+ }
110
+ }
111
+ }
112
+ return { ok: true, query, searched_path: path, results, match_count: results.length,
113
+ truncated: truncated || skippedSlow > 0, context_lines: context, search_backend: 'node',
114
+ ...(skippedSlow > 0 ? { skipped_slow_paths: skippedSlow } : {}) };
115
+ }
116
+
117
+ if (process.send && process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
118
+ process.once('message', input => {
119
+ void searchWorkspace(input).then(result => process.send(result), () => process.exit(1));
120
+ });
121
+ }
@@ -0,0 +1,37 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const worker = fileURLToPath(new URL('./workspace-search-worker.mjs', import.meta.url));
5
+ const failed = (code, message) => ({ ok: false, error_code: code, error_message: message });
6
+
7
+ export function runWorkspaceSearch(input, signal) {
8
+ const canceled = () => failed('canceled', 'workspace search canceled');
9
+ if (signal?.aborted) return Promise.resolve(canceled());
10
+ // Keep filesystem stalls and expensive regex evaluation off the Harness
11
+ // event loop. A stuck filesystem read can outlive termination of a worker
12
+ // thread, so this process has its own I/O pool and can be detached on timeout.
13
+ const child = fork(worker, { execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
14
+ env: { SystemRoot: process.env.SystemRoot }, windowsHide: true });
15
+ return new Promise(resolve => {
16
+ let settled = false;
17
+ const finish = value => {
18
+ if (settled) return;
19
+ settled = true;
20
+ clearTimeout(timer);
21
+ signal?.removeEventListener('abort', abort);
22
+ child.kill('SIGKILL');
23
+ child.channel?.unref();
24
+ child.unref();
25
+ resolve(value);
26
+ };
27
+ const abort = () => finish(canceled());
28
+ const unavailable = () => finish(failed('workspace_search_failed', 'workspace search worker stopped; retry with a narrower path'));
29
+ const timer = setTimeout(() => finish(failed('workspace_search_timeout', 'workspace search timed out; retry with a narrower path')), 30_000);
30
+ child.once('message', finish);
31
+ child.once('error', unavailable);
32
+ child.once('exit', unavailable);
33
+ signal?.addEventListener('abort', abort, { once: true });
34
+ if (signal?.aborted) abort();
35
+ else child.send(input, error => { if (error) unavailable(); });
36
+ });
37
+ }
@@ -19,7 +19,7 @@ import { publicErrorMessage, publicErrorCode, publicFailureContent } from '@king
19
19
  import { createHash } from 'node:crypto';
20
20
  import {
21
21
  chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync,
22
- readFileSync, readlinkSync, readSync, realpathSync, rmdirSync, statSync,
22
+ readlinkSync, readSync, realpathSync, rmdirSync, statSync,
23
23
  unlinkSync,
24
24
  } from 'node:fs';
25
25
  import { basename, join } from 'node:path';
@@ -30,13 +30,14 @@ import { prepareWorkspaceEdits } from './workspace-edit-match.mjs';
30
30
  import { prepareWorkspacePatch } from './workspace-patch.mjs';
31
31
  import { workspaceChangeDisplay } from './workspace-display.mjs';
32
32
  import { readBoundedWorkspaceImage } from './workspace-image.mjs';
33
+ import { runWorkspaceSearch } from './workspace-search.mjs';
33
34
  import { createWorkspaceCheckpointJournal, captureCheckpointFile, checkpointStatesEqual, WORKSPACE_CHECKPOINT_POLICY, CONVERSATION_WORKSPACE_CONTROL } from './workspace-checkpoints.mjs';
34
35
  import { parseStructuredPatch } from '@kingsoftcloud/agentkit-harness-core/patch-parser';
35
36
  import { canonical } from '@kingsoftcloud/agentkit-harness-core';
36
37
  import { captureWorkspaceSubject } from './workspace-subject-observer.mjs';
37
38
 
38
39
  import {
39
- WorkspacePathError, escapeRegex, fnmatch, publishWorkspaceBytes, sha256,
40
+ WorkspacePathError, fnmatch, publishWorkspaceBytes, sha256,
40
41
  TWO_MB, resolveWorkspacePath, workspaceRelative,
41
42
  } from './workspace-paths.mjs';
42
43
  import {
@@ -886,87 +887,9 @@ export function createNativeWorkspaceTools({
886
887
 
887
888
  function searchWorkspaceFiles(args, ctx) {
888
889
  const query = String(args.query ?? '');
890
+ if (!query.trim()) return { ok: false, error_message: 'query is required' };
889
891
  const path = String(args.path ?? '.');
890
- const isRegex = Boolean(args.is_regex);
891
- const glob = args.glob ?? null;
892
- const caseSensitive = Boolean(args.case_sensitive);
893
- const contextLines = Number(args.context_lines ?? 0);
894
- const maxResults = Number(args.max_results ?? 100);
895
- const needle = query.trim();
896
- if (!needle) return { ok: false, error_message: 'query is required' };
897
- const base = resolvePath(path);
898
- if (!existsSync(base)) return { ok: false, error_code: 'workspace_path_not_found', error_message: `workspace path not found: ${path}` };
899
- const candidates = [];
900
- if (lstatSync(base, { bigint: true }).isFile()) {
901
- candidates.push(base);
902
- } else {
903
- // Real files beneath the base subtree; symlinked directories are not
904
- // followed so the search cannot escape the workspace root.
905
- const stack = [base];
906
- while (stack.length) {
907
- const cur = stack.pop();
908
- let dirents;
909
- try { dirents = readdirSync(cur, { withFileTypes: true }); } catch { continue; }
910
- for (const d of dirents) {
911
- const abs = join(cur, d.name);
912
- if (d.isFile()) candidates.push(abs);
913
- else if (d.isDirectory() && !d.isSymbolicLink()) stack.push(abs);
914
- }
915
- }
916
- }
917
- let filtered = candidates;
918
- if (glob) {
919
- filtered = candidates.filter((c) => {
920
- const rel = relativeOf(c);
921
- return fnmatch(rel, glob) || fnmatch(basename(c), glob);
922
- });
923
- }
924
- let pattern;
925
- try {
926
- pattern = new RegExp(isRegex ? needle : escapeRegex(needle), caseSensitive ? '' : 'i');
927
- } catch (e) {
928
- return { ok: false, error_code: 'invalid_search_pattern', error_message: publicErrorMessage(e) };
929
- }
930
- const limit = Math.max(1, Math.min(maxResults || 100, 5000));
931
- const contextLimit = Math.max(0, Math.min(contextLines || 0, 20));
932
- const results = [];
933
- let truncated = false;
934
- outer:
935
- for (const item of filtered) {
936
- if (ctx?.signal?.aborted) return { ok: false, error_code: 'canceled', error_message: 'workspace search canceled' };
937
- let size;
938
- try { size = Number(lstatSync(item, { bigint: true }).size); } catch { continue; }
939
- if (size > 1024 * 1024) continue;
940
- let payload;
941
- try { payload = readFileSync(item); } catch { continue; }
942
- let text;
943
- try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(payload); }
944
- catch { continue; }
945
- const lines = splitlines(text);
946
- for (let i = 0; i < lines.length; i++) {
947
- const line = lines[i];
948
- if (!pattern.test(line)) continue;
949
- if (results.length >= limit) { truncated = true; break outer; }
950
- results.push({
951
- path: relativeOf(item),
952
- line: i + 1,
953
- text: line,
954
- snippet: line,
955
- context_before: lines.slice(Math.max(0, i - contextLimit), i),
956
- context_after: lines.slice(i + 1, i + 1 + contextLimit),
957
- });
958
- }
959
- }
960
- return {
961
- ok: true,
962
- query,
963
- searched_path: path,
964
- results,
965
- match_count: results.length,
966
- truncated,
967
- context_lines: contextLimit,
968
- search_backend: 'node',
969
- };
892
+ return runWorkspaceSearch({ args: { ...args, query, path }, root: pinnedRootReal, base: resolvePath(path) }, ctx?.signal);
970
893
  }
971
894
 
972
895
  function deleteWorkspaceFile(args) {
@@ -1208,14 +1131,14 @@ export function createNativeWorkspaceTools({
1208
1131
  return { status: 'error', content: { ok: false, error_type: publicErrorCode(e, 'internal_error'), error_message: publicErrorMessage(e) } };
1209
1132
  } finally { activeMutations = previousMutations; activeGuard = previousGuard; activeCheckpoint = previousCheckpoint; activeDisplayChanges = previousDisplayChanges;
1210
1133
  activePublications = previousPublications; activeReads = previousReads; release?.(); }
1211
- // The only asynchronous implementation parses captured read-only bytes.
1134
+ // The read-only syntax and search implementations can run asynchronously.
1212
1135
  // Restore mutation tracking before any await so concurrent writers cannot
1213
1136
  // attribute their publications to this invocation.
1214
1137
  if (result && typeof result.then === 'function') {
1215
1138
  try { result = await result; }
1216
1139
  catch (error) {
1217
1140
  if (signal?.aborted) return canceled();
1218
- return { status: 'error', content: { ok: false, error_type: publicErrorCode(error, 'python_syntax_unavailable'),
1141
+ return { status: 'error', content: { ok: false, error_type: publicErrorCode(error, name === 'search_workspace_files' ? 'workspace_search_failed' : 'python_syntax_unavailable'),
1219
1142
  error_message: publicErrorMessage(error) } };
1220
1143
  }
1221
1144
  }