dsh-linked-workspace 0.16.0 → 0.17.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 +25 -0
- package/README.en.md +16 -3
- package/README.md +17 -3
- package/docs/API.md +18 -4
- package/docs/VERIFY.md +21 -4
- package/lib/client.js +323 -12
- package/lib/index.js +374 -42
- 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 = 3
|
|
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',
|
|
@@ -106,6 +119,12 @@ const IMAGE_MIME = Object.freeze({
|
|
|
106
119
|
const MAX_NAME_LENGTH = 120
|
|
107
120
|
const CONNECT_TIMEOUT_MS = 20_000
|
|
108
121
|
const OP_TIMEOUT_MS = 60_000
|
|
122
|
+
// A failed probe only describes the moment it ran: a socket that never came up
|
|
123
|
+
// says nothing about the next request, which dials again. After this window the
|
|
124
|
+
// state degrades to "unknown" so a single glitch cannot paint a workspace red
|
|
125
|
+
// for the rest of the session. A live connection is different — when it drops,
|
|
126
|
+
// noteConnectionLost() records that, and the next success clears it.
|
|
127
|
+
const STATUS_TTL_MS = 60_000
|
|
109
128
|
// Directory listings are paged so a folder with tens of thousands of entries
|
|
110
129
|
// cannot stall the Host or flood the renderer.
|
|
111
130
|
const LIST_PAGE_SIZE = 500
|
|
@@ -153,6 +172,12 @@ const ERROR_STATUS = {
|
|
|
153
172
|
FS_EXISTS: 409,
|
|
154
173
|
CONFLICT: 409,
|
|
155
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,
|
|
156
181
|
}
|
|
157
182
|
|
|
158
183
|
class ApiError extends Error {
|
|
@@ -402,10 +427,32 @@ function isThemeId(value) {
|
|
|
402
427
|
return typeof value === 'string' && /^[a-z0-9][a-z0-9-]{0,39}$/.test(value)
|
|
403
428
|
}
|
|
404
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
|
+
|
|
405
452
|
class SettingsStore {
|
|
406
453
|
constructor(file) {
|
|
407
454
|
this.file = file
|
|
408
|
-
this.value = { ...SETTINGS_DEFAULTS }
|
|
455
|
+
this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [] }
|
|
409
456
|
const raw = readJsonFile(file, { version: SETTINGS_VERSION, settings: {} })
|
|
410
457
|
const settings = raw && typeof raw === 'object' && raw.settings && typeof raw.settings === 'object'
|
|
411
458
|
? raw.settings
|
|
@@ -416,6 +463,22 @@ class SettingsStore {
|
|
|
416
463
|
if (settings && typeof settings === 'object' && FILE_OPEN_MODES.has(settings.fileOpenMode)) {
|
|
417
464
|
this.value.fileOpenMode = settings.fileOpenMode
|
|
418
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
|
+
}
|
|
419
482
|
if (settings && typeof settings === 'object' && typeof settings.autoSave === 'boolean') {
|
|
420
483
|
this.value.autoSave = settings.autoSave
|
|
421
484
|
}
|
|
@@ -447,7 +510,11 @@ class SettingsStore {
|
|
|
447
510
|
}
|
|
448
511
|
|
|
449
512
|
get() {
|
|
450
|
-
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
|
+
}
|
|
451
518
|
}
|
|
452
519
|
|
|
453
520
|
update(patch = {}) {
|
|
@@ -475,6 +542,30 @@ class SettingsStore {
|
|
|
475
542
|
if (typeof patch.autoSave !== 'boolean') throw new ApiError('BAD_REQUEST', '自动保存设置无效')
|
|
476
543
|
this.value.autoSave = patch.autoSave
|
|
477
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
|
+
}
|
|
478
569
|
writeJsonAtomic(this.file, { version: SETTINGS_VERSION, settings: { ...this.value, themeExplicit: this.themeExplicit === true } })
|
|
479
570
|
return this.get()
|
|
480
571
|
}
|
|
@@ -1054,11 +1145,30 @@ export function apply(ctx) {
|
|
|
1054
1145
|
return runningCache.keys
|
|
1055
1146
|
}
|
|
1056
1147
|
|
|
1148
|
+
/**
|
|
1149
|
+
* Status as the UI should see it. A stale failure is reported as "unknown"
|
|
1150
|
+
* instead of "error": the connection is redialled on demand, so an old failed
|
|
1151
|
+
* attempt proves nothing about the workspace right now.
|
|
1152
|
+
*/
|
|
1153
|
+
const hostStatusView = (hostId) => {
|
|
1154
|
+
const status = pool.status(hostId)
|
|
1155
|
+
if (!status || typeof status.state !== 'string' || status.state === '') return { state: 'idle' }
|
|
1156
|
+
const checkedAt = typeof status.checkedAt === 'number' ? status.checkedAt : 0
|
|
1157
|
+
const fresh = checkedAt > 0 && Date.now() - checkedAt <= STATUS_TTL_MS
|
|
1158
|
+
if (status.state === 'error' && !fresh) return { state: 'idle', checkedAt }
|
|
1159
|
+
return {
|
|
1160
|
+
state: status.state,
|
|
1161
|
+
...(status.reason ? { reason: status.reason } : {}),
|
|
1162
|
+
...(status.message ? { message: status.message } : {}),
|
|
1163
|
+
...(typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
|
|
1164
|
+
...(checkedAt > 0 ? { checkedAt } : {}),
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1057
1168
|
const describeLink = (record, runningKeys) => {
|
|
1058
1169
|
const host = pool.host(record.hostId)
|
|
1059
1170
|
const snapshot = record.hostSnapshot || {}
|
|
1060
1171
|
const workspace = findWorkspaceByPath(linkedRegistry(), record.localPath)
|
|
1061
|
-
const status = pool.status(record.hostId)
|
|
1062
1172
|
return {
|
|
1063
1173
|
id: record.id,
|
|
1064
1174
|
name: record.name,
|
|
@@ -1074,12 +1184,7 @@ export function apply(ctx) {
|
|
|
1074
1184
|
createdAt: record.createdAt,
|
|
1075
1185
|
workspaceId: workspace ? String(workspace.id) : null,
|
|
1076
1186
|
workspaceTitle: workspace ? workspace.title : null,
|
|
1077
|
-
status:
|
|
1078
|
-
state: status ? status.state : 'idle',
|
|
1079
|
-
...(status && status.reason ? { reason: status.reason } : {}),
|
|
1080
|
-
...(status && status.message ? { message: status.message } : {}),
|
|
1081
|
-
...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
|
|
1082
|
-
},
|
|
1187
|
+
status: hostStatusView(record.hostId),
|
|
1083
1188
|
}
|
|
1084
1189
|
}
|
|
1085
1190
|
|
|
@@ -1089,7 +1194,6 @@ export function apply(ctx) {
|
|
|
1089
1194
|
const describeRemote = (record) => {
|
|
1090
1195
|
const host = pool.host(record.hostId)
|
|
1091
1196
|
const snapshot = record.hostSnapshot || {}
|
|
1092
|
-
const status = pool.status(record.hostId)
|
|
1093
1197
|
return {
|
|
1094
1198
|
id: record.id,
|
|
1095
1199
|
name: record.name,
|
|
@@ -1102,12 +1206,7 @@ export function apply(ctx) {
|
|
|
1102
1206
|
placeholderPath: record.placeholderPath,
|
|
1103
1207
|
workspaceId: record.workspaceId || null,
|
|
1104
1208
|
createdAt: record.createdAt,
|
|
1105
|
-
status:
|
|
1106
|
-
state: status ? status.state : 'idle',
|
|
1107
|
-
...(status && status.reason ? { reason: status.reason } : {}),
|
|
1108
|
-
...(status && status.message ? { message: status.message } : {}),
|
|
1109
|
-
...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
|
|
1110
|
-
},
|
|
1209
|
+
status: hostStatusView(record.hostId),
|
|
1111
1210
|
}
|
|
1112
1211
|
}
|
|
1113
1212
|
|
|
@@ -1436,8 +1535,9 @@ export function apply(ctx) {
|
|
|
1436
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).',
|
|
1437
1536
|
'- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
|
|
1438
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.',
|
|
1439
1539
|
'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere.',
|
|
1440
|
-
'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.',
|
|
1540
|
+
'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.',
|
|
1441
1541
|
'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.',
|
|
1442
1542
|
'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.',
|
|
1443
1543
|
].join('\n')
|
|
@@ -2151,6 +2251,48 @@ export function apply(ctx) {
|
|
|
2151
2251
|
return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
|
|
2152
2252
|
}
|
|
2153
2253
|
|
|
2254
|
+
// ── remote command execution ──────────────────────────────────────────────
|
|
2255
|
+
|
|
2256
|
+
/**
|
|
2257
|
+
* Append-only audit trail for `hosts.exec` (0.17.0). Every attempt is logged,
|
|
2258
|
+
* refusals included, so a later "did the agent run anything?" question has an
|
|
2259
|
+
* answer even when the command never reached the host.
|
|
2260
|
+
*/
|
|
2261
|
+
const execAuditFile = () => join(dir, EXEC_AUDIT_NAME)
|
|
2262
|
+
|
|
2263
|
+
const rotateExecAudit = async () => {
|
|
2264
|
+
const file = execAuditFile()
|
|
2265
|
+
const info = await fsStat(file).catch(() => null)
|
|
2266
|
+
if (!info || info.size < EXEC_AUDIT_MAX_BYTES) return
|
|
2267
|
+
await rm(`${file}.1`, { force: true }).catch(() => {})
|
|
2268
|
+
await rename(file, `${file}.1`).catch(() => {})
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
const appendExecAudit = async (entry) => {
|
|
2272
|
+
const file = execAuditFile()
|
|
2273
|
+
const line = `${JSON.stringify(entry)}\n`
|
|
2274
|
+
try {
|
|
2275
|
+
await rotateExecAudit()
|
|
2276
|
+
await appendFile(file, line, { mode: 0o600 })
|
|
2277
|
+
} catch {
|
|
2278
|
+
// Auditing must not turn a successful command into a failure, but a
|
|
2279
|
+
// silently unwritable log is worse: surface it on stderr once.
|
|
2280
|
+
if (!appendExecAudit.warned) {
|
|
2281
|
+
appendExecAudit.warned = true
|
|
2282
|
+
console.error('[dsh-linked-workspace] cannot write the exec audit log')
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
const clipOutput = (text, budget) => {
|
|
2288
|
+
const value = String(text || '')
|
|
2289
|
+
return {
|
|
2290
|
+
text: value.length > budget ? value.slice(0, budget) : value,
|
|
2291
|
+
bytes: Buffer.byteLength(value, 'utf8'),
|
|
2292
|
+
truncated: value.length > budget,
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2154
2296
|
// ── method table ─────────────────────────────────────────────────────────
|
|
2155
2297
|
|
|
2156
2298
|
const methods = {
|
|
@@ -2171,6 +2313,26 @@ export function apply(ctx) {
|
|
|
2171
2313
|
}
|
|
2172
2314
|
},
|
|
2173
2315
|
|
|
2316
|
+
/**
|
|
2317
|
+
* Cheap connection-state read for the sidebar. Reading it never dials, so the
|
|
2318
|
+
* client can poll it to keep the workspace cards honest: a dropped socket is
|
|
2319
|
+
* recorded by noteConnectionLost(), a successful request by connectHost().
|
|
2320
|
+
*/
|
|
2321
|
+
async 'hosts.status'(params = {}) {
|
|
2322
|
+
const requested = Array.isArray(params.hostIds) ? params.hostIds : null
|
|
2323
|
+
const ids = new Set()
|
|
2324
|
+
if (requested) {
|
|
2325
|
+
for (const id of requested) if (typeof id === 'string' && id !== '') ids.add(id)
|
|
2326
|
+
} else {
|
|
2327
|
+
for (const host of await refreshHosts()) ids.add(host.id)
|
|
2328
|
+
for (const record of linkedStore.list()) if (record && record.hostId) ids.add(record.hostId)
|
|
2329
|
+
for (const record of remoteStore.list()) if (record && record.hostId) ids.add(record.hostId)
|
|
2330
|
+
}
|
|
2331
|
+
const statuses = {}
|
|
2332
|
+
for (const id of ids) statuses[id] = hostStatusView(id)
|
|
2333
|
+
return { statuses }
|
|
2334
|
+
},
|
|
2335
|
+
|
|
2174
2336
|
/**
|
|
2175
2337
|
* Store a credential for one SSH host on this machine.
|
|
2176
2338
|
*
|
|
@@ -2274,6 +2436,133 @@ export function apply(ctx) {
|
|
|
2274
2436
|
return { disk: { path: target, size, used, avail, percent } }
|
|
2275
2437
|
},
|
|
2276
2438
|
|
|
2439
|
+
/**
|
|
2440
|
+
* Runs one non-interactive command on the remote host (0.17.0).
|
|
2441
|
+
*
|
|
2442
|
+
* Three gates must all pass: the feature switch, the host allow-list and —
|
|
2443
|
+
* when it is configured — the workspace allow-list. Every attempt, refusals
|
|
2444
|
+
* included, is written to `exec-audit.jsonl` before the caller hears back.
|
|
2445
|
+
*/
|
|
2446
|
+
async 'hosts.exec'(params = {}) {
|
|
2447
|
+
const settings = settingsStore.get()
|
|
2448
|
+
const startedAt = new Date().toISOString()
|
|
2449
|
+
const auditId = randomUUID()
|
|
2450
|
+
const command = String(typeof params.command === 'string' ? params.command : '').replace(/\r\n/g, '\n').trim()
|
|
2451
|
+
|
|
2452
|
+
let scope = null
|
|
2453
|
+
let host = null
|
|
2454
|
+
if (typeof params.linkedId === 'string' && params.linkedId.trim() !== '') {
|
|
2455
|
+
scope = await requireScope({ linkedId: params.linkedId })
|
|
2456
|
+
} else if (typeof params.remoteId === 'string' && params.remoteId.trim() !== '') {
|
|
2457
|
+
scope = await requireScope({ remoteId: params.remoteId })
|
|
2458
|
+
}
|
|
2459
|
+
if (scope) host = await findHost(scope.record.hostId)
|
|
2460
|
+
else if (typeof params.hostId === 'string' && params.hostId.trim() !== '') host = await findHost(params.hostId.trim())
|
|
2461
|
+
else throw new ApiError('BAD_REQUEST', 'hostId、linkedId 或 remoteId 三选一')
|
|
2462
|
+
|
|
2463
|
+
const hostId = host.id
|
|
2464
|
+
const hostName = host.name || host.host || hostId
|
|
2465
|
+
const kind = scope ? scope.kind : 'host'
|
|
2466
|
+
const workspaceId = scope && scope.record.workspaceId ? scope.record.workspaceId : ''
|
|
2467
|
+
|
|
2468
|
+
const audit = (extra) => appendExecAudit({
|
|
2469
|
+
ts: startedAt, auditId, hostId, hostName, workspaceId, kind, command, ...extra,
|
|
2470
|
+
})
|
|
2471
|
+
const denied = async (code, message) => {
|
|
2472
|
+
await audit({ refusal: code, message })
|
|
2473
|
+
return new ApiError(code, message)
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
if (settings.execEnabled !== true) {
|
|
2477
|
+
throw await denied('EXEC_DISABLED', '远端命令执行未启用:先到「设置 → 联动工作区 → 远端命令执行」打开开关,并把主机加入白名单')
|
|
2478
|
+
}
|
|
2479
|
+
if (!settings.execHostIds.includes(hostId)) {
|
|
2480
|
+
throw await denied('EXEC_HOST_NOT_ALLOWED', `主机「${hostName}」不在远端命令执行的白名单里`)
|
|
2481
|
+
}
|
|
2482
|
+
const workspaceAllow = settings.execWorkspaceIds
|
|
2483
|
+
if (workspaceAllow.length > 0) {
|
|
2484
|
+
const allowed = Boolean(scope)
|
|
2485
|
+
&& (workspaceAllow.includes(workspaceId) || workspaceAllow.includes(scope.record.id))
|
|
2486
|
+
if (!allowed) {
|
|
2487
|
+
const label = scope ? (scope.record.name || scope.record.id) : hostName
|
|
2488
|
+
throw await denied('EXEC_WORKSPACE_NOT_ALLOWED', `「${label}」不在远端命令执行的工作区白名单里`)
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
if (command === '') throw await denied('BAD_REQUEST', 'command 不能为空')
|
|
2492
|
+
if (command.length > EXEC_MAX_COMMAND) {
|
|
2493
|
+
throw await denied('BAD_REQUEST', `命令太长(上限 ${EXEC_MAX_COMMAND} 字符)`)
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
let cwd = scope ? scope.root : ''
|
|
2497
|
+
if (typeof params.cwd === 'string' && params.cwd.trim() !== '') {
|
|
2498
|
+
if (scope) {
|
|
2499
|
+
cwd = scopeTarget(scope, params.cwd)
|
|
2500
|
+
} else {
|
|
2501
|
+
const text = params.cwd.trim()
|
|
2502
|
+
if (!text.startsWith('/')) throw await denied('BAD_REQUEST', 'cwd 需要是绝对路径')
|
|
2503
|
+
cwd = posix.resolve(text)
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
const timeoutMs = clampInt(params.timeoutMs, 1000, EXEC_TIMEOUT_MAX, settings.execTimeoutMs || EXEC_TIMEOUT_DEFAULT)
|
|
2508
|
+
const budget = clampInt(settings.execMaxOutputChars, 1000, EXEC_OUTPUT_MAX, EXEC_OUTPUT_DEFAULT)
|
|
2509
|
+
const perStream = Math.max(1000, Math.floor(budget / 2))
|
|
2510
|
+
const shell = settings.execShell ? String(settings.execShell) : ''
|
|
2511
|
+
const script = shell ? `${shell} -lc ${shellQuoteArg(command)}` : command
|
|
2512
|
+
const wrapped = cwd ? `cd ${shellQuoteArg(cwd)} && ${script}` : script
|
|
2513
|
+
|
|
2514
|
+
const started = Date.now()
|
|
2515
|
+
let result
|
|
2516
|
+
try {
|
|
2517
|
+
const remote = scope ? scope.remote : await connectHost(host)
|
|
2518
|
+
result = await remote.exec(wrapped, { timeoutMs })
|
|
2519
|
+
} catch (error) {
|
|
2520
|
+
const durationMs = Date.now() - started
|
|
2521
|
+
const timedOut = error && error.code === 'TIMEOUT'
|
|
2522
|
+
const message = error && error.message ? error.message : String(error)
|
|
2523
|
+
await audit({ cwd, exitCode: null, durationMs, error: message })
|
|
2524
|
+
if (timedOut) {
|
|
2525
|
+
throw new ApiError('EXEC_TIMEOUT', `命令超时(${timeoutMs} ms 后中止):${command.slice(0, 120)}`)
|
|
2526
|
+
}
|
|
2527
|
+
throw new ApiError('EXEC_FAILED', message)
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2530
|
+
const durationMs = Date.now() - started
|
|
2531
|
+
const out = clipOutput(result.stdout, perStream)
|
|
2532
|
+
const err = clipOutput(result.stderr, perStream)
|
|
2533
|
+
const exitCode = Number.isFinite(result.code) ? result.code : 0
|
|
2534
|
+
const truncated = out.truncated || err.truncated
|
|
2535
|
+
const stdoutHead = out.text.slice(0, EXEC_OUTPUT_HEAD)
|
|
2536
|
+
const stderrHead = err.text.slice(0, EXEC_OUTPUT_HEAD)
|
|
2537
|
+
await audit({
|
|
2538
|
+
cwd,
|
|
2539
|
+
exitCode,
|
|
2540
|
+
durationMs,
|
|
2541
|
+
stdoutBytes: out.bytes,
|
|
2542
|
+
stderrBytes: err.bytes,
|
|
2543
|
+
truncated,
|
|
2544
|
+
stdoutHead,
|
|
2545
|
+
stderrHead,
|
|
2546
|
+
})
|
|
2547
|
+
return {
|
|
2548
|
+
hostId,
|
|
2549
|
+
hostName,
|
|
2550
|
+
workspaceId,
|
|
2551
|
+
kind,
|
|
2552
|
+
command,
|
|
2553
|
+
cwd,
|
|
2554
|
+
exitCode,
|
|
2555
|
+
stdout: out.text,
|
|
2556
|
+
stderr: err.text,
|
|
2557
|
+
stdoutBytes: out.bytes,
|
|
2558
|
+
stderrBytes: err.bytes,
|
|
2559
|
+
truncated,
|
|
2560
|
+
durationMs,
|
|
2561
|
+
startedAt,
|
|
2562
|
+
auditId,
|
|
2563
|
+
}
|
|
2564
|
+
},
|
|
2565
|
+
|
|
2277
2566
|
async 'fs.list'(params = {}) {
|
|
2278
2567
|
const scope = await requireScope(params)
|
|
2279
2568
|
const target = params.path === undefined || params.path === ''
|
|
@@ -2315,8 +2604,12 @@ export function apply(ctx) {
|
|
|
2315
2604
|
const target = scopeTarget(scope, params.path)
|
|
2316
2605
|
const stat = await scope.remote.stat(target)
|
|
2317
2606
|
if (stat.type === 'dir') throw new ApiError('FS_IS_DIR', '目标是目录,无法作为文件读取')
|
|
2318
|
-
|
|
2319
|
-
|
|
2607
|
+
// `preview` lifts the editor's 2 MB ceiling to the 8 MB read cap, so a
|
|
2608
|
+
// read-only preview (HTML pages, build logs) can show files the editor
|
|
2609
|
+
// refuses to edit. Editing stays capped at EDITABLE_LIMIT either way.
|
|
2610
|
+
const softLimit = params.preview === true ? READ_CAP : EDITABLE_LIMIT
|
|
2611
|
+
const limit = Math.min(Math.max(Number(params.maxBytes) || softLimit, 1024), READ_CAP)
|
|
2612
|
+
const tooLarge = stat.size > softLimit
|
|
2320
2613
|
const read = await scope.remote.readFile(target, { maxBytes: tooLarge ? Math.min(PEEK_LIMIT, limit) : limit })
|
|
2321
2614
|
const truncated = read.truncated || read.data.length < stat.size
|
|
2322
2615
|
const binary = looksBinary(read.data)
|
|
@@ -2726,7 +3019,12 @@ export function apply(ctx) {
|
|
|
2726
3019
|
* needs newer methods.
|
|
2727
3020
|
*/
|
|
2728
3021
|
async 'meta.info'() {
|
|
2729
|
-
return {
|
|
3022
|
+
return {
|
|
3023
|
+
version: PACKAGE_VERSION,
|
|
3024
|
+
apiRevision: API_REVISION,
|
|
3025
|
+
startedAt: STARTED_AT,
|
|
3026
|
+
execAuditFile: join(dir, EXEC_AUDIT_NAME),
|
|
3027
|
+
}
|
|
2730
3028
|
},
|
|
2731
3029
|
|
|
2732
3030
|
// ── settings ───────────────────────────────────────────────────────────
|
|
@@ -2868,7 +3166,8 @@ export function apply(ctx) {
|
|
|
2868
3166
|
throw mapLocalFsError(error)
|
|
2869
3167
|
}
|
|
2870
3168
|
if (info.isDirectory()) throw new ApiError('FS_IS_DIR', '目标是目录,无法作为文件读取')
|
|
2871
|
-
const
|
|
3169
|
+
const softLimit = params.preview === true ? READ_CAP : EDITABLE_LIMIT
|
|
3170
|
+
const tooLarge = info.size > softLimit
|
|
2872
3171
|
const cap = tooLarge ? PEEK_LIMIT : READ_CAP
|
|
2873
3172
|
// Read at most `cap` bytes. Reading the whole file first would pull
|
|
2874
3173
|
// multi-gigabyte files into Host memory (and on Windows readFileSync
|
|
@@ -3745,25 +4044,25 @@ export function apply(ctx) {
|
|
|
3745
4044
|
|
|
3746
4045
|
const host = await findHost(record.hostId)
|
|
3747
4046
|
const started = Date.now()
|
|
4047
|
+
let remote
|
|
4048
|
+
try {
|
|
4049
|
+
// connectHost() records the connection state itself: connected on
|
|
4050
|
+
// success, error only when the dialect really failed.
|
|
4051
|
+
remote = await connectHost(host)
|
|
4052
|
+
} catch (error) {
|
|
4053
|
+
const apiError = asApiError(error)
|
|
4054
|
+
return { ok: false, error: apiError.message, latencyMs: Date.now() - started }
|
|
4055
|
+
}
|
|
4056
|
+
const latencyMs = Date.now() - started
|
|
3748
4057
|
try {
|
|
3749
|
-
const remote = await connectHost(host)
|
|
3750
4058
|
const stat = await remote.stat(record.remotePath)
|
|
3751
|
-
|
|
3752
|
-
pool.setStatus(host.id, { state: 'connected', latencyMs })
|
|
3753
|
-
return {
|
|
3754
|
-
ok: true,
|
|
3755
|
-
latencyMs,
|
|
3756
|
-
exists: stat.type === 'dir',
|
|
3757
|
-
type: stat.type,
|
|
3758
|
-
}
|
|
4059
|
+
return { ok: true, latencyMs, exists: stat.type === 'dir', type: stat.type }
|
|
3759
4060
|
} catch (error) {
|
|
4061
|
+
// The host answered, so the link is fine; only this workspace's directory
|
|
4062
|
+
// is missing or unreadable. Reporting that as a connection error would
|
|
4063
|
+
// paint every other workspace on the same host red.
|
|
3760
4064
|
const apiError = asApiError(error)
|
|
3761
|
-
|
|
3762
|
-
return {
|
|
3763
|
-
ok: false,
|
|
3764
|
-
error: apiError.message,
|
|
3765
|
-
latencyMs: Date.now() - started,
|
|
3766
|
-
}
|
|
4065
|
+
return { ok: false, exists: false, error: apiError.message, latencyMs }
|
|
3767
4066
|
}
|
|
3768
4067
|
},
|
|
3769
4068
|
}
|
|
@@ -3879,7 +4178,7 @@ export function apply(ctx) {
|
|
|
3879
4178
|
isConcurrencySafe: (args) => ['list', 'info', 'list_dir', 'read', 'stat'].includes(String((args && args.action) || '').trim()),
|
|
3880
4179
|
description:
|
|
3881
4180
|
'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). '
|
|
3882
|
-
+ 'Actions: list (all linked and remote workspaces), info, list_dir, read, write, replace, stat, mkdir, rename, delete, sync (linked workspaces only). '
|
|
4181
|
+
+ '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). '
|
|
3883
4182
|
+ '`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. '
|
|
3884
4183
|
+ 'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere. '
|
|
3885
4184
|
+ 'Local files of a linked workspace (including .local/ and .remote/) still use the normal read/write/bash tools.',
|
|
@@ -3888,8 +4187,8 @@ export function apply(ctx) {
|
|
|
3888
4187
|
properties: {
|
|
3889
4188
|
action: {
|
|
3890
4189
|
type: 'string',
|
|
3891
|
-
enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync'],
|
|
3892
|
-
description: 'Operation to perform. sync only applies to a linked workspace with mirroring on.',
|
|
4190
|
+
enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec'],
|
|
4191
|
+
description: 'Operation to perform. sync only applies to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists.',
|
|
3893
4192
|
},
|
|
3894
4193
|
workspace: {
|
|
3895
4194
|
type: 'string',
|
|
@@ -3906,6 +4205,9 @@ export function apply(ctx) {
|
|
|
3906
4205
|
replace_all: { type: 'boolean', description: 'Replace every occurrence (default: exactly one occurrence).' },
|
|
3907
4206
|
if_modified_since: { type: 'number', description: 'Epoch milliseconds from a previous read/stat; refuse the write when the remote mtime differs.' },
|
|
3908
4207
|
max_bytes: { type: 'number', description: 'Read cap in bytes for read/list_dir metadata (default 262144, max 524288).' },
|
|
4208
|
+
command: { type: 'string', description: 'Command line for exec (≤ 8000 characters). Runs non-interactively on the remote host.' },
|
|
4209
|
+
cwd: { type: 'string', description: 'Working directory for exec: relative to the workspace root (or an absolute path inside it).' },
|
|
4210
|
+
timeout_ms: { type: 'number', description: 'exec timeout in milliseconds (default from settings, max 600000).' },
|
|
3909
4211
|
},
|
|
3910
4212
|
required: ['action'],
|
|
3911
4213
|
},
|
|
@@ -4104,6 +4406,36 @@ export function apply(ctx) {
|
|
|
4104
4406
|
)
|
|
4105
4407
|
}
|
|
4106
4408
|
|
|
4409
|
+
if (action === 'exec') {
|
|
4410
|
+
const command = String((args && args.command) || '')
|
|
4411
|
+
if (command.trim() === '') throw new ApiError('BAD_REQUEST', 'command is required for exec')
|
|
4412
|
+
const request = { command, cwd: args.cwd, timeoutMs: args.timeout_ms }
|
|
4413
|
+
let result
|
|
4414
|
+
try {
|
|
4415
|
+
result = await methods['hosts.exec'](
|
|
4416
|
+
remoteKind ? { remoteId: link.id, ...request } : { linkedId: link.id, ...request },
|
|
4417
|
+
)
|
|
4418
|
+
} catch (error) {
|
|
4419
|
+
const apiError = asApiError(error)
|
|
4420
|
+
const gated = apiError.code === 'EXEC_DISABLED'
|
|
4421
|
+
|| apiError.code === 'EXEC_HOST_NOT_ALLOWED'
|
|
4422
|
+
|| apiError.code === 'EXEC_WORKSPACE_NOT_ALLOWED'
|
|
4423
|
+
const hint = gated
|
|
4424
|
+
? ' Remote command execution is opt-in: the switch and both allow-lists live in Settings → Linked workspaces → Remote command execution.'
|
|
4425
|
+
: ''
|
|
4426
|
+
return { text: `${LINKED_TOOL_NAME} failed: ${apiError.message}${hint}`, isError: true }
|
|
4427
|
+
}
|
|
4428
|
+
const cap = 20000
|
|
4429
|
+
const cut = (text) => (text.length > cap
|
|
4430
|
+
? `${text.slice(0, cap)}\n… ${text.length - cap} more characters (narrow the command with tail/grep)`
|
|
4431
|
+
: text)
|
|
4432
|
+
const lines = [`exit ${result.exitCode} after ${result.durationMs} ms · ${result.cwd || '(remote home)'}`]
|
|
4433
|
+
if (result.stdout.replace(/\s+$/, '') !== '') lines.push(`stdout:\n${cut(result.stdout.replace(/\s+$/, ''))}`)
|
|
4434
|
+
if (result.stderr.replace(/\s+$/, '') !== '') lines.push(`stderr:\n${cut(result.stderr.replace(/\s+$/, ''))}`)
|
|
4435
|
+
if (result.stdout.trim() === '' && result.stderr.trim() === '') lines.push('(no output)')
|
|
4436
|
+
return toolText(lines.join('\n'))
|
|
4437
|
+
}
|
|
4438
|
+
|
|
4107
4439
|
throw new ApiError('BAD_REQUEST', `unknown action: ${action}`)
|
|
4108
4440
|
} catch (error) {
|
|
4109
4441
|
const apiError = asApiError(error)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-linked-workspace",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|