@jive-sh/skill-sync 0.4.2 → 0.4.3-latest-darwin-x64

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,368 +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: the `skills` folder in each `~/.claude*` home and in `~/.agents`. Which of them
16
- * sync, and the one list of skills that syncs in all of them, are held by the server and changed from the
17
- * dashboard, so they survive a reinstall and apply the moment they change. A skill not on the list is
18
- * never pushed or pulled.
19
- *
20
- * The daemon holds a WebSocket to the service's hub. That connection is how the dashboard knows this
21
- * machine is running, how a preference change arrives, and how a write from another machine triggers a
22
- * cycle here at once. Polling stays as the fallback: every 5 minutes while connected, every 30 seconds
23
- * while not, so a dropped connection costs latency and never correctness.
24
- *
25
- * The sync token exists only in this process's memory. The daemon starts signed out and waits; `skill-sync
26
- * login` asks it, over the control socket, to sign in, and the token arrives from the browser straight to
27
- * this process. A restart means signing in again — the price of never writing the credential down.
28
- */
29
-
30
- const POLL_CONNECTED_MS = 5 * 60_000;
31
- const POLL_DISCONNECTED_MS = 30_000;
32
- /** Long enough that an editor's write-rename-write lands as one cycle, short enough to feel immediate. */
33
- const SETTLE_MS = 1_000;
34
- const PING_MS = 30_000;
35
- /** No pong for this long means the connection is dead even if the socket has not noticed. */
36
- const PONG_TIMEOUT_MS = 75_000;
37
- const RECONNECT_MIN_MS = 5_000;
38
- const RECONNECT_MAX_MS = 5 * 60_000;
39
- /** How long a sign-in waits for the browser before giving up. */
40
- const LOGIN_TIMEOUT_MS = 5 * 60_000;
41
-
42
- exitWhenUninstalled();
43
-
44
- // Versions before 0.3 wrote the token to a file. It is never read: a credential left on disk is one
45
- // anything that can read the home directory can copy.
46
- if (existsSync(LEGACY_TOKEN_PATH)) {
47
- rmSync(LEGACY_TOKEN_PATH, { force: true });
48
- console.log(`deleted ${LEGACY_TOKEN_PATH}; the token now lives only in this daemon's memory`);
49
- }
50
-
51
- const settings = loadSettings();
52
- if (settings === undefined) {
53
- console.error("~/.jive/skill-sync.json needs an endpoint and a machine name");
54
- // Zero, not one: the service manager restarts a daemon that fails, and a file nobody has fixed would
55
- // only fill the log.
56
- process.exit(0);
57
- }
58
- const states = loadStates();
59
-
60
- /** Set while signed in. Everything that talks to the server reads it; signing out clears it. */
61
- let session: Config | undefined;
62
- /** The signed-in config, for code that only runs during a session. */
63
- function current(): Config {
64
- if (session === undefined) throw new Error("not signed in");
65
- return session;
66
- }
67
-
68
- /** What was last registered, so registration is repeated only when a folder or skill appears or goes. */
69
- let registered = "";
70
- /** The enabled folders, each with the synced list. */
71
- let prefs = new Map<string, ReadonlySet<string>>();
72
- const watchers = new Map<string, FSWatcher>();
73
-
74
- // ── Folders ─────────────────────────────────────────────────────────────────────────────────────────
75
-
76
- /** Reports this machine's folders and skills, and adopts the server's answer for what syncs. */
77
- async function registerFolders(): Promise<void> {
78
- const request = describe(current());
79
- applyPrefs(await register(current(), request));
80
- registered = JSON.stringify(request);
81
- }
82
-
83
- /** True when a folder or a skill has appeared or gone since the last registration. */
84
- const registrationStale = (): boolean => JSON.stringify(describe(current())) !== registered;
85
-
86
- function applyPrefs(folders: ReadonlyArray<FolderPrefs>): void {
87
- // Only folders this machine still has. The hub can hold a stale list — it answers a reconnect before
88
- // the next registration — and creating a listed folder whose agent home is gone would bring it back.
89
- const present = new Set(detectFolders());
90
- const next = new Map(folders.filter((folder) => present.has(folder.path))
91
- .map((folder) => [folder.path, new Set(folder.skills)] as const));
92
- for (const [folder, watcher] of watchers) {
93
- if (!next.has(folder)) {
94
- watcher.close();
95
- watchers.delete(folder);
96
- }
97
- }
98
- // An unticked folder leaves no trace of syncing: its state goes, so the state file lists only folders
99
- // that sync, and ticking it again starts it fresh.
100
- // Covers folders with state from an earlier run too, not only ones this run was syncing.
101
- const stopped = [...new Set([...prefs.keys(), ...Object.keys(states)])].filter((folder) => !next.has(folder));
102
- for (const folder of stopped) {
103
- delete states[folder];
104
- console.log(`stopped syncing ${folder}`);
105
- }
106
- if (stopped.length > 0) saveStates(states);
107
- for (const folder of next.keys()) {
108
- if (watchers.has(folder)) continue;
109
- mkdirSync(folder, { recursive: true });
110
- let settle: ReturnType<typeof setTimeout> | undefined;
111
- watchers.set(folder, watch(folder, { recursive: true }, () => {
112
- if (settle !== undefined) clearTimeout(settle);
113
- settle = setTimeout(runCycle, SETTLE_MS);
114
- }));
115
- }
116
- const changed = JSON.stringify([...next].map(([path, skills]) => [path, [...skills].sort()]))
117
- !== JSON.stringify([...prefs].map(([path, skills]) => [path, [...skills].sort()]));
118
- prefs = next;
119
- if (!changed) return;
120
- for (const [folder, skills] of prefs) console.log(`syncing ${folder}: ${[...skills].sort().join(", ") || "no skills"}`);
121
- if (prefs.size === 0) console.log("syncing no folders");
122
- void runCycle();
123
- }
124
-
125
- // ── Hub connection ──────────────────────────────────────────────────────────────────────────────────
126
-
127
- let socket: WebSocket | undefined;
128
- let lastPong = 0;
129
- let reconnectDelay = RECONNECT_MIN_MS;
130
- /** What the hub was last told about each folder (state and detail), so only changes are sent. */
131
- const reported = new Map<string, string>();
132
-
133
- function connect(): void {
134
- if (session === undefined) return;
135
- const config = session;
136
- const url = `${config.endpoint.replace(/^http/, "ws")}/daemon`;
137
- // Bun's WebSocket takes headers; the browser's does not, which is why the token can travel this way.
138
- const ws = new WebSocket(url, { headers: authHeaders(config, {}) } as unknown as string[]);
139
- ws.onopen = () => {
140
- socket = ws;
141
- lastPong = Date.now();
142
- reconnectDelay = RECONNECT_MIN_MS;
143
- console.log("connected to the hub");
144
- // Whatever the hub last heard from a previous connection is stale until re-sent.
145
- reported.clear();
146
- for (const folder of prefs.keys()) report(folder, "idle");
147
- };
148
- ws.onmessage = (event) => {
149
- const data = String(event.data);
150
- if (data === "pong") {
151
- lastPong = Date.now();
152
- return;
153
- }
154
- const message = JSON.parse(data) as HubToDaemon;
155
- if (message.type === "prefs") applyPrefs(message.folders);
156
- if (message.type === "changed") void runCycle();
157
- };
158
- ws.onclose = () => {
159
- if (socket === ws) socket = undefined;
160
- // Only the session that opened it reconnects: after a sign-out, or a sign-in with a new token, this
161
- // socket belongs to nobody.
162
- if (session !== config) return;
163
- setTimeout(connect, reconnectDelay);
164
- reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
165
- };
166
- ws.onerror = () => {
167
- // `onclose` follows and schedules the reconnect.
168
- };
169
- }
170
-
171
- setInterval(() => {
172
- if (socket === undefined) return;
173
- if (Date.now() - lastPong > PONG_TIMEOUT_MS) {
174
- console.error("hub connection went quiet; reconnecting");
175
- socket.close();
176
- return;
177
- }
178
- socket.send("ping");
179
- }, PING_MS);
180
-
181
- function report(folder: string, state: FolderState, detail?: string, activity?: string): void {
182
- const key = `${state}|${detail ?? ""}`;
183
- if (reported.get(folder) === key && activity === undefined) return;
184
- if (socket === undefined) return;
185
- const message: DaemonMessage = { type: "status", folder, state, detail, activity };
186
- socket.send(JSON.stringify(message));
187
- reported.set(folder, key);
188
- }
189
-
190
- // ── Sync cycles ─────────────────────────────────────────────────────────────────────────────────────
191
-
192
- let running = false;
193
- let cycleQueued = false;
194
-
195
- function summarise(result: Report): string {
196
- const parts = [
197
- result.pulled.length > 0 ? `pulled ${result.pulled.join(", ")}` : "",
198
- result.pushed.length > 0 ? `pushed ${result.pushed.join(", ")}` : "",
199
- result.deletedLocally.length > 0 ? `deleted ${result.deletedLocally.join(", ")}` : "",
200
- ];
201
- return parts.filter(Boolean).join("; ");
202
- }
203
-
204
- async function runCycle(): Promise<void> {
205
- if (session === undefined) return;
206
- if (running) {
207
- cycleQueued = true;
208
- return;
209
- }
210
- running = true;
211
- try {
212
- // Folders sync one after another against the same server, so a change pushed from one folder is
213
- // pulled into the others on the follow-up pass this triggers.
214
- for (const [folder, skills] of [...prefs]) {
215
- try {
216
- const result = await syncOnce(current(), folder, stateFor(states, folder), skills);
217
- saveStates(states);
218
- log(folder, result);
219
- if (result.rejected.length > 0) report(folder, "attention", result.rejected.join("; "), summarise(result) || undefined);
220
- else report(folder, "idle", undefined, isQuiet(result) ? undefined : summarise(result));
221
- // What this folder pushed is pulled into the machine's other folders on the follow-up pass.
222
- if (result.pushed.length > 0) cycleQueued = true;
223
- } catch (cause) {
224
- // One failed folder must not end the daemon or the other folders: the usual cause is the network.
225
- const reason = cause instanceof Error ? cause.message : String(cause);
226
- console.error(`${folder}: sync failed: ${reason}`);
227
- report(folder, "attention", `sync failed: ${reason}`);
228
- }
229
- }
230
- // A skill created or removed locally changes what the dashboard should list.
231
- if (registrationStale()) await registerFolders().catch(() => undefined);
232
- } finally {
233
- running = false;
234
- if (cycleQueued) {
235
- cycleQueued = false;
236
- setTimeout(runCycle, SETTLE_MS);
237
- }
238
- }
239
- }
240
-
241
- function log(folder: string, result: Report): void {
242
- for (const path of result.pulled) console.log(`${folder}: pulled ${path}`);
243
- for (const path of result.pushed) console.log(`${folder}: pushed ${path}`);
244
- for (const path of result.deletedLocally) console.log(`${folder}: deleted ${path}`);
245
- for (const path of result.rejected) console.error(`${folder}: refused a path the server sent: ${path}`);
246
- }
247
-
248
- let pollTimer: ReturnType<typeof setTimeout> | undefined;
249
-
250
- /** Re-detects folders each poll: an agent home created since the last one should join without a restart. */
251
- async function poll(): Promise<void> {
252
- if (session === undefined) return;
253
- try {
254
- if (registered === "" || registrationStale()) await registerFolders();
255
- } catch (cause) {
256
- console.error(`could not register folders: ${cause instanceof Error ? cause.message : String(cause)}`);
257
- }
258
- await runCycle();
259
- if (session !== undefined) pollTimer = setTimeout(poll, socket === undefined ? POLL_DISCONNECTED_MS : POLL_CONNECTED_MS);
260
- }
261
-
262
- // ── Signing in and out ──────────────────────────────────────────────────────────────────────────────
263
-
264
- /**
265
- * Starts a session with a token from the browser. Registering this machine's folders is the first call
266
- * that needs the token, so it doubles as the check that the token works: a failure leaves the daemon
267
- * signed out, not half-running.
268
- */
269
- async function signIn(token: string): Promise<void> {
270
- if (session !== undefined) await signOut();
271
- session = { ...settings!, token };
272
- try {
273
- await registerFolders();
274
- } catch (cause) {
275
- session = undefined;
276
- throw cause;
277
- }
278
- console.log(`signed in as ${session.machine}; syncing with ${session.endpoint}`);
279
- connect();
280
- void poll();
281
- }
282
-
283
- /** Revokes the token on the server, forgets it, and stops syncing. Returns whether the revoke succeeded. */
284
- async function signOut(): Promise<boolean> {
285
- const config = session;
286
- if (config === undefined) return false;
287
- session = undefined;
288
- if (pollTimer !== undefined) clearTimeout(pollTimer);
289
- socket?.close();
290
- socket = undefined;
291
- for (const watcher of watchers.values()) watcher.close();
292
- watchers.clear();
293
- prefs = new Map();
294
- registered = "";
295
- // Revoked, not just forgotten: a token copied while it was live would otherwise keep working.
296
- const revoked = await fetch(`${config.endpoint}/cli/token`, { method: "DELETE", headers: authHeaders(config, {}) })
297
- .then((response) => response.ok, () => false);
298
- console.log(`signed out${revoked ? "" : " (the server could not be reached to revoke the token)"}`);
299
- return revoked;
300
- }
301
-
302
- let loginInProgress = false;
303
-
304
- /**
305
- * One sign-in: listen on 127.0.0.1 for the browser to hand over the token, tell the CLI which URL to
306
- * open, and finish when the token arrives. The browser's login page posts to this listener only, never to
307
- * an address the request chose, so a page that tricks you into signing in cannot collect the token.
308
- */
309
- function login(reply: Reply): void {
310
- if (loginInProgress) {
311
- reply.send({ type: "error", message: "a sign-in is already in progress" });
312
- return;
313
- }
314
- loginInProgress = true;
315
- const done = (): void => {
316
- loginInProgress = false;
317
- listener.close();
318
- clearTimeout(timer);
319
- };
320
- const listener = createServer((request, response) => {
321
- const token = new URL(request.url ?? "/", "http://127.0.0.1").searchParams.get("token");
322
- response.writeHead(200, { "content-type": "text/html" });
323
- response.end(token ? "<p>Signed in. You can close this tab.</p>" : "<p>No token in the redirect.</p>");
324
- if (token === null) return;
325
- done();
326
- signIn(token).then(
327
- () => reply.send({ type: "signedIn", machine: settings!.machine }),
328
- (cause) => reply.send({ type: "error", message: `the server refused the sign-in: ${cause instanceof Error ? cause.message : String(cause)}` }),
329
- );
330
- });
331
- const timer = setTimeout(() => {
332
- done();
333
- reply.send({ type: "error", message: "timed out waiting for the browser" });
334
- }, LOGIN_TIMEOUT_MS);
335
- listener.listen(0, "127.0.0.1", () => {
336
- const port = (listener.address() as { port: number }).port;
337
- reply.send({ type: "open", url: `${settings!.endpoint}/cli/login?port=${port}&machine=${encodeURIComponent(settings!.machine)}` });
338
- });
339
- }
340
-
341
- /** The synced list, from the server: the CLI has no token to ask with, so it asks this daemon. */
342
- function list(reply: Reply): void {
343
- const config = session;
344
- if (config === undefined) {
345
- reply.send({ type: "error", message: "this machine is signed out; run `skill-sync login` first" });
346
- return;
347
- }
348
- fetch(`${config.endpoint}/skills`, { headers: authHeaders(config, {}) })
349
- .then(async (response) => {
350
- if (!response.ok) throw new Error(`GET /skills: ${response.status} ${await response.text()}`);
351
- reply.send({ type: "list", skills: (await response.json() as ListSkillsResponse).skills });
352
- })
353
- .catch((cause: unknown) => reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` }));
354
- }
355
-
356
- function handleControl(message: ControlRequest, reply: Reply): void {
357
- if (message.type === "login") login(reply);
358
- else if (message.type === "logout") void signOut().then((revoked) => reply.send({ type: "signedOut", revoked }));
359
- else if (message.type === "list") list(reply);
360
- else reply.send({ type: "error", message: `unknown request ${JSON.stringify(message)}` });
361
- }
362
-
363
- if (await serve(handleControl) === false) {
364
- console.log("another skill-sync daemon is already running for this user; standing down");
365
- // Zero: a second install's daemon is not a failure, and the service manager must not keep retrying it.
366
- process.exit(0);
367
- }
368
- 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 and Codex skills 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";