@jive-sh/skill-sync 0.4.1 → 0.4.2-latest-darwin-arm64

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.
@@ -1,367 +0,0 @@
1
- import { existsSync, mkdirSync, rmSync, watch, type FSWatcher } from "node:fs";
2
- import { createServer } from "node:http";
3
- import { exitWhenUninstalled } from "jive-abstract-library";
4
- import {
5
- LEGACY_TOKEN_PATH, detectFolders, loadSettings, loadStates, saveStates, stateFor, type Config,
6
- } from "../internal/config";
7
- import { serve, type ControlRequest, type Reply } from "../internal/control";
8
- import { authHeaders, describe, register } from "../internal/folders";
9
- import { isQuiet, syncOnce, type Report } from "../internal/sync";
10
- import type { DaemonMessage, FolderPrefs, FolderState, HubToDaemon, ListSkillsResponse } from "../internal/wire";
11
-
12
- /**
13
- * Keeps every enabled skills folder on this machine identical to every other machine's.
14
- *
15
- * Folders are detected (`~/.claude*` homes). Which of them sync, and the one list of skills that syncs in
16
- * all of them, are held by the server and changed from the dashboard, so they survive a reinstall and
17
- * apply the moment they change. A skill not on the list is never pushed or pulled.
18
- *
19
- * The daemon holds a WebSocket to the service's hub. That connection is how the dashboard knows this
20
- * machine is running, how a preference change arrives, and how a write from another machine triggers a
21
- * cycle here at once. Polling stays as the fallback: every 5 minutes while connected, every 30 seconds
22
- * while not, so a dropped connection costs latency and never correctness.
23
- *
24
- * The sync token exists only in this process's memory. The daemon starts signed out and waits; `skill-sync
25
- * login` asks it, over the control socket, to sign in, and the token arrives from the browser straight to
26
- * this process. A restart means signing in again — the price of never writing the credential down.
27
- */
28
-
29
- const POLL_CONNECTED_MS = 5 * 60_000;
30
- const POLL_DISCONNECTED_MS = 30_000;
31
- /** Long enough that an editor's write-rename-write lands as one cycle, short enough to feel immediate. */
32
- const SETTLE_MS = 1_000;
33
- const PING_MS = 30_000;
34
- /** No pong for this long means the connection is dead even if the socket has not noticed. */
35
- const PONG_TIMEOUT_MS = 75_000;
36
- const RECONNECT_MIN_MS = 5_000;
37
- const RECONNECT_MAX_MS = 5 * 60_000;
38
- /** How long a sign-in waits for the browser before giving up. */
39
- const LOGIN_TIMEOUT_MS = 5 * 60_000;
40
-
41
- exitWhenUninstalled();
42
-
43
- // Versions before 0.3 wrote the token to a file. It is never read: a credential left on disk is one
44
- // anything that can read the home directory can copy.
45
- if (existsSync(LEGACY_TOKEN_PATH)) {
46
- rmSync(LEGACY_TOKEN_PATH, { force: true });
47
- console.log(`deleted ${LEGACY_TOKEN_PATH}; the token now lives only in this daemon's memory`);
48
- }
49
-
50
- const settings = loadSettings();
51
- if (settings === undefined) {
52
- console.error("~/.jive/skill-sync.json needs an endpoint and a machine name");
53
- // Zero, not one: the service manager restarts a daemon that fails, and a file nobody has fixed would
54
- // only fill the log.
55
- process.exit(0);
56
- }
57
- const states = loadStates();
58
-
59
- /** Set while signed in. Everything that talks to the server reads it; signing out clears it. */
60
- let session: Config | undefined;
61
- /** The signed-in config, for code that only runs during a session. */
62
- function current(): Config {
63
- if (session === undefined) throw new Error("not signed in");
64
- return session;
65
- }
66
-
67
- /** What was last registered, so registration is repeated only when a folder or skill appears or goes. */
68
- let registered = "";
69
- /** The enabled folders, each with the synced list. */
70
- let prefs = new Map<string, ReadonlySet<string>>();
71
- const watchers = new Map<string, FSWatcher>();
72
-
73
- // ── Folders ─────────────────────────────────────────────────────────────────────────────────────────
74
-
75
- /** Reports this machine's folders and skills, and adopts the server's answer for what syncs. */
76
- async function registerFolders(): Promise<void> {
77
- const request = describe(current());
78
- applyPrefs(await register(current(), request));
79
- registered = JSON.stringify(request);
80
- }
81
-
82
- /** True when a folder or a skill has appeared or gone since the last registration. */
83
- const registrationStale = (): boolean => JSON.stringify(describe(current())) !== registered;
84
-
85
- function applyPrefs(folders: ReadonlyArray<FolderPrefs>): void {
86
- // Only folders this machine still has. The hub can hold a stale list — it answers a reconnect before
87
- // the next registration — and creating a listed folder whose Claude home is gone would bring it back.
88
- const present = new Set(detectFolders());
89
- const next = new Map(folders.filter((folder) => present.has(folder.path))
90
- .map((folder) => [folder.path, new Set(folder.skills)] as const));
91
- for (const [folder, watcher] of watchers) {
92
- if (!next.has(folder)) {
93
- watcher.close();
94
- watchers.delete(folder);
95
- }
96
- }
97
- // An unticked folder leaves no trace of syncing: its state goes, so the state file lists only folders
98
- // that sync, and ticking it again starts it fresh.
99
- // Covers folders with state from an earlier run too, not only ones this run was syncing.
100
- const stopped = [...new Set([...prefs.keys(), ...Object.keys(states)])].filter((folder) => !next.has(folder));
101
- for (const folder of stopped) {
102
- delete states[folder];
103
- console.log(`stopped syncing ${folder}`);
104
- }
105
- if (stopped.length > 0) saveStates(states);
106
- for (const folder of next.keys()) {
107
- if (watchers.has(folder)) continue;
108
- mkdirSync(folder, { recursive: true });
109
- let settle: ReturnType<typeof setTimeout> | undefined;
110
- watchers.set(folder, watch(folder, { recursive: true }, () => {
111
- if (settle !== undefined) clearTimeout(settle);
112
- settle = setTimeout(runCycle, SETTLE_MS);
113
- }));
114
- }
115
- const changed = JSON.stringify([...next].map(([path, skills]) => [path, [...skills].sort()]))
116
- !== JSON.stringify([...prefs].map(([path, skills]) => [path, [...skills].sort()]));
117
- prefs = next;
118
- if (!changed) return;
119
- for (const [folder, skills] of prefs) console.log(`syncing ${folder}: ${[...skills].sort().join(", ") || "no skills"}`);
120
- if (prefs.size === 0) console.log("syncing no folders");
121
- void runCycle();
122
- }
123
-
124
- // ── Hub connection ──────────────────────────────────────────────────────────────────────────────────
125
-
126
- let socket: WebSocket | undefined;
127
- let lastPong = 0;
128
- let reconnectDelay = RECONNECT_MIN_MS;
129
- /** What the hub was last told about each folder (state and detail), so only changes are sent. */
130
- const reported = new Map<string, string>();
131
-
132
- function connect(): void {
133
- if (session === undefined) return;
134
- const config = session;
135
- const url = `${config.endpoint.replace(/^http/, "ws")}/daemon`;
136
- // Bun's WebSocket takes headers; the browser's does not, which is why the token can travel this way.
137
- const ws = new WebSocket(url, { headers: authHeaders(config, {}) } as unknown as string[]);
138
- ws.onopen = () => {
139
- socket = ws;
140
- lastPong = Date.now();
141
- reconnectDelay = RECONNECT_MIN_MS;
142
- console.log("connected to the hub");
143
- // Whatever the hub last heard from a previous connection is stale until re-sent.
144
- reported.clear();
145
- for (const folder of prefs.keys()) report(folder, "idle");
146
- };
147
- ws.onmessage = (event) => {
148
- const data = String(event.data);
149
- if (data === "pong") {
150
- lastPong = Date.now();
151
- return;
152
- }
153
- const message = JSON.parse(data) as HubToDaemon;
154
- if (message.type === "prefs") applyPrefs(message.folders);
155
- if (message.type === "changed") void runCycle();
156
- };
157
- ws.onclose = () => {
158
- if (socket === ws) socket = undefined;
159
- // Only the session that opened it reconnects: after a sign-out, or a sign-in with a new token, this
160
- // socket belongs to nobody.
161
- if (session !== config) return;
162
- setTimeout(connect, reconnectDelay);
163
- reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
164
- };
165
- ws.onerror = () => {
166
- // `onclose` follows and schedules the reconnect.
167
- };
168
- }
169
-
170
- setInterval(() => {
171
- if (socket === undefined) return;
172
- if (Date.now() - lastPong > PONG_TIMEOUT_MS) {
173
- console.error("hub connection went quiet; reconnecting");
174
- socket.close();
175
- return;
176
- }
177
- socket.send("ping");
178
- }, PING_MS);
179
-
180
- function report(folder: string, state: FolderState, detail?: string, activity?: string): void {
181
- const key = `${state}|${detail ?? ""}`;
182
- if (reported.get(folder) === key && activity === undefined) return;
183
- if (socket === undefined) return;
184
- const message: DaemonMessage = { type: "status", folder, state, detail, activity };
185
- socket.send(JSON.stringify(message));
186
- reported.set(folder, key);
187
- }
188
-
189
- // ── Sync cycles ─────────────────────────────────────────────────────────────────────────────────────
190
-
191
- let running = false;
192
- let cycleQueued = false;
193
-
194
- function summarise(result: Report): string {
195
- const parts = [
196
- result.pulled.length > 0 ? `pulled ${result.pulled.join(", ")}` : "",
197
- result.pushed.length > 0 ? `pushed ${result.pushed.join(", ")}` : "",
198
- result.deletedLocally.length > 0 ? `deleted ${result.deletedLocally.join(", ")}` : "",
199
- ];
200
- return parts.filter(Boolean).join("; ");
201
- }
202
-
203
- async function runCycle(): Promise<void> {
204
- if (session === undefined) return;
205
- if (running) {
206
- cycleQueued = true;
207
- return;
208
- }
209
- running = true;
210
- try {
211
- // Folders sync one after another against the same server, so a change pushed from one folder is
212
- // pulled into the others on the follow-up pass this triggers.
213
- for (const [folder, skills] of [...prefs]) {
214
- try {
215
- const result = await syncOnce(current(), folder, stateFor(states, folder), skills);
216
- saveStates(states);
217
- log(folder, result);
218
- if (result.rejected.length > 0) report(folder, "attention", result.rejected.join("; "), summarise(result) || undefined);
219
- else report(folder, "idle", undefined, isQuiet(result) ? undefined : summarise(result));
220
- // What this folder pushed is pulled into the machine's other folders on the follow-up pass.
221
- if (result.pushed.length > 0) cycleQueued = true;
222
- } catch (cause) {
223
- // One failed folder must not end the daemon or the other folders: the usual cause is the network.
224
- const reason = cause instanceof Error ? cause.message : String(cause);
225
- console.error(`${folder}: sync failed: ${reason}`);
226
- report(folder, "attention", `sync failed: ${reason}`);
227
- }
228
- }
229
- // A skill created or removed locally changes what the dashboard should list.
230
- if (registrationStale()) await registerFolders().catch(() => undefined);
231
- } finally {
232
- running = false;
233
- if (cycleQueued) {
234
- cycleQueued = false;
235
- setTimeout(runCycle, SETTLE_MS);
236
- }
237
- }
238
- }
239
-
240
- function log(folder: string, result: Report): void {
241
- for (const path of result.pulled) console.log(`${folder}: pulled ${path}`);
242
- for (const path of result.pushed) console.log(`${folder}: pushed ${path}`);
243
- for (const path of result.deletedLocally) console.log(`${folder}: deleted ${path}`);
244
- for (const path of result.rejected) console.error(`${folder}: refused a path the server sent: ${path}`);
245
- }
246
-
247
- let pollTimer: ReturnType<typeof setTimeout> | undefined;
248
-
249
- /** Re-detects folders each poll: a Claude home created since the last one should join without a restart. */
250
- async function poll(): Promise<void> {
251
- if (session === undefined) return;
252
- try {
253
- if (registered === "" || registrationStale()) await registerFolders();
254
- } catch (cause) {
255
- console.error(`could not register folders: ${cause instanceof Error ? cause.message : String(cause)}`);
256
- }
257
- await runCycle();
258
- if (session !== undefined) pollTimer = setTimeout(poll, socket === undefined ? POLL_DISCONNECTED_MS : POLL_CONNECTED_MS);
259
- }
260
-
261
- // ── Signing in and out ──────────────────────────────────────────────────────────────────────────────
262
-
263
- /**
264
- * Starts a session with a token from the browser. Registering this machine's folders is the first call
265
- * that needs the token, so it doubles as the check that the token works: a failure leaves the daemon
266
- * signed out, not half-running.
267
- */
268
- async function signIn(token: string): Promise<void> {
269
- if (session !== undefined) await signOut();
270
- session = { ...settings!, token };
271
- try {
272
- await registerFolders();
273
- } catch (cause) {
274
- session = undefined;
275
- throw cause;
276
- }
277
- console.log(`signed in as ${session.machine}; syncing with ${session.endpoint}`);
278
- connect();
279
- void poll();
280
- }
281
-
282
- /** Revokes the token on the server, forgets it, and stops syncing. Returns whether the revoke succeeded. */
283
- async function signOut(): Promise<boolean> {
284
- const config = session;
285
- if (config === undefined) return false;
286
- session = undefined;
287
- if (pollTimer !== undefined) clearTimeout(pollTimer);
288
- socket?.close();
289
- socket = undefined;
290
- for (const watcher of watchers.values()) watcher.close();
291
- watchers.clear();
292
- prefs = new Map();
293
- registered = "";
294
- // Revoked, not just forgotten: a token copied while it was live would otherwise keep working.
295
- const revoked = await fetch(`${config.endpoint}/cli/token`, { method: "DELETE", headers: authHeaders(config, {}) })
296
- .then((response) => response.ok, () => false);
297
- console.log(`signed out${revoked ? "" : " (the server could not be reached to revoke the token)"}`);
298
- return revoked;
299
- }
300
-
301
- let loginInProgress = false;
302
-
303
- /**
304
- * One sign-in: listen on 127.0.0.1 for the browser to hand over the token, tell the CLI which URL to
305
- * open, and finish when the token arrives. The browser's login page posts to this listener only, never to
306
- * an address the request chose, so a page that tricks you into signing in cannot collect the token.
307
- */
308
- function login(reply: Reply): void {
309
- if (loginInProgress) {
310
- reply.send({ type: "error", message: "a sign-in is already in progress" });
311
- return;
312
- }
313
- loginInProgress = true;
314
- const done = (): void => {
315
- loginInProgress = false;
316
- listener.close();
317
- clearTimeout(timer);
318
- };
319
- const listener = createServer((request, response) => {
320
- const token = new URL(request.url ?? "/", "http://127.0.0.1").searchParams.get("token");
321
- response.writeHead(200, { "content-type": "text/html" });
322
- response.end(token ? "<p>Signed in. You can close this tab.</p>" : "<p>No token in the redirect.</p>");
323
- if (token === null) return;
324
- done();
325
- signIn(token).then(
326
- () => reply.send({ type: "signedIn", machine: settings!.machine }),
327
- (cause) => reply.send({ type: "error", message: `the server refused the sign-in: ${cause instanceof Error ? cause.message : String(cause)}` }),
328
- );
329
- });
330
- const timer = setTimeout(() => {
331
- done();
332
- reply.send({ type: "error", message: "timed out waiting for the browser" });
333
- }, LOGIN_TIMEOUT_MS);
334
- listener.listen(0, "127.0.0.1", () => {
335
- const port = (listener.address() as { port: number }).port;
336
- reply.send({ type: "open", url: `${settings!.endpoint}/cli/login?port=${port}&machine=${encodeURIComponent(settings!.machine)}` });
337
- });
338
- }
339
-
340
- /** The synced list, from the server: the CLI has no token to ask with, so it asks this daemon. */
341
- function list(reply: Reply): void {
342
- const config = session;
343
- if (config === undefined) {
344
- reply.send({ type: "error", message: "this machine is signed out; run `skill-sync login` first" });
345
- return;
346
- }
347
- fetch(`${config.endpoint}/skills`, { headers: authHeaders(config, {}) })
348
- .then(async (response) => {
349
- if (!response.ok) throw new Error(`GET /skills: ${response.status} ${await response.text()}`);
350
- reply.send({ type: "list", skills: (await response.json() as ListSkillsResponse).skills });
351
- })
352
- .catch((cause: unknown) => reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` }));
353
- }
354
-
355
- function handleControl(message: ControlRequest, reply: Reply): void {
356
- if (message.type === "login") login(reply);
357
- else if (message.type === "logout") void signOut().then((revoked) => reply.send({ type: "signedOut", revoked }));
358
- else if (message.type === "list") list(reply);
359
- else reply.send({ type: "error", message: `unknown request ${JSON.stringify(message)}` });
360
- }
361
-
362
- if (await serve(handleControl) === false) {
363
- console.log("another skill-sync daemon is already running for this user; standing down");
364
- // Zero: a second install's daemon is not a failure, and the service manager must not keep retrying it.
365
- process.exit(0);
366
- }
367
- console.log(`skill-sync daemon for ${settings.machine}; waiting for \`skill-sync login\``);
@@ -1,135 +0,0 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { Command } from "commander";
3
- import { Effect } from "effect";
4
- import { daemonStatuses, upgrade } from "jive-abstract-library";
5
- import { name } from "../../package.json";
6
- import { DaemonUnreachable, request, type ControlEvent, type ControlRequest } from "../internal/control";
7
-
8
- /**
9
- * The CLI that accompanies the daemon: `login`, `logout`, `list` and `upgrade`, and nothing else — which
10
- * folders and skills sync is chosen on the dashboard.
11
- *
12
- * The daemon owns the sync token and keeps it only in memory. `login`, `logout` and `list` are requests to
13
- * it over the control socket; the token goes from the browser straight to the daemon and never through here.
14
- */
15
-
16
- const program = new Command("skill-sync")
17
- .description("keep the skills you choose identical across every Claude folder on every machine; choose them at https://skill-sync.jive.sh/");
18
-
19
- program
20
- .command("login")
21
- .description("sign this machine in with your passkey in the browser; the daemon keeps the token in memory")
22
- .action(async () => {
23
- const result = await withDaemon({ type: "login" }, (event) => {
24
- if (event.type !== "open") return;
25
- console.log(`Opening ${event.url}`);
26
- openBrowser(event.url);
27
- });
28
- if (result.type === "signedIn") {
29
- console.log(`Signed in. ${result.machine} is syncing; choose what syncs at https://skill-sync.jive.sh/`);
30
- } else {
31
- fail(result);
32
- }
33
- });
34
-
35
- program
36
- .command("logout")
37
- .description("revoke this machine's token and stop syncing until the next login")
38
- .action(async () => {
39
- const result = await withDaemon({ type: "logout" }, () => undefined);
40
- if (result.type === "signedOut") {
41
- console.log(result.revoked ? "Signed out; the token is revoked." : "Signed out locally; the server could not be reached to revoke the token.");
42
- } else {
43
- fail(result);
44
- }
45
- });
46
-
47
- program
48
- .command("list")
49
- .description("list the skills that sync, as the server holds them; needs this machine signed in")
50
- .action(async () => {
51
- const result = await withDaemon({ type: "list" }, () => undefined);
52
- if (result.type !== "list") fail(result);
53
- if (result.skills.length === 0) {
54
- console.log("No skills sync yet; tick them at https://skill-sync.jive.sh/");
55
- return;
56
- }
57
- const width = Math.max(...result.skills.map((skill) => skill.name.length));
58
- for (const skill of result.skills) {
59
- const detail = skill.editedAt === null
60
- ? "no files yet"
61
- : `${skill.files} ${skill.files === 1 ? "file" : "files"}, last edited ${new Date(skill.editedAt).toLocaleString()} on ${skill.editedBy}`;
62
- console.log(`${skill.name.padEnd(width)} ${detail}`);
63
- }
64
- });
65
-
66
- program
67
- .command("upgrade")
68
- .description("upgrade skill-sync to the latest version with the package manager that installed it")
69
- .action(async () => {
70
- await Effect.runPromise(upgrade({ packageName: name })).catch((cause: unknown) => {
71
- console.error(`Upgrade failed: ${cause instanceof Error ? cause.message : String(cause)}`);
72
- process.exit(1);
73
- });
74
- });
75
-
76
- program.parse();
77
- if (process.argv.length <= 2) program.help();
78
-
79
- /**
80
- * Sends a request to the running daemon. If none is listening — stopped, or never started since the
81
- * install — this package's registered daemon is started through its service manager and the request is
82
- * retried for a few seconds.
83
- */
84
- async function withDaemon(message: ControlRequest, onEvent: (event: ControlEvent) => void): Promise<ControlEvent> {
85
- try {
86
- return await request(message, onEvent);
87
- } catch (cause) {
88
- if (!(cause instanceof DaemonUnreachable)) throw cause;
89
- }
90
- await startDaemons();
91
- for (let attempt = 0; ; attempt++) {
92
- await new Promise((resolve) => setTimeout(resolve, 500));
93
- try {
94
- return await request(message, onEvent);
95
- } catch (cause) {
96
- if (!(cause instanceof DaemonUnreachable) || attempt >= 20) {
97
- console.error(`${cause instanceof Error ? cause.message : String(cause)}. Reinstall skill-sync to register its daemon.`);
98
- process.exit(1);
99
- }
100
- }
101
- }
102
- }
103
-
104
- function fail(event: ControlEvent): never {
105
- console.error(event.type === "error" ? event.message : `unexpected answer from the daemon: ${JSON.stringify(event)}`);
106
- process.exit(1);
107
- }
108
-
109
- /** Starts this package's registered daemons through their service manager. */
110
- async function startDaemons(): Promise<void> {
111
- const statuses = await Effect.runPromise(daemonStatuses).catch(() => []);
112
- const ours = statuses.filter((status) => status.registration.packageName === name && status.executableExists);
113
- if (ours.length === 0) {
114
- return;
115
- }
116
- for (const { registration } of ours) {
117
- const command: string[] = registration.kind === "launchd"
118
- ? ["launchctl", "kickstart", "-k", `gui/${process.getuid?.() ?? 0}/${registration.unit}`]
119
- : registration.kind === "systemd"
120
- ? ["systemctl", "--user", "restart", registration.unit]
121
- : ["schtasks", "/Run", "/TN", registration.unit];
122
- const result = spawnSync(command[0]!, command.slice(1), { stdio: ["ignore", "ignore", "pipe"] });
123
- if (result.status !== 0) {
124
- console.error(`Could not start ${registration.unit}: ${String(result.stderr ?? "").trim() || `exit ${result.status}`}`);
125
- }
126
- }
127
- }
128
-
129
- function openBrowser(url: string): void {
130
- const command = process.platform === "darwin" ? "open"
131
- : process.platform === "win32" ? "cmd"
132
- : "xdg-open";
133
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
134
- spawn(command, args, { stdio: "ignore", detached: true }).unref();
135
- }
package/src/index.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * What the service needs from this package.
3
- *
4
- * The daemon and CLI are the product; this entrypoint exists so the service can share the path rules
5
- * and wire types rather than restate them. A rule restated is a rule that drifts, and these two are
6
- * exactly the pair that must not: one validates what the other writes to disk.
7
- */
8
-
9
- export { invalidPathReason, isValidPath } from "./internal/path";
10
- export { skillOf } from "./internal/wire";
11
- export type {
12
- DaemonMessage, DashboardMessage, FileHash, FolderPrefs, FolderState, FolderView, FoldersRequest, FoldersResponse,
13
- HubToDaemon, ListedSkill, ListFilesResponse, ListSkillsResponse, LocalSkill, MachineView, PutFileRequest, RemoteFile,
14
- SkillView, Snapshot, SyncedSkill,
15
- } from "./internal/wire";
@@ -1,165 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, statSync } from "node:fs";
3
- import { homedir, hostname, userInfo } from "node:os";
4
- import { join, relative, sep } from "node:path";
5
-
6
- /**
7
- * Per-machine settings and sync state, both under `~/.jive/`. The sync token is not here: it lives only in
8
- * the running daemon's memory.
9
- *
10
- * A file rather than environment variables: the endpoint and which machine this is differ per computer
11
- * and have to survive a login, which is exactly what a config file is for and exactly what an environment
12
- * variable is not. Which folders to sync is not in here: they are detected, and the choice to leave one
13
- * out is kept on the server so the dashboard can change it and a reinstalled daemon still remembers it.
14
- */
15
-
16
- const JIVE_HOME = join(homedir(), ".jive");
17
- export const CONFIG_PATH = join(JIVE_HOME, "skill-sync.json");
18
- const STATE_PATH = join(JIVE_HOME, "skill-sync-state.json");
19
- /**
20
- * Where versions before 0.3 kept the sync token. The token now lives only in the running daemon's memory,
21
- * so the daemon deletes this file whenever it finds one: a credential left on disk is one anything that
22
- * can read the home directory can copy.
23
- */
24
- export const LEGACY_TOKEN_PATH = join(homedir(), ".skill-sync-token.json");
25
- /**
26
- * How the CLI reaches the running daemon: a Unix socket in `~/.jive/`, or a named pipe on Windows. Only
27
- * this user can open either, which is what lets the CLI hand the daemon work that involves the token.
28
- */
29
- export const CONTROL_SOCKET = process.platform === "win32"
30
- ? `\\\\.\\pipe\\jive-skill-sync-${userInfo().username}`
31
- : join(JIVE_HOME, "skill-sync.sock");
32
-
33
- /** Managed by Claude's own cloud sync; see `Settings.exclude`. */
34
- const DEFAULT_EXCLUDE = ["synced"] as const;
35
-
36
- /** What `~/.jive/skill-sync.json` holds: nothing secret, so it can live in a file. */
37
- export interface Settings {
38
- readonly endpoint: string;
39
- /**
40
- * Top-level directory names under each synced folder to leave alone.
41
- *
42
- * `synced` holds the skills Claude already pulls from the cloud itself. Syncing them here would mean
43
- * two systems writing the same files, each undoing the other, and none of them are yours to edit.
44
- */
45
- readonly exclude: ReadonlyArray<string>;
46
- /** Names this machine on the server: on the dashboard, and as the machine each edit came from. */
47
- readonly machine: string;
48
- }
49
-
50
- /** Settings plus the token, which exists only in the daemon's memory after a sign-in. */
51
- export interface Config extends Settings {
52
- readonly token: string;
53
- }
54
-
55
- /** Sync progress for one folder. Each folder syncs with the server on its own, so each has its own. */
56
- export interface State {
57
- /** Highest server sequence number already applied. */
58
- cursor: number;
59
- /** Last hash this machine agreed with the server on, per relative path. Absent means never synced. */
60
- known: Record<string, string>;
61
- /** The synced list as of last cycle, to notice a skill being added to it. */
62
- skills?: string[];
63
- }
64
-
65
- /** Every folder's `State`, keyed by the folder's absolute path. */
66
- export type States = Record<string, State>;
67
-
68
- /**
69
- * The settings, writing a template on first run. Undefined when the file lacks an endpoint or a machine
70
- * name, which only happens if someone edited it.
71
- */
72
- export function loadSettings(): Settings | undefined {
73
- if (!existsSync(CONFIG_PATH)) {
74
- mkdirSync(JIVE_HOME, { recursive: true });
75
- writeFileSync(CONFIG_PATH, `${JSON.stringify({
76
- endpoint: "https://skill-sync.jive.sh",
77
- machine: machineName(),
78
- exclude: DEFAULT_EXCLUDE,
79
- }, null, 2)}\n`);
80
- }
81
- const settings = readJson<Partial<Settings>>(CONFIG_PATH);
82
- if (!settings.endpoint || !settings.machine) return undefined;
83
- return { endpoint: settings.endpoint, machine: settings.machine, exclude: settings.exclude ?? DEFAULT_EXCLUDE };
84
- }
85
-
86
- function readJson<T>(path: string): T {
87
- try {
88
- return JSON.parse(readFileSync(path, "utf-8")) as T;
89
- } catch {
90
- return {} as T;
91
- }
92
- }
93
-
94
- /**
95
- * Every folder's sync state.
96
- *
97
- * Before folders were detected the file held one folder's `{ cursor, known }`, for the folder then named
98
- * by `skillsDir` in the settings. That state is carried over to that folder: dropping it would make the
99
- * folder look never-synced, and every file in it that differs from the server would become a conflict.
100
- */
101
- export function loadStates(): States {
102
- const stored = readJson<Partial<State> & { folders?: States }>(STATE_PATH);
103
- if (stored.folders !== undefined) return stored.folders;
104
- const legacyFolder = readJson<{ skillsDir?: string }>(CONFIG_PATH).skillsDir;
105
- if (legacyFolder !== undefined && stored.cursor !== undefined && stored.known !== undefined) {
106
- return { [legacyFolder]: { cursor: stored.cursor, known: stored.known } };
107
- }
108
- return {};
109
- }
110
-
111
- export function stateFor(states: States, folder: string): State {
112
- states[folder] ??= { cursor: 0, known: {} };
113
- return states[folder];
114
- }
115
-
116
- export function saveStates(states: States): void {
117
- mkdirSync(JIVE_HOME, { recursive: true });
118
- writeFileSync(STATE_PATH, `${JSON.stringify({ folders: states }, null, 2)}\n`);
119
- }
120
-
121
- /** `HOSTNAME` is not set on macOS, so the template was writing "unknown" on exactly this machine. */
122
- function machineName(): string {
123
- return hostname().replace(/\.local$/, "").replace(/[^A-Za-z0-9-]+/g, "-") || "unknown";
124
- }
125
-
126
- /**
127
- * The `skills` folder of every Claude home on this machine: `~/.claude` and each `~/.claude-<name>`.
128
- *
129
- * Every home is a candidate, whether or not it has a `skills` folder yet, so a Claude account added
130
- * later joins without anyone listing it. Which of them actually sync is the user's choice on the
131
- * dashboard; a folder that is synced and missing is created.
132
- */
133
- export function detectFolders(): string[] {
134
- return readdirSync(homedir())
135
- .filter((entry) => entry === ".claude" || entry.startsWith(".claude-"))
136
- .filter((entry) => statSync(join(homedir(), entry)).isDirectory())
137
- .map((entry) => join(homedir(), entry, "skills"))
138
- .sort();
139
- }
140
-
141
- export function hashBytes(bytes: Uint8Array): string {
142
- return createHash("sha256").update(bytes).digest("hex");
143
- }
144
-
145
- /**
146
- * Every file under a synced folder, as paths relative to it with forward slashes.
147
- *
148
- * Normalised because the same skill synced from Windows and macOS must be one row, not two.
149
- */
150
- export function listLocalFiles(folder: string, exclude: ReadonlyArray<string> = DEFAULT_EXCLUDE): string[] {
151
- if (!existsSync(folder)) return [];
152
-
153
- const found: string[] = [];
154
- const walk = (dir: string, top: boolean): void => {
155
- for (const entry of readdirSync(dir)) {
156
- if (entry.startsWith(".")) continue;
157
- if (top && exclude.includes(entry)) continue;
158
- const full = join(dir, entry);
159
- if (statSync(full).isDirectory()) walk(full, false);
160
- else found.push(relative(folder, full).split(sep).join("/"));
161
- }
162
- };
163
- walk(folder, true);
164
- return found.sort();
165
- }