dsh-linked-workspace 0.16.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.en.md +19 -1
- package/README.md +20 -1
- package/docs/API.md +25 -4
- package/docs/VERIFY.md +24 -0
- package/lib/client.js +326 -3
- package/lib/index.js +585 -33
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { randomUUID } from 'node:crypto'
|
|
19
19
|
import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
20
20
|
import { spawn } from 'node:child_process'
|
|
21
|
-
import { mkdir, readdir, rm, stat as fsStat } from 'node:fs/promises'
|
|
21
|
+
import { appendFile, mkdir, readdir, rename, rm, stat as fsStat } from 'node:fs/promises'
|
|
22
22
|
import { homedir, tmpdir } from 'node:os'
|
|
23
23
|
import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
|
|
24
24
|
import { fileURLToPath } from 'node:url'
|
|
@@ -38,7 +38,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
|
|
|
38
38
|
* is still running an older copy of the Host — refreshing the page only swaps
|
|
39
39
|
* the browser bundle, so the two halves can drift by one restart.
|
|
40
40
|
*/
|
|
41
|
-
const API_REVISION =
|
|
41
|
+
const API_REVISION = 4
|
|
42
42
|
|
|
43
43
|
/** When this copy of the Host was loaded; shown by `meta.info`. */
|
|
44
44
|
const STARTED_AT = new Date().toISOString()
|
|
@@ -55,7 +55,9 @@ const PACKAGE_VERSION = (() => {
|
|
|
55
55
|
|
|
56
56
|
const DATA_VERSION = 1
|
|
57
57
|
const SETTINGS_VERSION = 1
|
|
58
|
-
const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false })
|
|
58
|
+
const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '' })
|
|
59
|
+
/** Exec allow-lists travel as arrays, so they are not part of the frozen defaults. */
|
|
60
|
+
const EMPTY_ID_LIST = Object.freeze([])
|
|
59
61
|
const EDITOR_THEME_FAMILIES = new Set(['github', 'solarized', 'one', 'dracula', 'monokai', 'nord', 'vscode', 'xcode', 'catppuccin'])
|
|
60
62
|
const THEME_FAMILY_OF = (id) => {
|
|
61
63
|
const value = String(id || '')
|
|
@@ -92,6 +94,17 @@ const PEEK_LIMIT = 512 * 1024
|
|
|
92
94
|
const READ_CAP = 8 * 1024 * 1024
|
|
93
95
|
const MAX_WRITE_BYTES = 8 * 1024 * 1024
|
|
94
96
|
const MAX_MEDIA_BYTES = 24 * 1024 * 1024
|
|
97
|
+
// ── remote command execution (0.17.0) ───────────────────────────────────────
|
|
98
|
+
/** Longest command line accepted; anything longer is almost always a paste error. */
|
|
99
|
+
const EXEC_MAX_COMMAND = 8000
|
|
100
|
+
const EXEC_TIMEOUT_DEFAULT = 60_000
|
|
101
|
+
const EXEC_TIMEOUT_MAX = 600_000
|
|
102
|
+
const EXEC_OUTPUT_DEFAULT = 200_000
|
|
103
|
+
const EXEC_OUTPUT_MAX = 400_000
|
|
104
|
+
const EXEC_OUTPUT_HEAD = 4000
|
|
105
|
+
const EXEC_AUDIT_NAME = 'exec-audit.jsonl'
|
|
106
|
+
const EXEC_AUDIT_MAX_BYTES = 5 * 1024 * 1024
|
|
107
|
+
const EXEC_SHELL_RE = /^[\w./-]{1,200}$/
|
|
95
108
|
const IMAGE_MIME = Object.freeze({
|
|
96
109
|
'.png': 'image/png',
|
|
97
110
|
'.jpg': 'image/jpeg',
|
|
@@ -159,6 +172,12 @@ const ERROR_STATUS = {
|
|
|
159
172
|
FS_EXISTS: 409,
|
|
160
173
|
CONFLICT: 409,
|
|
161
174
|
INTERNAL: 500,
|
|
175
|
+
// 0.17.0 — remote command execution
|
|
176
|
+
EXEC_DISABLED: 403,
|
|
177
|
+
EXEC_HOST_NOT_ALLOWED: 403,
|
|
178
|
+
EXEC_WORKSPACE_NOT_ALLOWED: 403,
|
|
179
|
+
EXEC_TIMEOUT: 504,
|
|
180
|
+
EXEC_FAILED: 502,
|
|
162
181
|
}
|
|
163
182
|
|
|
164
183
|
class ApiError extends Error {
|
|
@@ -408,10 +427,32 @@ function isThemeId(value) {
|
|
|
408
427
|
return typeof value === 'string' && /^[a-z0-9][a-z0-9-]{0,39}$/.test(value)
|
|
409
428
|
}
|
|
410
429
|
|
|
430
|
+
/** Keeps only non-empty strings, trims them and drops duplicates. */
|
|
431
|
+
function normalizeIdList(value) {
|
|
432
|
+
if (!Array.isArray(value)) return []
|
|
433
|
+
const seen = new Set()
|
|
434
|
+
const out = []
|
|
435
|
+
for (const item of value) {
|
|
436
|
+
if (typeof item !== 'string') continue
|
|
437
|
+
const id = item.trim()
|
|
438
|
+
if (id === '' || seen.has(id)) continue
|
|
439
|
+
seen.add(id)
|
|
440
|
+
out.push(id)
|
|
441
|
+
if (out.length >= 200) break
|
|
442
|
+
}
|
|
443
|
+
return out
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function clampInt(value, min, max, fallback) {
|
|
447
|
+
const number = Number(value)
|
|
448
|
+
if (!Number.isFinite(number)) return fallback
|
|
449
|
+
return Math.min(max, Math.max(min, Math.round(number)))
|
|
450
|
+
}
|
|
451
|
+
|
|
411
452
|
class SettingsStore {
|
|
412
453
|
constructor(file) {
|
|
413
454
|
this.file = file
|
|
414
|
-
this.value = { ...SETTINGS_DEFAULTS }
|
|
455
|
+
this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [] }
|
|
415
456
|
const raw = readJsonFile(file, { version: SETTINGS_VERSION, settings: {} })
|
|
416
457
|
const settings = raw && typeof raw === 'object' && raw.settings && typeof raw.settings === 'object'
|
|
417
458
|
? raw.settings
|
|
@@ -422,6 +463,22 @@ class SettingsStore {
|
|
|
422
463
|
if (settings && typeof settings === 'object' && FILE_OPEN_MODES.has(settings.fileOpenMode)) {
|
|
423
464
|
this.value.fileOpenMode = settings.fileOpenMode
|
|
424
465
|
}
|
|
466
|
+
if (settings && typeof settings === 'object' && typeof settings.execEnabled === 'boolean') {
|
|
467
|
+
this.value.execEnabled = settings.execEnabled
|
|
468
|
+
}
|
|
469
|
+
if (settings && typeof settings === 'object') {
|
|
470
|
+
this.value.execHostIds = normalizeIdList(settings.execHostIds)
|
|
471
|
+
this.value.execWorkspaceIds = normalizeIdList(settings.execWorkspaceIds)
|
|
472
|
+
if (settings.execTimeoutMs !== undefined) {
|
|
473
|
+
this.value.execTimeoutMs = clampInt(settings.execTimeoutMs, 1000, EXEC_TIMEOUT_MAX, EXEC_TIMEOUT_DEFAULT)
|
|
474
|
+
}
|
|
475
|
+
if (settings.execMaxOutputChars !== undefined) {
|
|
476
|
+
this.value.execMaxOutputChars = clampInt(settings.execMaxOutputChars, 1000, EXEC_OUTPUT_MAX, EXEC_OUTPUT_DEFAULT)
|
|
477
|
+
}
|
|
478
|
+
if (typeof settings.execShell === 'string' && (settings.execShell === '' || EXEC_SHELL_RE.test(settings.execShell))) {
|
|
479
|
+
this.value.execShell = settings.execShell
|
|
480
|
+
}
|
|
481
|
+
}
|
|
425
482
|
if (settings && typeof settings === 'object' && typeof settings.autoSave === 'boolean') {
|
|
426
483
|
this.value.autoSave = settings.autoSave
|
|
427
484
|
}
|
|
@@ -453,7 +510,11 @@ class SettingsStore {
|
|
|
453
510
|
}
|
|
454
511
|
|
|
455
512
|
get() {
|
|
456
|
-
return {
|
|
513
|
+
return {
|
|
514
|
+
...this.value,
|
|
515
|
+
execHostIds: this.value.execHostIds ? this.value.execHostIds.slice() : [],
|
|
516
|
+
execWorkspaceIds: this.value.execWorkspaceIds ? this.value.execWorkspaceIds.slice() : [],
|
|
517
|
+
}
|
|
457
518
|
}
|
|
458
519
|
|
|
459
520
|
update(patch = {}) {
|
|
@@ -481,6 +542,30 @@ class SettingsStore {
|
|
|
481
542
|
if (typeof patch.autoSave !== 'boolean') throw new ApiError('BAD_REQUEST', '自动保存设置无效')
|
|
482
543
|
this.value.autoSave = patch.autoSave
|
|
483
544
|
}
|
|
545
|
+
if (patch && typeof patch === 'object' && patch.execEnabled !== undefined) {
|
|
546
|
+
if (typeof patch.execEnabled !== 'boolean') throw new ApiError('BAD_REQUEST', '远端命令执行设置无效')
|
|
547
|
+
this.value.execEnabled = patch.execEnabled
|
|
548
|
+
}
|
|
549
|
+
if (patch && typeof patch === 'object' && patch.execHostIds !== undefined) {
|
|
550
|
+
if (!Array.isArray(patch.execHostIds)) throw new ApiError('BAD_REQUEST', '执行白名单必须是主机 id 数组')
|
|
551
|
+
this.value.execHostIds = normalizeIdList(patch.execHostIds)
|
|
552
|
+
}
|
|
553
|
+
if (patch && typeof patch === 'object' && patch.execWorkspaceIds !== undefined) {
|
|
554
|
+
if (!Array.isArray(patch.execWorkspaceIds)) throw new ApiError('BAD_REQUEST', '执行白名单必须是工作区 id 数组')
|
|
555
|
+
this.value.execWorkspaceIds = normalizeIdList(patch.execWorkspaceIds)
|
|
556
|
+
}
|
|
557
|
+
if (patch && typeof patch === 'object' && patch.execTimeoutMs !== undefined) {
|
|
558
|
+
this.value.execTimeoutMs = clampInt(patch.execTimeoutMs, 1000, EXEC_TIMEOUT_MAX, EXEC_TIMEOUT_DEFAULT)
|
|
559
|
+
}
|
|
560
|
+
if (patch && typeof patch === 'object' && patch.execMaxOutputChars !== undefined) {
|
|
561
|
+
this.value.execMaxOutputChars = clampInt(patch.execMaxOutputChars, 1000, EXEC_OUTPUT_MAX, EXEC_OUTPUT_DEFAULT)
|
|
562
|
+
}
|
|
563
|
+
if (patch && typeof patch === 'object' && patch.execShell !== undefined) {
|
|
564
|
+
if (typeof patch.execShell !== 'string' || (patch.execShell !== '' && !EXEC_SHELL_RE.test(patch.execShell))) {
|
|
565
|
+
throw new ApiError('BAD_REQUEST', '解释器路径无效')
|
|
566
|
+
}
|
|
567
|
+
this.value.execShell = patch.execShell
|
|
568
|
+
}
|
|
484
569
|
writeJsonAtomic(this.file, { version: SETTINGS_VERSION, settings: { ...this.value, themeExplicit: this.themeExplicit === true } })
|
|
485
570
|
return this.get()
|
|
486
571
|
}
|
|
@@ -1450,8 +1535,10 @@ export function apply(ctx) {
|
|
|
1450
1535
|
'- action "info" | "list_dir" | "read" | "write" | "replace" | "stat" | "mkdir" | "rename" | "delete" takes `path` relative to the remote root (or an absolute path inside it).',
|
|
1451
1536
|
'- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
|
|
1452
1537
|
'- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
|
|
1538
|
+
'- action "exec" runs ONE non-interactive command on the remote host (builds, tests, logs). It only works when the user switched remote execution on and allow-listed this host/workspace; every attempt is audited.',
|
|
1539
|
+
'- action "references" lists workspace paths matching a query (best match first, directories marked `dir`), which is how you resolve a remote path a user mentioned by name.',
|
|
1453
1540
|
'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere.',
|
|
1454
|
-
'For a REMOTE workspace do not create project files in the placeholder and do not expect local paths to exist: read, write, build and inspect logs on the remote host, through linked_workspace actions or `ssh` when an action does not fit.',
|
|
1541
|
+
'For a REMOTE workspace do not create project files in the placeholder and do not expect local paths to exist: read, write, build and inspect logs on the remote host, through linked_workspace actions or `ssh` when an action does not fit. Prefer action "exec" over `ssh` when it is enabled: it keeps the audit trail and the output limits.',
|
|
1455
1542
|
'Locally installed skills (~/.dsh/skills, ~/.agents/skills) remain available; use `linked_skills` to list or read them. A linked workspace also sees the project skills of its local directory.',
|
|
1456
1543
|
'Do not hand-edit `.remote/`; it is a mirror of the remote tree. Prefer linked_workspace over bash/read/write for anything under the remote root, and list first when unsure which workspace you are in.',
|
|
1457
1544
|
].join('\n')
|
|
@@ -1727,6 +1814,22 @@ export function apply(ctx) {
|
|
|
1727
1814
|
job.updatedAt = Date.now()
|
|
1728
1815
|
}
|
|
1729
1816
|
|
|
1817
|
+
// A content search can run for seconds; the client can stop it by job id the
|
|
1818
|
+
// same way it stops a transfer. The flag is checked between files.
|
|
1819
|
+
const GREP_JOB_TTL_MS = 60 * 1000
|
|
1820
|
+
const grepJobs = new Map()
|
|
1821
|
+
|
|
1822
|
+
const beginGrepJob = (id) => {
|
|
1823
|
+
if (typeof id !== 'string' || id.trim() === '') return null
|
|
1824
|
+
const now = Date.now()
|
|
1825
|
+
for (const [key, value] of grepJobs) {
|
|
1826
|
+
if (now - value.startedAt > GREP_JOB_TTL_MS) grepJobs.delete(key)
|
|
1827
|
+
}
|
|
1828
|
+
const job = { id, cancelled: false, startedAt: now }
|
|
1829
|
+
grepJobs.set(id, job)
|
|
1830
|
+
return job
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1730
1833
|
/** Download one remote file/folder into the OS Downloads folder. */
|
|
1731
1834
|
const downloadRemotePath = async (remote, target, destDir) => {
|
|
1732
1835
|
await mkdir(destDir, { recursive: true })
|
|
@@ -1991,9 +2094,16 @@ export function apply(ctx) {
|
|
|
1991
2094
|
const GREP_MAX_FILES = 2000
|
|
1992
2095
|
const GREP_MAX_BYTES = 8 * 1024 * 1024
|
|
1993
2096
|
const GREP_DEADLINE_MS = 5000
|
|
2097
|
+
const GREP_DEADLINE_MAX = 10000
|
|
1994
2098
|
const GREP_PREVIEW_CHARS = 120
|
|
1995
2099
|
const GREP_MAX_QUERY = 200
|
|
1996
2100
|
|
|
2101
|
+
// Path completion (`fs.references`) is about names, not contents, so it walks
|
|
2102
|
+
// more entries but reads no files.
|
|
2103
|
+
const REFERENCE_MAX_RESULTS = 200
|
|
2104
|
+
const REFERENCE_MAX_ENTRIES = 20000
|
|
2105
|
+
const REFERENCE_DEADLINE_MS = 3000
|
|
2106
|
+
|
|
1997
2107
|
// Dependency trees and build output make a content search useless: they
|
|
1998
2108
|
// dwarf the project and always win the result budget. Both sides skip them.
|
|
1999
2109
|
const GREP_EXCLUDED_DIRS = [
|
|
@@ -2003,7 +2113,13 @@ export function apply(ctx) {
|
|
|
2003
2113
|
'.ipynb_checkpoints', '.gradle', '.idea', '.vscode',
|
|
2004
2114
|
]
|
|
2005
2115
|
|
|
2006
|
-
|
|
2116
|
+
// Version-control metadata stays hidden even when the user asks for ignored
|
|
2117
|
+
// directories: nobody wants `.git/objects` in a completion list.
|
|
2118
|
+
const GREP_ALWAYS_EXCLUDED = new Set(['.git', '.hg', '.svn'])
|
|
2119
|
+
|
|
2120
|
+
function grepDirectoryExcluded(name, includeIgnored) {
|
|
2121
|
+
if (GREP_ALWAYS_EXCLUDED.has(name)) return true
|
|
2122
|
+
if (includeIgnored) return false
|
|
2007
2123
|
return LINKED_SYNC_EXCLUDES.has(name) || GREP_EXCLUDED_DIRS.indexOf(name) !== -1
|
|
2008
2124
|
}
|
|
2009
2125
|
|
|
@@ -2040,21 +2156,51 @@ export function apply(ctx) {
|
|
|
2040
2156
|
return { line: 0, preview: '' }
|
|
2041
2157
|
}
|
|
2042
2158
|
|
|
2159
|
+
/** Count occurrences of the query in one file body (used by `files` mode). */
|
|
2160
|
+
function countMatches(text, query, options) {
|
|
2161
|
+
if (query === '') return 0
|
|
2162
|
+
if (options && options.regex) {
|
|
2163
|
+
let expression
|
|
2164
|
+
try {
|
|
2165
|
+
expression = new RegExp(query, options.ignoreCase ? 'gi' : 'g')
|
|
2166
|
+
} catch {
|
|
2167
|
+
return 0
|
|
2168
|
+
}
|
|
2169
|
+
const found = text.match(expression)
|
|
2170
|
+
return found ? found.length : 0
|
|
2171
|
+
}
|
|
2172
|
+
const haystack = options && options.ignoreCase ? text.toLowerCase() : text
|
|
2173
|
+
const needle = options && options.ignoreCase ? query.toLowerCase() : query
|
|
2174
|
+
let count = 0
|
|
2175
|
+
let index = haystack.indexOf(needle)
|
|
2176
|
+
while (index !== -1) {
|
|
2177
|
+
count += 1
|
|
2178
|
+
index = haystack.indexOf(needle, index + needle.length)
|
|
2179
|
+
}
|
|
2180
|
+
return count
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2043
2183
|
function contentSearchLocal(root, query, maxResults, options = {}) {
|
|
2044
2184
|
const matcher = compileSearch(query, options)
|
|
2045
2185
|
const entries = []
|
|
2046
2186
|
const started = Date.now()
|
|
2187
|
+
const maxFiles = clampInt(options.maxFiles, 1, GREP_MAX_FILES, GREP_MAX_FILES)
|
|
2188
|
+
const maxFileBytes = clampInt(options.maxFileBytes, 1024, GREP_MAX_FILE_BYTES, GREP_MAX_FILE_BYTES)
|
|
2189
|
+
const deadline = clampInt(options.timeoutMs, 500, GREP_DEADLINE_MAX, GREP_DEADLINE_MS)
|
|
2190
|
+
const filesOnly = options.resultMode === 'files'
|
|
2047
2191
|
let files = 0
|
|
2048
2192
|
let bytes = 0
|
|
2193
|
+
let skippedFiles = 0
|
|
2049
2194
|
let truncatedReason = ''
|
|
2050
2195
|
const stop = (reason) => {
|
|
2051
2196
|
if (truncatedReason === '') truncatedReason = reason
|
|
2052
2197
|
}
|
|
2053
2198
|
const visit = (directory, prefix) => {
|
|
2054
2199
|
if (truncatedReason !== '') return
|
|
2055
|
-
if (files >=
|
|
2200
|
+
if (files >= maxFiles) return stop('files')
|
|
2056
2201
|
if (bytes >= GREP_MAX_BYTES) return stop('bytes')
|
|
2057
|
-
if (Date.now() - started >
|
|
2202
|
+
if (Date.now() - started > deadline) return stop('deadline')
|
|
2203
|
+
if (options.job && options.job.cancelled) return stop('cancelled')
|
|
2058
2204
|
let listing
|
|
2059
2205
|
try {
|
|
2060
2206
|
listing = readdirSync(directory, { withFileTypes: true })
|
|
@@ -2063,7 +2209,8 @@ export function apply(ctx) {
|
|
|
2063
2209
|
}
|
|
2064
2210
|
for (const entry of listing) {
|
|
2065
2211
|
if (truncatedReason !== '') return
|
|
2066
|
-
if (
|
|
2212
|
+
if (options.job && options.job.cancelled) return stop('cancelled')
|
|
2213
|
+
if (grepDirectoryExcluded(entry.name, options.includeIgnored)) continue
|
|
2067
2214
|
const absolute = join(directory, entry.name)
|
|
2068
2215
|
const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
|
|
2069
2216
|
if (entry.isDirectory()) {
|
|
@@ -2071,21 +2218,26 @@ export function apply(ctx) {
|
|
|
2071
2218
|
continue
|
|
2072
2219
|
}
|
|
2073
2220
|
if (!entry.isFile()) continue
|
|
2074
|
-
if (files >=
|
|
2221
|
+
if (files >= maxFiles) return stop('files')
|
|
2075
2222
|
if (bytes >= GREP_MAX_BYTES) return stop('bytes')
|
|
2076
|
-
if (Date.now() - started >
|
|
2223
|
+
if (Date.now() - started > deadline) return stop('deadline')
|
|
2077
2224
|
files += 1
|
|
2078
2225
|
// Skip oversized files before reading them: pulling a 2 GB blob into
|
|
2079
2226
|
// memory to answer a text query would stall the whole Host.
|
|
2080
2227
|
try {
|
|
2081
|
-
if (statSync(absolute).size >
|
|
2228
|
+
if (statSync(absolute).size > maxFileBytes) {
|
|
2229
|
+
skippedFiles += 1
|
|
2230
|
+
continue
|
|
2231
|
+
}
|
|
2082
2232
|
} catch {
|
|
2233
|
+
skippedFiles += 1
|
|
2083
2234
|
continue
|
|
2084
2235
|
}
|
|
2085
2236
|
let data
|
|
2086
2237
|
try {
|
|
2087
2238
|
data = readFileSync(absolute)
|
|
2088
2239
|
} catch {
|
|
2240
|
+
skippedFiles += 1
|
|
2089
2241
|
continue
|
|
2090
2242
|
}
|
|
2091
2243
|
bytes += data.length
|
|
@@ -2093,12 +2245,25 @@ export function apply(ctx) {
|
|
|
2093
2245
|
const text = data.toString('utf8')
|
|
2094
2246
|
if (!matcher.test(text)) continue
|
|
2095
2247
|
if (entries.length >= maxResults) return stop('results')
|
|
2096
|
-
|
|
2097
|
-
|
|
2248
|
+
if (filesOnly) {
|
|
2249
|
+
entries.push({ path: absolute, relative, size: data.length, line: 0, preview: '', matches: countMatches(text, query, options) })
|
|
2250
|
+
} else {
|
|
2251
|
+
const hit = firstMatchLine(text, matcher)
|
|
2252
|
+
entries.push({ path: absolute, relative, size: data.length, line: hit.line, preview: hit.preview })
|
|
2253
|
+
}
|
|
2098
2254
|
}
|
|
2099
2255
|
}
|
|
2100
2256
|
visit(resolve(root), '')
|
|
2101
|
-
return {
|
|
2257
|
+
return {
|
|
2258
|
+
ok: true,
|
|
2259
|
+
query,
|
|
2260
|
+
entries,
|
|
2261
|
+
truncated: truncatedReason !== '',
|
|
2262
|
+
truncatedReason,
|
|
2263
|
+
scannedFiles: files,
|
|
2264
|
+
scannedBytes: bytes,
|
|
2265
|
+
skippedFiles,
|
|
2266
|
+
}
|
|
2102
2267
|
}
|
|
2103
2268
|
|
|
2104
2269
|
async function contentSearchRemote(remote, root, query, maxResults, options = {}) {
|
|
@@ -2120,17 +2285,26 @@ export function apply(ctx) {
|
|
|
2120
2285
|
if (normalized === '..' || normalized.startsWith('../')) throw new ApiError('BAD_REQUEST', '搜索路径超出工作区范围')
|
|
2121
2286
|
searchRoot = normalized === '' ? root : posix.join(root, normalized)
|
|
2122
2287
|
}
|
|
2123
|
-
const
|
|
2288
|
+
const ignores = options.includeIgnored
|
|
2289
|
+
? [...GREP_ALWAYS_EXCLUDED]
|
|
2290
|
+
: GREP_EXCLUDED_DIRS
|
|
2291
|
+
const excludes = ignores.map((dir) => `--exclude-dir=${shellQuoteArg(dir)}`).join(' ')
|
|
2124
2292
|
const pattern = useRegex ? `-E ${shellQuoteArg(query)}` : `-e ${shellQuoteArg(query)}`
|
|
2125
|
-
const
|
|
2293
|
+
const filesOnly = options.resultMode === 'files'
|
|
2294
|
+
const deadline = clampInt(options.timeoutMs, 500, GREP_DEADLINE_MAX, GREP_DEADLINE_MS)
|
|
2295
|
+
const listFlag = filesOnly ? 'Il' : 'In'
|
|
2296
|
+
const command = `grep -r${listFlag}${ignoreCase ? 'i' : ''} --binary-files=without-match ${excludes} ${pattern}`
|
|
2126
2297
|
+ ` -- ${shellQuoteArg(searchRoot)} 2>/dev/null | head -n ${maxResults + 1}`
|
|
2127
2298
|
let result
|
|
2128
2299
|
try {
|
|
2129
|
-
result = await remote.exec(command, { timeoutMs: 20000 })
|
|
2300
|
+
result = await remote.exec(command, { timeoutMs: Math.max(deadline + 2000, 20000) })
|
|
2130
2301
|
} catch (error) {
|
|
2131
2302
|
// A timeout means "we looked, but not everywhere": report it as a
|
|
2132
2303
|
// truncated result instead of failing the whole search.
|
|
2133
|
-
return {
|
|
2304
|
+
return {
|
|
2305
|
+
ok: true, query, entries: [], truncated: true, truncatedReason: 'deadline',
|
|
2306
|
+
scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
|
|
2307
|
+
}
|
|
2134
2308
|
}
|
|
2135
2309
|
if (result.code !== 0 && String(result.stdout || '').trim() === '') {
|
|
2136
2310
|
// grep exits 1 when nothing matched; a real failure has code > 1.
|
|
@@ -2139,30 +2313,187 @@ export function apply(ctx) {
|
|
|
2139
2313
|
if (result.code === 2 && /invalid/i.test(detail)) throw new ApiError('BAD_REQUEST', `正则表达式无效:${detail}`)
|
|
2140
2314
|
throw new ApiError('INTERNAL', `内容搜索失败:${detail}`)
|
|
2141
2315
|
}
|
|
2142
|
-
return {
|
|
2316
|
+
return {
|
|
2317
|
+
ok: true, query, entries: [], truncated: false, truncatedReason: '',
|
|
2318
|
+
scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
|
|
2319
|
+
}
|
|
2143
2320
|
}
|
|
2144
|
-
const lines = String(result.stdout || '').split('\n').filter((line) => line.trim() !== '')
|
|
2321
|
+
const lines = String(result.stdout || '').replace(/\r/g, '').split('\n').filter((line) => line.trim() !== '')
|
|
2145
2322
|
const entries = []
|
|
2323
|
+
const seen = new Set()
|
|
2146
2324
|
let truncatedReason = ''
|
|
2147
2325
|
for (const raw of lines) {
|
|
2148
2326
|
if (entries.length >= maxResults) {
|
|
2149
2327
|
truncatedReason = 'results'
|
|
2150
2328
|
break
|
|
2151
2329
|
}
|
|
2152
|
-
const
|
|
2153
|
-
if (!
|
|
2154
|
-
const file =
|
|
2330
|
+
const common = filesOnly ? /^(.*)$/.exec(raw) : /^(.*?):(\d+):(.*)$/.exec(raw)
|
|
2331
|
+
if (!common) continue
|
|
2332
|
+
const file = common[1]
|
|
2333
|
+
seen.add(file)
|
|
2155
2334
|
const relative = file.startsWith(`${searchRoot}/`) ? file.slice(searchRoot.length + 1) : file
|
|
2156
2335
|
entries.push({
|
|
2157
2336
|
path: file,
|
|
2158
2337
|
relative,
|
|
2159
2338
|
size: null,
|
|
2160
|
-
line: Number(
|
|
2161
|
-
preview:
|
|
2339
|
+
line: filesOnly ? 0 : Number(common[2]),
|
|
2340
|
+
preview: filesOnly ? '' : common[3].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS),
|
|
2162
2341
|
})
|
|
2163
2342
|
}
|
|
2164
2343
|
if (truncatedReason === '' && lines.length > maxResults) truncatedReason = 'results'
|
|
2165
|
-
return {
|
|
2344
|
+
return {
|
|
2345
|
+
ok: true,
|
|
2346
|
+
query,
|
|
2347
|
+
entries,
|
|
2348
|
+
truncated: truncatedReason !== '',
|
|
2349
|
+
truncatedReason,
|
|
2350
|
+
scannedFiles: seen.size,
|
|
2351
|
+
scannedBytes: 0,
|
|
2352
|
+
skippedFiles: 0,
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
// ── path completion (`fs.references`, 0.18.0) ─────────────────────────────
|
|
2357
|
+
// Ordering rule: an exact file name wins, then names that start with the
|
|
2358
|
+
// query, then anything else — shorter paths first inside each group, so the
|
|
2359
|
+
// obvious candidate is always at the top of the list.
|
|
2360
|
+
|
|
2361
|
+
function rankReferenceCandidates(list, needle, limit) {
|
|
2362
|
+
const scored = list.map((item) => {
|
|
2363
|
+
const name = item.name.toLowerCase()
|
|
2364
|
+
let score = 2
|
|
2365
|
+
if (name === needle) score = 0
|
|
2366
|
+
else if (name.startsWith(needle)) score = 1
|
|
2367
|
+
return { item, score }
|
|
2368
|
+
})
|
|
2369
|
+
scored.sort((left, right) => {
|
|
2370
|
+
if (left.score !== right.score) return left.score - right.score
|
|
2371
|
+
if (left.item.relative.length !== right.item.relative.length) {
|
|
2372
|
+
return left.item.relative.length - right.item.relative.length
|
|
2373
|
+
}
|
|
2374
|
+
return left.item.relative.localeCompare(right.item.relative)
|
|
2375
|
+
})
|
|
2376
|
+
return scored.slice(0, limit).map((entry) => entry.item)
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
function referenceCandidatesLocal(root, query, limit, options = {}) {
|
|
2380
|
+
const needle = query.toLowerCase()
|
|
2381
|
+
const started = Date.now()
|
|
2382
|
+
const hits = []
|
|
2383
|
+
let visited = 0
|
|
2384
|
+
let truncated = false
|
|
2385
|
+
const walk = (directory, prefix) => {
|
|
2386
|
+
if (truncated) return
|
|
2387
|
+
if (visited >= REFERENCE_MAX_ENTRIES || Date.now() - started > REFERENCE_DEADLINE_MS) {
|
|
2388
|
+
truncated = true
|
|
2389
|
+
return
|
|
2390
|
+
}
|
|
2391
|
+
let listing
|
|
2392
|
+
try {
|
|
2393
|
+
listing = readdirSync(directory, { withFileTypes: true })
|
|
2394
|
+
} catch {
|
|
2395
|
+
return
|
|
2396
|
+
}
|
|
2397
|
+
for (const entry of listing) {
|
|
2398
|
+
if (visited >= REFERENCE_MAX_ENTRIES || Date.now() - started > REFERENCE_DEADLINE_MS) {
|
|
2399
|
+
truncated = true
|
|
2400
|
+
return
|
|
2401
|
+
}
|
|
2402
|
+
if (grepDirectoryExcluded(entry.name, options.includeIgnored)) continue
|
|
2403
|
+
visited += 1
|
|
2404
|
+
const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
|
|
2405
|
+
if (entry.isDirectory()) {
|
|
2406
|
+
if (relative.toLowerCase().indexOf(needle) !== -1) {
|
|
2407
|
+
hits.push({ relative, name: entry.name, kind: 'directory' })
|
|
2408
|
+
}
|
|
2409
|
+
walk(join(directory, entry.name), relative)
|
|
2410
|
+
} else if (entry.isFile() && relative.toLowerCase().indexOf(needle) !== -1) {
|
|
2411
|
+
hits.push({ relative, name: entry.name, kind: 'file' })
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
walk(resolve(root), '')
|
|
2416
|
+
const candidates = rankReferenceCandidates(hits, needle, limit)
|
|
2417
|
+
return { ok: true, query, candidates, total: hits.length, truncated, scannedEntries: visited }
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
async function referenceCandidatesRemote(remote, root, query, limit, options = {}) {
|
|
2421
|
+
const needle = query.toLowerCase()
|
|
2422
|
+
const ignores = options.includeIgnored ? [...GREP_ALWAYS_EXCLUDED] : GREP_EXCLUDED_DIRS
|
|
2423
|
+
const excluded = ignores.length === 0
|
|
2424
|
+
? ''
|
|
2425
|
+
: ` | grep -Ev ${shellQuoteArg(ignores.map((dir) => `/${dir}/`).join('|'))}`
|
|
2426
|
+
const command = `find ${shellQuoteArg(root)} -mindepth 1 -printf '%y\\t%p\\n' 2>/dev/null`
|
|
2427
|
+
+ `${excluded} | head -n ${REFERENCE_MAX_ENTRIES + 1}`
|
|
2428
|
+
let result
|
|
2429
|
+
try {
|
|
2430
|
+
result = await remote.exec(command, { timeoutMs: 20000 })
|
|
2431
|
+
} catch {
|
|
2432
|
+
return { ok: true, query, candidates: [], total: 0, truncated: true, scannedEntries: 0 }
|
|
2433
|
+
}
|
|
2434
|
+
const rows = String(result.stdout || '').split('\n').filter((line) => line.indexOf('\t') !== -1)
|
|
2435
|
+
const truncated = rows.length > REFERENCE_MAX_ENTRIES
|
|
2436
|
+
const hits = []
|
|
2437
|
+
for (const row of rows.slice(0, REFERENCE_MAX_ENTRIES)) {
|
|
2438
|
+
const tab = row.indexOf('\t')
|
|
2439
|
+
const kindCode = row.slice(0, tab)
|
|
2440
|
+
const absolute = row.slice(tab + 1)
|
|
2441
|
+
const kind = kindCode === 'd' ? 'directory' : kindCode === 'f' ? 'file' : ''
|
|
2442
|
+
if (kind === '') continue
|
|
2443
|
+
const relative = absolute.startsWith(`${root}/`) ? absolute.slice(root.length + 1) : absolute
|
|
2444
|
+
if (relative.toLowerCase().indexOf(needle) === -1) continue
|
|
2445
|
+
hits.push({ relative, name: posix.basename(relative), kind })
|
|
2446
|
+
}
|
|
2447
|
+
return {
|
|
2448
|
+
ok: true,
|
|
2449
|
+
query,
|
|
2450
|
+
candidates: rankReferenceCandidates(hits, needle, limit),
|
|
2451
|
+
total: hits.length,
|
|
2452
|
+
truncated,
|
|
2453
|
+
scannedEntries: rows.length,
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
// ── remote command execution ──────────────────────────────────────────────
|
|
2458
|
+
|
|
2459
|
+
/**
|
|
2460
|
+
* Append-only audit trail for `hosts.exec` (0.17.0). Every attempt is logged,
|
|
2461
|
+
* refusals included, so a later "did the agent run anything?" question has an
|
|
2462
|
+
* answer even when the command never reached the host.
|
|
2463
|
+
*/
|
|
2464
|
+
const execAuditFile = () => join(dir, EXEC_AUDIT_NAME)
|
|
2465
|
+
|
|
2466
|
+
const rotateExecAudit = async () => {
|
|
2467
|
+
const file = execAuditFile()
|
|
2468
|
+
const info = await fsStat(file).catch(() => null)
|
|
2469
|
+
if (!info || info.size < EXEC_AUDIT_MAX_BYTES) return
|
|
2470
|
+
await rm(`${file}.1`, { force: true }).catch(() => {})
|
|
2471
|
+
await rename(file, `${file}.1`).catch(() => {})
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
const appendExecAudit = async (entry) => {
|
|
2475
|
+
const file = execAuditFile()
|
|
2476
|
+
const line = `${JSON.stringify(entry)}\n`
|
|
2477
|
+
try {
|
|
2478
|
+
await rotateExecAudit()
|
|
2479
|
+
await appendFile(file, line, { mode: 0o600 })
|
|
2480
|
+
} catch {
|
|
2481
|
+
// Auditing must not turn a successful command into a failure, but a
|
|
2482
|
+
// silently unwritable log is worse: surface it on stderr once.
|
|
2483
|
+
if (!appendExecAudit.warned) {
|
|
2484
|
+
appendExecAudit.warned = true
|
|
2485
|
+
console.error('[dsh-linked-workspace] cannot write the exec audit log')
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
const clipOutput = (text, budget) => {
|
|
2491
|
+
const value = String(text || '')
|
|
2492
|
+
return {
|
|
2493
|
+
text: value.length > budget ? value.slice(0, budget) : value,
|
|
2494
|
+
bytes: Buffer.byteLength(value, 'utf8'),
|
|
2495
|
+
truncated: value.length > budget,
|
|
2496
|
+
}
|
|
2166
2497
|
}
|
|
2167
2498
|
|
|
2168
2499
|
// ── method table ─────────────────────────────────────────────────────────
|
|
@@ -2308,6 +2639,133 @@ export function apply(ctx) {
|
|
|
2308
2639
|
return { disk: { path: target, size, used, avail, percent } }
|
|
2309
2640
|
},
|
|
2310
2641
|
|
|
2642
|
+
/**
|
|
2643
|
+
* Runs one non-interactive command on the remote host (0.17.0).
|
|
2644
|
+
*
|
|
2645
|
+
* Three gates must all pass: the feature switch, the host allow-list and —
|
|
2646
|
+
* when it is configured — the workspace allow-list. Every attempt, refusals
|
|
2647
|
+
* included, is written to `exec-audit.jsonl` before the caller hears back.
|
|
2648
|
+
*/
|
|
2649
|
+
async 'hosts.exec'(params = {}) {
|
|
2650
|
+
const settings = settingsStore.get()
|
|
2651
|
+
const startedAt = new Date().toISOString()
|
|
2652
|
+
const auditId = randomUUID()
|
|
2653
|
+
const command = String(typeof params.command === 'string' ? params.command : '').replace(/\r\n/g, '\n').trim()
|
|
2654
|
+
|
|
2655
|
+
let scope = null
|
|
2656
|
+
let host = null
|
|
2657
|
+
if (typeof params.linkedId === 'string' && params.linkedId.trim() !== '') {
|
|
2658
|
+
scope = await requireScope({ linkedId: params.linkedId })
|
|
2659
|
+
} else if (typeof params.remoteId === 'string' && params.remoteId.trim() !== '') {
|
|
2660
|
+
scope = await requireScope({ remoteId: params.remoteId })
|
|
2661
|
+
}
|
|
2662
|
+
if (scope) host = await findHost(scope.record.hostId)
|
|
2663
|
+
else if (typeof params.hostId === 'string' && params.hostId.trim() !== '') host = await findHost(params.hostId.trim())
|
|
2664
|
+
else throw new ApiError('BAD_REQUEST', 'hostId、linkedId 或 remoteId 三选一')
|
|
2665
|
+
|
|
2666
|
+
const hostId = host.id
|
|
2667
|
+
const hostName = host.name || host.host || hostId
|
|
2668
|
+
const kind = scope ? scope.kind : 'host'
|
|
2669
|
+
const workspaceId = scope && scope.record.workspaceId ? scope.record.workspaceId : ''
|
|
2670
|
+
|
|
2671
|
+
const audit = (extra) => appendExecAudit({
|
|
2672
|
+
ts: startedAt, auditId, hostId, hostName, workspaceId, kind, command, ...extra,
|
|
2673
|
+
})
|
|
2674
|
+
const denied = async (code, message) => {
|
|
2675
|
+
await audit({ refusal: code, message })
|
|
2676
|
+
return new ApiError(code, message)
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
if (settings.execEnabled !== true) {
|
|
2680
|
+
throw await denied('EXEC_DISABLED', '远端命令执行未启用:先到「设置 → 联动工作区 → 远端命令执行」打开开关,并把主机加入白名单')
|
|
2681
|
+
}
|
|
2682
|
+
if (!settings.execHostIds.includes(hostId)) {
|
|
2683
|
+
throw await denied('EXEC_HOST_NOT_ALLOWED', `主机「${hostName}」不在远端命令执行的白名单里`)
|
|
2684
|
+
}
|
|
2685
|
+
const workspaceAllow = settings.execWorkspaceIds
|
|
2686
|
+
if (workspaceAllow.length > 0) {
|
|
2687
|
+
const allowed = Boolean(scope)
|
|
2688
|
+
&& (workspaceAllow.includes(workspaceId) || workspaceAllow.includes(scope.record.id))
|
|
2689
|
+
if (!allowed) {
|
|
2690
|
+
const label = scope ? (scope.record.name || scope.record.id) : hostName
|
|
2691
|
+
throw await denied('EXEC_WORKSPACE_NOT_ALLOWED', `「${label}」不在远端命令执行的工作区白名单里`)
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
if (command === '') throw await denied('BAD_REQUEST', 'command 不能为空')
|
|
2695
|
+
if (command.length > EXEC_MAX_COMMAND) {
|
|
2696
|
+
throw await denied('BAD_REQUEST', `命令太长(上限 ${EXEC_MAX_COMMAND} 字符)`)
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2699
|
+
let cwd = scope ? scope.root : ''
|
|
2700
|
+
if (typeof params.cwd === 'string' && params.cwd.trim() !== '') {
|
|
2701
|
+
if (scope) {
|
|
2702
|
+
cwd = scopeTarget(scope, params.cwd)
|
|
2703
|
+
} else {
|
|
2704
|
+
const text = params.cwd.trim()
|
|
2705
|
+
if (!text.startsWith('/')) throw await denied('BAD_REQUEST', 'cwd 需要是绝对路径')
|
|
2706
|
+
cwd = posix.resolve(text)
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
|
|
2710
|
+
const timeoutMs = clampInt(params.timeoutMs, 1000, EXEC_TIMEOUT_MAX, settings.execTimeoutMs || EXEC_TIMEOUT_DEFAULT)
|
|
2711
|
+
const budget = clampInt(settings.execMaxOutputChars, 1000, EXEC_OUTPUT_MAX, EXEC_OUTPUT_DEFAULT)
|
|
2712
|
+
const perStream = Math.max(1000, Math.floor(budget / 2))
|
|
2713
|
+
const shell = settings.execShell ? String(settings.execShell) : ''
|
|
2714
|
+
const script = shell ? `${shell} -lc ${shellQuoteArg(command)}` : command
|
|
2715
|
+
const wrapped = cwd ? `cd ${shellQuoteArg(cwd)} && ${script}` : script
|
|
2716
|
+
|
|
2717
|
+
const started = Date.now()
|
|
2718
|
+
let result
|
|
2719
|
+
try {
|
|
2720
|
+
const remote = scope ? scope.remote : await connectHost(host)
|
|
2721
|
+
result = await remote.exec(wrapped, { timeoutMs })
|
|
2722
|
+
} catch (error) {
|
|
2723
|
+
const durationMs = Date.now() - started
|
|
2724
|
+
const timedOut = error && error.code === 'TIMEOUT'
|
|
2725
|
+
const message = error && error.message ? error.message : String(error)
|
|
2726
|
+
await audit({ cwd, exitCode: null, durationMs, error: message })
|
|
2727
|
+
if (timedOut) {
|
|
2728
|
+
throw new ApiError('EXEC_TIMEOUT', `命令超时(${timeoutMs} ms 后中止):${command.slice(0, 120)}`)
|
|
2729
|
+
}
|
|
2730
|
+
throw new ApiError('EXEC_FAILED', message)
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
const durationMs = Date.now() - started
|
|
2734
|
+
const out = clipOutput(result.stdout, perStream)
|
|
2735
|
+
const err = clipOutput(result.stderr, perStream)
|
|
2736
|
+
const exitCode = Number.isFinite(result.code) ? result.code : 0
|
|
2737
|
+
const truncated = out.truncated || err.truncated
|
|
2738
|
+
const stdoutHead = out.text.slice(0, EXEC_OUTPUT_HEAD)
|
|
2739
|
+
const stderrHead = err.text.slice(0, EXEC_OUTPUT_HEAD)
|
|
2740
|
+
await audit({
|
|
2741
|
+
cwd,
|
|
2742
|
+
exitCode,
|
|
2743
|
+
durationMs,
|
|
2744
|
+
stdoutBytes: out.bytes,
|
|
2745
|
+
stderrBytes: err.bytes,
|
|
2746
|
+
truncated,
|
|
2747
|
+
stdoutHead,
|
|
2748
|
+
stderrHead,
|
|
2749
|
+
})
|
|
2750
|
+
return {
|
|
2751
|
+
hostId,
|
|
2752
|
+
hostName,
|
|
2753
|
+
workspaceId,
|
|
2754
|
+
kind,
|
|
2755
|
+
command,
|
|
2756
|
+
cwd,
|
|
2757
|
+
exitCode,
|
|
2758
|
+
stdout: out.text,
|
|
2759
|
+
stderr: err.text,
|
|
2760
|
+
stdoutBytes: out.bytes,
|
|
2761
|
+
stderrBytes: err.bytes,
|
|
2762
|
+
truncated,
|
|
2763
|
+
durationMs,
|
|
2764
|
+
startedAt,
|
|
2765
|
+
auditId,
|
|
2766
|
+
}
|
|
2767
|
+
},
|
|
2768
|
+
|
|
2311
2769
|
async 'fs.list'(params = {}) {
|
|
2312
2770
|
const scope = await requireScope(params)
|
|
2313
2771
|
const target = params.path === undefined || params.path === ''
|
|
@@ -2764,7 +3222,12 @@ export function apply(ctx) {
|
|
|
2764
3222
|
* needs newer methods.
|
|
2765
3223
|
*/
|
|
2766
3224
|
async 'meta.info'() {
|
|
2767
|
-
return {
|
|
3225
|
+
return {
|
|
3226
|
+
version: PACKAGE_VERSION,
|
|
3227
|
+
apiRevision: API_REVISION,
|
|
3228
|
+
startedAt: STARTED_AT,
|
|
3229
|
+
execAuditFile: join(dir, EXEC_AUDIT_NAME),
|
|
3230
|
+
}
|
|
2768
3231
|
},
|
|
2769
3232
|
|
|
2770
3233
|
// ── settings ───────────────────────────────────────────────────────────
|
|
@@ -3233,19 +3696,59 @@ export function apply(ctx) {
|
|
|
3233
3696
|
const scope = await requireScope(params)
|
|
3234
3697
|
const query = typeof params.query === 'string' ? params.query.trim() : ''
|
|
3235
3698
|
const maxResults = Math.min(Math.max(Number(params.maxResults) || 200, 1), 1000)
|
|
3236
|
-
if (query === '')
|
|
3699
|
+
if (query === '') {
|
|
3700
|
+
return {
|
|
3701
|
+
ok: true, query: '', entries: [], truncated: false, truncatedReason: '',
|
|
3702
|
+
scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
|
|
3703
|
+
}
|
|
3704
|
+
}
|
|
3237
3705
|
if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
|
|
3238
3706
|
const side = params.side === 'local' ? 'local' : 'remote'
|
|
3239
3707
|
const options = {
|
|
3240
3708
|
path: typeof params.path === 'string' ? params.path : '',
|
|
3241
3709
|
ignoreCase: params.ignoreCase !== false,
|
|
3242
3710
|
regex: Boolean(params.regex),
|
|
3711
|
+
includeIgnored: params.includeIgnored === true,
|
|
3712
|
+
resultMode: params.resultMode === 'files' ? 'files' : 'lines',
|
|
3713
|
+
maxFiles: params.maxFiles,
|
|
3714
|
+
maxFileBytes: params.maxFileBytes,
|
|
3715
|
+
timeoutMs: params.timeoutMs,
|
|
3716
|
+
job: beginGrepJob(params.jobId),
|
|
3243
3717
|
}
|
|
3244
3718
|
if (side === 'remote') return await contentSearchRemote(scope.remote, scope.root, query, maxResults, options)
|
|
3245
3719
|
if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
|
|
3246
3720
|
return contentSearchLocal(scope.record.localPath, query, maxResults, options)
|
|
3247
3721
|
},
|
|
3248
3722
|
|
|
3723
|
+
/** Stop a running `fs.grep` (checked between files on the Host). */
|
|
3724
|
+
async 'fs.grepCancel'(params = {}) {
|
|
3725
|
+
const id = typeof params.jobId === 'string' ? params.jobId : ''
|
|
3726
|
+
const job = grepJobs.get(id)
|
|
3727
|
+
if (!job) return { cancelled: false }
|
|
3728
|
+
job.cancelled = true
|
|
3729
|
+
return { cancelled: true }
|
|
3730
|
+
},
|
|
3731
|
+
|
|
3732
|
+
/**
|
|
3733
|
+
* Path completion for `@`-style references (0.18.0). Returns candidate
|
|
3734
|
+
* paths relative to the remote root, best match first. Names only.
|
|
3735
|
+
*/
|
|
3736
|
+
async 'fs.references'(params = {}) {
|
|
3737
|
+
const scope = await requireScope(params)
|
|
3738
|
+
const query = typeof params.query === 'string' ? params.query.trim() : ''
|
|
3739
|
+
const limit = clampInt(params.limit, 1, REFERENCE_MAX_RESULTS, 50)
|
|
3740
|
+
const options = { includeIgnored: params.includeIgnored === true }
|
|
3741
|
+
if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
|
|
3742
|
+
if (query === '') {
|
|
3743
|
+
return { ok: true, query: '', candidates: [], total: 0, truncated: false, scannedEntries: 0 }
|
|
3744
|
+
}
|
|
3745
|
+
if (params.side === 'local') {
|
|
3746
|
+
if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
|
|
3747
|
+
return referenceCandidatesLocal(scope.record.localPath, query, limit, options)
|
|
3748
|
+
}
|
|
3749
|
+
return await referenceCandidatesRemote(scope.remote, scope.root, query, limit, options)
|
|
3750
|
+
},
|
|
3751
|
+
|
|
3249
3752
|
/**
|
|
3250
3753
|
* Read-only comparison of one directory pair. Lists files that exist on one
|
|
3251
3754
|
* side only and files whose size or mtime disagree; it never touches data.
|
|
@@ -3918,7 +4421,7 @@ export function apply(ctx) {
|
|
|
3918
4421
|
isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'stat'].includes(String((args && args.action) || '').trim()),
|
|
3919
4422
|
description:
|
|
3920
4423
|
'Read and edit files of a remote project over SSH: either a linked workspace (a local directory paired with a remote directory) or a remote workspace (a remote directory whose session runs in an empty local placeholder). '
|
|
3921
|
-
+ 'Actions: list (all linked and remote workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync (linked workspaces only). '
|
|
4424
|
+
+ 'Actions: list (all linked and remote workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync (linked workspaces only), exec (runs one non-interactive command on the remote host; needs the switch and allow-lists). '
|
|
3922
4425
|
+ '`path` is relative to the remote root (or an absolute path inside it). Writes are atomic; pass `if_modified_since` from a previous read/stat to refuse a stale overwrite. '
|
|
3923
4426
|
+ 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere. '
|
|
3924
4427
|
+ 'Local files of a linked workspace (including .local/ and .remote/) still use the normal read/write/bash tools.',
|
|
@@ -3927,8 +4430,8 @@ export function apply(ctx) {
|
|
|
3927
4430
|
properties: {
|
|
3928
4431
|
action: {
|
|
3929
4432
|
type: 'string',
|
|
3930
|
-
enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync'],
|
|
3931
|
-
description: 'Operation to perform. sync only applies to a linked workspace with mirroring on.',
|
|
4433
|
+
enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec', 'references'],
|
|
4434
|
+
description: 'Operation to perform. sync only applies to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists.',
|
|
3932
4435
|
},
|
|
3933
4436
|
workspace: {
|
|
3934
4437
|
type: 'string',
|
|
@@ -3945,6 +4448,11 @@ export function apply(ctx) {
|
|
|
3945
4448
|
replace_all: { type: 'boolean', description: 'Replace every occurrence (default: exactly one occurrence).' },
|
|
3946
4449
|
if_modified_since: { type: 'number', description: 'Epoch milliseconds from a previous read/stat; refuse the write when the remote mtime differs.' },
|
|
3947
4450
|
max_bytes: { type: 'number', description: 'Read cap in bytes for read/list_dir metadata (default 262144, max 524288).' },
|
|
4451
|
+
command: { type: 'string', description: 'Command line for exec (≤ 8000 characters). Runs non-interactively on the remote host.' },
|
|
4452
|
+
cwd: { type: 'string', description: 'Working directory for exec: relative to the workspace root (or an absolute path inside it).' },
|
|
4453
|
+
timeout_ms: { type: 'number', description: 'exec timeout in milliseconds (default from settings, max 600000).' },
|
|
4454
|
+
query: { type: 'string', description: 'Search text for references (matches the path, case-insensitive; ≤ 200 characters).' },
|
|
4455
|
+
limit: { type: 'number', description: 'How many candidates references returns (default 50, max 200).' },
|
|
3948
4456
|
},
|
|
3949
4457
|
required: ['action'],
|
|
3950
4458
|
},
|
|
@@ -4143,6 +4651,50 @@ export function apply(ctx) {
|
|
|
4143
4651
|
)
|
|
4144
4652
|
}
|
|
4145
4653
|
|
|
4654
|
+
if (action === 'exec') {
|
|
4655
|
+
const command = String((args && args.command) || '')
|
|
4656
|
+
if (command.trim() === '') throw new ApiError('BAD_REQUEST', 'command is required for exec')
|
|
4657
|
+
const request = { command, cwd: args.cwd, timeoutMs: args.timeout_ms }
|
|
4658
|
+
let result
|
|
4659
|
+
try {
|
|
4660
|
+
result = await methods['hosts.exec'](
|
|
4661
|
+
remoteKind ? { remoteId: link.id, ...request } : { linkedId: link.id, ...request },
|
|
4662
|
+
)
|
|
4663
|
+
} catch (error) {
|
|
4664
|
+
const apiError = asApiError(error)
|
|
4665
|
+
const gated = apiError.code === 'EXEC_DISABLED'
|
|
4666
|
+
|| apiError.code === 'EXEC_HOST_NOT_ALLOWED'
|
|
4667
|
+
|| apiError.code === 'EXEC_WORKSPACE_NOT_ALLOWED'
|
|
4668
|
+
const hint = gated
|
|
4669
|
+
? ' Remote command execution is opt-in: the switch and both allow-lists live in Settings → Linked workspaces → Remote command execution.'
|
|
4670
|
+
: ''
|
|
4671
|
+
return { text: `${LINKED_TOOL_NAME} failed: ${apiError.message}${hint}`, isError: true }
|
|
4672
|
+
}
|
|
4673
|
+
const cap = 20000
|
|
4674
|
+
const cut = (text) => (text.length > cap
|
|
4675
|
+
? `${text.slice(0, cap)}\n… ${text.length - cap} more characters (narrow the command with tail/grep)`
|
|
4676
|
+
: text)
|
|
4677
|
+
const lines = [`exit ${result.exitCode} after ${result.durationMs} ms · ${result.cwd || '(remote home)'}`]
|
|
4678
|
+
if (result.stdout.replace(/\s+$/, '') !== '') lines.push(`stdout:\n${cut(result.stdout.replace(/\s+$/, ''))}`)
|
|
4679
|
+
if (result.stderr.replace(/\s+$/, '') !== '') lines.push(`stderr:\n${cut(result.stderr.replace(/\s+$/, ''))}`)
|
|
4680
|
+
if (result.stdout.trim() === '' && result.stderr.trim() === '') lines.push('(no output)')
|
|
4681
|
+
return toolText(lines.join('\n'))
|
|
4682
|
+
}
|
|
4683
|
+
|
|
4684
|
+
if (action === 'references') {
|
|
4685
|
+
const query = String((args && args.query) || ((args && args.path) || ''))
|
|
4686
|
+
if (query.trim() === '') throw new ApiError('BAD_REQUEST', 'query is required for references')
|
|
4687
|
+
const result = await methods['fs.references'](
|
|
4688
|
+
remoteKind
|
|
4689
|
+
? { remoteId: link.id, query, limit: args.limit }
|
|
4690
|
+
: { linkedId: link.id, query, limit: args.limit },
|
|
4691
|
+
)
|
|
4692
|
+
if (result.candidates.length === 0) return toolText('(no matching path)')
|
|
4693
|
+
const lines = result.candidates.map((item) => `${item.kind === 'directory' ? 'dir ' : 'file'} ${item.relative}`)
|
|
4694
|
+
if (result.truncated) lines.push(`… stopped after ${result.scannedEntries} entries; narrow the query`)
|
|
4695
|
+
return toolText(lines.join('\n'))
|
|
4696
|
+
}
|
|
4697
|
+
|
|
4146
4698
|
throw new ApiError('BAD_REQUEST', `unknown action: ${action}`)
|
|
4147
4699
|
} catch (error) {
|
|
4148
4700
|
const apiError = asApiError(error)
|