ssh-fleet-mcp-server 0.2.1 → 0.2.3
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/README.md +21 -14
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/package.json +27 -24
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# ssh-fleet-mcp-server
|
|
2
2
|
|
|
3
|
-
[](./LICENSE)
|
|
4
4
|
[](https://www.npmjs.com/package/ssh-fleet-mcp-server)
|
|
5
5
|
|
|
6
6
|
**ssh-fleet-mcp-server** is a Model Context Protocol (MCP) server that manages a fleet of SSH hosts behind a pooled connection layer. LLMs and MCP clients get a single server that can route `exec` and `tmux_*` commands to any configured host by name — no separate server process per host required.
|
|
@@ -224,6 +224,8 @@ List tmux sessions on a fleet host. Returns a JSON array of session names, empty
|
|
|
224
224
|
|
|
225
225
|
The `tmux_*` tools find tmux on the host's `PATH`, then in `/opt/homebrew/bin` and `/usr/local/bin`. That covers Homebrew on macOS, where a command sent over SSH gets only `/usr/bin:/bin:/usr/sbin:/sbin`. `exec` gets no such help: to run other Homebrew tools through it, load Homebrew's `PATH` in the host's `~/.zshenv`.
|
|
226
226
|
|
|
227
|
+
They need a POSIX login shell, such as sh, bash or zsh, for the SSH account: sshd runs each command with it, and csh, tcsh and fish can't parse the commands. On such an account the tools fail and say so; `exec` is unaffected.
|
|
228
|
+
|
|
227
229
|
| Parameter | Type | Required | Description |
|
|
228
230
|
| --------- | ------ | -------- | --------------------- |
|
|
229
231
|
| `host` | string | yes | Configured host name. |
|
|
@@ -348,14 +350,14 @@ user = "fleet-ro"
|
|
|
348
350
|
ca = "home"
|
|
349
351
|
```
|
|
350
352
|
|
|
351
|
-
| `[[cas]]` key | Description
|
|
352
|
-
| ---------------- |
|
|
353
|
-
| `name` | Letters, digits, hyphen, underscore. Hosts refer to it with `ca = "<name>"`.
|
|
354
|
-
| `key_cmd` | A shell command whose output is the CA private key (a keychain or password-manager read).
|
|
355
|
-
| `key_env` | An env var holding the CA private key; removed from the environment once read.
|
|
356
|
-
| `key_file` | A key file: a regular file (not a symlink), mode `0600` or stricter, owned by the hub user.
|
|
357
|
-
| `principal` | The principal certificates name (default `"fleet"`). A host may override it with its own `principal`.
|
|
358
|
-
| `source_address` | An IPv4 or IPv6 CIDR; certificates are only accepted from those addresses.
|
|
353
|
+
| `[[cas]]` key | Description |
|
|
354
|
+
| ---------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
355
|
+
| `name` | Letters, digits, hyphen, underscore, checked when the config loads. Hosts refer to it with `ca = "<name>"`. |
|
|
356
|
+
| `key_cmd` | A shell command whose output is the CA private key (a keychain or password-manager read). |
|
|
357
|
+
| `key_env` | An env var holding the CA private key; removed from the environment once read. |
|
|
358
|
+
| `key_file` | A key file: a regular file (not a symlink), mode `0600` or stricter, owned by the hub user. |
|
|
359
|
+
| `principal` | The principal certificates name (default `"fleet"`). A host may override it with its own `principal`. |
|
|
360
|
+
| `source_address` | An IPv4 or IPv6 CIDR; certificates are only accepted from those addresses. |
|
|
359
361
|
|
|
360
362
|
Exactly one of `key_cmd`, `key_env` or `key_file`. Inline keys are rejected.
|
|
361
363
|
|
|
@@ -446,7 +448,7 @@ With no `--config`, the server uses `~/.config/ssh-fleet/fleet.toml` and creates
|
|
|
446
448
|
"mcpServers": {
|
|
447
449
|
"ssh-fleet": {
|
|
448
450
|
"command": "node",
|
|
449
|
-
"args": ["
|
|
451
|
+
"args": ["servers/ssh-fleet/dist/index.js"],
|
|
450
452
|
"env": { "MINI_SSH_PASSWORD": "…" }
|
|
451
453
|
}
|
|
452
454
|
}
|
|
@@ -506,7 +508,7 @@ npm install -g ssh-fleet-mcp-server@<version>
|
|
|
506
508
|
To try a build that isn't released yet, pack it on a machine with this repo, copy the tarball to the hub, and install that the same way:
|
|
507
509
|
|
|
508
510
|
```sh
|
|
509
|
-
cd
|
|
511
|
+
cd servers/ssh-fleet && pnpm build && pnpm pack # → ssh-fleet-mcp-server-<version>.tgz
|
|
510
512
|
scp ssh-fleet-mcp-server-<version>.tgz <hub>:/tmp/
|
|
511
513
|
npm install -g /tmp/ssh-fleet-mcp-server-<version>.tgz # on the hub
|
|
512
514
|
```
|
|
@@ -564,7 +566,7 @@ Two limits: enrolling a host needs root once, and only one server can run per `r
|
|
|
564
566
|
ssh-fleet-mcp-server check [--config=<path>]
|
|
565
567
|
```
|
|
566
568
|
|
|
567
|
-
Connects to every host from a terminal and runs `true`, printing one line per host as it finishes, then
|
|
569
|
+
Connects to every host from a terminal and runs `true`, printing one line per host as it finishes, then a line per CA, even when there are no hosts yet: its enrollment line, or the hint that its `key_file` is missing. Exits 0 when every host passes (or there are none), 1 otherwise. Each line names the account it connects as: the host's `user`, else the hub's `$USER`, else `root`.
|
|
568
570
|
|
|
569
571
|
```
|
|
570
572
|
ok mini me@mini.local:22 password_env 212 ms
|
|
@@ -574,7 +576,7 @@ CA home: cert-authority,principals="fleet" ssh-ed25519 AAAA… ssh-fleet-ca-home
|
|
|
574
576
|
|
|
575
577
|
- It never creates a config or key. A CA whose `key_file` is missing fails its hosts with a hint, without connecting.
|
|
576
578
|
- It skips policy, so it can run `true` even on a `readonly` or `deny` host. Each probe is audited with `tool: "check"`, `agent: "operator"`, `bypass: "policy"`. It isn't reachable over MCP.
|
|
577
|
-
- It uses its own runtime dir (`<runtime_dir>-check`), so it works while the server is running.
|
|
579
|
+
- It uses its own runtime dir (`<runtime_dir>-check`), so it works while the server is running. Once the check has started probing hosts, Ctrl-C or `SIGTERM` (as from `timeout 30 ssh-fleet-mcp-server check`) stops its CA agent before it exits.
|
|
578
580
|
- A `ForceCommand` account that doesn't allow `true` fails the check.
|
|
579
581
|
- Run it with the same environment the MCP client gives the server, so `password_env` and `key_env` variables are set.
|
|
580
582
|
|
|
@@ -583,16 +585,21 @@ CA home: cert-authority,principals="fleet" ssh-ed25519 AAAA… ssh-fleet-ca-home
|
|
|
583
585
|
All tooling is delegated to [`ts-builds`](https://github.com/jordanburke/ts-builds). Run from the repo root:
|
|
584
586
|
|
|
585
587
|
```bash
|
|
586
|
-
pnpm
|
|
588
|
+
pnpm validate # every server in the workspace, ssh-core and ssh-client included
|
|
587
589
|
```
|
|
588
590
|
|
|
589
591
|
Or from this package directory:
|
|
590
592
|
|
|
591
593
|
```bash
|
|
592
594
|
pnpm validate # format → lint → typecheck → test → build
|
|
595
|
+
pnpm run ci # validate's checks without fixing, as CI runs them (type `run`: `pnpm ci` is a clean install)
|
|
593
596
|
pnpm test # vitest run
|
|
594
597
|
pnpm test:watch # vitest watch mode
|
|
595
598
|
pnpm build # production build to dist/
|
|
596
599
|
```
|
|
597
600
|
|
|
598
601
|
Integration tests (requiring a live SSH server on localhost) are automatically skipped when the host is not reachable — CI remains green in environments without SSH available.
|
|
602
|
+
|
|
603
|
+
---
|
|
604
|
+
|
|
605
|
+
Maintained by [Jordan Burke](https://github.com/jordanburke) · **Affiliated with <a href="https://sapientsai.com/"><img src="https://sapientsai.com/images/logo.svg" alt="SapientsAI logo" width="18" align="absmiddle"></a> <a href="https://sapientsai.com/">SapientsAI</a>**
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`).filter(e=>e.startsWith(`ssh-`)):[]},
|
|
4
|
-
`).map(e=>e.trim()).filter(e=>e.length>0)):et.test(e.stderr)?k([]):E(V(`tmux list-sessions`,e)):E(V(`tmux list-sessions`,e)),nt=e=>t=>t.timedOutMs===void 0?B(t)?E(z):t.code===0?k(void 0):E(V(e,t)):E(V(e,t)),rt=e=>t=>t.timedOutMs===void 0?B(t)?E(z):t.code===0?k(Ke(t.stdout)):$e.test(t.stderr)?E(`No tmux session "${e}" — list with tmux_list, or tmux_send creates one`):E(V(`tmux capture-pane`,t)):E(V(`tmux capture-pane`,t)),it=e=>t=>t.timedOutMs===void 0?B(t)?E(z):t.code===0?k(void 0):$e.test(t.stderr)?E(`No tmux session "${e}" — list with tmux_list, or tmux_send creates one`):E(V(`tmux send-keys`,t)):E(V(`tmux send-keys`,t)),at=async e=>tt(await e(Ye())),ot=async(e,t)=>{let n=Xe(t.session,t.input,t.submit);return n.isLeft()?E(n.value):nt(`tmux_send`)(await e(n.value))},st=async(e,t)=>{let n=Ze(t.session,t.lines);return n.isLeft()?E(n.value):rt(t.session)(await e(n.value))},ct=async(e,t)=>{let n=Qe(t.session,t.keys);return n.isLeft()?E(n.value):it(t.session)(await e(n.value))},lt=e=>O(y.signals[`SIG${e}`]).fold(()=>255,e=>128+e),ut=(e,t,n,r)=>{if(typeof n==`number`)return{stdout:e,stderr:t,code:n};if(typeof r!=`string`||r===``)return{stdout:e,stderr:t,code:255,noExitStatus:!0};let i=r.replace(/^SIG/,``);return{stdout:e,stderr:t,code:lt(i),signal:i}},dt=(e,t,n)=>({stdout:e,stderr:t,code:124,timedOutMs:n}),ft=e=>{if(e.code===0)return k(e.stderr?`${e.stdout}\n[stderr]\n${e.stderr}`:e.stdout);let t=e.stderr&&e.stdout?`${e.stderr}\n[stdout]\n${e.stdout}`:e.stderr||e.stdout;return E(`${Re(e)}:\n${t}`)},pt=e=>new Promise(t=>setTimeout(t,e)),mt=e=>[`-p`,String(e.port??22),`${e.username??``}@${e.host??``}`],ht=(e,t,n,r)=>[`-F`,`/dev/null`,`-M`,`-N`,`-S`,t,`-o`,`ControlPersist=no`,`-o`,`IdentitiesOnly=yes`,`-o`,`IdentityAgent=none`,`-o`,`IdentityFile=${r.keyPath}`,`-o`,`CertificateFile=${r.certPath}`,`-o`,`BatchMode=yes`,`-o`,`StrictHostKeyChecking=accept-new`,`-o`,`UserKnownHostsFile=${n}`,`-o`,`ConnectTimeout=10`,`-o`,`ServerAliveInterval=15`,`-o`,`ServerAliveCountMax=3`,...mt(e)],gt=(e,t,n)=>[`-F`,`/dev/null`,`-S`,t,`-o`,`ControlMaster=no`,`-o`,`ProxyCommand=false`,`-o`,`BatchMode=yes`,...mt(e),`--`,n],_t=e=>{let t={run:O.none()};return()=>t.run.fold(()=>{let n=e();return t.run=O(n),n},e=>e)},vt=e=>{let{proc:t,socketPath:r,knownHosts:i}=e,a=e.readyTimeoutMs??15e3,o=e.drainTimeoutMs??6e4,s=e.setTimer??((e,t)=>setTimeout(e,t)),c=e.clearTimer??(e=>clearTimeout(e)),l=(e,t)=>Promise.race([new Promise(t=>e.onExit(()=>t())),new Promise(e=>s(e,t))]),u=(e,t)=>l(e,o).then(()=>(e.kill(),t())),d=new globalThis.Set,f=(e,n,r)=>t.run(`ssh`,[`-F`,`/dev/null`,`-S`,n,`-O`,e,...mt(r)],{env:P()}),p=(e,t,n,r)=>e.exited()?Promise.resolve(E(`master for ${n.host} exited: ${e.stderr().trim()}`)):Date.now()>r?Promise.resolve(E(`master for ${n.host} did not come up: ${e.stderr().trim()}`)):f(`check`,t,n).then(i=>i.code===0&&!e.exited()?k(void 0):pt(100).then(()=>p(e,t,n,r)));return{connect:async o=>{let l=await e.mintFor();if(l.isLeft())throw Error(l.value);let m=l.value,h=_t(m.dispose),v=r.replace(/\.sock$/,`-${n(2).toString(`hex`)}.sock`),y=v.replace(/\.sock$/,`.pid`),b=t.spawn(`ssh`,ht(o,v,i,m),{env:P()}),x=b.pid();x!==void 0&&A(()=>_(y,String(x),{mode:384})),b.onExit(()=>A(()=>g(y)));let S=await p(b,v,o,Date.now()+a);if(S.isLeft())throw b.kill(),await h(),Error(S.value);let C={closing:!1,closed:!1,retired:!1},w=[],T=()=>{C.closed||(C.closed=!0,w.splice(0).forEach(e=>e()))};b.onExit(()=>{T(),h()});let E=s(()=>{C.closing||C.retired||(C.retired=!0,T(),f(`stop`,v,o).catch(()=>void 0).then(()=>u(b,h)))},e.retireAfterMs??Math.max(0,m.validUntil.getTime()-Date.now()));b.onExit(()=>c(E));let ee=()=>{c(E),!(C.closing||C.retired)&&(C.closing=!0,f(`exit`,v,o).catch(()=>void 0).then(()=>u(b,h)))},D={child:b,close:ee};return d.add(D),b.onExit(()=>d.delete(D)),{exec:async(e,n={})=>{if(b.exited()||C.closing||C.retired)throw Error(`master for ${o.host} is gone`);let r=await t.run(`ssh`,gt(o,v,e),{env:P(),timeoutMs:n.timeoutMs});return r.timedOut===!0?dt(r.stdout,r.stderr,n.timeoutMs??0):{stdout:r.stdout,stderr:r.stderr,code:r.code}},close:ee,onClose:e=>{w.push(e)}}},shutdown:async()=>{let e=[...d];e.forEach(e=>e.close()),await Promise.all(e.map(e=>e.child.exited()?Promise.resolve():l(e.child,o)))}}},yt=e=>new Promise((t,n)=>{let r=new ie,i=[];r.on(`ready`,()=>t({exec:(e,t={})=>new Promise((n,i)=>{r.exec(e,(e,r)=>{if(e){i(e);return}let a=[],o=[],s=t.timeoutMs===void 0?void 0:setTimeout(()=>{let e=t.timeoutMs??0;n(dt(Buffer.concat(a).toString(),Buffer.concat(o).toString(),e)),r.signal(`KILL`),r.close()},t.timeoutMs);r.on(`close`,(e,t)=>{clearTimeout(s),n(ut(Buffer.concat(a).toString(),Buffer.concat(o).toString(),e,t))}),r.on(`data`,e=>a.push(e)),r.stderr.on(`data`,e=>o.push(e))})}),close:()=>r.end(),onClose:e=>i.push(e)})),r.on(`error`,e=>{i.forEach(e=>e()),n(e)}),r.on(`close`,()=>i.forEach(e=>e())),r.connect({keepaliveInterval:15e3,...e})}),bt=(e,t,n=yt)=>{let r=D.of(...e.map(e=>[e.name,{name:e.name,sshConfig:e.sshConfig,inFlight:0,waiters:[]}])),i=()=>[...r].map(([,e])=>e),a=e=>{e.conn=void 0,e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=void 0)},o=async e=>e.conn?e.conn:(e.connecting||(e.connecting=n(e.sshConfig).then(t=>(t.onClose(()=>{e.conn===t&&a(e)}),e.conn=t,e.connecting=void 0,t)),e.connecting.catch(()=>{e.connecting=void 0})),e.connecting),s=e=>e.inFlight<t.maxPerHost?(e.inFlight++,Promise.resolve()):new Promise((n,r)=>{let i=()=>{clearTimeout(a),n()},a=setTimeout(()=>{let n=e.waiters.indexOf(i);n!==-1&&e.waiters.splice(n,1),r(/* @__PURE__ */ Error(`host "${e.name}" busy: no free connection slot after ${t.acquireTimeoutMs}ms`))},t.acquireTimeoutMs);e.waiters.push(i)}),c=e=>{let n=e.waiters.shift();n?n():(e.inFlight--,e.inFlight===0&&e.conn&&(e.idleTimer=setTimeout(()=>{e.conn?.close(),a(e)},t.idleTimeoutMs)))};return{run:async(e,t,n)=>{let i=r.get(e).orThrow(/* @__PURE__ */ Error(`unknown host "${e}"`));i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=void 0),await s(i);try{return await(await o(i)).exec(t,n).catch(async()=>(a(i),(await o(i)).exec(t,n)))}finally{c(i)}},status:()=>i().map(e=>({name:e.name,state:e.conn?e.inFlight>0?`connected`:`idle`:`disconnected`,inFlight:e.inFlight})),shutdown:()=>(i().forEach(e=>{e.idleTimer&&clearTimeout(e.idleTimer),e.conn?.close(),a(e)}),Promise.resolve())}},xt=`Call hosts_list for the configured host names.`,St=e=>e.startsWith(`unknown host`),Ct=e=>St(e)?new M(e,{category:`not_found`,suggestions:[xt]}):Ue(e)?new M(e,{category:`validation`,suggestions:[]}):Be(e)?new M(e,{category:`timeout`,suggestions:[`tmux took longer than [pool].exec_timeout_ms. Try again, or raise it.`]}):new M(e,{category:`execution`,suggestions:[]}),wt=(e,t)=>new M(`[${e}] ${t}`,{category:`timeout`,suggestions:[`The command may still be running on ${e}. For a long job, start it in tmux with tmux_send and check it with tmux_read, or pass a larger timeout_ms.`]}),Tt=e=>new M(e,{category:`auth`,suggestions:[`This host's policy doesn't allow it. Use a command or tool the policy allows, or ask the operator.`]}),H=e=>t=>{if(t instanceof M)throw t;if(t instanceof TypeError||t instanceof RangeError)throw new M(t.message,{category:`internal`,suggestions:[]});let n=t instanceof Error?t.message:String(t);throw St(n)?new M(n,{category:`not_found`,suggestions:[xt]}):n.includes(` busy: no free connection slot`)?new M(n,{category:`timeout`,suggestions:[`Every connection to ${e} is in use. Try again, or raise [pool].max_per_host.`]}):new M(`[${e}] ${n}`,{category:`execution`,suggestions:[`Call fleet_setup to see ${e}'s connection state and what to configure.`]})},U=`unknown`,Et=`~/.local/state/ssh-fleet/audit.jsonl`,Dt=e=>O(e.name).flatMap(t=>Ot(e.version===void 0?t:`${t}/${e.version}`)),Ot=e=>O(e).map(e=>Array.from(e.replace(/\p{Cc}/gu,``).trim()).slice(0,64).join(``)).filter(e=>e.length>0),kt=e=>Array.from(e).slice(0,1024).join(``),At=e=>e.timedOutMs===void 0&&e.noExitStatus!==!0?{}:{status:`error`,error:Re(e)},W=e=>e instanceof Error?e.message:String(e),jt=(e,t)=>e.fold(()=>t,e=>`${e}:${t}`),Mt=e=>e.verdict.decision===`allow`?{decision:`allow`,...e.verdict.rule.fold(()=>({}),t=>({rule:jt(e.host,t)}))}:{decision:`deny`,rule:jt(e.host,e.verdict.rule),reason:e.verdict.reason},Nt=({sink:e,now:t,newId:n,client:r})=>{let i=(t,n)=>A(()=>e(JSON.stringify(t))).fold(e=>{throw new M(`audit log write failed ${n}: ${W(e)}`,{category:`internal`,suggestions:[`The server refuses every call while it can't write its audit log. Check the [audit].path file.`]})},()=>void 0);return{audited:async(e,a,o)=>{let s=n(),c={agent:e.agent,...r===void 0?{}:{client:r},tool:e.tool,...e.host.fold(()=>({}),e=>({host:e}))},l=t();if(i({ts:l.toISOString(),id:s,event:`decision`,...c,...e.fields,...Mt(e)},`— call not executed`),e.verdict.decision===`deny`){let t=e.host.fold(()=>``,e=>`[${e}] `);throw Tt(`${t}denied by rule ${e.verdict.rule}: ${e.verdict.reason}`)}let u=await Promise.resolve().then(a).then(e=>({ok:!0,value:e}),e=>({ok:!1,error:e})),d=t(),f={ts:d.toISOString(),id:s,event:`result`,...c},p=d.getTime()-l.getTime();if(u.ok)return i({...f,status:`ok`,ms:p,...o(u.value)},`after execution`),u.value;throw i({...f,status:`error`,ms:p,error:W(u.error)},`after execution`),u.error}}},Pt=o.O_WRONLY|o.O_APPEND|o.O_CREAT|o.O_NOFOLLOW,Ft=(e,t)=>{let n=d(e,Pt,384);try{t(n)}finally{a(n)}},It=(e,t)=>Ft(e,e=>{let n=`${t}\n`,r=Buffer.byteLength(n),i=v(e,n);if(i!==r)throw Error(`short write: ${i} of ${r} bytes`)}),Lt=e=>{(l(e).mode&511)!=384&&c(e,384)},Rt=e=>j.expand(e).fold(t=>E(`invalid audit path ${e}: ${W(t)}`),e=>A(()=>{u(C(e),{recursive:!0,mode:448}),Ft(e,Lt)}).fold(t=>E(`audit log ${e} is not writable: ${W(t)}`),()=>k(t=>It(e,t)))),zt=()=>({commit:`934c335c18cf`,branch:`fleet-v0.2.1`,date:`2026-11-05T23:14:20.306Z`}),Bt=[`readonly`,`readwrite`,`deny`],Vt=[`approve`,`open`],Ht=[`mode`,`tmux`,`allow`,`needs_approval`,`agents`],G={mode:O.none(),tmux:O.none(),allow:O.none(),needsApproval:O.none(),agents:O.none()},Ut=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Wt=(e,t,n)=>e===void 0?k(O.none()):typeof e==`string`&&t.includes(e)?k(O(e)):E(n),Gt=(e,t)=>e===void 0?k(O.none()):Array.isArray(e)&&e.every(e=>typeof e==`string`)?k(O(e)):E(t),Kt=e=>e.fold(e=>[e],()=>[]),qt=(e,t)=>{if(e===void 0)return k(G);if(!Ut(e))return E([`${t} must be a table`]);let n=Wt(e.mode,Bt,`${t}.mode must be one of readonly, readwrite, deny`),r=Wt(e.tmux,Vt,`${t}.tmux must be approve or open`),i=Gt(e.allow,`${t}.allow must be an array of strings`),a=Gt(e.needs_approval,`${t}.needs_approval must be an array of strings`),o=Gt(e.agents,`${t}.agents must be an array of strings`),s=[...Object.keys(e).filter(e=>!Ht.includes(e)).map(e=>`${t}: unknown key "${e}"`),...[n,r,i,a,o].flatMap(Kt)];return s.length>0?E(s):k({mode:n.orElse(G.mode),tmux:r.orElse(G.tmux),allow:i.orElse(G.allow),needsApproval:a.orElse(G.needsApproval),agents:o.orElse(G.agents)})},Jt=e=>e.filter(e=>e.length>0).orElse([]),Yt=(e,t,n,r)=>{let i=n.map(n=>A(()=>new RegExp(r(new RegExp(n).source))).fold(r=>E(`${e}: invalid regex in ${t}: "${n}" (${r.message})`),e=>k(e))),a=i.flatMap(Kt);return a.length>0?E(a):k(i.flatMap(e=>e.fold(()=>[],e=>[e])))},Xt=e=>e.fold(e=>e,()=>[]),Zt=(e,t,n)=>{let r=n.mode.or(t.mode).orElse(`readwrite`),i=n.tmux.or(t.tmux).orElse(`open`),a=Jt(n.allow.or(t.allow)),o=Jt(n.needsApproval.or(t.needsApproval)),s=Jt(n.agents.or(t.agents)),c=Yt(e,`allow`,a,e=>`^(?:${e})$`),l=Yt(e,`needs_approval`,o,e=>e),u=[...Xt(c),...Xt(l),...a.length>0&&r!==`readonly`?[`${e}: allow applies only to mode = "readonly"`]:[],...o.length>0&&r!==`readwrite`?[`${e}: needs_approval applies only to mode = "readwrite"`]:[]];return u.length>0?E(u):k({mode:r,tmux:i,allow:c.orElse([]),needsApproval:l.orElse([]).map((e,t)=>({pattern:o[t]??e.source,re:e})),agents:s.length>0?O(s):O.none()})},K={decision:`allow`,rule:O.none()},q=e=>({decision:`allow`,rule:O(e)}),J=(e,t)=>({decision:`deny`,rule:e,reason:t}),Qt=/[\n\r\0;&|$`()<>{}\\'"*?[~]/,$t=`command is longer than 4096 characters`,en=(e,t)=>e.some(e=>t===e||t.startsWith(`${e}@`)),tn=e=>e.mode===`readonly`?J(`readonly`,`tmux input is not allowed on a readonly host`):e.tmux===`approve`?J(`tmux`,`tmux input requires approval, which is not available yet`):q(`readwrite`),nn=(e,t)=>{let n=t.length>4096&&Array.from(t).length>4096;if(e.mode===`readonly`)return n?J(`readonly`,$t):Qt.test(t)?J(`readonly`,`command contains a newline or shell metacharacter`):e.allow.some(e=>e.test(t))?q(`readonly`):J(`readonly`,`command not in allow list`);if(n&&e.needsApproval.length>0)return J(`needs_approval`,$t);let r=e.needsApproval.find(e=>e.re.test(t));return r===void 0?q(`readwrite`):J(`needs_approval`,`matches "${r.pattern}" and needs approval, which is not available yet`)},rn=(e,t)=>e.mode===`deny`?J(`deny`,`host is closed by policy`):e.agents.fold(()=>!1,e=>!en(e,t.agent))?J(`agents`,`agent "${t.agent}" is not in agents`):t.tool===`exec`?nn(e,t.command):t.tool===`tmux_send`||t.tool===`tmux_keys`?tn(e):q(e.mode),an=6e5,on=36e5,sn={maxPerHost:2,idleTimeoutMs:6e4,acquireTimeoutMs:3e4,execTimeoutMs:an,maxExecTimeoutMs:on},Y=e=>typeof e==`string`&&e.length>0?O(e):O.none(),cn=e=>typeof e==`number`?O(e):O.none(),ln=(e,t)=>{if(t.password!==void 0||t.private_key!==void 0)return E(`host "${e}": secrets must not be inline; use key/key_env/agent/password_env/ca`);let n=[Y(t.key).map(()=>`key`),Y(t.key_env).map(()=>`key_env`),Y(t.password_env).map(()=>`password_env`),t.agent===!0?O(`agent`):O.none(),Y(t.ca).map(()=>`ca`)].flatMap(e=>e.toArray());if(n.length===0)return E(`host "${e}": no auth mode (need exactly one of key/key_env/agent/password_env/ca)`);if(n.length>1)return E(`host "${e}": exactly one auth mode allowed, found ${n.length}`);let r={password:Y(t.password_env).flatMap(e=>O(process.env[e]??``)).filter(e=>e.length>0),keyPath:Y(t.key),keyEnvVar:Y(t.key_env),useAgent:t.agent===!0};return k({auth:r,kind:n[0]})},un=2**31-1,X=(e,t,n)=>{let r=e[t];return r===void 0?k(n):typeof r==`number`&&Number.isInteger(r)&&r>=1&&r<=un?k(r):E(`pool.${t} must be a whole number from 1 to ${un}`)},dn=e=>{let t=e.pool??{},n=[X(t,`max_per_host`,2),X(t,`idle_timeout_ms`,6e4),X(t,`acquire_timeout_ms`,3e4),X(t,`exec_timeout_ms`,an),X(t,`max_exec_timeout_ms`,on)],r=n.flatMap(e=>e.fold(e=>[e],()=>[])),[i,a,o,s,c]=n.map(e=>e.orElse(0));return r.length>0?E(r):k({maxPerHost:i,idleTimeoutMs:a,acquireTimeoutMs:o,execTimeoutMs:s,maxExecTimeoutMs:c})},fn=e=>e.length>0&&!e.includes(`,`),pn=e=>e.split(`.`).reduce((e,t)=>(e<<8n)+BigInt(t),0n),mn=e=>{if(e.includes(`.`))return O.none();let[t,n=``]=e.split(`::`),r=t?t.split(`:`):[],i=e.includes(`::`)&&n?n.split(`:`):[],a=e.includes(`::`)?8-r.length-i.length:0,o=[...r,...Array.from({length:a},()=>`0`),...i];return o.length===8?O(o.reduce((e,t)=>(e<<16n)+BigInt(`0x${t||`0`}`),0n)):O.none()},hn=(e,t,n)=>(e&(1n<<BigInt(t-n))-1n)==0n,gn=e=>{let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!/^\d{1,3}$/.test(r))return!1;let i=Number(r),a=ce(n);return a===4?i<=32&&hn(pn(n),32,i):a===6&&i<=128&&mn(n).fold(()=>!1,e=>hn(e,128,i))},_n=e=>{let t=Y(e.name);if(t.isNone())return E(`[[cas]] entry has no name`);let n=t.orElse(``);if(e.key!==void 0||e.private_key!==void 0)return E(`ca "${n}": keys must not be inline; use key_cmd, key_env or key_file`);let r=[...Y(e.key_cmd).fold(()=>[],e=>[{kind:`cmd`,cmd:e}]),...Y(e.key_env).fold(()=>[],e=>[{kind:`env`,name:e}]),...Y(e.key_file).fold(()=>[],e=>[{kind:`file`,path:e}])];if(r.length!==1)return E(`ca "${n}": exactly one of key_cmd, key_env, key_file is required`);let i=r[0],a=e.principal===void 0?`fleet`:typeof e.principal==`string`?e.principal:``;if(!fn(a))return E(`ca "${n}": principal must be non-empty with no commas`);let o=Y(e.source_address);return e.source_address!==void 0&&!o.fold(()=>!1,gn)?E(`ca "${n}": source_address must be an IPv4 or IPv6 CIDR`):k({name:n,key:i,principal:a,sourceAddress:o})},vn=e=>{let t=e.audit??{};return t.path===void 0?k({path:Et}):Y(t.path).fold(()=>E(`audit.path must be a non-empty string`),e=>k({path:e}))},yn=e=>{let t=e,n=t.message.split(`
|
|
5
|
-
`)[0];return t.line===void 0?`Invalid TOML: ${n}`:`Invalid TOML at line ${t.line}, column ${t.column}: ${n}`},
|
|
6
|
-
`));return
|
|
7
|
-
`)}`):
|
|
2
|
+
import{createHash as e,randomBytes as t,randomUUID as n}from"node:crypto";import{chmodSync as r,closeSync as i,constants as a,existsSync as o,fchmodSync as s,fstatSync as c,mkdirSync as l,openSync as u,readFileSync as d,readdirSync as f,rmdirSync as p,statSync as m,unlinkSync as h,writeFileSync as g,writeSync as _}from"node:fs";import{createRequire as v}from"node:module";import{constants as y,homedir as b,uptime as x}from"node:os";import{Either as S,Left as C,List as w,Map as T,Option as E,Right as D,Set as ee,Try as O}from"functype";import{createServer as te}from"somamcp/node";import{z as k}from"zod";import{basename as ne,dirname as A,join as j}from"node:path";import{Fs as re,Path as M}from"functype-os";import{spawn as ie}from"node:child_process";import{UserError as N}from"somamcp";import{Client as ae}from"ssh2";import{lstat as oe,readFile as se}from"node:fs/promises";import{isIP as ce}from"node:net";import{parse as le}from"smol-toml";const ue=(e,t)=>t.cause instanceof Error?t.cause.message.includes(e)?`Failed to read SSH key: ${t.cause.message}`:`Failed to read SSH key ${e}: ${t.cause.message}`:`Failed to read SSH key ${e}: ${t.message}`,de=async e=>{if(e.password.isSome())return D({password:e.password.value});if(e.keyPath.isSome()){let t=M.expand(e.keyPath.value);if(t.isLeft())return C(`Invalid SSH key path ${e.keyPath.value}: ${t.value.message}`);let n=t.value;return(await re.readFile(n)).fold(e=>C(ue(n,e)),e=>D({privateKey:e}))}if(e.keyEnvVar.isSome()){let t=e.keyEnvVar.value,n=process.env[t];return n?D({privateKey:n}):C(`--key-env=${t} but environment variable is not set or empty`)}if(e.useAgent){let e=process.env.SSH_AUTH_SOCK;return e?D({agent:e}):C(`--agent set but SSH_AUTH_SOCK is not set; start ssh-agent or unlock your password manager's SSH agent`)}return D({})},fe=[`PATH`,`HOME`,`USER`,`LOGNAME`,`LANG`],P=(e={})=>({...Object.fromEntries(fe.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]})),...e}),F={run:(e,t,{env:n,input:r,timeoutMs:i})=>new Promise((a,o)=>{let s=ie(e,[...t],{env:{...n},stdio:[`pipe`,`pipe`,`pipe`],detached:i!==void 0}),c=[],l=[],u={done:!1},d=e=>{u.done||(u.done=!0,clearTimeout(f),a(e))},f=setTimeout(()=>{let{pid:e}=s;e!==void 0&&O(()=>process.kill(-e,`SIGKILL`)),d({code:-1,stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(l).toString(),timedOut:!0})},i??2**31-1);s.stdout.on(`data`,e=>c.push(e)),s.stderr.on(`data`,e=>l.push(e)),s.on(`error`,e=>{clearTimeout(f),o(e)}),s.on(`close`,e=>d({code:e??-1,stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(l).toString()})),s.stdin.on(`error`,()=>void 0),s.stdin.end(r??``)}),spawn:(e,t,{env:n})=>{let r=ie(e,[...t],{env:{...n},stdio:[`ignore`,`ignore`,`pipe`]}),i={tail:``,exited:!1,code:null},a=[],o=e=>{i.exited||(i.exited=!0,i.code=e,a.splice(0).forEach(t=>t(e)))};return r.stderr.on(`data`,e=>{i.tail=(i.tail+e.toString()).slice(-4096)}),r.on(`exit`,e=>o(e)),r.on(`error`,e=>{i.tail=(i.tail+e.message).slice(-4096),o(null)}),{onExit:e=>{i.exited?queueMicrotask(()=>e(i.code)):a.push(e)},kill:()=>{i.exited||r.kill()},stderr:()=>i.tail,exited:()=>i.exited,pid:()=>r.pid}}},pe={SSH_ASKPASS:`/bin/false`,SSH_ASKPASS_REQUIRE:`force`},me=[[`ssh`,[`-V`]],[`ssh-keygen`,[`-?`]],[`ssh-agent`,[`-?`]],[`ssh-add`,[`-?`]]],he=async e=>{let t=await Promise.all(me.map(([t,n])=>e.run(t,n,{env:P()}).then(()=>!0,()=>!1))),n=me.filter((e,n)=>!t[n]).map(([e])=>e);return n.length===0?D(void 0):C(`OpenSSH binaries missing: ${n.join(`, `)}`)},ge=e=>new Promise(t=>setTimeout(t,e)),_e=(e,t)=>e()?Promise.resolve(!0):Date.now()>t?Promise.resolve(!1):ge(50).then(()=>_e(e,t)),ve=e=>O(()=>process.kill(e,0)).fold(()=>!1,()=>!0),ye=e=>e===`agent.sock`||e===`agent.pid`||/^m-.*\.(sock|pid)$/.test(e)||e.startsWith(`k-`)||/^ca-.*\.pub$/.test(e),be=`hub.lock`,xe=e=>e===be||ye(e),Se=e=>O(()=>Number(d(e,`utf8`).trim())).orElse(NaN),Ce=e=>Number.isInteger(e)&&e>0&&ve(e),we=async(e,t,n,r)=>{if(!Ce(e))return;let i=await r.run(`ps`,[`-ww`,`-p`,String(e),`-o`,`args=`],{env:P()}).catch(()=>({code:1,stdout:``,stderr:``})),a=i.stdout.trim(),o=ne(a.split(` `)[0]??``).replace(/:$/,``);i.code===0&&o===t&&a.includes(n)&&(O(()=>process.kill(e,`SIGTERM`)),await _e(()=>!ve(e),Date.now()+2e3))},Te=async(e,t)=>{await we(Se(j(e,`agent.pid`)),`ssh-agent`,j(e,`agent.sock`),t);let n=f(e).filter(e=>/^m-.*\.pid$/.test(e));await Promise.all(n.map(n=>we(Se(j(e,n)),`ssh`,j(e,n.replace(/\.pid$/,`.sock`)),t))),f(e).filter(ye).forEach(t=>O(()=>h(j(e,t))))},Ee=e=>O(()=>(l(e,{recursive:!0,mode:448}),f(e).filter(e=>!xe(e)))).fold(t=>C(`runtime_dir ${e}: ${t.message}`),t=>t.length>0?C(`runtime_dir ${e} holds files the hub did not create (${t.slice(0,3).join(`, `)}); give runtime_dir a directory of its own`):O(()=>r(e,448)).fold(t=>C(`runtime_dir ${e}: ${t.message}`),()=>D(void 0))),De=e=>O(()=>m(e).mtimeMs>=Date.now()-x()*1e3).orElse(!1),Oe=e=>{let t=j(e,be),n=Se(t);return Ce(n)&&De(t)?C(`runtime_dir ${e} is in use by pid ${n}; give each hub its own runtime_dir (delete ${t} if that process is not a hub)`):O(()=>{O(()=>h(t)),g(t,String(process.pid),{mode:384,flag:`wx`})}).fold(t=>C(`runtime_dir ${e}: can't take ${be}: ${t.message}`),()=>D(void 0))},ke=e=>{O(()=>f(e)).orElse([]).filter(xe).forEach(t=>O(()=>h(j(e,t)))),O(()=>p(e))},Ae=/^[\w-]+$/,je=e=>Ae.test(e),Me=async(e,t)=>{let n=await t.run(`ssh-add`,[`-L`],{env:P({SSH_AUTH_SOCK:e})});return n.code===0?n.stdout.split(`
|
|
3
|
+
`).filter(e=>e.startsWith(`ssh-`)):[]},Ne=async(e,t,n,r)=>{let i=(t,n)=>C(`CA "${e.name}": ${t} failed: ${n.trim()}`);if(!je(e.name))return i(`naming`,`use letters, digits, hyphen or underscore`);let a=await e.key();if(a.isLeft())return i(`reading the key`,a.value);let o=P({...pe,SSH_AUTH_SOCK:n}),s=await Me(n,r),c=await r.run(`ssh-add`,[`-`],{env:o,input:a.value});if(c.code!==0)return i(`loading into the agent`,c.stderr);let l=(await Me(n,r)).filter(e=>!s.includes(e));if(l.length!==1)return i(`loading into the agent`,`the key is already loaded for another CA`);let u=j(t,`ca-${e.name}.pub`);return g(u,`${l[0]}\n`,{mode:384}),D([e.name,u])},Pe=async e=>{e.kill(),await Promise.race([new Promise(t=>e.onExit(()=>t())),ge(2e3)])},Fe=async(e,t,n)=>{let r=Ee(e).flatMap(()=>Oe(e));if(r.isLeft())return C(r.value);await Te(e,n);let i=j(e,`agent.sock`),a=n.spawn(`ssh-agent`,[`-D`,`-a`,i],{env:P()});if(!await _e(()=>o(i)||a.exited(),Date.now()+5e3)||a.exited())return await Pe(a),ke(e),C(`ssh-agent failed to start: ${a.stderr().trim()||`timed out`}`);let s=a.pid();s!==void 0&&g(j(e,`agent.pid`),String(s),{mode:384});let c=await S.traverseAsync(t,t=>Ne(t,e,i,n));if(c.isLeft())return await Pe(a),ke(e),C(c.value);let l=T.of(...c.value.map(([e,t])=>[e,t]));return D({runtimeDir:e,agentSock:i,pubPath:e=>l.get(e),shutdown:async()=>{await Pe(a),ke(e)}})},Ie=(t,n,r)=>{let i=e(`sha256`).update(`${n}\0${r}`).digest(`hex`).slice(0,12),a=j(t,`m-${i}.sock`);return Buffer.byteLength(a)+5<=86?D(a):C(`runtime_dir ${t} is too long for control sockets (socket paths must be at most 86 bytes)`)},I={last:0n},Le=e=>{let t=BigInt(e)*1000n;return I.last=t>I.last?t:I.last+1n,I.last},Re=e=>[`-O`,`no-port-forwarding`,`-O`,`no-agent-forwarding`,`-O`,`no-x11-forwarding`,`-O`,`no-user-rc`,...e.fold(()=>[],e=>[`-O`,`source-address=${e}`])],ze=async(e,n,r,i=()=>/* @__PURE__ */ new Date)=>{let a=(e,t)=>C(`CA "${n.ca}": ${e} failed: ${t.trim()}`),o=e.pubPath(n.ca);if(o.isNone())return a(`signing`,`no CA named "${n.ca}" in custody`);let s=j(e.runtimeDir,`k-${t(8).toString(`hex`)}`),c=`${s}-cert.pub`,l=[s,`${s}.pub`,c],u=()=>(l.forEach(e=>O(()=>h(e))),Promise.resolve()),d=await r.run(`ssh-keygen`,[`-q`,`-t`,`ed25519`,`-N`,``,`-C`,``,`-f`,s],{env:P()});if(d.code!==0)return await u(),a(`key generation`,d.stderr);let f=i(),p=Le(f.getTime()),m=await r.run(`ssh-keygen`,[`-U`,`-s`,o.orElse(``),`-I`,n.agent,`-n`,n.principal,`-V`,`-5m:+10m`,`-z`,p.toString(),...Re(n.sourceAddress),`${s}.pub`],{env:P({SSH_AUTH_SOCK:e.agentSock})});return m.code===0?D({keyPath:s,certPath:c,validUntil:new Date(f.getTime()+6e5),serial:p.toString(),dispose:u}):(await u(),a(`signing`,m.stderr))},L=e=>e.timedOutMs===void 0?e.noExitStatus===!0?`exit ${e.code} (no exit status: channel closed)`:e.signal===void 0?`exit ${e.code}`:`exit ${e.code} (signal ${e.signal})`:`timed out after ${e.timedOutMs} ms`,Be=/^tmux[\w -]* timed out after \d+ ms$/,Ve=e=>Be.test(e),He=/^[A-Za-z0-9_-]+$/,R=e=>He.test(e)?D(e):C(`Invalid session name "${e}": only letters, digits, hyphen, and underscore are allowed`),Ue=[`Invalid session name `,`Unsupported key `,`No keys provided`],We=e=>Ue.some(t=>e.startsWith(t)),Ge=e=>`'${e.replaceAll(`'`,`'\\''`)}'`,Ke=e=>Math.max(1,Math.min(2e3,Math.floor(e))),qe=e=>e.replace(/\s+$/,``),Je=/* @__PURE__ */ new Set([`Enter`,`Escape`,`Tab`,`Space`,`BSpace`,`Up`,`Down`,`Left`,`Right`,`Home`,`End`,`PageUp`,`PageDown`,`C-c`,`C-d`,`C-z`,`C-l`,`C-u`,`C-a`,`C-e`,`C-r`]),Ye=e=>Je.has(e)?D(e):C(`Unsupported key "${e}": allowed keys are ${[...Je].join(`, `)}`),Xe=e=>`PATH="$PATH:/opt/homebrew/bin:/usr/local/bin"; ${e}`,Ze=()=>Xe(`tmux list-sessions -F '#{session_name}'`),Qe=(e,t,n)=>R(e).map(e=>{let r=`{ tmux has-session -t ${e} 2>/dev/null || tmux new-session -d -s ${e}; }`,i=`tmux send-keys -t ${e} -l -- ${Ge(t)}`,a=n?` && tmux send-keys -t ${e} Enter`:``;return Xe(`${r} && ${i}${a}`)}),$e=(e,t)=>R(e).map(e=>Xe(`tmux capture-pane -t ${e} -p -J -S -${Ke(t)}`)),et=(e,t)=>R(e).flatMap(e=>{if(t.length===0)return C(`No keys provided`);let n=t.find(e=>Ye(e).isLeft());return n===void 0?D(Xe(`tmux send-keys -t ${e} ${t.join(` `)}`)):Ye(n)}),tt=`the SSH account's login shell isn't POSIX-compatible (csh, tcsh or fish), so it can't parse tmux commands — set it to sh, bash or zsh, or use the exec tool instead`,nt=/^Bad : modifier in \$|Unsupported use of '='/m,rt=e=>e.code!==0&&nt.test(e.stderr),z=`tmux not found on the remote host — install tmux (e.g. apt/brew install tmux) or use the exec tool instead`,it=/can't find session|can't find pane|session not found/i,at=/no server running|error connecting to .+ \(No such file or directory\)/i,B=e=>e.code===127||/tmux: ([Cc]ommand )?not found/i.test(e.stderr),V=(e,t)=>t.timedOutMs===void 0?`${e} failed: ${t.stderr.trim()||L(t)}`:`${e} ${L(t)}`,ot=e=>e.timedOutMs===void 0?rt(e)?C(tt):B(e)?C(z):e.code===0?D(e.stdout.split(`
|
|
4
|
+
`).map(e=>e.trim()).filter(e=>e.length>0)):at.test(e.stderr)?D([]):C(V(`tmux list-sessions`,e)):C(V(`tmux list-sessions`,e)),st=e=>t=>t.timedOutMs===void 0?rt(t)?C(tt):B(t)?C(z):t.code===0?D(void 0):C(V(e,t)):C(V(e,t)),ct=e=>t=>t.timedOutMs===void 0?rt(t)?C(tt):B(t)?C(z):t.code===0?D(qe(t.stdout)):it.test(t.stderr)?C(`No tmux session "${e}" — list with tmux_list, or tmux_send creates one`):C(V(`tmux capture-pane`,t)):C(V(`tmux capture-pane`,t)),lt=e=>t=>t.timedOutMs===void 0?rt(t)?C(tt):B(t)?C(z):t.code===0?D(void 0):it.test(t.stderr)?C(`No tmux session "${e}" — list with tmux_list, or tmux_send creates one`):C(V(`tmux send-keys`,t)):C(V(`tmux send-keys`,t)),ut=async e=>ot(await e(Ze())),dt=async(e,t)=>{let n=Qe(t.session,t.input,t.submit);return n.isLeft()?C(n.value):st(`tmux_send`)(await e(n.value))},ft=async(e,t)=>{let n=$e(t.session,t.lines);return n.isLeft()?C(n.value):ct(t.session)(await e(n.value))},pt=async(e,t)=>{let n=et(t.session,t.keys);return n.isLeft()?C(n.value):lt(t.session)(await e(n.value))},mt=e=>E(y.signals[`SIG${e}`]).fold(()=>255,e=>128+e),ht=(e,t,n,r)=>{if(typeof n==`number`)return{stdout:e,stderr:t,code:n};if(typeof r!=`string`||r===``)return{stdout:e,stderr:t,code:255,noExitStatus:!0};let i=r.replace(/^SIG/,``);return{stdout:e,stderr:t,code:mt(i),signal:i}},gt=(e,t,n)=>({stdout:e,stderr:t,code:124,timedOutMs:n}),_t=e=>{if(e.code===0)return D(e.stderr?`${e.stdout}\n[stderr]\n${e.stderr}`:e.stdout);let t=e.stderr&&e.stdout?`${e.stderr}\n[stdout]\n${e.stdout}`:e.stderr||e.stdout;return C(`${L(e)}:\n${t}`)},vt=e=>new Promise(t=>setTimeout(t,e)),yt=e=>[`-p`,String(e.port??22),`${e.username??``}@${e.host??``}`],bt=(e,t,n,r)=>[`-F`,`/dev/null`,`-M`,`-N`,`-S`,t,`-o`,`ControlPersist=no`,`-o`,`IdentitiesOnly=yes`,`-o`,`IdentityAgent=none`,`-o`,`IdentityFile=${r.keyPath}`,`-o`,`CertificateFile=${r.certPath}`,`-o`,`BatchMode=yes`,`-o`,`StrictHostKeyChecking=accept-new`,`-o`,`UserKnownHostsFile=${n}`,`-o`,`ConnectTimeout=10`,`-o`,`ServerAliveInterval=15`,`-o`,`ServerAliveCountMax=3`,...yt(e)],xt=(e,t,n)=>[`-F`,`/dev/null`,`-S`,t,`-o`,`ControlMaster=no`,`-o`,`ProxyCommand=false`,`-o`,`BatchMode=yes`,...yt(e),`--`,n],St=e=>{let t={run:E.none()};return()=>t.run.fold(()=>{let n=e();return t.run=E(n),n},e=>e)},Ct=e=>{let{proc:n,socketPath:r,knownHosts:i}=e,a=e.readyTimeoutMs??15e3,o=e.drainTimeoutMs??6e4,s=e.setTimer??((e,t)=>setTimeout(e,t)),c=e.clearTimer??(e=>clearTimeout(e)),l=(e,t)=>Promise.race([new Promise(t=>e.onExit(()=>t())),new Promise(e=>s(e,t))]),u=(e,t)=>l(e,o).then(()=>(e.kill(),t())),d=new globalThis.Set,f=(e,t,r)=>n.run(`ssh`,[`-F`,`/dev/null`,`-S`,t,`-O`,e,...yt(r)],{env:P()}),p=(e,t,n,r)=>e.exited()?Promise.resolve(C(`master for ${n.host} exited: ${e.stderr().trim()}`)):Date.now()>r?Promise.resolve(C(`master for ${n.host} did not come up: ${e.stderr().trim()}`)):f(`check`,t,n).then(i=>i.code===0&&!e.exited()?D(void 0):vt(100).then(()=>p(e,t,n,r)));return{connect:async o=>{let l=await e.mintFor();if(l.isLeft())throw Error(l.value);let m=l.value,_=St(m.dispose),v=r.replace(/\.sock$/,`-${t(2).toString(`hex`)}.sock`),y=v.replace(/\.sock$/,`.pid`),b=n.spawn(`ssh`,bt(o,v,i,m),{env:P()}),x=b.pid();x!==void 0&&O(()=>g(y,String(x),{mode:384})),b.onExit(()=>O(()=>h(y)));let S=await p(b,v,o,Date.now()+a);if(S.isLeft())throw b.kill(),await _(),Error(S.value);let C={closing:!1,closed:!1,retired:!1},w=[],T=()=>{C.closed||(C.closed=!0,w.splice(0).forEach(e=>e()))};b.onExit(()=>{T(),_()});let E=s(()=>{C.closing||C.retired||(C.retired=!0,T(),f(`stop`,v,o).catch(()=>void 0).then(()=>u(b,_)))},e.retireAfterMs??Math.max(0,m.validUntil.getTime()-Date.now()));b.onExit(()=>c(E));let D=()=>{c(E),C.closing||C.retired||(C.closing=!0,f(`exit`,v,o).catch(()=>void 0).then(()=>u(b,_)))},ee={child:b,close:D};return d.add(ee),b.onExit(()=>d.delete(ee)),{exec:async(e,t={})=>{if(b.exited()||C.closing||C.retired)throw Error(`master for ${o.host} is gone`);let r=await n.run(`ssh`,xt(o,v,e),{env:P(),timeoutMs:t.timeoutMs});return r.timedOut===!0?gt(r.stdout,r.stderr,t.timeoutMs??0):{stdout:r.stdout,stderr:r.stderr,code:r.code}},close:D,onClose:e=>{w.push(e)}}},shutdown:async()=>{let e=[...d];e.forEach(e=>e.close()),await Promise.all(e.map(e=>e.child.exited()?Promise.resolve():l(e.child,o)))}}},wt=e=>new Promise((t,n)=>{let r=new ae,i=[];r.on(`ready`,()=>t({exec:(e,t={})=>new Promise((n,i)=>{r.exec(e,(e,r)=>{if(e){i(e);return}let a=[],o=[],s=t.timeoutMs===void 0?void 0:setTimeout(()=>{let e=t.timeoutMs??0;n(gt(Buffer.concat(a).toString(),Buffer.concat(o).toString(),e)),r.signal(`KILL`),r.close()},t.timeoutMs);r.on(`close`,(e,t)=>{clearTimeout(s),n(ht(Buffer.concat(a).toString(),Buffer.concat(o).toString(),e,t))}),r.on(`data`,e=>a.push(e)),r.stderr.on(`data`,e=>o.push(e))})}),close:()=>r.end(),onClose:e=>i.push(e)})),r.on(`error`,e=>{i.forEach(e=>e()),n(e)}),r.on(`close`,()=>i.forEach(e=>e())),r.connect({keepaliveInterval:15e3,...e})}),Tt=(e,t,n=wt)=>{let r=T.of(...e.map(e=>[e.name,{name:e.name,sshConfig:e.sshConfig,inFlight:0,waiters:[]}])),i=()=>[...r].map(([,e])=>e),a=e=>{e.conn=void 0,e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=void 0)},o=async e=>e.conn?e.conn:(e.connecting||(e.connecting=n(e.sshConfig).then(t=>(t.onClose(()=>{e.conn===t&&a(e)}),e.conn=t,e.connecting=void 0,t)),e.connecting.catch(()=>{e.connecting=void 0})),e.connecting),s=e=>e.inFlight<t.maxPerHost?(e.inFlight++,Promise.resolve()):new Promise((n,r)=>{let i=()=>{clearTimeout(a),n()},a=setTimeout(()=>{let n=e.waiters.indexOf(i);n!==-1&&e.waiters.splice(n,1),r(/* @__PURE__ */ Error(`host "${e.name}" busy: no free connection slot after ${t.acquireTimeoutMs}ms`))},t.acquireTimeoutMs);e.waiters.push(i)}),c=e=>{let n=e.waiters.shift();n?n():(e.inFlight--,e.inFlight===0&&e.conn&&(e.idleTimer=setTimeout(()=>{e.conn?.close(),a(e)},t.idleTimeoutMs)))};return{run:async(e,t,n)=>{let i=r.get(e).orThrow(/* @__PURE__ */ Error(`unknown host "${e}"`));i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=void 0),await s(i);try{return await(await o(i)).exec(t,n).catch(async()=>(a(i),(await o(i)).exec(t,n)))}finally{c(i)}},status:()=>i().map(e=>({name:e.name,state:e.conn?e.inFlight>0?`connected`:`idle`:`disconnected`,inFlight:e.inFlight})),shutdown:()=>(i().forEach(e=>{e.idleTimer&&clearTimeout(e.idleTimer),e.conn?.close(),a(e)}),Promise.resolve())}},Et=`Call hosts_list for the configured host names.`,Dt=e=>e.startsWith(`unknown host`),Ot=e=>Dt(e)?new N(e,{category:`not_found`,suggestions:[Et]}):We(e)?new N(e,{category:`validation`,suggestions:[]}):Ve(e)?new N(e,{category:`timeout`,suggestions:[`tmux took longer than [pool].exec_timeout_ms. Try again, or raise it.`]}):new N(e,{category:`execution`,suggestions:[]}),kt=(e,t)=>new N(`[${e}] ${t}`,{category:`timeout`,suggestions:[`The command may still be running on ${e}. For a long job, start it in tmux with tmux_send and check it with tmux_read, or pass a larger timeout_ms.`]}),At=e=>new N(e,{category:`auth`,suggestions:[`This host's policy doesn't allow it. Use a command or tool the policy allows, or ask the operator.`]}),H=e=>t=>{if(t instanceof N)throw t;if(t instanceof TypeError||t instanceof RangeError)throw new N(t.message,{category:`internal`,suggestions:[]});let n=t instanceof Error?t.message:String(t);throw Dt(n)?new N(n,{category:`not_found`,suggestions:[Et]}):n.includes(` busy: no free connection slot`)?new N(n,{category:`timeout`,suggestions:[`Every connection to ${e} is in use. Try again, or raise [pool].max_per_host.`]}):new N(`[${e}] ${n}`,{category:`execution`,suggestions:[`Call fleet_setup to see ${e}'s connection state and what to configure.`]})},U=`unknown`,jt=`~/.local/state/ssh-fleet/audit.jsonl`,Mt=e=>E(e.name).flatMap(t=>Nt(e.version===void 0?t:`${t}/${e.version}`)),Nt=e=>E(e).map(e=>Array.from(e.replace(/\p{Cc}/gu,``).trim()).slice(0,64).join(``)).filter(e=>e.length>0),Pt=e=>Array.from(e).slice(0,1024).join(``),Ft=e=>e.timedOutMs===void 0&&e.noExitStatus!==!0?{}:{status:`error`,error:L(e)},W=e=>e instanceof Error?e.message:String(e),It=(e,t)=>e.fold(()=>t,e=>`${e}:${t}`),Lt=e=>e.verdict.decision===`allow`?{decision:`allow`,...e.verdict.rule.fold(()=>({}),t=>({rule:It(e.host,t)}))}:{decision:`deny`,rule:It(e.host,e.verdict.rule),reason:e.verdict.reason},Rt=({sink:e,now:t,newId:n,client:r})=>{let i=(t,n)=>O(()=>e(JSON.stringify(t))).fold(e=>{throw new N(`audit log write failed ${n}: ${W(e)}`,{category:`internal`,suggestions:[`The server refuses every call while it can't write its audit log. Check the [audit].path file.`]})},()=>void 0);return{audited:async(e,a,o)=>{let s=n(),c={agent:e.agent,...r===void 0?{}:{client:r},tool:e.tool,...e.host.fold(()=>({}),e=>({host:e}))},l=t();if(i({ts:l.toISOString(),id:s,event:`decision`,...c,...e.fields,...Lt(e)},`— call not executed`),e.verdict.decision===`deny`){let t=e.host.fold(()=>``,e=>`[${e}] `);throw At(`${t}denied by rule ${e.verdict.rule}: ${e.verdict.reason}`)}let u=await Promise.resolve().then(a).then(e=>({ok:!0,value:e}),e=>({ok:!1,error:e})),d=t(),f={ts:d.toISOString(),id:s,event:`result`,...c},p=d.getTime()-l.getTime();if(u.ok)return i({...f,status:`ok`,ms:p,...o(u.value)},`after execution`),u.value;throw i({...f,status:`error`,ms:p,error:W(u.error)},`after execution`),u.error}}},zt=a.O_WRONLY|a.O_APPEND|a.O_CREAT|a.O_NOFOLLOW,Bt=(e,t)=>{let n=u(e,zt,384);try{t(n)}finally{i(n)}},Vt=(e,t)=>Bt(e,e=>{let n=`${t}\n`,r=Buffer.byteLength(n),i=_(e,n);if(i!==r)throw Error(`short write: ${i} of ${r} bytes`)}),Ht=e=>{(c(e).mode&511)!=384&&s(e,384)},Ut=e=>M.expand(e).fold(t=>C(`invalid audit path ${e}: ${W(t)}`),e=>O(()=>{l(A(e),{recursive:!0,mode:448}),Bt(e,Ht)}).fold(t=>C(`audit log ${e} is not writable: ${W(t)}`),()=>D(t=>Vt(e,t)))),Wt=()=>({commit:`ea8d88438f0e`,branch:`ssh-fleet-mcp-server@0.2.3`,date:`2026-11-29T15:59:56.803Z`}),Gt=[`readonly`,`readwrite`,`deny`],Kt=[`approve`,`open`],qt=[`mode`,`tmux`,`allow`,`needs_approval`,`agents`],G={mode:E.none(),tmux:E.none(),allow:E.none(),needsApproval:E.none(),agents:E.none()},Jt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Yt=(e,t,n)=>e===void 0?D(E.none()):typeof e==`string`&&t.includes(e)?D(E(e)):C(n),Xt=(e,t)=>e===void 0?D(E.none()):Array.isArray(e)&&e.every(e=>typeof e==`string`)?D(E(e)):C(t),Zt=e=>e.fold(e=>[e],()=>[]),Qt=(e,t)=>{if(e===void 0)return D(G);if(!Jt(e))return C([`${t} must be a table`]);let n=Yt(e.mode,Gt,`${t}.mode must be one of readonly, readwrite, deny`),r=Yt(e.tmux,Kt,`${t}.tmux must be approve or open`),i=Xt(e.allow,`${t}.allow must be an array of strings`),a=Xt(e.needs_approval,`${t}.needs_approval must be an array of strings`),o=Xt(e.agents,`${t}.agents must be an array of strings`),s=[...Object.keys(e).filter(e=>!qt.includes(e)).map(e=>`${t}: unknown key "${e}"`),...[n,r,i,a,o].flatMap(Zt)];return s.length>0?C(s):D({mode:n.orElse(G.mode),tmux:r.orElse(G.tmux),allow:i.orElse(G.allow),needsApproval:a.orElse(G.needsApproval),agents:o.orElse(G.agents)})},$t=e=>e.filter(e=>e.length>0).orElse([]),en=(e,t,n,r)=>{let i=n.map(n=>O(()=>new RegExp(r(new RegExp(n).source))).fold(r=>C(`${e}: invalid regex in ${t}: "${n}" (${r.message})`),e=>D(e))),a=i.flatMap(Zt);return a.length>0?C(a):D(i.flatMap(e=>e.fold(()=>[],e=>[e])))},tn=e=>e.fold(e=>e,()=>[]),nn=(e,t,n)=>{let r=n.mode.or(t.mode).orElse(`readwrite`),i=n.tmux.or(t.tmux).orElse(`open`),a=$t(n.allow.or(t.allow)),o=$t(n.needsApproval.or(t.needsApproval)),s=$t(n.agents.or(t.agents)),c=en(e,`allow`,a,e=>`^(?:${e})$`),l=en(e,`needs_approval`,o,e=>e),u=[...tn(c),...tn(l),...a.length>0&&r!==`readonly`?[`${e}: allow applies only to mode = "readonly"`]:[],...o.length>0&&r!==`readwrite`?[`${e}: needs_approval applies only to mode = "readwrite"`]:[]];return u.length>0?C(u):D({mode:r,tmux:i,allow:c.orElse([]),needsApproval:l.orElse([]).map((e,t)=>({pattern:o[t]??e.source,re:e})),agents:s.length>0?E(s):E.none()})},K={decision:`allow`,rule:E.none()},q=e=>({decision:`allow`,rule:E(e)}),J=(e,t)=>({decision:`deny`,rule:e,reason:t}),rn=/[\n\r\0;&|$`()<>{}\\'"*?[~]/,an=`command is longer than 4096 characters`,on=(e,t)=>e.some(e=>t===e||t.startsWith(`${e}@`)),sn=e=>e.mode===`readonly`?J(`readonly`,`tmux input is not allowed on a readonly host`):e.tmux===`approve`?J(`tmux`,`tmux input requires approval, which is not available yet`):q(`readwrite`),cn=(e,t)=>{let n=t.length>4096&&Array.from(t).length>4096;if(e.mode===`readonly`)return n?J(`readonly`,an):rn.test(t)?J(`readonly`,`command contains a newline or shell metacharacter`):e.allow.some(e=>e.test(t))?q(`readonly`):J(`readonly`,`command not in allow list`);if(n&&e.needsApproval.length>0)return J(`needs_approval`,an);let r=e.needsApproval.find(e=>e.re.test(t));return r===void 0?q(`readwrite`):J(`needs_approval`,`matches "${r.pattern}" and needs approval, which is not available yet`)},ln=(e,t)=>e.mode===`deny`?J(`deny`,`host is closed by policy`):e.agents.fold(()=>!1,e=>!on(e,t.agent))?J(`agents`,`agent "${t.agent}" is not in agents`):t.tool===`exec`?cn(e,t.command):t.tool===`tmux_send`||t.tool===`tmux_keys`?sn(e):q(e.mode),un=e=>e.user.orElse(process.env.USER??`root`),dn=6e5,fn=36e5,pn={maxPerHost:2,idleTimeoutMs:6e4,acquireTimeoutMs:3e4,execTimeoutMs:dn,maxExecTimeoutMs:fn},Y=e=>typeof e==`string`&&e.length>0?E(e):E.none(),mn=e=>typeof e==`number`?E(e):E.none(),hn=(e,t)=>{if(t.password!==void 0||t.private_key!==void 0)return C(`host "${e}": secrets must not be inline; use key/key_env/agent/password_env/ca`);let n=[Y(t.key).map(()=>`key`),Y(t.key_env).map(()=>`key_env`),Y(t.password_env).map(()=>`password_env`),t.agent===!0?E(`agent`):E.none(),Y(t.ca).map(()=>`ca`)].flatMap(e=>e.toArray());if(n.length===0)return C(`host "${e}": no auth mode (need exactly one of key/key_env/agent/password_env/ca)`);if(n.length>1)return C(`host "${e}": exactly one auth mode allowed, found ${n.length}`);let r={password:Y(t.password_env).flatMap(e=>E(process.env[e]??``)).filter(e=>e.length>0),keyPath:Y(t.key),keyEnvVar:Y(t.key_env),useAgent:t.agent===!0};return D({auth:r,kind:n[0]})},gn=2**31-1,X=(e,t,n)=>{let r=e[t];return r===void 0?D(n):typeof r==`number`&&Number.isInteger(r)&&r>=1&&r<=gn?D(r):C(`pool.${t} must be a whole number from 1 to ${gn}`)},_n=e=>{let t=e.pool??{},n=[X(t,`max_per_host`,2),X(t,`idle_timeout_ms`,6e4),X(t,`acquire_timeout_ms`,3e4),X(t,`exec_timeout_ms`,dn),X(t,`max_exec_timeout_ms`,fn)],r=n.flatMap(e=>e.fold(e=>[e],()=>[])),[i,a,o,s,c]=n.map(e=>e.orElse(0));return r.length>0?C(r):D({maxPerHost:i,idleTimeoutMs:a,acquireTimeoutMs:o,execTimeoutMs:s,maxExecTimeoutMs:c})},vn=e=>e.length>0&&!e.includes(`,`),yn=e=>e.split(`.`).reduce((e,t)=>(e<<8n)+BigInt(t),0n),bn=e=>{if(e.includes(`.`))return E.none();let[t,n=``]=e.split(`::`),r=t?t.split(`:`):[],i=e.includes(`::`)&&n?n.split(`:`):[],a=e.includes(`::`)?8-r.length-i.length:0,o=[...r,...Array.from({length:a},()=>`0`),...i];return o.length===8?E(o.reduce((e,t)=>(e<<16n)+BigInt(`0x${t||`0`}`),0n)):E.none()},xn=(e,t,n)=>(e&(1n<<BigInt(t-n))-1n)==0n,Sn=e=>{let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!/^\d{1,3}$/.test(r))return!1;let i=Number(r),a=ce(n);return a===4?i<=32&&xn(yn(n),32,i):a===6&&i<=128&&bn(n).fold(()=>!1,e=>xn(e,128,i))},Cn=e=>{let t=Y(e.name);if(t.isNone())return C(`[[cas]] entry has no name`);let n=t.orElse(``);if(!je(n))return C(`ca "${n}": name must use only letters, digits, hyphen or underscore`);if(e.key!==void 0||e.private_key!==void 0)return C(`ca "${n}": keys must not be inline; use key_cmd, key_env or key_file`);let r=[...Y(e.key_cmd).fold(()=>[],e=>[{kind:`cmd`,cmd:e}]),...Y(e.key_env).fold(()=>[],e=>[{kind:`env`,name:e}]),...Y(e.key_file).fold(()=>[],e=>[{kind:`file`,path:e}])];if(r.length!==1)return C(`ca "${n}": exactly one of key_cmd, key_env, key_file is required`);let i=r[0],a=e.principal===void 0?`fleet`:typeof e.principal==`string`?e.principal:``;if(!vn(a))return C(`ca "${n}": principal must be non-empty with no commas`);let o=Y(e.source_address);return e.source_address!==void 0&&!o.fold(()=>!1,Sn)?C(`ca "${n}": source_address must be an IPv4 or IPv6 CIDR`):D({name:n,key:i,principal:a,sourceAddress:o})},wn=e=>{let t=e.audit??{};return t.path===void 0?D({path:jt}):Y(t.path).fold(()=>C(`audit.path must be a non-empty string`),e=>D({path:e}))},Tn=e=>{let t=e,n=t.message.split(`
|
|
5
|
+
`)[0];return t.line===void 0?`Invalid TOML: ${n}`:`Invalid TOML at line ${t.line}, column ${t.column}: ${n}`},En=e=>{let t=O(()=>le(e));if(t.isFailure())return C(Tn(t.error));let n=t.orThrow(),r=n.defaults??{},i=mn(r.port).orElse(22),a=Y(r.user),o=Y(r.tmux_session).orElse(`agent`),s=Array.isArray(n.hosts)?n.hosts:[],c=Qt(r.policy,`defaults.policy`),l=c.orElse(G),u=s.map(e=>Y(e.name).orElse(``)),d=Array.isArray(n.cas)?n.cas:[],f=d.map(e=>Y(e.name).orElse(``)),p=(e,t)=>{let n=Y(e.name).orElse(``);if(!R(n).isRight())return C(`invalid host name "${n}": only letters, digits, hyphen, underscore`);if(u.indexOf(n)<t)return C(`duplicate host name "${n}"`);let r=Y(e.host);if(r.isNone())return C(`host "${n}": missing host address`);if(e.log_output!==void 0&&typeof e.log_output!=`boolean`)return C(`host "${n}": log_output must be true or false`);let s=Y(e.ca);if(s.isSome()&&!f.includes(s.orElse(``)))return C(`host "${n}": ca "${s.orElse(``)}" is not defined in [[cas]]`);let c=typeof e.principal==`string`?E(e.principal):E.none();if(e.principal!==void 0&&s.isNone())return C(`host "${n}": principal applies only to ca auth`);if(e.principal!==void 0&&!c.fold(()=>!1,vn))return C(`host "${n}": principal must be non-empty with no commas`);let d=`host "${n}": policy`,p=Qt(e.policy,d).flatMap(e=>nn(d,l,e)).mapLeft(e=>e.join(`
|
|
6
|
+
`));return hn(n,e).flatMap(({auth:t,kind:l})=>p.map(u=>({name:n,host:r.orElse(``),port:mn(e.port).orElse(i),user:Y(e.user).or(a),auth:t,authKind:l,passwordEnv:Y(e.password_env),tmuxSession:Y(e.tmux_session).orElse(o),logOutput:e.log_output===!0,policy:u,ca:s,principal:c})))},m=wn(n),h=s.map(p),g=d.map(Cn),_=[...g.flatMap(e=>e.fold(e=>[e],()=>[])),...f.filter((e,t)=>e!==``&&f.indexOf(e)<t).map(e=>`ca "${e}": duplicate name`)],v=_n(n),y=[..._,...c.fold(e=>[...e],()=>[]),...v.fold(e=>[...e],()=>[]),...[m,...h].flatMap(e=>e.fold(e=>[e],()=>[]))],b=h.flatMap(e=>e.fold(()=>[],e=>[e]));return y.length>0?C(`Fleet config errors:\n${w(y).toArray().join(`
|
|
7
|
+
`)}`):D({hosts:b,pool:v.orElse(pn),audit:m.orElse({path:jt}),cas:g.flatMap(e=>e.fold(()=>[],e=>[e])),runtimeDir:Y(n.runtime_dir),knownHosts:Y(n.known_hosts)})},Dn=e=>[...e.hosts.length===0?[`no hosts configured; add a [[hosts]] entry and restart`]:[],...e.hosts.flatMap(e=>e.passwordEnv.filter(e=>!process.env[e]).fold(()=>[],t=>[`host "${e.name}": password_env ${t} is not set`])),...e.hosts.filter(e=>e.policy.agents.isSome()).map(e=>`host "${e.name}": policy.agents is set, so every call is denied until agent identity is available`)],On=e=>e.status().map(t=>t.state===`disconnected`?e.lastError(t.name.split(` `)[0]).fold(()=>t,e=>({...t,state:`error`,last_error:e})):t),kn=()=>j(b(),`.local`,`state`,`ssh-fleet`),An=()=>{let e=process.env.XDG_RUNTIME_DIR;return e?j(e,`ssh-fleet`):j(kn(),`run`)},jn=()=>j(kn(),`known_hosts`),Mn=async e=>{let t=M.expand(e);if(t.isLeft())return C(`key_file ${e}: ${t.value.message}`);let n=t.value,r=await oe(n).catch(e=>e);return r instanceof Error?C(`key_file ${n}: ${r.message}`):r.isSymbolicLink()?C(`key_file ${n} is a symlink`):r.isFile()?r.mode&63?C(`key_file ${n} must be mode 0600 or stricter`):r.uid===process.getuid?.()?D(await se(n,`utf8`)):C(`key_file ${n} is not owned by the hub user`):C(`key_file ${n} is not a regular file`)},Nn=async(e,t)=>{switch(e.kind){case`cmd`:{let n=Object.fromEntries(Object.entries(process.env).flatMap(([e,t])=>t===void 0?[]:[[e,t]])),r=await F.run(`sh`,[`-c`,e.cmd],{env:n,timeoutMs:t}).catch(e=>({code:-1,stdout:``,stderr:e.message}));return r.code===0&&r.stdout.trim().length>0?D(`${r.stdout.trim()}\n`):C(r.timedOut===!0?`key_cmd timed out after ${t} ms`:`key_cmd exited ${r.code}: ${r.stderr.trim()||`no output`}`)}case`env`:{let t=process.env[e.name];return delete process.env[e.name],t?D(t):C(`environment variable ${e.name} is not set`)}case`file`:return Mn(e.path)}},Pn=(e,t={})=>({name:e.name,key:()=>Nn(e.key,t.timeoutMs??3e4)}),Fn=async(e,t,n)=>(await S.traverseAsync(t,async t=>(await ze(e,{ca:t.name,agent:`self-test`,principal:t.principal,sourceAddress:t.sourceAddress},n)).fold(e=>Promise.resolve(C(e)),e=>e.dispose().then(()=>D(void 0))))).map(()=>void 0),In=e=>({host:e.host,port:e.port,username:un(e)}),Ln=async e=>(await de(e.auth)).map(t=>({...In(e),...t})),Rn=async(e,t,n=E.none())=>{let r=e.hosts.filter(e=>e.ca.isSome()),i=e.hosts.filter(e=>e.ca.isNone());if(r.length>0&&n.isNone())return C(`host "${r[0].name}" uses ca auth but CA custody is not running`);let a=await Promise.all(i.map(async e=>({name:e.name,sshConfig:await Ln(e)}))),o=a.flatMap(({name:e,sshConfig:t})=>t.fold(()=>[],t=>[{name:e,sshConfig:t}])),s=a.flatMap(({name:e,sshConfig:t})=>t.fold(t=>[[e,t]],()=>[]));return D(Bn(e,o,s,r,n,t))},zn=(e,t,n,r)=>{let i=Ie(e.custody.runtimeDir,n,r.name);return Ct({proc:e.proc,knownHosts:e.knownHosts,socketPath:i.orElse(``),mintFor:()=>i.fold(e=>Promise.resolve(C(e)),()=>ze(e.custody,{ca:t.name,agent:n,principal:r.principal.orElse(t.principal),sourceAddress:t.sourceAddress},e.proc))})},Bn=(e,t,n,r,i,a)=>{let o=T.of(...e.hosts.map(e=>[e.name,e.tmuxSession])),s=T.of(...e.hosts.map(e=>[e.name,e.logOutput])),c=T.of(...e.hosts.map(e=>[e.name,e.policy])),l=T.of(...r.map(e=>[e.name,e])),u=T.of(...e.cas.map(e=>[e.name,e])),d=Tt(t,e.pool,a),f=ee.of(...e.hosts.map(e=>e.name)),p=new globalThis.Map,m=(t,n,r)=>{let i=`${n}\0${t.name}`,a=p.get(i);if(a!==void 0)return a.pool;let o=u.get(t.ca.orElse(``)).orThrow(/* @__PURE__ */ Error(`ca "${t.ca.orElse(``)}" is not defined`)),s=(r.openFor??((e,t)=>zn(r,o,e,t)))(n,t),c=Tt([{name:t.name,sshConfig:In(t)}],e.pool,s.connect);return p.set(i,{host:t.name,agent:n,pool:c,openssh:s}),c},h=(e,t,n,r)=>l.get(e).fold(()=>d.run(e,t,r),a=>i.fold(()=>Promise.reject(/* @__PURE__ */ Error(`CA custody is not running, and this host uses ca auth`)),i=>m(a,n,i).run(e,t,r))),g=T.of(...n.map(([e,t])=>[e,t])),_=(e,t,n,r)=>g.get(e).fold(()=>h(e,t,n,r),e=>Promise.reject(Error(e))),v=(/* @__PURE__ */ new Date()).toISOString(),y=new globalThis.Map(n.map(([e,t])=>[e,{message:t,at:v}])),b=t=>Math.min(t??e.pool.execTimeoutMs,e.pool.maxExecTimeoutMs),x=(e,t,n,r)=>_(e,t,n,{timeoutMs:b(r)}).then(t=>(y.delete(e),t),t=>(f.has(e)&&g.get(e).isNone()&&y.set(e,{message:t.message,at:(/* @__PURE__ */ new Date()).toISOString()}),Promise.reject(t))),S=()=>r.flatMap(e=>{let t=[...p.values()].filter(t=>t.host===e.name);return t.length===0?[{name:e.name,state:`disconnected`,inFlight:0}]:t.flatMap(t=>t.pool.status().map(n=>({...n,name:`${e.name} (${t.agent})`})))}),w=e=>f.size===0?`unknown host "${e}" — no hosts are configured`:`unknown host "${e}" — configured: ${[...f].join(`, `)}`;return{hostNames:e.hosts.map(e=>e.name),sessionFor:e=>o.get(e).orElse(`agent`),logOutputFor:e=>s.get(e).orElse(!1),policyFor:e=>c.get(e),tmuxRunnerFor:(e,t)=>f.has(e)?D(n=>x(e,n,t)):C(w(e)),exec:(e,t,n,r)=>f.has(e)?x(e,t,n,r):Promise.reject(Error(w(e))),status:()=>[...d.status(),...n.map(([e])=>({name:e,state:`disconnected`,inFlight:0})),...S()],lastError:e=>E(y.get(e)),shutdown:async()=>{let e=[...p.values()];await Promise.all([d.shutdown(),...e.map(e=>e.pool.shutdown())]),await Promise.all(e.map(e=>e.openssh.shutdown())),await i.fold(()=>Promise.resolve(),e=>e.custody.shutdown())}}},Vn=(e,t,n)=>{let r=e.find(e=>e.startsWith(`--config=`));return r?{path:r.slice(9),explicit:!0}:E(t.SSH_FLEET_CONFIG).filter(e=>e.length>0).fold(()=>({path:j(n,`.config`,`ssh-fleet`,`fleet.toml`),explicit:!1}),e=>({path:e,explicit:!0}))},Hn=(e,t)=>e.code===t,Un=e=>{let{path:t}=e;return e.explicit?O(()=>m(t)).fold(e=>C(Hn(e,`ENOENT`)?`Cannot read fleet config at ${t}: no such file (only the default path is created on first start)`:`Cannot read fleet config at ${t}: ${e.message}`),()=>D({path:t,created:!1})):O(()=>{l(A(t),{recursive:!0,mode:448}),g(t,`# ssh-fleet-mcp-server config.
|
|
8
8
|
#
|
|
9
9
|
# Add at least one [[hosts]] entry, then restart the server. In Claude Code, use /mcp and
|
|
10
10
|
# reconnect. The fleet_setup tool shows what is configured and what is still missing.
|
|
@@ -16,7 +16,7 @@ import{createRequire as e}from"node:module";import{createHash as t,randomBytes a
|
|
|
16
16
|
# key_env = env var holding a key (PEM) agent = true (uses SSH_AUTH_SOCK)
|
|
17
17
|
# ca = a [[cas]] entry: the server signs a 10-minute certificate per connection
|
|
18
18
|
#
|
|
19
|
-
# Reference: https://github.com/
|
|
19
|
+
# Reference: https://github.com/sapientsai/mcp-servers/tree/main/servers/ssh-fleet#fleet-config-schema
|
|
20
20
|
|
|
21
21
|
# --- example: host with a password from the environment ---
|
|
22
22
|
# [[hosts]]
|
|
@@ -62,5 +62,5 @@ import{createRequire as e}from"node:module";import{createHash as t,randomBytes a
|
|
|
62
62
|
# user = "fleet"
|
|
63
63
|
# ca = "home"
|
|
64
64
|
# --- end ---
|
|
65
|
-
`,{flag:`wx`,mode:384})}).fold(e=>In(e,`EEXIST`)?k({path:t,created:!1}):E(`Cannot create fleet config at ${t}: ${e.message}`),()=>k({path:t,created:!0}))},Rn=async e=>{if(e.key.kind!==`file`)return k(O.none());let t=j.expand(e.key.path);if(t.isLeft())return E(`CA "${e.name}": key_file ${e.key.path}: ${t.value.message}`);let n=t.value,r=await oe(n).then(()=>!1,e=>In(e,`ENOENT`));return k(r?O(n):O.none())},zn=async(e,t)=>(await T.traverseAsync(e,async e=>{let n=await Rn(e);if(n.isLeft())return E(n.value);if(n.value.isNone())return k([]);let r=n.value.orElse(``),i=A(()=>u(C(r),{recursive:!0,mode:448}));if(i.isFailure())return E(`CA "${e.name}": creating key_file ${r} failed: ${i.error.message}`);let a=await t.run(`ssh-keygen`,[`-q`,`-t`,`ed25519`,`-N`,``,`-C`,`ssh-fleet-ca-${e.name}`,`-f`,r],{env:P(),input:``});return a.code===0?k([e.name]):s(r)?k([]):E(`CA "${e.name}": creating key_file ${r} failed: ${a.stderr.trim()||`exit ${a.code}`}`)})).map(e=>e.flat()),Bn=(e,t)=>`cert-authority,principals="${e}" ${t.trim()}`,Vn=e=>e.user.fold(()=>`${e.host}:${e.port}`,t=>`${t}@${e.host}:${e.port}`),Hn={cmd:`key_cmd`,env:`key_env`,file:`key_file`},Un=(e,t,n,r)=>{let i=e.ca.flatMap(e=>O(t.fleet.cas.find(t=>t.name===e))),a=e.principal.or(i.map(e=>e.principal)),o=i.flatMap(e=>t.caPublicKeys.get(e.name)).flatMap(e=>a.map(t=>Bn(t,e)));return{name:e.name,address:Vn(e),auth:e.authKind,...e.passwordEnv.fold(()=>({}),e=>({password_env:e,env_set:!!r[e]})),...e.ca.fold(()=>({}),e=>({ca:e,principal:a.orElse(``)})),connections:Sn(n).filter(t=>t.name===e.name||t.name.startsWith(`${e.name} (`)),...n.lastError(e.name).fold(()=>({}),e=>({last_error:e})),...o.fold(()=>({}),e=>({enroll_line:e}))}},Wn=(e,t)=>{let n=t.caPublicKeys.get(e.name);return{name:e.name,key_source:Hn[e.key.kind],...e.key.kind===`file`?{key_file:e.key.path}:{},created_this_start:t.caCreated.includes(e.name),...n.fold(()=>({}),t=>({public_key:t.trim(),enroll_line:Bn(e.principal,t)}))}},Gn=e=>{let t=e.readConfig();return t.isRight()&&t.value===e.loadedConfig?{changed:!1,fields:{changed_since_start:!1},step:[]}:t.flatMap(bn).fold(e=>({changed:!0,fields:{changed_since_start:!0,errors_on_disk:e},step:[`fleet.toml changed since the server started and now has errors; fix them before reconnecting: ${e}`]}),t=>({changed:!0,fields:{changed_since_start:!0,hosts_on_disk:t.hosts.length},step:[`fleet.toml changed since the server started (${t.hosts.length} hosts on disk, ${e.fleet.hosts.length} loaded): reconnect the server to load it (in Claude Code: /mcp, then reconnect).`]}))},Kn=(e,t,n=process.env)=>{let r=e.fleet.hosts.map(r=>Un(r,e,t,n)),i=e.fleet.cas.map(t=>Wn(t,e)),a=Gn(e),o=[...a.step,...r.length===0&&!a.changed?[`Add a [[hosts]] entry to ${e.configPath}, then restart the server.`]:[],...r.filter(e=>e.env_set===!1).map(e=>`${e.name}: set ${e.password_env} in the MCP client's env for this server, then restart.`),...i.filter(e=>e.created_this_start&&e.enroll_line!==void 0).map(e=>`Add CA "${e.name}"'s line to a root-owned authorized-keys file on each host that uses it: ${e.enroll_line}`),...r.flatMap(e=>e.last_error?[`${e.name}: ${e.last_error.message}`]:[])];return{config:{path:e.configPath,created_this_start:e.configCreated,...a.fields},next_steps:o,hosts:r,cas:i,audit_log:e.fleet.audit.path,...e.runtimeDir.fold(()=>({}),e=>({runtime_dir:e})),...e.knownHosts.fold(()=>({}),e=>({known_hosts:e}))}},qn=e=>A(()=>f(e,`utf8`)).fold(t=>t.code===`ENOENT`?E(`No fleet config at ${e}. Start the server once to create one at the default path, or pass --config=.`):E(`Cannot read fleet config at ${e}: ${t.message}`),e=>k(e)),Jn=e=>`${e}-check`,Yn=(e,t)=>e.code===0?{ok:!0,detail:`${Date.now()-t} ms`}:{ok:!1,detail:e.stderr.trim()||`exit ${e.code}`},Xn=async e=>{let{fleet:t,out:n}=e;if(t.hosts.length===0)return n(`No hosts configured; add a [[hosts]] entry to ${e.configPath}.`),0;let r=Math.max(...t.hosts.map(e=>e.name.length)),i=Math.max(...t.hosts.map(e=>Vn(e).length)),a=(e,t)=>[(t.ok?`ok`:`FAIL`).padEnd(5),e.name.padEnd(r),Vn(e).padEnd(i),e.authKind.padEnd(12),t.detail].join(` `),o=async t=>{if(t.ca.exists(t=>e.missingKeyCas.includes(t)))return{ok:!1,detail:`key_file missing: the server creates it on first start`};let n=Date.now();return e.auditor.audited({agent:`operator`,tool:`check`,host:O(t.name),fields:{bypass:`policy`},verdict:K},()=>e.runner.exec(t.name,`true`,`operator`),e=>({...At(e),code:e.code})).then(e=>Yn(e,n),e=>({ok:!1,detail:e.message}))},s=await Promise.all(t.hosts.map(e=>o(e).then(t=>(n(a(e,t)),t))));return t.cas.forEach(t=>e.caPublicKeys.get(t.name).forEach(e=>n(`CA ${t.name}: ${Bn(t.principal,e)}`))),+!s.every(e=>e.ok)},Z=e=>e.fold(e=>{throw Ct(e)},e=>e),Zn=e=>Buffer.byteLength(e,`utf8`),Q=()=>({}),Qn=(e,t,n)=>{let r=(e,t,n,r={})=>({agent:U,tool:e,host:t,fields:r,verdict:n}),i=(t,n,i={})=>r(n.tool,O(t),e.policyFor(t).fold(()=>K,e=>rn(e,n)),i),a=t=>n=>({...At(n),code:n.code,...n.signal===void 0?{}:{signal:n.signal},...n.timedOutMs===void 0?{}:{timed_out_ms:n.timedOutMs},...n.noExitStatus===!0?{no_exit_status:!0}:{},stdout_bytes:Zn(n.stdout),stderr_bytes:Zn(n.stderr),...e.logOutputFor(t)?{stdout_excerpt:kt(n.stdout),stderr_excerpt:kt(n.stderr)}:{}});return{hostsList:()=>t.audited(r(`hosts_list`,O.none(),K),()=>Promise.resolve(JSON.stringify(Sn(e))),Q),fleetSetup:()=>t.audited(r(`fleet_setup`,O.none(),K),()=>Promise.resolve(JSON.stringify(Kn(n,e))),Q),exec:async({host:n,command:r,timeout_ms:o})=>{let s=await t.audited(i(n,{tool:`exec`,agent:U,command:r},{command:r,...o===void 0?{}:{timeout_ms:o}}),()=>e.exec(n,r,U,o),a(n)).catch(H(n));return ft(s).fold(e=>{throw s.timedOutMs===void 0?Ct(`[${n}] ${e}`):wt(n,e)},e=>e)},tmuxList:({host:n})=>t.audited(i(n,{tool:`tmux_list`,agent:U}),async()=>JSON.stringify(Z(await at(Z(e.tmuxRunnerFor(n,U))))),Q).catch(H(n)),tmuxSend:({host:n,session:r,input:a,submit:o})=>{let s=r??e.sessionFor(n),c=o??!0;return t.audited(i(n,{tool:`tmux_send`,agent:U},{session:s,input:a,submit:c}),async()=>(Z(await ot(Z(e.tmuxRunnerFor(n,U)),{session:s,input:a,submit:c})),`[${n}] sent to tmux session "${s}".`),Q).catch(H(n))},tmuxRead:({host:n,session:r,lines:a})=>{let o=r??e.sessionFor(n),s=a??200;return t.audited(i(n,{tool:`tmux_read`,agent:U},{session:o,lines:s}),async()=>Z(await st(Z(e.tmuxRunnerFor(n,U)),{session:o,lines:s})),e=>({stdout_bytes:Zn(e)})).catch(H(n))},tmuxKeys:({host:n,session:r,keys:a})=>{let o=r??e.sessionFor(n);return t.audited(i(n,{tool:`tmux_keys`,agent:U},{session:o,keys:a}),async()=>(Z(await ct(Z(e.tmuxRunnerFor(n,U)),{session:o,keys:a})),`[${n}] sent keys [${a.join(`, `)}] to tmux session "${o}".`),Q).catch(H(n))}}},{version:$n}=e(import.meta.url)(`../package.json`),$=e=>(console.error(e),process.exit(1)),er=e=>j.expand(e).fold(t=>$(`invalid path ${e}: ${t.message}`),e=>e),tr=async(e,t)=>{if(e.cas.length===0)return{wiring:O.none(),created:[]};(await me(F)).fold($,()=>void 0);let n=t===`serve`?(await zn(e.cas,F)).fold($,e=>e):[];e.cas.filter(e=>n.includes(e.name)).forEach(e=>console.error(`created CA "${e.name}" key at ${e.key.kind===`file`?e.key.path:``}; add its line to each host (see fleet_setup)`));let r=e.runtimeDir.map(er).orElse(wn()),i=t===`check`?Jn(r):r,a=e.knownHosts.map(er).orElse(Tn());Pe(i,`unknown`,`host`).fold($,()=>void 0),u(C(a),{recursive:!0,mode:448});let o=(await Ne(i,e.cas.map(e=>On(e)),F)).fold($,e=>e),s=await kn(o,e.cas,F);return s.isLeft()&&(await o.shutdown(),$(s.value)),{wiring:O({custody:o,proc:F,knownHosts:a}),created:n}},nr=async(e,t)=>(await Mn(e,void 0,t)).fold(async e=>(console.error(e),await t.fold(()=>Promise.resolve(),e=>e.custody.shutdown()),process.exit(1)),e=>Promise.resolve(e)),rr=(e,t)=>t.fold(()=>D.of(),t=>D.of(...e.cas.flatMap(e=>t.custody.pubPath(e.name).flatMap(e=>A(()=>f(e,`utf8`)).toOption()).fold(()=>[],t=>[[e.name,t.trim()]])))),ir=e=>{let t=bn(e).fold($,e=>e);return xn(t).forEach(e=>console.error(`warning: ${e}`)),t};async function ar(){let{path:e}=Fn(process.argv.slice(2),process.env,b()),t=ir(qn(e).fold($,e=>e)),n=Rt(t.audit.path).fold($,e=>e),i=(await T.traverseAsync(t.cas,async e=>(await Rn(e)).map(t=>t.fold(()=>[],()=>[e.name])))).fold($,e=>e.flat()),a={...t,cas:t.cas.filter(e=>!i.includes(e.name)),hosts:t.hosts.filter(e=>!e.ca.exists(e=>i.includes(e)))},{wiring:o}=await tr(a,`check`),s=await nr(a,o),c=await Xn({fleet:t,configPath:e,runner:s,auditor:Nt({sink:n,now:()=>/* @__PURE__ */ new Date,newId:r}),missingKeyCas:i,caPublicKeys:rr(a,o),out:e=>console.log(e)});await s.shutdown(),process.exit(c)}async function or(){let e=Ln(Fn(process.argv.slice(2),process.env,b())).fold($,e=>e);e.created&&console.error(`created fleet config at ${e.path}`);let t=e.path,n=A(()=>f(t,`utf8`)).fold(e=>(console.error(`Cannot read fleet config at ${t}: ${e.message}`),process.exit(1)),e=>e),i=ir(n),a=Rt(i.audit.path).fold(e=>{console.error(e),process.exit(1)},e=>e),{wiring:o,created:s}=await tr(i,`serve`),c=await nr(i,o);i.hosts.forEach(e=>c.lastError(e.name).forEach(e=>console.error(`warning: ${e.message}`)));let l={configPath:t,configCreated:e.created,fleet:i,loadedConfig:n,readConfig:()=>A(()=>f(t,`utf8`)).fold(e=>E(`Cannot read ${t}: ${e.message}`),e=>k(e)),caPublicKeys:rr(i,o),caCreated:s,runtimeDir:o.map(e=>e.custody.runtimeDir),knownHosts:o.map(e=>e.knownHosts)},u=Ot(process.env.SSH_FLEET_CLIENT),d=e=>Qn(c,Nt({sink:a,now:()=>/* @__PURE__ */ new Date,newId:r,client:u.or(Dt(e.client)).orUndefined()}),l),p=ae({name:`ssh-fleet-mcp-server`,version:$n,build:zt(),instructions:`Manage a fleet of SSH hosts: pooled connections, host-routed exec and tmux tools. Call fleet_setup first if hosts_list is empty or a host fails to connect; it says what to configure next.`}),m=N.string().describe(`Configured host name (see hosts_list)`);p.addTool({name:`hosts_list`,description:`List configured fleet hosts and their live connection status. If a host you expect is missing, call fleet_setup: the config may have changed since the server started.`,parameters:N.object({}),execute:(e,t)=>d(t).hostsList()}),p.addTool({name:`fleet_setup`,description:`Show setup state: config path, each host's connection state and last error, each CA's public key and the line to add on hosts, and what to do next. Read-only.`,parameters:N.object({}),execute:(e,t)=>d(t).fleetSetup()}),p.addTool({name:`exec`,description:`Run a one-shot shell command on a fleet host over SSH.`,parameters:N.object({host:m,command:N.string().min(1).describe(`Shell command`),timeout_ms:N.number().int().positive().optional().describe(`How long to wait, in ms. Default ${i.pool.execTimeoutMs}; at most ${i.pool.maxExecTimeoutMs}, and a larger value is lowered to it. On timeout the call fails with the output so far, and the command may still be running. For longer jobs, run them in tmux (tmux_send, then tmux_read).`)}),execute:({host:e,command:t,timeout_ms:n},r)=>d(r).exec({host:e,command:t,timeout_ms:n})}),p.addTool({name:`tmux_list`,description:`List tmux sessions on a fleet host. Returns a JSON array of session names.`,parameters:N.object({host:m}),execute:({host:e},t)=>d(t).tmuxList({host:e})}),p.addTool({name:`tmux_send`,description:`Type text into a persistent tmux session on a fleet host (creates it if absent).`,parameters:N.object({host:m,session:N.string().optional().describe(`tmux session (defaults to the host's configured session)`),input:N.string().min(1).describe(`Text to type`),submit:N.boolean().optional().describe(`Press Enter after the text (default true)`)}),execute:({host:e,session:t,input:n,submit:r},i)=>d(i).tmuxSend({host:e,session:t,input:n,submit:r})}),p.addTool({name:`tmux_read`,description:`Capture the recent pane transcript of a tmux session on a fleet host.`,parameters:N.object({host:m,session:N.string().optional().describe(`tmux session (defaults to the host's configured session)`),lines:N.number().int().min(1).optional().describe(`Lines of scrollback (default 200; capped at 2000)`)}),execute:({host:e,session:t,lines:n},r)=>d(r).tmuxRead({host:e,session:t,lines:n})}),p.addTool({name:`tmux_keys`,description:`Send control/special keys (e.g. C-c) to a tmux session on a fleet host.`,parameters:N.object({host:m,session:N.string().optional().describe(`tmux session (defaults to the host's configured session)`),keys:N.array(N.string()).min(1).describe(`tmux key names, e.g. ['C-c']`)}),execute:({host:e,session:t,keys:n},r)=>d(r).tmuxKeys({host:e,session:t,keys:n})}),await p.start({transportType:`stdio`}),console.error(`SSH Fleet MCP Server running on stdio (${c.hostNames.length} hosts); audit log: ${i.audit.path}`);let h=async()=>{await c.shutdown(),await p.stop(),process.exit(0)};process.on(`SIGINT`,()=>void h()),process.on(`SIGTERM`,()=>void h())}(process.argv[2]===`check`?ar:or)().catch(e=>{console.error(`Fatal error in main():`,e),process.exit(1)});export{};
|
|
65
|
+
`,{flag:`wx`,mode:384})}).fold(e=>Hn(e,`EEXIST`)?D({path:t,created:!1}):C(`Cannot create fleet config at ${t}: ${e.message}`),()=>D({path:t,created:!0}))},Wn=async e=>{if(e.key.kind!==`file`)return D(E.none());let t=M.expand(e.key.path);if(t.isLeft())return C(`CA "${e.name}": key_file ${e.key.path}: ${t.value.message}`);let n=t.value,r=await oe(n).then(()=>!1,e=>Hn(e,`ENOENT`));return D(r?E(n):E.none())},Gn=async(e,t)=>(await S.traverseAsync(e,async e=>{let n=await Wn(e);if(n.isLeft())return C(n.value);if(n.value.isNone())return D([]);let r=n.value.orElse(``),i=O(()=>l(A(r),{recursive:!0,mode:448}));if(i.isFailure())return C(`CA "${e.name}": creating key_file ${r} failed: ${i.error.message}`);let a=await t.run(`ssh-keygen`,[`-q`,`-t`,`ed25519`,`-N`,``,`-C`,`ssh-fleet-ca-${e.name}`,`-f`,r],{env:P(),input:``});return a.code===0?D([e.name]):o(r)?D([]):C(`CA "${e.name}": creating key_file ${r} failed: ${a.stderr.trim()||`exit ${a.code}`}`)})).map(e=>e.flat()),Kn=(e,t)=>`cert-authority,principals="${e}" ${t.trim()}`,qn=e=>`${un(e)}@${e.host}:${e.port}`,Jn={cmd:`key_cmd`,env:`key_env`,file:`key_file`},Yn=(e,t,n,r)=>{let i=e.ca.flatMap(e=>E(t.fleet.cas.find(t=>t.name===e))),a=e.principal.or(i.map(e=>e.principal)),o=i.flatMap(e=>t.caPublicKeys.get(e.name)).flatMap(e=>a.map(t=>Kn(t,e)));return{name:e.name,address:qn(e),auth:e.authKind,...e.passwordEnv.fold(()=>({}),e=>({password_env:e,env_set:!!r[e]})),...e.ca.fold(()=>({}),e=>({ca:e,principal:a.orElse(``)})),connections:On(n).filter(t=>t.name===e.name||t.name.startsWith(`${e.name} (`)),...n.lastError(e.name).fold(()=>({}),e=>({last_error:e})),...o.fold(()=>({}),e=>({enroll_line:e}))}},Xn=(e,t)=>{let n=t.caPublicKeys.get(e.name);return{name:e.name,key_source:Jn[e.key.kind],...e.key.kind===`file`?{key_file:e.key.path}:{},created_this_start:t.caCreated.includes(e.name),...n.fold(()=>({}),t=>({public_key:t.trim(),enroll_line:Kn(e.principal,t)}))}},Zn=e=>{let t=e.readConfig();return t.isRight()&&t.value===e.loadedConfig?{changed:!1,fields:{changed_since_start:!1},step:[]}:t.flatMap(En).fold(e=>({changed:!0,fields:{changed_since_start:!0,errors_on_disk:e},step:[`fleet.toml changed since the server started and now has errors; fix them before reconnecting: ${e}`]}),t=>({changed:!0,fields:{changed_since_start:!0,hosts_on_disk:t.hosts.length},step:[`fleet.toml changed since the server started (${t.hosts.length} hosts on disk, ${e.fleet.hosts.length} loaded): reconnect the server to load it (in Claude Code: /mcp, then reconnect).`]}))},Qn=(e,t,n=process.env)=>{let r=e.fleet.hosts.map(r=>Yn(r,e,t,n)),i=e.fleet.cas.map(t=>Xn(t,e)),a=Zn(e),o=[...a.step,...r.length===0&&!a.changed?[`Add a [[hosts]] entry to ${e.configPath}, then restart the server.`]:[],...r.filter(e=>e.env_set===!1).map(e=>`${e.name}: set ${e.password_env} in the MCP client's env for this server, then restart.`),...i.filter(e=>e.created_this_start&&e.enroll_line!==void 0).map(e=>`Add CA "${e.name}"'s line to a root-owned authorized-keys file on each host that uses it: ${e.enroll_line}`),...r.flatMap(e=>e.last_error?[`${e.name}: ${e.last_error.message}`]:[])];return{config:{path:e.configPath,created_this_start:e.configCreated,...a.fields},next_steps:o,hosts:r,cas:i,audit_log:e.fleet.audit.path,...e.runtimeDir.fold(()=>({}),e=>({runtime_dir:e})),...e.knownHosts.fold(()=>({}),e=>({known_hosts:e}))}},$n=e=>O(()=>d(e,`utf8`)).fold(t=>t.code===`ENOENT`?C(`No fleet config at ${e}. Start the server once to create one at the default path, or pass --config=.`):C(`Cannot read fleet config at ${e}: ${t.message}`),e=>D(e)),er=e=>`${e}-check`,tr=`key_file missing: the server creates it on first start`,nr=(e,t)=>({...e,cas:e.cas.filter(e=>!t.includes(e.name)),hosts:e.hosts.filter(e=>!e.ca.exists(e=>t.includes(e)))}),rr=(e,t)=>e.code===0?{ok:!0,detail:`${Date.now()-t} ms`}:{ok:!1,detail:e.stderr.trim()||`exit ${e.code}`},ir=async e=>{let{fleet:t,out:n}=e,r=()=>t.cas.forEach(t=>e.missingKeyCas.includes(t.name)?n(`CA ${t.name}: ${tr}`):e.caPublicKeys.get(t.name).forEach(e=>n(`CA ${t.name}: ${Kn(t.principal,e)}`)));if(t.hosts.length===0)return n(`No hosts configured; add a [[hosts]] entry to ${e.configPath}.`),r(),0;let i=Math.max(...t.hosts.map(e=>e.name.length)),a=Math.max(...t.hosts.map(e=>qn(e).length)),o=(e,t)=>[(t.ok?`ok`:`FAIL`).padEnd(5),e.name.padEnd(i),qn(e).padEnd(a),e.authKind.padEnd(12),t.detail].join(` `),s=async t=>{if(t.ca.exists(t=>e.missingKeyCas.includes(t)))return{ok:!1,detail:tr};let n=Date.now();return e.auditor.audited({agent:`operator`,tool:`check`,host:E(t.name),fields:{bypass:`policy`},verdict:K},()=>e.runner.exec(t.name,`true`,`operator`),e=>({...Ft(e),code:e.code})).then(e=>rr(e,n),e=>({ok:!1,detail:e.message}))},c=await Promise.all(t.hosts.map(e=>s(e).then(t=>(n(o(e,t)),t))));return r(),+!c.every(e=>e.ok)},ar={proc:F,checkOpenSsh:()=>he(F),ensureKeyFiles:e=>Gn(e,F),makeDir:e=>l(e,{recursive:!0,mode:448}),startCustody:(e,t)=>Fe(e,t.map(e=>Pn(e)),F),selfTest:(e,t)=>Fn(e,t,F),log:e=>console.error(e)},or=e=>M.expand(e).fold(t=>C(`invalid path ${e}: ${t.message}`),e=>D(e)),sr={wiring:E.none(),created:[]},cr=async(e,t,n=ar)=>{if(e.cas.length===0)return D(sr);let r=await n.checkOpenSsh();if(r.isLeft())return C(r.value);let i=e.runtimeDir.fold(()=>D(An()),or);if(i.isLeft())return C(i.value);let a=t===`check`?er(i.value):i.value,o=e.knownHosts.fold(()=>D(jn()),or);if(o.isLeft())return C(o.value);let s=o.value,c=Ie(a,`unknown`,`host`);if(c.isLeft())return C(c.value);let l=t===`serve`?await n.ensureKeyFiles(e.cas):D([]);if(l.isLeft())return C(l.value);let u=l.value;e.cas.filter(e=>u.includes(e.name)).forEach(e=>n.log(`created CA "${e.name}" key at ${e.key.kind===`file`?e.key.path:``}; add its line to each host (see fleet_setup)`));let d=O(()=>n.makeDir(A(s)));if(d.isFailure())return C(`cannot create ${A(s)}: ${d.error.message}`);let f=await n.startCustody(a,e.cas);if(f.isLeft())return C(f.value);let p=await n.selfTest(f.value,e.cas);return p.isLeft()?(await f.value.shutdown(),C(p.value)):D({wiring:E({custody:f.value,proc:n.proc,knownHosts:s}),created:u})},lr=(e,t,n=e=>d(e,`utf8`))=>t.fold(()=>D(T.of()),t=>S.traverse(e,e=>t.custody.pubPath(e.name).fold(()=>C(`CA "${e.name}": custody has no public key for it`),t=>O(()=>n(t)).fold(n=>C(`CA "${e.name}": cannot read ${t}: ${n.message}`),t=>D([e.name,t.trim()])))).map(e=>T.of(...e.map(([e,t])=>[e,t])))),Z=e=>e.fold(e=>{throw Ot(e)},e=>e),ur=e=>Buffer.byteLength(e,`utf8`),Q=()=>({}),dr=(e,t,n)=>{let r=(e,t,n,r={})=>({agent:U,tool:e,host:t,fields:r,verdict:n}),i=(t,n,i={})=>r(n.tool,E(t),e.policyFor(t).fold(()=>K,e=>ln(e,n)),i),a=t=>n=>({...Ft(n),code:n.code,...n.signal===void 0?{}:{signal:n.signal},...n.timedOutMs===void 0?{}:{timed_out_ms:n.timedOutMs},...n.noExitStatus===!0?{no_exit_status:!0}:{},stdout_bytes:ur(n.stdout),stderr_bytes:ur(n.stderr),...e.logOutputFor(t)?{stdout_excerpt:Pt(n.stdout),stderr_excerpt:Pt(n.stderr)}:{}});return{hostsList:()=>t.audited(r(`hosts_list`,E.none(),K),()=>Promise.resolve(JSON.stringify(On(e))),Q),fleetSetup:()=>t.audited(r(`fleet_setup`,E.none(),K),()=>Promise.resolve(JSON.stringify(Qn(n,e))),Q),exec:async({host:n,command:r,timeout_ms:o})=>{let s=await t.audited(i(n,{tool:`exec`,agent:U,command:r},{command:r,...o===void 0?{}:{timeout_ms:o}}),()=>e.exec(n,r,U,o),a(n)).catch(H(n));return _t(s).fold(e=>{throw s.timedOutMs===void 0?Ot(`[${n}] ${e}`):kt(n,e)},e=>e)},tmuxList:({host:n})=>t.audited(i(n,{tool:`tmux_list`,agent:U}),async()=>JSON.stringify(Z(await ut(Z(e.tmuxRunnerFor(n,U))))),Q).catch(H(n)),tmuxSend:({host:n,session:r,input:a,submit:o})=>{let s=r??e.sessionFor(n),c=o??!0;return t.audited(i(n,{tool:`tmux_send`,agent:U},{session:s,input:a,submit:c}),async()=>(Z(await dt(Z(e.tmuxRunnerFor(n,U)),{session:s,input:a,submit:c})),`[${n}] sent to tmux session "${s}".`),Q).catch(H(n))},tmuxRead:({host:n,session:r,lines:a})=>{let o=r??e.sessionFor(n),s=a??200;return t.audited(i(n,{tool:`tmux_read`,agent:U},{session:o,lines:s}),async()=>Z(await ft(Z(e.tmuxRunnerFor(n,U)),{session:o,lines:s})),e=>({stdout_bytes:ur(e)})).catch(H(n))},tmuxKeys:({host:n,session:r,keys:a})=>{let o=r??e.sessionFor(n);return t.audited(i(n,{tool:`tmux_keys`,agent:U},{session:o,keys:a}),async()=>(Z(await pt(Z(e.tmuxRunnerFor(n,U)),{session:o,keys:a})),`[${n}] sent keys [${a.join(`, `)}] to tmux session "${o}".`),Q).catch(H(n))}}},{version:fr}=v(import.meta.url)(`../package.json`),$=e=>(console.error(e),process.exit(1)),pr=async(e,t)=>(await Rn(e,void 0,t)).fold(async e=>(console.error(e),await t.fold(()=>Promise.resolve(),e=>e.custody.shutdown()),process.exit(1)),e=>Promise.resolve(e)),mr=async(e,t)=>(await cr(e,t)).fold($,e=>e),hr=async(e,t,n)=>lr(e.cas,t).fold(async e=>(await n.shutdown(),$(e)),e=>Promise.resolve(e)),gr=e=>{let t=En(e).fold($,e=>e);return Dn(t).forEach(e=>console.error(`warning: ${e}`)),t};async function _r(){let{path:e}=Vn(process.argv.slice(2),process.env,b()),t=gr($n(e).fold($,e=>e)),r=Ut(t.audit.path).fold($,e=>e),i=(await S.traverseAsync(t.cas,async e=>(await Wn(e)).map(t=>t.fold(()=>[],()=>[e.name])))).fold($,e=>e.flat()),a=nr(t,i),{wiring:o}=await mr(a,`check`),s=await pr(a,o),c=e=>()=>void s.shutdown().finally(()=>process.exit(e));process.on(`SIGINT`,c(130)),process.on(`SIGTERM`,c(143));let l=await hr(a,o,s),u=await ir({fleet:t,configPath:e,runner:s,auditor:Rt({sink:r,now:()=>/* @__PURE__ */ new Date,newId:n}),missingKeyCas:i,caPublicKeys:l,out:e=>console.log(e)});await s.shutdown(),process.exitCode=u}async function vr(){let e=Un(Vn(process.argv.slice(2),process.env,b())).fold($,e=>e);e.created&&console.error(`created fleet config at ${e.path}`);let t=e.path,r=O(()=>d(t,`utf8`)).fold(e=>(console.error(`Cannot read fleet config at ${t}: ${e.message}`),process.exit(1)),e=>e),i=gr(r),a=Ut(i.audit.path).fold(e=>{console.error(e),process.exit(1)},e=>e),{wiring:o,created:s}=await mr(i,`serve`),c=await pr(i,o),l=await hr(i,o,c);i.hosts.forEach(e=>c.lastError(e.name).forEach(e=>console.error(`warning: ${e.message}`)));let u={configPath:t,configCreated:e.created,fleet:i,loadedConfig:r,readConfig:()=>O(()=>d(t,`utf8`)).fold(e=>C(`Cannot read ${t}: ${e.message}`),e=>D(e)),caPublicKeys:l,caCreated:s,runtimeDir:o.map(e=>e.custody.runtimeDir),knownHosts:o.map(e=>e.knownHosts)},f=Nt(process.env.SSH_FLEET_CLIENT),p=e=>dr(c,Rt({sink:a,now:()=>/* @__PURE__ */ new Date,newId:n,client:f.or(Mt(e.client)).orUndefined()}),u),m=te({name:`ssh-fleet-mcp-server`,version:fr,build:Wt(),instructions:`Manage a fleet of SSH hosts: pooled connections, host-routed exec and tmux tools. Call fleet_setup first if hosts_list is empty or a host fails to connect; it says what to configure next.`}),h=k.string().describe(`Configured host name (see hosts_list)`);m.addTool({name:`hosts_list`,description:`List configured fleet hosts and their live connection status. If a host you expect is missing, call fleet_setup: the config may have changed since the server started.`,parameters:k.object({}),execute:(e,t)=>p(t).hostsList()}),m.addTool({name:`fleet_setup`,description:`Show setup state: config path, each host's connection state and last error, each CA's public key and the line to add on hosts, and what to do next. Read-only.`,parameters:k.object({}),execute:(e,t)=>p(t).fleetSetup()}),m.addTool({name:`exec`,description:`Run a one-shot shell command on a fleet host over SSH.`,parameters:k.object({host:h,command:k.string().min(1).describe(`Shell command`),timeout_ms:k.number().int().positive().optional().describe(`How long to wait, in ms. Default ${i.pool.execTimeoutMs}; at most ${i.pool.maxExecTimeoutMs}, and a larger value is lowered to it. On timeout the call fails with the output so far, and the command may still be running. For longer jobs, run them in tmux (tmux_send, then tmux_read).`)}),execute:({host:e,command:t,timeout_ms:n},r)=>p(r).exec({host:e,command:t,timeout_ms:n})}),m.addTool({name:`tmux_list`,description:`List tmux sessions on a fleet host. Returns a JSON array of session names.`,parameters:k.object({host:h}),execute:({host:e},t)=>p(t).tmuxList({host:e})}),m.addTool({name:`tmux_send`,description:`Type text into a persistent tmux session on a fleet host (creates it if absent).`,parameters:k.object({host:h,session:k.string().optional().describe(`tmux session (defaults to the host's configured session)`),input:k.string().min(1).describe(`Text to type`),submit:k.boolean().optional().describe(`Press Enter after the text (default true)`)}),execute:({host:e,session:t,input:n,submit:r},i)=>p(i).tmuxSend({host:e,session:t,input:n,submit:r})}),m.addTool({name:`tmux_read`,description:`Capture the recent pane transcript of a tmux session on a fleet host.`,parameters:k.object({host:h,session:k.string().optional().describe(`tmux session (defaults to the host's configured session)`),lines:k.number().int().min(1).optional().describe(`Lines of scrollback (default 200; capped at 2000)`)}),execute:({host:e,session:t,lines:n},r)=>p(r).tmuxRead({host:e,session:t,lines:n})}),m.addTool({name:`tmux_keys`,description:`Send control/special keys (e.g. C-c) to a tmux session on a fleet host.`,parameters:k.object({host:h,session:k.string().optional().describe(`tmux session (defaults to the host's configured session)`),keys:k.array(k.string()).min(1).describe(`tmux key names, e.g. ['C-c']`)}),execute:({host:e,session:t,keys:n},r)=>p(r).tmuxKeys({host:e,session:t,keys:n})}),await m.start({transportType:`stdio`}),console.error(`SSH Fleet MCP Server running on stdio (${c.hostNames.length} hosts); audit log: ${i.audit.path}`);let g=async()=>{await c.shutdown(),await m.stop(),process.exit(0)};process.on(`SIGINT`,()=>void g()),process.on(`SIGTERM`,()=>void g())}(process.argv[2]===`check`?_r:vr)().catch(e=>{console.error(`Fatal error in main():`,e),process.exit(1)});export{};
|
|
66
66
|
//# sourceMappingURL=index.js.map
|