@fish-under-sea/dsh-ssh-fish 0.0.0-stage → 0.5.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.
Files changed (80) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +98 -2
  4. package/README.zh.md +99 -0
  5. package/cordis.patch.yml +12 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +16487 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +3511 -0
  10. package/lib/types/client/api.d.ts +141 -0
  11. package/lib/types/client/index.d.ts +37 -0
  12. package/lib/types/client/locales.d.ts +164 -0
  13. package/lib/types/client/native-panel.d.ts +70 -0
  14. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  15. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  16. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  17. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  18. package/lib/types/client/panel/TerminalTab.d.ts +22 -0
  19. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  20. package/lib/types/client/panel/TunnelsTab.d.ts +19 -0
  21. package/lib/types/client/panel/controller.d.ts +89 -0
  22. package/lib/types/client/panel/helpers.d.ts +45 -0
  23. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  24. package/lib/types/client/settings-binding.d.ts +61 -0
  25. package/lib/types/dsh-home.d.ts +16 -0
  26. package/lib/types/engine/cluster.d.ts +19 -0
  27. package/lib/types/engine/connection-pool.d.ts +112 -0
  28. package/lib/types/engine/proxy-command.d.ts +36 -0
  29. package/lib/types/engine/pty.d.ts +32 -0
  30. package/lib/types/engine/sftp.d.ts +20 -0
  31. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  32. package/lib/types/engine/tunnel.d.ts +36 -0
  33. package/lib/types/engine.d.ts +89 -0
  34. package/lib/types/http.d.ts +59 -0
  35. package/lib/types/index.d.ts +83 -0
  36. package/lib/types/loopback.d.ts +24 -0
  37. package/lib/types/mount-once.d.ts +55 -0
  38. package/lib/types/protocol.d.ts +239 -0
  39. package/lib/types/routes.d.ts +33 -0
  40. package/lib/types/ssh-config.d.ts +34 -0
  41. package/lib/types/store.d.ts +71 -0
  42. package/lib/types/tool-surface.d.ts +71 -0
  43. package/lib/types/tools.d.ts +42 -0
  44. package/package.json +106 -4
  45. package/src/client/api.ts +562 -0
  46. package/src/client/css-modules.d.ts +5 -0
  47. package/src/client/index.ts +137 -0
  48. package/src/client/locales.ts +338 -0
  49. package/src/client/native-panel.tsx +141 -0
  50. package/src/client/panel/ClusterTab.tsx +123 -0
  51. package/src/client/panel/HostFormDialog.tsx +258 -0
  52. package/src/client/panel/HostsTab.tsx +325 -0
  53. package/src/client/panel/SshPanel.tsx +90 -0
  54. package/src/client/panel/TerminalTab.tsx +330 -0
  55. package/src/client/panel/TransferTab.tsx +232 -0
  56. package/src/client/panel/TunnelsTab.tsx +244 -0
  57. package/src/client/panel/controller.ts +167 -0
  58. package/src/client/panel/helpers.ts +84 -0
  59. package/src/client/panel/panel.module.css +876 -0
  60. package/src/client/panel/xterm.css.ts +2 -0
  61. package/src/client/settings-binding.ts +165 -0
  62. package/src/dsh-home.ts +42 -0
  63. package/src/engine/cluster.ts +60 -0
  64. package/src/engine/connection-pool.ts +543 -0
  65. package/src/engine/proxy-command.ts +248 -0
  66. package/src/engine/pty.ts +78 -0
  67. package/src/engine/sftp.ts +226 -0
  68. package/src/engine/terminal-sessions.ts +280 -0
  69. package/src/engine/tunnel.ts +194 -0
  70. package/src/engine.ts +176 -0
  71. package/src/http.ts +127 -0
  72. package/src/index.ts +234 -0
  73. package/src/loopback.ts +63 -0
  74. package/src/mount-once.ts +142 -0
  75. package/src/protocol.ts +230 -0
  76. package/src/routes.ts +494 -0
  77. package/src/ssh-config.ts +153 -0
  78. package/src/store.ts +419 -0
  79. package/src/tool-surface.ts +95 -0
  80. package/src/tools.ts +404 -0
package/src/store.ts ADDED
@@ -0,0 +1,419 @@
1
+ /**
2
+ * Host config store: one JSON file (`$DSH_HOME/dsh-ssh.json`, defaulting
3
+ * to `~/.dsh`) holding every
4
+ * SSH host entry, written atomically (tmp + rename). Also parses the user's
5
+ * standard `~/.ssh/config` for one-shot import. Secrets (passwords,
6
+ * passphrases) live in this user-owned file in plaintext — same trust model
7
+ * as ssh-skill's annotated ssh-config comments; document it, never log it.
8
+ */
9
+
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
11
+ import { homedir } from 'node:os'
12
+ import { dirname, join, resolve } from 'node:path'
13
+ import { dshHome } from './dsh-home.ts'
14
+ import type { HostPayload, ImportResult, ImportSkipBlock, ImportSkipReason, SshHostEntry, SshHostSummary } from './protocol.ts'
15
+ import { readSshConfigBlocks } from './ssh-config.ts'
16
+
17
+ /** File format version. */
18
+ const FORMAT_VERSION = 1
19
+
20
+ /** Store file location: $DSH_HOME/dsh-ssh.json (defaults to ~/.dsh). */
21
+ export function storePath(): string {
22
+ return join(dshHome(), 'dsh-ssh.json')
23
+ }
24
+
25
+ /** The user's standard OpenSSH config path. */
26
+ export function sshConfigPath(): string {
27
+ return join(homedir(), '.ssh', 'config')
28
+ }
29
+
30
+ interface StoreFile {
31
+ version: number
32
+ hosts: SshHostEntry[]
33
+ }
34
+
35
+ /** Validate the wire shape of a host payload; returns a message or undefined. */
36
+ export function validateHostPayload(payload: unknown): string | undefined {
37
+ if (typeof payload !== 'object' || payload === null) return 'body must be a JSON object'
38
+ const p = payload as Record<string, unknown>
39
+ if (typeof p.host !== 'string' || p.host.trim() === '') return 'host is required'
40
+ if (typeof p.user !== 'string' || p.user.trim() === '') return 'user is required'
41
+ const auth = p.auth as Record<string, unknown> | undefined
42
+ if (auth !== undefined) {
43
+ if (typeof auth !== 'object' || auth === null) return 'auth must be an object'
44
+ if (auth.kind !== 'key' && auth.kind !== 'password' && auth.kind !== 'agent') return 'auth.kind must be key, password or agent'
45
+ if (auth.kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
46
+ return 'auth.keyPath is required for key auth'
47
+ }
48
+ if (auth.kind === 'password' && auth.password !== undefined && typeof auth.password !== 'string') {
49
+ return 'auth.password must be a string when provided'
50
+ }
51
+ if (auth.kind === 'agent' && auth.agentPath !== undefined && typeof auth.agentPath !== 'string') {
52
+ return 'auth.agentPath must be a string when provided'
53
+ }
54
+ }
55
+ if (p.port !== undefined && (typeof p.port !== 'number' || !Number.isInteger(p.port) || p.port < 1 || p.port > 65535)) {
56
+ return 'port must be an integer in 1..65535'
57
+ }
58
+ if (p.proxyJump !== undefined && (!Array.isArray(p.proxyJump) || p.proxyJump.some(x => typeof x !== 'string' || x === ''))) {
59
+ return 'proxyJump must be an array of alias strings'
60
+ }
61
+ if (p.proxyCommand !== undefined && typeof p.proxyCommand !== 'string') {
62
+ return 'proxyCommand must be a string when provided'
63
+ }
64
+ // OpenSSH resolves ProxyCommand and ProxyJump by "whichever appears first in
65
+ // the config"; a stored entry has no order, so the combination is rejected
66
+ // instead of silently picking one transport.
67
+ const proxyCommand = typeof p.proxyCommand === 'string' ? normalizeProxyCommand(p.proxyCommand) : undefined
68
+ const proxyJump = Array.isArray(p.proxyJump) ? p.proxyJump as string[] : []
69
+ if (proxyCommand !== undefined && proxyJump.length > 0) {
70
+ return 'proxyCommand and proxyJump cannot be combined — pick one transport per host'
71
+ }
72
+ if (p.tags !== undefined && (!Array.isArray(p.tags) || p.tags.some(x => typeof x !== 'string'))) {
73
+ return 'tags must be an array of strings'
74
+ }
75
+ return undefined
76
+ }
77
+
78
+ /** Alias grammar: letters/digits plus dots, hyphens, underscores (IP/domain aliases included). */
79
+ const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
80
+
81
+ /** Validate an alias for creation. */
82
+ export function validateAlias(alias: string): string | undefined {
83
+ if (!ALIAS_RE.test(alias)) return 'alias must be letters, digits, dots, hyphens or underscores'
84
+ return undefined
85
+ }
86
+
87
+ /**
88
+ * The host store. Pure file I/O — no cordis dependency, unit-testable.
89
+ */
90
+ export class HostStore {
91
+ /** The JSON file path. */
92
+ readonly path: string
93
+ /** Optional override of the ~/.ssh/config path (tests). */
94
+ private readonly sshConfigOverride: string | undefined
95
+
96
+ /**
97
+ * @param path - store file path (defaults to the standard location).
98
+ * @param sshConfigOverride - ssh config path override (tests only).
99
+ */
100
+ constructor(path?: string, sshConfigOverride?: string) {
101
+ this.path = resolve(path ?? storePath())
102
+ this.sshConfigOverride = sshConfigOverride
103
+ }
104
+
105
+ /** Load all entries (empty store when the file is absent). */
106
+ list(): SshHostEntry[] {
107
+ const file = this.load()
108
+ return file.hosts
109
+ }
110
+
111
+ /** Find one entry by alias. */
112
+ find(alias: string): SshHostEntry | undefined {
113
+ return this.list().find(entry => entry.alias === alias)
114
+ }
115
+
116
+ /** Secret-free projection for the browser and agent surfaces. */
117
+ summarize(entry: SshHostEntry): SshHostSummary {
118
+ let keyReady = true
119
+ if (entry.auth.kind === 'key' && entry.auth.keyPath) {
120
+ keyReady = existsSync(expandHome(entry.auth.keyPath))
121
+ } else if (entry.auth.kind === 'agent') {
122
+ keyReady = false
123
+ }
124
+ return {
125
+ alias: entry.alias,
126
+ host: entry.host,
127
+ port: entry.port,
128
+ user: entry.user,
129
+ auth: entry.auth.kind,
130
+ keyReady,
131
+ proxyJump: [...entry.proxyJump],
132
+ ...(entry.proxyCommand !== undefined ? { proxyCommand: entry.proxyCommand } : {}),
133
+ // Optional fields are spread conditionally: the tool bridge rejects
134
+ // undefined-valued properties as non-lossless JSON.
135
+ ...(entry.description !== undefined ? { description: entry.description } : {}),
136
+ ...(entry.environment !== undefined ? { environment: entry.environment } : {}),
137
+ tags: [...entry.tags],
138
+ ...(entry.location !== undefined ? { location: entry.location } : {}),
139
+ createdAt: entry.createdAt,
140
+ updatedAt: entry.updatedAt,
141
+ }
142
+ }
143
+
144
+ /** Create one entry. Throws on alias collision or invalid payload. */
145
+ create(payload: HostPayload): SshHostEntry {
146
+ const alias = payload.alias?.trim()
147
+ if (!alias) throw new Error('alias is required')
148
+ const aliasError = validateAlias(alias)
149
+ if (aliasError !== undefined) throw new Error(aliasError)
150
+ const bodyError = validateHostPayload(payload)
151
+ if (bodyError !== undefined) throw new Error(bodyError)
152
+ if (payload.auth === undefined) throw new Error('auth is required')
153
+ const file = this.load()
154
+ if (file.hosts.some(entry => entry.alias === alias)) throw new Error(`alias '${alias}' already exists`)
155
+ const now = Date.now()
156
+ const entry: SshHostEntry = {
157
+ alias,
158
+ host: payload.host.trim(),
159
+ port: payload.port ?? 22,
160
+ user: payload.user.trim(),
161
+ auth: {
162
+ kind: payload.auth.kind,
163
+ keyPath: payload.auth.kind === 'key' ? expandHome(payload.auth.keyPath?.trim() ?? '') : undefined,
164
+ passphrase: payload.auth.kind === 'key' ? payload.auth.passphrase ?? undefined : undefined,
165
+ password: payload.auth.kind === 'password' ? payload.auth.password : undefined,
166
+ agentPath: payload.auth.kind === 'agent' ? normalizeAgentPath(payload.auth.agentPath) : undefined,
167
+ },
168
+ proxyJump: [...(payload.proxyJump ?? [])],
169
+ proxyCommand: normalizeProxyCommand(payload.proxyCommand),
170
+ description: payload.description?.trim() || undefined,
171
+ environment: payload.environment?.trim() || undefined,
172
+ tags: [...(payload.tags ?? [])].map(tag => tag.trim()).filter(tag => tag !== ''),
173
+ location: payload.location?.trim() || undefined,
174
+ createdAt: now,
175
+ updatedAt: now,
176
+ }
177
+ file.hosts.push(entry)
178
+ this.save(file)
179
+ return entry
180
+ }
181
+
182
+ /** Update the fields present in `patch`; unknown aliases throw. */
183
+ update(alias: string, patch: Partial<HostPayload>): SshHostEntry {
184
+ const file = this.load()
185
+ const entry = file.hosts.find(candidate => candidate.alias === alias)
186
+ if (entry === undefined) throw new Error(`alias '${alias}' not found`)
187
+ // Partial-patch validation: only the present fields are checked (a
188
+ // caller may update just tags without resending host/user).
189
+ if (patch.host !== undefined && (typeof patch.host !== 'string' || patch.host.trim() === '')) {
190
+ throw new Error('host is required')
191
+ }
192
+ if (patch.user !== undefined && (typeof patch.user !== 'string' || patch.user.trim() === '')) {
193
+ throw new Error('user is required')
194
+ }
195
+ if (patch.port !== undefined && (typeof patch.port !== 'number' || !Number.isInteger(patch.port) || patch.port < 1 || patch.port > 65535)) {
196
+ throw new Error('port must be an integer in 1..65535')
197
+ }
198
+ if (patch.proxyJump !== undefined && (!Array.isArray(patch.proxyJump) || patch.proxyJump.some(x => typeof x !== 'string' || x === ''))) {
199
+ throw new Error('proxyJump must be an array of alias strings')
200
+ }
201
+ if (patch.proxyCommand !== undefined && typeof patch.proxyCommand !== 'string') {
202
+ throw new Error('proxyCommand must be a string when provided')
203
+ }
204
+ // The mutual exclusion is checked on the MERGED view: a patch that only
205
+ // adds one transport must not slip past a stored value of the other.
206
+ const mergedProxyCommand = patch.proxyCommand !== undefined
207
+ ? normalizeProxyCommand(patch.proxyCommand)
208
+ : entry.proxyCommand
209
+ if (mergedProxyCommand !== undefined && (patch.proxyJump ?? entry.proxyJump).length > 0) {
210
+ throw new Error('proxyCommand and proxyJump cannot be combined — pick one transport per host')
211
+ }
212
+ if (patch.tags !== undefined && (!Array.isArray(patch.tags) || patch.tags.some(x => typeof x !== 'string'))) {
213
+ throw new Error('tags must be an array of strings')
214
+ }
215
+ if (patch.host !== undefined) entry.host = patch.host.trim()
216
+ if (patch.port !== undefined) entry.port = patch.port
217
+ if (patch.user !== undefined) entry.user = patch.user.trim()
218
+ if (patch.auth !== undefined) {
219
+ const auth = patch.auth
220
+ if (auth.kind !== 'key' && auth.kind !== 'password' && auth.kind !== 'agent') throw new Error('auth.kind must be key, password or agent')
221
+ if (auth.kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
222
+ throw new Error('auth.keyPath is required for key auth')
223
+ }
224
+ if (auth.kind === 'password' && auth.password !== undefined && typeof auth.password !== 'string') {
225
+ throw new Error('auth.password must be a string when provided')
226
+ }
227
+ if (auth.kind === 'agent' && auth.agentPath !== undefined && typeof auth.agentPath !== 'string') {
228
+ throw new Error('auth.agentPath must be a string when provided')
229
+ }
230
+ // A changed key path with no passphrase means the new key has none;
231
+ // only keep the old passphrase when the key path is unchanged.
232
+ const keyChanged = auth.kind === 'key'
233
+ && auth.keyPath !== undefined
234
+ && expandHome(auth.keyPath.trim()) !== entry.auth.keyPath
235
+ entry.auth = {
236
+ kind: auth.kind,
237
+ keyPath: auth.kind === 'key' ? expandHome(auth.keyPath?.trim() ?? '') : undefined,
238
+ passphrase: auth.kind === 'key'
239
+ ? (auth.passphrase !== undefined ? auth.passphrase : (keyChanged ? undefined : entry.auth.passphrase))
240
+ : undefined,
241
+ password: auth.kind === 'password' ? auth.password : undefined,
242
+ agentPath: auth.kind === 'agent'
243
+ ? (auth.agentPath !== undefined ? normalizeAgentPath(auth.agentPath) : entry.auth.agentPath)
244
+ : undefined,
245
+ }
246
+ }
247
+ if (patch.proxyJump !== undefined) entry.proxyJump = [...patch.proxyJump]
248
+ if (patch.proxyCommand !== undefined) entry.proxyCommand = mergedProxyCommand
249
+ if (patch.description !== undefined) entry.description = patch.description.trim() || undefined
250
+ if (patch.environment !== undefined) entry.environment = patch.environment.trim() || undefined
251
+ if (patch.tags !== undefined) entry.tags = [...patch.tags].map(tag => tag.trim()).filter(tag => tag !== '')
252
+ if (patch.location !== undefined) entry.location = patch.location.trim() || undefined
253
+ entry.updatedAt = Date.now()
254
+ this.save(file)
255
+ return entry
256
+ }
257
+
258
+ /** Remove one entry. */
259
+ delete(alias: string): void {
260
+ const file = this.load()
261
+ const index = file.hosts.findIndex(candidate => candidate.alias === alias)
262
+ if (index < 0) throw new Error(`alias '${alias}' not found`)
263
+ file.hosts.splice(index, 1)
264
+ this.save(file)
265
+ }
266
+
267
+ /**
268
+ * Import hosts from `~/.ssh/config`: Host blocks with a single non-wildcard
269
+ * pattern become entries (a missing HostName falls back to the pattern
270
+ * itself; key auth via IdentityFile; jump hosts via ProxyJump; ProxyCommand
271
+ * kept verbatim). `Include` files are expanded, and `Match` blocks,
272
+ * wildcard patterns, and aliases that already exist are skipped with a
273
+ * reason instead of silently disappearing.
274
+ * @returns import statistics.
275
+ */
276
+ importFromSshConfig(): ImportResult {
277
+ // Per-run statistics: a later import must not report earlier runs' skips.
278
+ this.skippedBlocks = []
279
+ const configPath = this.sshConfigOverride ?? sshConfigPath()
280
+ if (!existsSync(configPath)) return { parsed: 0, added: 0, skipped: 0, skippedBlocks: [] }
281
+ const { blocks, skipped } = readSshConfigBlocks(configPath)
282
+ this.skippedBlocks = [...skipped]
283
+ const skip = (name: string, reason: ImportSkipReason): void => {
284
+ if (name === '') return
285
+ if (this.skippedBlocks.some(block => block.name === name)) return
286
+ this.skippedBlocks.push({ name, reason })
287
+ }
288
+ let added = 0
289
+ for (const block of blocks) {
290
+ const pattern = block.pattern.split(/\s+/)[0]
291
+ if (pattern.includes('*') || pattern.includes('?')) {
292
+ skip(pattern, 'wildcard')
293
+ continue
294
+ }
295
+ if (this.list().some(entry => entry.alias === pattern)) {
296
+ skip(pattern, 'existing')
297
+ continue
298
+ }
299
+ // A block without HostName is a usable OpenSSH entry: the Host pattern
300
+ // itself is the hostname.
301
+ const hostName = block.props.hostname !== undefined && block.props.hostname !== ''
302
+ ? block.props.hostname
303
+ : pattern
304
+ const payload: HostPayload = {
305
+ alias: pattern,
306
+ host: hostName,
307
+ port: block.props.port !== undefined ? Number.parseInt(block.props.port, 10) : 22,
308
+ user: block.props.user ?? process.env.USER ?? 'root',
309
+ auth: {
310
+ kind: block.props.identityfile !== undefined
311
+ ? 'key'
312
+ : block.props.identityagent !== undefined && block.props.identityagent.toLowerCase() !== 'none'
313
+ ? 'agent'
314
+ : 'password',
315
+ keyPath: block.props.identityfile,
316
+ password: block.props.password,
317
+ agentPath: block.props.identityagent !== undefined && block.props.identityagent.toLowerCase() !== 'none'
318
+ ? normalizeAgentPath(block.props.identityagent)
319
+ : undefined,
320
+ },
321
+ proxyJump: block.props.proxyjump !== undefined
322
+ ? block.props.proxyjump.split(',').map(hop => hop.trim()).filter(hop => hop !== '')
323
+ : [],
324
+ proxyCommand: block.props.proxycommand,
325
+ description: block.props.description,
326
+ environment: block.props.environment,
327
+ tags: (block.props.tags ?? '').split(',').map(tag => tag.trim()).filter(tag => tag !== ''),
328
+ location: block.props.location,
329
+ }
330
+ try {
331
+ this.create(payload)
332
+ added += 1
333
+ } catch {
334
+ // Unusable entry (bad alias grammar, conflicting transports, ...).
335
+ skip(pattern, 'invalid')
336
+ }
337
+ }
338
+ return { parsed: blocks.length, added, skipped: this.skippedBlocks.length, skippedBlocks: [...this.skippedBlocks] }
339
+ }
340
+
341
+ private skippedBlocks: ImportSkipBlock[] = []
342
+
343
+ /**
344
+ * Last parsed store keyed by file identity. list/find ride every acquire
345
+ * and GUI refresh; re-reading and re-parsing the whole file each call is
346
+ * wasted work when the file has not changed. Any save invalidates.
347
+ */
348
+ private cache: { mtimeMs: number; size: number; file: StoreFile } | undefined
349
+
350
+ private load(): StoreFile {
351
+ let stats: { mtimeMs: number; size: number }
352
+ try {
353
+ stats = statSync(this.path)
354
+ } catch {
355
+ this.cache = undefined
356
+ return { version: FORMAT_VERSION, hosts: [] }
357
+ }
358
+ if (this.cache !== undefined && this.cache.mtimeMs === stats.mtimeMs && this.cache.size === stats.size) {
359
+ return this.cache.file
360
+ }
361
+ try {
362
+ const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as StoreFile
363
+ if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.hosts)) {
364
+ throw new Error('store file shape invalid')
365
+ }
366
+ this.cache = { mtimeMs: stats.mtimeMs, size: stats.size, file: parsed }
367
+ return parsed
368
+ } catch {
369
+ // A corrupt store must not brick the plugin — and must not be silently
370
+ // overwritten by the next save: rename it aside for manual recovery
371
+ // (the plugin then starts from an empty list).
372
+ this.cache = undefined
373
+ try {
374
+ renameSync(this.path, `${this.path}.corrupt-${Date.now()}`)
375
+ } catch { /* best effort */ }
376
+ return { version: FORMAT_VERSION, hosts: [] }
377
+ }
378
+ }
379
+
380
+ private save(file: StoreFile): void {
381
+ const dir = dirname(this.path)
382
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
383
+ const tmp = this.path + '.tmp'
384
+ // Secrets live in this file: keep it readable by the owner only. The
385
+ // tmp file carries the 0600 mode through the rename.
386
+ writeFileSync(tmp, JSON.stringify(file, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
387
+ renameSync(tmp, this.path)
388
+ this.cache = undefined
389
+ }
390
+ }
391
+
392
+ /** Normalize an agent endpoint for storage: trim, expand `~`, and resolve the SSH_AUTH_SOCK token. */
393
+ export function normalizeAgentPath(agentPath: string | undefined): string | undefined {
394
+ const trimmed = agentPath?.trim()
395
+ if (trimmed === undefined || trimmed === '') return undefined
396
+ if (trimmed === 'SSH_AUTH_SOCK' || trimmed === '$SSH_AUTH_SOCK') {
397
+ const sock = process.env.SSH_AUTH_SOCK
398
+ return sock !== undefined && sock !== '' ? sock : undefined
399
+ }
400
+ return expandHome(trimmed)
401
+ }
402
+
403
+ /**
404
+ * Normalize a ProxyCommand for storage: trim, and treat an empty value or
405
+ * OpenSSH's `none` keyword as "no proxy command" (an explicit clear).
406
+ */
407
+ export function normalizeProxyCommand(raw: string | undefined): string | undefined {
408
+ const trimmed = raw?.trim()
409
+ if (trimmed === undefined || trimmed === '') return undefined
410
+ if (trimmed.toLowerCase() === 'none') return undefined
411
+ return trimmed
412
+ }
413
+
414
+ /** Expand a leading `~` in a filesystem path. */
415
+ export function expandHome(path: string): string {
416
+ if (path === '~') return homedir()
417
+ if (path.startsWith('~/')) return join(homedir(), path.slice(2))
418
+ return path
419
+ }
@@ -0,0 +1,95 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/tool-surface.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Family-shared tool-surface conventions for the packages that register
4
+ * model-facing tools.
5
+ *
6
+ * One home for the prompt-section placement and the visibility gate this
7
+ * family previously restated per package.
8
+ *
9
+ * Modelled on the official tool packages:
10
+ * - `@deepseek-ai/dsh-tool-subagent` renders its section through
11
+ * `tools.get(name, context.scope) === undefined ? '' : text`, so guidance
12
+ * disappears together with a restricted tool.
13
+ * - 21 of the 22 official tool packages register their tools GLOBALLY and gate
14
+ * them with a setting, not per agent. Only the Agent Teams tool package —
15
+ * whose tools belong to one membership — installs into each `agent.ctx`.
16
+ * This family follows the majority: registration stays global so the
17
+ * registry's per-scope `restrict()` mask (which filters inherited global
18
+ * tools and REJECTS scope-local names) can still withhold these tools.
19
+ *
20
+ * Structural types only: this copy lands in packages that do not all depend on
21
+ * the same SDK service packages.
22
+ */
23
+
24
+ /**
25
+ * Prompt-section order for each package's tool guidance.
26
+ *
27
+ * These sit in the family band between the deployment persona and the SDK's
28
+ * `PLAN_POLICY` (500). Values are owned here rather than written per package so
29
+ * the host plugins whose guidance shares one prompt cannot drift into an
30
+ * accidental tie.
31
+ */
32
+ export const PLUGIN_TOOL_SECTION_ORDERS = {
33
+ ssh: 150,
34
+ 'task-board': 200,
35
+ } as const
36
+
37
+ /** One plugin id keyed by {@link PLUGIN_TOOL_SECTION_ORDERS}. */
38
+ export type PluginToolSectionId = keyof typeof PLUGIN_TOOL_SECTION_ORDERS
39
+
40
+ /**
41
+ * Order of an external provider extension's own guidance section, right after
42
+ * the band of the plugin it extends.
43
+ *
44
+ * An extension names itself, not the plugin it plugs into, so its order stays
45
+ * out of {@link PLUGIN_TOOL_SECTION_ORDERS}: every package's copy of this module
46
+ * then carries no provider id. The slot still has one owner and cannot collide
47
+ * with a host plugin's band.
48
+ */
49
+ export const EXTENSION_TOOL_SECTION_ORDER = 210
50
+
51
+ /**
52
+ * The scoped tool lookup a section provider needs: the registry read for one
53
+ * assembly's scope. Matches `ctx.tools.get(name, scope)`.
54
+ */
55
+ export interface ScopedToolLookup {
56
+ get(name: string, scope?: unknown): unknown
57
+ }
58
+
59
+ /** One assembly context carrying the scope the section is rendered for. */
60
+ export interface SectionScopeContext {
61
+ scope?: unknown
62
+ }
63
+
64
+ /**
65
+ * Build a section provider that renders \`text\` only while at least one of
66
+ * \`toolNames\` is visible to the rendering scope.
67
+ *
68
+ * The native convention: a tool that a restriction, a preset, or a missing
69
+ * registry removed must not leave guidance behind telling the model to call it.
70
+ * An unreadable registry renders the text unchanged — guidance that outlives a
71
+ * momentary read failure is recoverable; guidance for a tool that is gone is
72
+ * not.
73
+ * @param tools - the scoped tool registry, when the deployment serves one.
74
+ * @param toolNames - registered names the guidance describes.
75
+ * @param text - the guidance rendered while they are reachable.
76
+ * @returns the section text provider.
77
+ */
78
+ export function visibleToolText(
79
+ tools: ScopedToolLookup | undefined,
80
+ toolNames: readonly string[],
81
+ text: string,
82
+ ): (context: SectionScopeContext) => string {
83
+ if (tools === undefined) return () => text
84
+ return (context: SectionScopeContext) => {
85
+ for (const name of toolNames) {
86
+ try {
87
+ if (tools.get(name, context.scope) !== undefined) return text
88
+ } catch {
89
+ // A refused lookup is not proof the tool is gone; keep the guidance.
90
+ return text
91
+ }
92
+ }
93
+ return ''
94
+ }
95
+ }