ferncli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -2
- package/bin/ferncli.mjs +131 -0
- package/lib.mjs +25 -0
- package/package.json +22 -4
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Fern CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
FernLab's AI coding assistant in your terminal. Runs on [OpenCode](https://opencode.ai), installed for you.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
curl -fsSL https://fernlab.si/install | sh # macOS, Linux
|
|
7
|
+
irm https://fernlab.si/install.ps1 | iex # Windows (PowerShell)
|
|
8
|
+
ferncli
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
No Node.js needed (the installer brings its own). Already have Node.js 20+? `npm i -g ferncli` works too.
|
|
12
|
+
|
|
13
|
+
The first run opens your browser to log in to your FernLab account. You need a plan: https://fernlab.si
|
|
14
|
+
|
|
15
|
+
| Command | What it does |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `ferncli` | Start (any OpenCode options work, e.g. `ferncli run "explain this repo"`) |
|
|
18
|
+
| `ferncli login` / `logout` | Log in again / log out of this computer |
|
|
19
|
+
| `ferncli status` | Show which account is logged in |
|
|
20
|
+
|
|
21
|
+
Use it only on systems you own or have written permission to test.
|
|
22
|
+
|
|
23
|
+
## Maintainers
|
|
24
|
+
|
|
25
|
+
- OpenCode is pinned (`@opencode/cli` in package.json). To move: bump it, `npm install`, `npm test`, then run the manual check in SPEC.md §5b.
|
|
26
|
+
- Settings reach OpenCode via `OPENCODE_CONFIG_CONTENT` (`lib.mjs`); the token is read from `~/.config/ferncli/token` (0600) via `{file:...}`.
|
|
27
|
+
- Publish: `npm publish` (owner's npm account).
|
package/bin/ferncli.mjs
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Fern CLI: logs in to FernLab (device login, SPEC.md §5) and starts the pinned OpenCode pointed at our gateway.
|
|
3
|
+
// ferncli [opencode args] · ferncli login · ferncli logout · ferncli status
|
|
4
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { createRequire } from "node:module";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { opencodeArgs, opencodeConfig } from "../lib.mjs";
|
|
10
|
+
|
|
11
|
+
const APP = process.env.FERNLAB_APP_URL ?? "https://app.fernlab.si"; // env overrides: local testing only
|
|
12
|
+
const API = process.env.FERNLAB_API_URL ?? "https://api.fernlab.si/v1";
|
|
13
|
+
const CLIENT_ID = "fernlab-opencode";
|
|
14
|
+
const DIR = process.platform === "win32"
|
|
15
|
+
? join(process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "ferncli")
|
|
16
|
+
: join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "ferncli");
|
|
17
|
+
const TOKEN = join(DIR, "token");
|
|
18
|
+
const MODELS = join(DIR, "models.json");
|
|
19
|
+
|
|
20
|
+
const die = (msg) => { console.error(msg); process.exit(1); };
|
|
21
|
+
const readToken = () => (existsSync(TOKEN) ? readFileSync(TOKEN, "utf8").trim() : "");
|
|
22
|
+
const bearer = (t) => ({ authorization: `Bearer ${t}` });
|
|
23
|
+
|
|
24
|
+
function save(path, text) {
|
|
25
|
+
mkdirSync(DIR, { recursive: true, mode: 0o700 });
|
|
26
|
+
writeFileSync(path, text, { mode: 0o600 });
|
|
27
|
+
chmodSync(path, 0o600); // mode above only applies when the file is new
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// null = logged out or expired; undefined = couldn't reach FernLab (don't force a login while offline).
|
|
31
|
+
async function session(token) {
|
|
32
|
+
try {
|
|
33
|
+
const res = await fetch(`${APP}/api/auth/get-session`, { headers: bearer(token) });
|
|
34
|
+
return res.ok ? await res.json() : undefined;
|
|
35
|
+
} catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function post(path, body, headers = {}) {
|
|
41
|
+
const res = await fetch(`${APP}/api/auth/${path}`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
|
|
42
|
+
return { ok: res.ok, data: await res.json().catch(() => ({})) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function openBrowser(url) {
|
|
46
|
+
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
47
|
+
try { spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref(); } catch {}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function login() {
|
|
51
|
+
const start = await post("device/code", { client_id: CLIENT_ID });
|
|
52
|
+
if (!start.ok) die(`Couldn't start login: ${start.data.error_description ?? start.data.error ?? "FernLab is unreachable"}`);
|
|
53
|
+
const { device_code, user_code, verification_uri_complete } = start.data;
|
|
54
|
+
let interval = (start.data.interval ?? 5) * 1000;
|
|
55
|
+
console.log(`\nOpen this page and approve the code ${user_code}:\n ${verification_uri_complete}\n`);
|
|
56
|
+
openBrowser(verification_uri_complete);
|
|
57
|
+
console.log("Waiting for approval...");
|
|
58
|
+
for (;;) {
|
|
59
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
60
|
+
const r = await post("device/token", { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code, client_id: CLIENT_ID });
|
|
61
|
+
if (r.ok && r.data.access_token) {
|
|
62
|
+
save(TOKEN, r.data.access_token);
|
|
63
|
+
const s = await session(r.data.access_token);
|
|
64
|
+
console.log(`Logged in${s?.user?.email ? ` as ${s.user.email}` : ""}.`);
|
|
65
|
+
return r.data.access_token;
|
|
66
|
+
}
|
|
67
|
+
if (r.data.error === "authorization_pending") continue;
|
|
68
|
+
if (r.data.error === "slow_down") { interval += 5000; continue; }
|
|
69
|
+
die(r.data.error === "access_denied" ? "Login denied." : r.data.error === "expired_token" ? "The code expired. Run ferncli login again." : `Login failed: ${r.data.error ?? "unknown error"}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The gateway's model list, so models added on the server show up without a new ferncli. Last good copy if offline.
|
|
74
|
+
async function models() {
|
|
75
|
+
try {
|
|
76
|
+
const res = await fetch(`${API}/models`);
|
|
77
|
+
if (!res.ok) throw new Error(String(res.status));
|
|
78
|
+
const list = (await res.json()).data;
|
|
79
|
+
if (!list?.length) throw new Error("empty");
|
|
80
|
+
save(MODELS, JSON.stringify(list));
|
|
81
|
+
return list;
|
|
82
|
+
} catch {
|
|
83
|
+
if (existsSync(MODELS)) return JSON.parse(readFileSync(MODELS, "utf8"));
|
|
84
|
+
die(`Can't reach FernLab (${API}). Check your connection and try again.`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// npm may skip OpenCode's install script (it swaps its small placeholder for the real program); run it ourselves then.
|
|
89
|
+
function opencodeBin() {
|
|
90
|
+
const pkg = dirname(createRequire(import.meta.url).resolve("@opencode/cli/package.json"));
|
|
91
|
+
const bin = join(pkg, "bin", "opencode.exe");
|
|
92
|
+
if (statSync(bin).size < 10_000) {
|
|
93
|
+
console.log("Finishing the OpenCode install (one time)...");
|
|
94
|
+
const r = spawnSync(process.execPath, [join(pkg, "postinstall.mjs")], { cwd: pkg, stdio: "inherit" });
|
|
95
|
+
if (r.status !== 0 || statSync(bin).size < 10_000) die("Couldn't install OpenCode. Reinstall with: npm i -g ferncli");
|
|
96
|
+
}
|
|
97
|
+
return bin;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
101
|
+
|
|
102
|
+
if (cmd === "login") {
|
|
103
|
+
await login();
|
|
104
|
+
} else if (cmd === "logout") {
|
|
105
|
+
const t = readToken();
|
|
106
|
+
if (t) await post("sign-out", {}, bearer(t)).catch(() => {});
|
|
107
|
+
rmSync(TOKEN, { force: true });
|
|
108
|
+
console.log("Logged out.");
|
|
109
|
+
} else if (cmd === "status") {
|
|
110
|
+
const t = readToken();
|
|
111
|
+
const s = t ? await session(t) : null;
|
|
112
|
+
console.log(s === undefined ? "Can't reach FernLab right now." : s?.user ? `Logged in as ${s.user.email}.` : "Not logged in. Run: ferncli login");
|
|
113
|
+
} else if (cmd === "-v" || cmd === "--version") {
|
|
114
|
+
// Also finishes the OpenCode install if npm skipped it, so installers can call this and the first real start is clean.
|
|
115
|
+
const oc = spawnSync(opencodeBin(), ["--version"], { encoding: "utf8" }).stdout?.trim();
|
|
116
|
+
console.log(`ferncli ${JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version} (${oc || "OpenCode not found"})`);
|
|
117
|
+
} else {
|
|
118
|
+
// Checking the session also keeps it alive: sessions last 7 days and roll forward on use.
|
|
119
|
+
let token = readToken();
|
|
120
|
+
if (!token || (await session(token)) === null) {
|
|
121
|
+
console.log(token ? "Your login expired." : "Welcome to Fern CLI. Let's log you in.");
|
|
122
|
+
token = await login();
|
|
123
|
+
}
|
|
124
|
+
const config = opencodeConfig(await models(), API, TOKEN);
|
|
125
|
+
const child = spawn(opencodeBin(), opencodeArgs(process.argv.slice(2)), {
|
|
126
|
+
stdio: "inherit",
|
|
127
|
+
env: { ...process.env, OPENCODE_CONFIG_CONTENT: JSON.stringify(config), OPENCODE_DISABLE_FREE_MODELS: "1" },
|
|
128
|
+
});
|
|
129
|
+
for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => {}); // the TUI handles Ctrl+C itself
|
|
130
|
+
child.on("exit", (code, signal) => process.exit(signal ? 1 : (code ?? 0)));
|
|
131
|
+
}
|
package/lib.mjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Pure helpers for bin/ferncli.mjs (tested in lib.test.mjs).
|
|
2
|
+
|
|
3
|
+
// OpenCode subcommands that refuse --standalone (checked on 2.4.5). Everything else gets it, so OpenCode runs a private
|
|
4
|
+
// server with our settings instead of reusing a background one started without them.
|
|
5
|
+
const NO_STANDALONE = new Set(["mcp", "plugin", "debug", "acp", "service", "upgrade", "update", "uninstall", "pair", "serve"]);
|
|
6
|
+
export const opencodeArgs = (args) => (NO_STANDALONE.has(args[0]) ? args : [...args, "--standalone"]);
|
|
7
|
+
|
|
8
|
+
// OpenCode settings (passed as OPENCODE_CONFIG_CONTENT): one provider, "fernlab", pointing at our gateway. The token is
|
|
9
|
+
// read from its file by OpenCode itself ({file:...}), so it never sits in an environment variable tools inherit.
|
|
10
|
+
// `models` is the gateway's GET /v1/models `data`; the first is the default.
|
|
11
|
+
export function opencodeConfig(models, apiUrl, tokenPath) {
|
|
12
|
+
return {
|
|
13
|
+
update: "disable", // ferncli pins the OpenCode version
|
|
14
|
+
share: "disabled", // never publish sessions to OpenCode's share service
|
|
15
|
+
model: `fernlab/${models[0].id}`,
|
|
16
|
+
providers: {
|
|
17
|
+
fernlab: {
|
|
18
|
+
name: "FernLab",
|
|
19
|
+
package: "@opencode/ai/providers/openai-compatible",
|
|
20
|
+
settings: { baseURL: apiUrl, apiKey: `{file:${tokenPath.replace(/\\/g, "/")}}` },
|
|
21
|
+
models: Object.fromEntries(models.map((m) => [m.id, { name: m.usage > 1 ? `${m.name} (×${m.usage} usage)` : m.name }])),
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ferncli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Fern CLI: the FernLab AI coding assistant in your terminal (runs on OpenCode)",
|
|
5
|
+
"homepage": "https://fernlab.si",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"bin": {
|
|
9
|
+
"ferncli": "bin/ferncli.mjs"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"bin",
|
|
13
|
+
"lib.mjs"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@opencode/cli": "2.4.5"
|
|
23
|
+
}
|
|
24
|
+
}
|