dsh-remote 0.8.90 → 0.8.92

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 (139) hide show
  1. package/README.en.md +1 -0
  2. package/README.md +1 -0
  3. package/lib/client.js +184 -70
  4. package/lib/credential.js +7 -0
  5. package/lib/index.js +125 -31
  6. package/lib/openssh.js +60 -1
  7. package/lib/pool.js +127 -68
  8. package/lib/posix-shell.cjs +34 -0
  9. package/lib/remote-shell-child.cjs +8 -11
  10. package/lib/remote-skills.js +312 -0
  11. package/lib/routes-fs.js +6 -0
  12. package/lib/routes-misc.js +38 -1
  13. package/lib/web-attach.js +17 -7
  14. package/package.json +11 -8
  15. package/node_modules/buildcheck/.eslintrc.js +0 -5
  16. package/node_modules/buildcheck/.github/workflows/ci.yml +0 -88
  17. package/node_modules/buildcheck/.github/workflows/lint.yml +0 -27
  18. package/node_modules/buildcheck/.npmignore +0 -3
  19. package/node_modules/buildcheck/LICENSE +0 -19
  20. package/node_modules/buildcheck/README.md +0 -106
  21. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +0 -250
  22. package/node_modules/buildcheck/lib/findvs.js +0 -361
  23. package/node_modules/buildcheck/lib/index.js +0 -738
  24. package/node_modules/buildcheck/package.json +0 -36
  25. package/node_modules/buildcheck/test/test.js +0 -8
  26. package/node_modules/cpu-features/.eslintrc.js +0 -5
  27. package/node_modules/cpu-features/.github/workflows/ci.yml +0 -74
  28. package/node_modules/cpu-features/.github/workflows/lint.yml +0 -27
  29. package/node_modules/cpu-features/LICENSE +0 -19
  30. package/node_modules/cpu-features/README.md +0 -59
  31. package/node_modules/cpu-features/binding.gyp +0 -16
  32. package/node_modules/cpu-features/buildcheck.js +0 -32
  33. package/node_modules/cpu-features/deps/cpu_features/.clang-format +0 -4
  34. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +0 -31
  35. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +0 -5
  36. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +0 -30
  37. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +0 -22
  38. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +0 -26
  39. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +0 -31
  40. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +0 -43
  41. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +0 -25
  42. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +0 -31
  43. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +0 -24
  44. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +0 -30
  45. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +0 -29
  46. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +0 -28
  47. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +0 -27
  48. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +0 -21
  49. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +0 -329
  50. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +0 -261
  51. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +0 -23
  52. package/node_modules/cpu-features/deps/cpu_features/LICENSE +0 -230
  53. package/node_modules/cpu-features/deps/cpu_features/README.md +0 -272
  54. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +0 -19
  55. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +0 -5
  56. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +0 -11
  57. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +0 -3
  58. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +0 -3
  59. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +0 -30
  60. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +0 -252
  61. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +0 -40
  62. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +0 -64
  63. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +0 -312
  64. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +0 -7
  65. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +0 -48
  66. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +0 -34
  67. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +0 -22
  68. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +0 -11
  69. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +0 -107
  70. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +0 -15
  71. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +0 -105
  72. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +0 -54
  73. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +0 -384
  74. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +0 -259
  75. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +0 -121
  76. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +0 -74
  77. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +0 -149
  78. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +0 -72
  79. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +0 -108
  80. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +0 -288
  81. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +0 -40
  82. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +0 -37
  83. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +0 -39
  84. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +0 -240
  85. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +0 -49
  86. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +0 -110
  87. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +0 -70
  88. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +0 -60
  89. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +0 -4
  90. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +0 -205
  91. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +0 -320
  92. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +0 -12
  93. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +0 -456
  94. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +0 -165
  95. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +0 -75
  96. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +0 -490
  97. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +0 -79
  98. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +0 -19
  99. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +0 -86
  100. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +0 -26
  101. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +0 -22
  102. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +0 -62
  103. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +0 -169
  104. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +0 -88
  105. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +0 -79
  106. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +0 -82
  107. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +0 -138
  108. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +0 -212
  109. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +0 -93
  110. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +0 -163
  111. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +0 -111
  112. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +0 -120
  113. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +0 -2055
  114. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +0 -68
  115. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +0 -58
  116. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +0 -57
  117. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +0 -58
  118. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +0 -132
  119. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +0 -192
  120. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +0 -461
  121. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +0 -114
  122. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +0 -53
  123. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +0 -396
  124. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +0 -384
  125. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +0 -176
  126. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +0 -131
  127. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +0 -180
  128. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +0 -82
  129. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +0 -1729
  130. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +0 -103
  131. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +0 -61
  132. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +0 -52
  133. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +0 -31
  134. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +0 -132
  135. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +0 -202
  136. package/node_modules/cpu-features/lib/index.js +0 -5
  137. package/node_modules/cpu-features/package.json +0 -40
  138. package/node_modules/cpu-features/src/binding.cc +0 -151
  139. package/node_modules/cpu-features/test/test.js +0 -12
package/lib/index.js CHANGED
@@ -69,6 +69,7 @@ import { createUpdateRoutes } from './routes-update.js'
69
69
  import { createWebAttachRoutes } from './routes-web-attach.js'
70
70
  import { createWorkspaceRoutes } from './routes-workspace.js'
71
71
  import { listDirStructured, removeRemoteTree } from './remote-fs.js'
72
+ import { registerRemoteSkills } from './remote-skills.js'
72
73
 
73
74
  export const name = 'dsh-remote'
74
75
 
@@ -451,6 +452,8 @@ const machineId = _machineId
451
452
  // ── host-key registry (TOFU) ──────────────────────────────────────────────
452
453
  const KNOWN_HOSTS_FILE = 'known_hosts.json'
453
454
  const knownHostsFile = () => path.join(remoteWorkspacesRoot(), KNOWN_HOSTS_FILE)
455
+ // OpenSSH must append plain known_hosts lines, never the native JSON registry.
456
+ const opensshKnownHostsFile = () => path.join(remoteWorkspacesRoot(), 'known_hosts')
454
457
  const isHostKeyKnown = (host, port) => _isHostKeyKnown(knownHostsFile(), host, port)
455
458
 
456
459
  // ── encoding helpers ───────────────────────────────────────────────────────
@@ -469,7 +472,7 @@ function encodeText(s, enc) {
469
472
  export async function apply(ctx, config) {
470
473
  // The ACTIVE pool: a delegating facade, because `backend` is per machine and
471
474
  // the plugin must keep ONE long-lived object to hang its hooks on (issue #51).
472
- const pool = new ActivePool(config, { knownHostsFile })
475
+ const pool = new ActivePool(config, { knownHostsFile, opensshKnownHostsFile })
473
476
  ctx.effect(() => () => pool.close(), 'dsh-remote.close')
474
477
 
475
478
  migrateLegacyData()
@@ -986,7 +989,7 @@ export async function apply(ctx, config) {
986
989
  // session passes its own mirror-resolved remote path explicitly.
987
990
  workspace: '',
988
991
  })
989
- const created = new ActivePool(poolConfig, { knownHostsFile })
992
+ const created = new ActivePool(poolConfig, { knownHostsFile, opensshKnownHostsFile })
990
993
  // Keychain-backed passwords resolve against THIS pool's machine record.
991
994
  created.passwordResolver = async () => machinePassword(eff || { id: '', password: poolConfig.password })
992
995
  machinePools.set(key, created)
@@ -1269,6 +1272,7 @@ export async function apply(ctx, config) {
1269
1272
  }
1270
1273
  }
1271
1274
  saveSyncState(localDir, next)
1275
+ if (remoteSkills) remoteSkills.invalidate()
1272
1276
  }
1273
1277
  const startAutoPush = (localDir) => {
1274
1278
  if (!config.autoPush || autoPushWatchers.has(localDir)) return
@@ -1378,6 +1382,15 @@ export async function apply(ctx, config) {
1378
1382
  * session switching machines cannot redirect this session's commands. */
1379
1383
  const resolveMirrorForLocal = (local) => resolveMirror(local, remoteWorkspacesRoot())
1380
1384
 
1385
+ // Issue #120: project skills live on the REMOTE host, not only in the local
1386
+ // mirror. The optional provider supplements (never replaces) the core's local
1387
+ // filesystem provider and is inert on hosts without the skills service.
1388
+ const remoteSkills = registerRemoteSkills(ctx, {
1389
+ resolveBinding: resolveMirrorForLocal,
1390
+ poolForMachine,
1391
+ logger: typeof ctx.get === 'function' ? ctx.get('logger') : undefined,
1392
+ })
1393
+
1381
1394
  /**
1382
1395
  * The whole local-mirror registry with each mirror's recorded remote origin
1383
1396
  * (issue #49).
@@ -2423,20 +2436,26 @@ export async function apply(ctx, config) {
2423
2436
  throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2424
2437
  }
2425
2438
  const state = loadSyncState(local)
2426
- const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes })
2427
- if (!args.dryRun) saveSyncState(local, nextState)
2428
- let text = `${args.dryRun ? 'WOULD upload' : 'Uploaded'} ${stats.files} file(s) from ${local} → ${p}.`
2429
- if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit maxFiles=${maxFiles} cap; raise maxFiles and re-run).`
2430
- if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2431
- if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
2432
- if (stats.staleLocal) text += ` ${stats.staleLocal} local entries gone remotely (kept remotely; use rw_remove to mirror deletions).`
2433
- if (stats.conflicts.length) {
2434
- text += `\n⚠ ${stats.conflicts.length} conflict(s), NOT overwritten:`
2435
- for (const c of stats.conflicts.slice(0, 10)) text += `\n ${c.path} — ${c.reason}`
2436
- if (stats.conflicts.length > 10) text += `\n … and ${stats.conflicts.length - 10} more`
2437
- text += '\n(use force=true to override)'
2439
+ try {
2440
+ const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes })
2441
+ if (!args.dryRun) saveSyncState(local, nextState)
2442
+ let text = `${args.dryRun ? 'WOULD upload' : 'Uploaded'} ${stats.files} file(s) from ${local} → ${p}.`
2443
+ if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit maxFiles=${maxFiles} cap; raise maxFiles and re-run).`
2444
+ if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2445
+ if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
2446
+ if (stats.staleLocal) text += ` ${stats.staleLocal} local entries gone remotely (kept remotely; use rw_remove to mirror deletions).`
2447
+ if (stats.conflicts.length) {
2448
+ text += `\n⚠ ${stats.conflicts.length} conflict(s), NOT overwritten:`
2449
+ for (const c of stats.conflicts.slice(0, 10)) text += `\n ${c.path} — ${c.reason}`
2450
+ if (stats.conflicts.length > 10) text += `\n … and ${stats.conflicts.length - 10} more`
2451
+ text += '\n(use force=true to override)'
2452
+ }
2453
+ return { text }
2454
+ } finally {
2455
+ // Sync AND async tasks share this body: invalidate only after the
2456
+ // actual push settles (partial uploads may have changed the remote).
2457
+ if (!args.dryRun && remoteSkills) remoteSkills.invalidate()
2438
2458
  }
2439
- return { text }
2440
2459
  }
2441
2460
  if (args.async) {
2442
2461
  const t = tasks.start('push', `push ${p}`, runPush)
@@ -3104,22 +3123,74 @@ export async function apply(ctx, config) {
3104
3123
  },
3105
3124
  })
3106
3125
 
3107
- // ── local-session tool visibility (issue #63) ────────────────────────────
3126
+ // ── local-session tool visibility (issues #63 / #117) ────────────────────
3108
3127
  // All rw_* tools register globally (at registration time there is no session
3109
- // to consult), but in a LOCAL session the operation tools can never succeed:
3110
- // bindingFor() refuses them with "this session is LOCAL". Exposing them
3111
- // anyway costs every local request a few thousand tokens of dead schema.
3112
- // The `system-prompt/assemble` waterfall is where the final per-request tool
3113
- // list passes with the calling agent attached, so the SAME cwd test the
3114
- // prompt section above already performs can trim the list there. A session
3115
- // whose cwd maps to a mirror keeps the full surface; anything else — a
3116
- // plain local directory, or a mirror whose meta is missing/unparsable
3117
- // (resolveMirror reports no binding; bindingFor refuses it as local too) —
3118
- // is reduced per config.localTools. An assembly without agent/cwd is left
3119
- // alone, matching bindingFor's "no caller context" semantics. `ctx.on` is
3120
- // cordis-core, but guard like the other
3121
- // optional surfaces: a minimal embedding (or a small test double) without
3122
- // event support simply keeps the legacy full surface.
3128
+ // to consult). A scoped restriction is the primary filter: DSH feeds the
3129
+ // SAME visible set to native schemas, the PTC SDK, run_code bindings and
3130
+ // dispatch. Filtering assembled.tools alone cannot touch the PTC SDK, which
3131
+ // is rendered from scope visibility before the assemble waterfall runs.
3132
+ //
3133
+ // Use deny, not an allowlist containing only the bootstrap tools: an allow
3134
+ // filter applies to every inherited tool and would hide unrelated Harness
3135
+ // capabilities too. Existing agents must be covered because this plugin
3136
+ // hot-reloads; created/disposed listeners cover the normal agent lifecycle.
3137
+ const localToolRestrictions = new Map()
3138
+ const localToolNames = tools.map((t) => t.name)
3139
+ const installLocalToolRestriction = (agent) => {
3140
+ if (localToolRestrictions.has(agent)) return
3141
+ const mode = normalizeLocalTools(config.localTools)
3142
+ if (mode === 'all') return
3143
+ const cwd = agent && agent.session && agent.session.header && agent.session.header.cwd
3144
+ if (!cwd) return // no caller context → not definitively local
3145
+ const { remotePath, machine } = resolveMirrorForLocal(String(cwd))
3146
+ if (remotePath && machine) return // remote session → full surface
3147
+ const agentCtx = agent && agent.ctx
3148
+ // Optional service lookup avoids Cordis's "without inject" property error
3149
+ // on custom/older agent contexts; get() still preserves the caller scope.
3150
+ const agentTools = agentCtx && (typeof agentCtx.get === 'function' ? agentCtx.get('tools') : agentCtx.tools)
3151
+ // Older DSH versions without scoped restriction keep the native waterfall
3152
+ // fallback below instead of failing agent creation.
3153
+ if (!agentTools || typeof agentTools.restrict !== 'function') return
3154
+ const deny = mode === 'none'
3155
+ ? localToolNames
3156
+ : localToolNames.filter((name) => !LOCAL_BOOTSTRAP_TOOLS.includes(name))
3157
+ if (deny.length === 0) return
3158
+ try {
3159
+ const dispose = agentTools.restrict({ deny })
3160
+ if (typeof dispose === 'function') localToolRestrictions.set(agent, dispose)
3161
+ } catch (error) {
3162
+ // A creation listener must not reject the whole agent for a presentation
3163
+ // compatibility problem. Native filtering remains active; surface the
3164
+ // degraded PTC behavior instead of silently pretending it was fixed.
3165
+ fileReferenceLog(`local tool restriction failed: ${(error && error.message) || error}`)
3166
+ }
3167
+ }
3168
+ const disposeLocalToolRestriction = (agent) => {
3169
+ const dispose = localToolRestrictions.get(agent)
3170
+ if (!dispose) return Promise.resolve()
3171
+ localToolRestrictions.delete(agent)
3172
+ return Promise.resolve()
3173
+ .then(() => dispose())
3174
+ .catch((error) => fileReferenceLog(`local tool restriction cleanup failed: ${(error && error.message) || error}`))
3175
+ }
3176
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
3177
+ if (agents && typeof agents.list === 'function') {
3178
+ for (const agent of agents.list()) installLocalToolRestriction(agent)
3179
+ }
3180
+ if (typeof ctx.on === 'function') {
3181
+ ctx.on('agent/created', ({ agent }) => installLocalToolRestriction(agent))
3182
+ ctx.on('agent/disposed', ({ agent }) => { void disposeLocalToolRestriction(agent) })
3183
+ }
3184
+ ctx.effect(
3185
+ () => () => Promise.all([...localToolRestrictions.keys()].map((agent) => disposeLocalToolRestriction(agent))),
3186
+ 'dsh-remote.local-tool-visibility',
3187
+ )
3188
+
3189
+ // Native/legacy fallback: the final per-request wire list also passes through
3190
+ // this waterfall. PTC keeps only run_code here; its SDK is handled by the
3191
+ // scoped restriction above. An assembly without agent/cwd is left alone,
3192
+ // matching bindingFor's "no caller context" semantics. Minimal embeddings
3193
+ // without event support retain the legacy full surface.
3123
3194
  if (typeof ctx.on === 'function') {
3124
3195
  ctx.on('system-prompt/assemble', async (_assembly, assembleContext, next) => {
3125
3196
  const assembled = await next()
@@ -3206,6 +3277,28 @@ export async function apply(ctx, config) {
3206
3277
  })
3207
3278
  }
3208
3279
 
3280
+ // Remote skill catalogs are cached by cwd/revision. Invalidate after any
3281
+ // operation that MAY have changed the remote (a failed/partial write counts
3282
+ // too), but never after caller cancellation. rw_push has its own settlement
3283
+ // hook above; rw_sync only downloads and need not invalidate.
3284
+ if (remoteSkills && typeof ctx.on === 'function') {
3285
+ const SKILL_MUTATIONS = new Set([
3286
+ 'rw_write_file', 'rw_edit', 'rw_append', 'rw_remove', 'rw_move',
3287
+ 'rw_mkdir', 'rw_upload', 'rw_exec',
3288
+ // Rebinding a workspace/connection must not resurrect the old catalog.
3289
+ 'rw_connect', 'rw_pick_workspace', 'rw_disconnect',
3290
+ ])
3291
+ ctx.on('tools/result', (result, hookContext) => {
3292
+ try {
3293
+ const name = String((hookContext && hookContext.name) || (result && result.name) || '')
3294
+ if (!SKILL_MUTATIONS.has(name)) return
3295
+ const signal = (hookContext && hookContext.signal) || (result && result.signal)
3296
+ if (signal && signal.aborted) return
3297
+ remoteSkills.invalidate()
3298
+ } catch { /* cache invalidation is best-effort and never blocks the tool */ }
3299
+ })
3300
+ }
3301
+
3209
3302
  // ── slash commands ─────────────────────────────────────────────────────────
3210
3303
  const commands = ctx.get('commands')
3211
3304
  if (commands !== undefined) {
@@ -3766,7 +3859,7 @@ export async function apply(ctx, config) {
3766
3859
  proxy: (probeTarget && !probeIsOpenssh && probeTarget.proxy) ? probeTarget.proxy : cred.proxy,
3767
3860
  connectTimeoutMs: Math.min(Math.max(Number(body.connectTimeoutMs) || config.connectTimeoutMs, 2000), 30000),
3768
3861
  commandTimeoutMs: 10000,
3769
- }, { knownHostsFile })
3862
+ }, { knownHostsFile, opensshKnownHostsFile })
3770
3863
  // Same lazy resolution the active pool uses: if the merged password was
3771
3864
  // empty because the secret lives in the OS keychain, the pool asks again
3772
3865
  // at dial time instead of failing with "no credentials".
@@ -4172,6 +4265,7 @@ export async function apply(ctx, config) {
4172
4265
  }),
4173
4266
  ...createFsRoutes({
4174
4267
  sendJson, readBody, resolveRequestBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4268
+ onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4175
4269
  }),
4176
4270
 
4177
4271
  // Embedded terminal (P1): one host-owned PTY session per machine, polled.
package/lib/openssh.js CHANGED
@@ -164,6 +164,41 @@ export function askpassEnv(secret) {
164
164
  }
165
165
  }
166
166
 
167
+ /**
168
+ * Keep an EPIPE on a child's stdin from becoming a process-wide crash.
169
+ *
170
+ * A child that stops reading — the remote side of `ssh -s sftp` dying mid-
171
+ * transfer is the one that bites — makes the NEXT write to its stdin fail. Node
172
+ * reports that asynchronously through the Writable's `'error'` event, so a
173
+ * synchronous `try/catch` around `write()` never sees it; an unhandled
174
+ * `'error'` on a stream is an uncaught exception, and the Host treats one of
175
+ * those as fatal (issue #118: `dsh: fatal uncaught exception: Error: write
176
+ * EPIPE` → the whole app's host process exits and every session is lost).
177
+ *
178
+ * Every `spawn` in this file therefore gets this hook: swallow the pipe error,
179
+ * report it to `onError` when the caller has cleanup to do, and let the
180
+ * existing `'close'`/`'error'` handling own the rest. A missing `ssh` binary
181
+ * is a different signal — spawn reports it on the CHILD, not on its stdin — so
182
+ * it still reaches the caller as a real error.
183
+ *
184
+ * @param {import('node:child_process').ChildProcess} child
185
+ * @param {(err: Error) => void} [onError] - e.g. drop the cached SFTP session.
186
+ * @returns {import('node:child_process').ChildProcess} the same child.
187
+ */
188
+ export function guardChildStdin(child, onError) {
189
+ const stdin = child && child.stdin
190
+ if (!stdin || typeof stdin.on !== 'function') return child
191
+ // A listener is the difference between "this stream reported a problem" and
192
+ // "this process died": without one Node re-throws the error as an uncaught
193
+ // exception. There is nothing to retry here — the pipe is gone — so all that
194
+ // is left is to let the caller drop whatever it cached for this child; the
195
+ // child's own 'close'/'error' handling still reports the real failure.
196
+ stdin.on('error', (err) => {
197
+ if (typeof onError === 'function') { try { onError(err) } catch { /* best effort */ } }
198
+ })
199
+ return child
200
+ }
201
+
167
202
  /** Is `ssh` runnable? Used to fail with an actionable message, not ENOENT. */
168
203
  export function sshBinaryAvailable(binary) {
169
204
  if (binary.includes('/') || binary.includes('\\')) {
@@ -257,6 +292,11 @@ export class OpenSshConnection extends EventEmitter {
257
292
  })
258
293
  this.children.add(child)
259
294
  const reap = () => this.children.delete(child)
295
+ // Every connection-level child goes through here (the `ssh -W` forward
296
+ // channel and the `ssh -N` reverse forward), so the stdin guard for those
297
+ // two paths belongs here rather than at each call site: a tunnel whose peer
298
+ // vanished must end as a closed channel, not as a fatal EPIPE (issue #118).
299
+ guardChildStdin(child)
260
300
  child.on('close', reap)
261
301
  child.on('error', reap)
262
302
  if (tty) { /* no pty support through the CLI without a tty helper */ }
@@ -377,7 +417,10 @@ export class OpenSshConnection extends EventEmitter {
377
417
  export class SystemOpenSshPool {
378
418
  constructor(config, opts = {}) {
379
419
  this.config = config
380
- this._knownHostsFile = opts.knownHostsFile
420
+ // The native backend's JSON fingerprint registry is NOT an OpenSSH
421
+ // known_hosts file. ActivePool supplies a dedicated plain-text path; the
422
+ // fallback preserves direct-construction compatibility (issue #118).
423
+ this._knownHostsFile = opts.opensshKnownHostsFile ?? opts.knownHostsFile
381
424
  this.client = null
382
425
  this.connecting = null
383
426
  this.proxyPool = null
@@ -540,6 +583,10 @@ export class SystemOpenSshPool {
540
583
  } catch (err) {
541
584
  return resolve({ code: -1, signal: 'SPAWN_FAILED', stdout: '', stderr: String((err && err.message) || err) })
542
585
  }
586
+ // This path may stream a script into `bash -s` and can be written to
587
+ // after the command already exited (Git Bash); a broken pipe there must
588
+ // fail the call, not the process (issue #118).
589
+ guardChildStdin(child)
543
590
  let stdout = ''
544
591
  let stderr = ''
545
592
  let settled = false
@@ -754,6 +801,14 @@ export class SystemOpenSshPool {
754
801
  incoming: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
755
802
  outgoing: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
756
803
  }
804
+ // The stdin pipe can die underneath the engine at any moment (the remote
805
+ // side of the sftp subsystem exits, the link drops — issue #118). Each write
806
+ // after that fails, and without an 'error' listener the failure is an
807
+ // uncaught exception that takes the whole Host down. Registering the guard
808
+ // here, next to the only two places that write to this pipe, keeps the
809
+ // blast radius at "this session is gone": 'close' fires as usual and the
810
+ // cached session is dropped by sftp()'s own handler.
811
+ guardChildStdin(child, () => { try { child.kill() } catch { /* already gone */ } })
757
812
  const sftp = new Sftp(fakeClient, chanInfo, {})
758
813
  chan.sftp = sftp
759
814
 
@@ -770,6 +825,10 @@ export class SystemOpenSshPool {
770
825
  }
771
826
  }
772
827
  child.stdin.on('drain', onStdinDrain)
828
+ // A dead SSH process reports stdin EPIPE asynchronously. Without a stream
829
+ // error listener Node crashes the host before close/drop can reset the
830
+ // cached session (issue #118); kill it so that existing recovery runs.
831
+ child.stdin.on('error', () => { try { child.kill() } catch {} })
773
832
 
774
833
  return new Promise((resolve, reject) => {
775
834
  let stderr = ''
package/lib/pool.js CHANGED
@@ -256,6 +256,11 @@ export class SshPool {
256
256
  this.onCloseHook = null
257
257
  /** Consecutive SFTP subchannel-open timeouts (issue #65). */
258
258
  this._sftpTimeouts = 0
259
+ /** One SFTP session per live client/epoch (issue #121). */
260
+ this._sftpSession = null
261
+ this._sftpRaw = null
262
+ this._sftpClient = null
263
+ this._sftpEpoch = -1
259
264
  }
260
265
 
261
266
  resolveKeyPath() {
@@ -420,7 +425,10 @@ export class SshPool {
420
425
  })
421
426
  client.on('error', (e) => rejectOnce(e))
422
427
  client.on('close', () => {
423
- if (isCurrent() && this.client === client) this.client = null
428
+ if (isCurrent() && this.client === client) {
429
+ this.client = null
430
+ this._dropSftpSession()
431
+ }
424
432
  rejectOnce(new Error('ssh connection closed'))
425
433
  })
426
434
 
@@ -820,86 +828,123 @@ export class SshPool {
820
828
  )
821
829
  }
822
830
 
823
- /** Resolve a promisified SFTP client. All paths normalized via toSftpPath(). */
824
- sftp() {
825
- return this.connect().then(
831
+ /**
832
+ * Resolve the shared promisified SFTP client for the CURRENT connection.
833
+ * Keeping one channel per client/epoch avoids leaking a channel per tool call
834
+ * into sshd's MaxSessions limit (issue #121).
835
+ */
836
+ sftp() { return this._sftp(false) }
837
+
838
+ _sftp(isRetry) {
839
+ const staleClient = this._sftpClient && this.client && this._sftpClient !== this.client
840
+ if (this._sftpSession && (this._sftpEpoch !== this.epoch || staleClient)) this._dropSftpSession()
841
+ if (this._sftpSession) return this._sftpSession
842
+
843
+ const epoch = this.epoch
844
+ const connected = isRetry
845
+ ? this.connect().catch((e) => { throw new Error('ssh sftp failed (reconnect): ' + ((e && e.message) || e)) })
846
+ : this.connect()
847
+ const session = connected.then(
826
848
  (client) =>
827
849
  new Promise((resolve, reject) => {
828
- let retried = false
829
- const runOn = (c) => {
830
- // Bound the subchannel open itself, per attempt. Without this, a
831
- // remote whose sftp subsystem is unresponsive (overloaded sshd,
832
- // exceeded MaxSessions, half-open TCP) leaves `c.sftp(cb)` parked
833
- // forever with no callback — issue #44 point 3. ssh2 only calls back
834
- // on success or on a channel error, and a wedged peer produces
835
- // neither.
836
- //
837
- // The timer must be created per attempt, not once outside: the
838
- // callback clears it, so a single outer timer would leave the retry
839
- // (below) with no timeout at all.
840
- let timedOut = false
841
- const attemptTimer = setTimeout(() => {
842
- timedOut = true
843
- reject(new Error(`ssh sftp open timed out after ${this.config.commandTimeoutMs}ms`))
844
- }, this.config.commandTimeoutMs)
845
- // ★ 这里**不能 unref**。
846
- //
847
- // 这个定时器是"本次 await 的 sftp 打开"的**唯一结算者**:要么它超时 reject,
848
- // 要么 ssh2 回调 resolve。若把它 unref,而进程此刻没有别的 pending 句柄,
849
- // Node 会认为无事可做而**直接退出**,调用方永远等不到结果。
850
- // 实测症状:CI 上该用例之后的 4 个用例被标记 `cancelledByParent`
851
- // (同文件子进程提前退出),而本地因运行器恰好持着句柄而侥幸通过。
852
- // 注意与上面 exec() 的超时定时器保持一致 —— 那个本来就没有 unref。
853
- // 下面的 hardClose 仍然 unref,因为它只做清理、不负责结算。
854
- const clearAttempt = () => { clearTimeout(attemptTimer) }
855
- try {
856
- c.sftp((err, sftp) => {
857
- clearAttempt()
858
- if (timedOut) return
859
- if (err) {
860
- // Same dead-connection recovery as exec(): a channel open
861
- // failure — or a session termination (remote closed the
862
- // SFTP subchannel, e.g. transient network blip / sshd idle
863
- // drop) — means the pooled connection is stale: drop it and
864
- // retry ONCE on a fresh connection.
865
- if (!retried && /channel open failure|open failed|unexpected sftp session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
866
- retried = true
867
- this.invalidate()
868
- return this.connect().then(
869
- (fresh) => runOn(fresh),
870
- (e2) => reject(new Error('ssh sftp failed (reconnect): ' + ((e2 && e2.message) || e2))),
871
- )
872
- }
873
- return reject(new Error('ssh sftp failed: ' + ((err && err.message) || err)))
850
+ // Bound the subchannel open itself, per attempt. Without this, a
851
+ // remote whose sftp subsystem is unresponsive (overloaded sshd,
852
+ // exceeded MaxSessions, half-open TCP) leaves `client.sftp(cb)` parked
853
+ // forever with no callback — issue #44 point 3.
854
+ let timedOut = false
855
+ const attemptTimer = setTimeout(() => {
856
+ timedOut = true
857
+ reject(new Error(`ssh sftp open timed out after ${this.config.commandTimeoutMs}ms`))
858
+ }, this.config.commandTimeoutMs)
859
+ // ★ 这里**不能 unref**。
860
+ //
861
+ // 这个定时器是"本次 await 的 sftp 打开"的**唯一结算者**:要么它超时 reject,
862
+ // 要么 ssh2 回调 resolve。若把它 unref,而进程此刻没有别的 pending 句柄,
863
+ // Node 会认为无事可做而**直接退出**,调用方永远等不到结果。
864
+ // 实测症状:CI 上该用例之后的 4 个用例被标记 `cancelledByParent`
865
+ // (同文件子进程提前退出),而本地因运行器恰好持着句柄而侥幸通过。
866
+ // 注意与上面 exec() 的超时定时器保持一致 —— 那个本来就没有 unref。
867
+ const clearAttempt = () => { clearTimeout(attemptTimer) }
868
+ try {
869
+ client.sftp((err, sftp) => {
870
+ clearAttempt()
871
+ // A late success after the watchdog rejected still owns a real
872
+ // channel. Close it, and never adopt it into the cache.
873
+ if (timedOut) {
874
+ if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
875
+ return
876
+ }
877
+ const wrongClient = this.client && this.client !== client
878
+ if (this.epoch !== epoch || this._sftpSession !== session || wrongClient) {
879
+ if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
880
+ return reject(new Error('ssh target changed while opening sftp'))
881
+ }
882
+ if (err) {
883
+ // Same dead-connection recovery as before: retry ONCE on a fresh
884
+ // connection. The new session has its own epoch and is adopted by
885
+ // callers of this promise; isRetry prevents recursive reconnects.
886
+ if (!isRetry && /channel open failure|open failed|unexpected sftp session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
887
+ this.invalidate()
888
+ return resolve(this._sftp(true))
874
889
  }
875
- // A successful open proves the connection healthy: the strike
876
- // counter counts CONSECUTIVE timeouts, so it resets here —
877
- // two unrelated transient blips hours apart must not tear down
878
- // a fine connection.
879
- this._sftpTimeouts = 0
880
- // The promisified surface (timeouts, dead-channel fail-fast,
881
- // range reads) is shared verbatim with the system-OpenSSH
882
- // backend — see lib/sftp-surface.js for the rules it encodes.
890
+ return reject(new Error('ssh sftp failed: ' + ((err && err.message) || err)))
891
+ }
892
+
893
+ const drop = () => {
894
+ if (this._sftpSession === session) {
895
+ this._sftpSession = null
896
+ this._sftpEpoch = -1
897
+ }
898
+ if (this._sftpRaw === sftp) {
899
+ this._sftpRaw = null
900
+ this._sftpClient = null
901
+ }
902
+ }
903
+ if (typeof sftp.on === 'function') {
904
+ sftp.on('end', drop)
905
+ sftp.on('close', drop)
906
+ sftp.on('error', drop)
907
+ }
908
+ this._sftpRaw = sftp
909
+ this._sftpClient = client
910
+ // A successful open proves the connection healthy: reset the
911
+ // consecutive-timeout strike counter (issue #65).
912
+ this._sftpTimeouts = 0
913
+ try {
883
914
  resolve(buildSftpSurface(sftp, {
884
915
  commandTimeoutMs: this.config.commandTimeoutMs,
885
916
  onTimeout: () => {
886
- // A timed-out SFTP subchannel is dead: close it so the next
887
- // operation does not queue behind the wedged one, and count
888
- // the strike so a second consecutive timeout tears down the
889
- // whole pooled connection (issue #65).
917
+ // A timed-out channel is dead: close AND forget it so the
918
+ // next call reopens instead of returning a dead surface.
890
919
  try { sftp.end() } catch { /* already gone */ }
920
+ drop()
891
921
  this._noteSftpTimeout()
892
922
  },
893
923
  }))
894
- })
895
- } catch (e) {
896
- clearAttempt()
897
- reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
898
- }
924
+ } catch (e) {
925
+ drop()
926
+ try { sftp.end() } catch { /* already gone */ }
927
+ reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
928
+ }
929
+ })
930
+ } catch (e) {
931
+ clearAttempt()
932
+ reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
899
933
  }
900
- runOn(client)
901
934
  }),
902
935
  )
936
+ // Never cache a rejected open: the next call must retry rather than get the
937
+ // same error back forever. Raw fields are only set after a successful open.
938
+ session.catch(() => {
939
+ if (this._sftpSession === session) {
940
+ this._sftpSession = null
941
+ this._sftpEpoch = -1
942
+ this._sftpClient = null
943
+ }
944
+ })
945
+ this._sftpSession = session
946
+ this._sftpEpoch = epoch
947
+ return session
903
948
  }
904
949
 
905
950
  /**
@@ -912,6 +957,18 @@ export class SshPool {
912
957
  if (this._sftpTimeouts >= 2) this.invalidate()
913
958
  }
914
959
 
960
+ _dropSftpSession() {
961
+ const session = this._sftpSession
962
+ const raw = this._sftpRaw
963
+ this._sftpSession = null
964
+ this._sftpRaw = null
965
+ this._sftpClient = null
966
+ this._sftpEpoch = -1
967
+ if (raw) { try { raw.end() } catch { /* already gone */ } }
968
+ // Swallow the rejection: nobody awaits a session we are tearing down.
969
+ if (session && typeof session.catch === 'function') session.catch(() => {})
970
+ }
971
+
915
972
  /**
916
973
  * Drop the cached client and force a fresh connection on the next call.
917
974
  * Called when a channel open fails (e.g. "Channel open failure: open
@@ -924,6 +981,7 @@ export class SshPool {
924
981
  this.epoch++
925
982
  const client = this.client
926
983
  this.client = null
984
+ this._dropSftpSession()
927
985
  const pending = this.connecting
928
986
  this.connecting = null
929
987
  if (pending && typeof pending.catch === 'function') {
@@ -949,6 +1007,7 @@ export class SshPool {
949
1007
  this.epoch++
950
1008
  const client = this.client
951
1009
  this.client = null
1010
+ this._dropSftpSession()
952
1011
  const pending = this.connecting
953
1012
  this.connecting = null
954
1013
  if (pending && typeof pending.catch === 'function') {
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Quote one string for a POSIX shell using single quotes only.
5
+ *
6
+ * A single quote inside the value is emitted as the three-step sequence
7
+ * close-quote, escaped-quote, reopen-quote. The result preserves the value
8
+ * literally, including newlines, dollar signs, backticks and double quotes.
9
+ *
10
+ * @param {unknown} value
11
+ * @returns {string}
12
+ */
13
+ function quotePosix(value) {
14
+ return "'" + String(value).replace(/'/g, "'\\''") + "'"
15
+ }
16
+
17
+ /**
18
+ * Run a generated POSIX script through `sh` instead of the remote login shell.
19
+ *
20
+ * sshd gives an exec request to the user's login shell. That shell may be fish,
21
+ * csh or another non-POSIX implementation, while this package's internal launch
22
+ * and probe scripts are deliberately POSIX. The outer shell only has to parse
23
+ * the simple `sh -c '<quoted script>'` invocation; `sh` then parses the actual
24
+ * script. Generic rw_exec commands are NOT routed through this helper, so users
25
+ * retain their login-shell semantics.
26
+ *
27
+ * @param {string} command
28
+ * @returns {string}
29
+ */
30
+ function posixViaSh(command) {
31
+ return `sh -c ${quotePosix(command)}`
32
+ }
33
+
34
+ module.exports = { posixViaSh, quotePosix }