@jive-sh/skill-sync 0.4.4-latest-darwin-arm64 → 0.4.4

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.
@@ -0,0 +1,418 @@
1
+ import { mkdirSync, watch, type FSWatcher } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { exitWhenUninstalled } from "jive-abstract-library";
4
+ import {
5
+ TOKEN_PATH, deleteToken, detectFolders, loadSettings, loadStates, loadToken, saveStates, saveToken, stateFor,
6
+ type Config,
7
+ } from "../internal/config";
8
+ import { serve, type ControlRequest, type Reply } from "../internal/control";
9
+ import { describe, register } from "../internal/folders";
10
+ import { authHeaders, fetchServer, TokenRejected } from "../internal/server";
11
+ import { isQuiet, syncOnce, type Report } from "../internal/sync";
12
+ import type { DaemonMessage, FolderPrefs, FolderState, HubToDaemon, ListSkillsResponse } from "../internal/wire";
13
+
14
+ /**
15
+ * Keeps every enabled skills folder on this machine identical to every other machine's.
16
+ *
17
+ * Folders are detected: the `skills` folder in each `~/.claude*` home and Codex's `~/.agents/skills`
18
+ * (see `detectFolders`). Which of them sync, and the one list of skills that syncs in all of them, are
19
+ * held by the server and changed from the dashboard, so they survive a reinstall and apply the moment
20
+ * they change. A skill not on the list is never pushed or pulled.
21
+ *
22
+ * The daemon holds a WebSocket to the service's hub. That connection is how the dashboard knows this
23
+ * machine is running, how a preference change arrives, and how a write from another machine triggers a
24
+ * cycle here at once. Polling stays as the fallback: every 5 minutes while connected, every 30 seconds
25
+ * while not, so a dropped connection costs latency and never correctness.
26
+ *
27
+ * `skill-sync login` asks the daemon, over the control socket, to sign in; the token arrives from the
28
+ * browser straight to this process, which keeps it in `~/.jive/skill-sync-token.json` (`TOKEN_PATH`). A
29
+ * daemon that starts and finds that file is signed in, so a restart, a reboot or an upgrade needs no
30
+ * sign-in. Signing out, or the server rejecting the token, deletes the file.
31
+ */
32
+
33
+ const POLL_CONNECTED_MS = 5 * 60_000;
34
+ const POLL_DISCONNECTED_MS = 30_000;
35
+ /** Long enough that an editor's write-rename-write lands as one cycle, short enough to feel immediate. */
36
+ const SETTLE_MS = 1_000;
37
+ const PING_MS = 30_000;
38
+ /** No pong for this long means the connection is dead even if the socket has not noticed. */
39
+ const PONG_TIMEOUT_MS = 75_000;
40
+ const RECONNECT_MIN_MS = 5_000;
41
+ const RECONNECT_MAX_MS = 5 * 60_000;
42
+ /** How long a sign-in waits for the browser before giving up. */
43
+ const LOGIN_TIMEOUT_MS = 5 * 60_000;
44
+
45
+ exitWhenUninstalled();
46
+
47
+ const settings = loadSettings();
48
+ if (settings === undefined) {
49
+ console.error("~/.jive/skill-sync.json needs an endpoint and a machine name");
50
+ // Zero, not one: the service manager restarts a daemon that fails, and a file nobody has fixed would
51
+ // only fill the log.
52
+ process.exit(0);
53
+ }
54
+ const states = loadStates();
55
+
56
+ /** Set while signed in. Everything that talks to the server reads it; signing out clears it. */
57
+ let session: Config | undefined;
58
+ /** The signed-in config, for code that only runs during a session. */
59
+ function current(): Config {
60
+ if (session === undefined) throw new Error("not signed in");
61
+ return session;
62
+ }
63
+
64
+ /** What was last registered, so registration is repeated only when a folder or skill appears or goes. */
65
+ let registered = "";
66
+ /** The enabled folders, each with the synced list. */
67
+ let prefs = new Map<string, ReadonlySet<string>>();
68
+ const watchers = new Map<string, FSWatcher>();
69
+
70
+ // ── Folders ─────────────────────────────────────────────────────────────────────────────────────────
71
+
72
+ /** Reports this machine's folders and skills, and adopts the server's answer for what syncs. */
73
+ async function registerFolders(): Promise<void> {
74
+ const request = describe(current());
75
+ applyPrefs(await register(current(), request));
76
+ registered = JSON.stringify(request);
77
+ }
78
+
79
+ /** True when a folder or a skill has appeared or gone since the last registration. */
80
+ const registrationStale = (): boolean => JSON.stringify(describe(current())) !== registered;
81
+
82
+ function applyPrefs(folders: ReadonlyArray<FolderPrefs>): void {
83
+ // Only folders this machine still has. The hub can hold a stale list — it answers a reconnect before
84
+ // the next registration — and creating a listed folder whose agent home is gone would bring it back.
85
+ const present = new Set(detectFolders());
86
+ const next = new Map(folders.filter((folder) => present.has(folder.path))
87
+ .map((folder) => [folder.path, new Set(folder.skills)] as const));
88
+ for (const [folder, watcher] of watchers) {
89
+ if (!next.has(folder)) {
90
+ watcher.close();
91
+ watchers.delete(folder);
92
+ }
93
+ }
94
+ // An unticked folder leaves no trace of syncing: its state goes, so the state file lists only folders
95
+ // that sync, and ticking it again starts it fresh.
96
+ // Covers folders with state from an earlier run too, not only ones this run was syncing.
97
+ const stopped = [...new Set([...prefs.keys(), ...Object.keys(states)])].filter((folder) => !next.has(folder));
98
+ for (const folder of stopped) {
99
+ delete states[folder];
100
+ console.log(`stopped syncing ${folder}`);
101
+ }
102
+ if (stopped.length > 0) saveStates(states);
103
+ for (const folder of next.keys()) {
104
+ if (watchers.has(folder)) continue;
105
+ mkdirSync(folder, { recursive: true });
106
+ let settle: ReturnType<typeof setTimeout> | undefined;
107
+ watchers.set(folder, watch(folder, { recursive: true }, () => {
108
+ if (settle !== undefined) clearTimeout(settle);
109
+ settle = setTimeout(runCycle, SETTLE_MS);
110
+ }));
111
+ }
112
+ const changed = JSON.stringify([...next].map(([path, skills]) => [path, [...skills].sort()]))
113
+ !== JSON.stringify([...prefs].map(([path, skills]) => [path, [...skills].sort()]));
114
+ prefs = next;
115
+ if (!changed) return;
116
+ for (const [folder, skills] of prefs) console.log(`syncing ${folder}: ${[...skills].sort().join(", ") || "no skills"}`);
117
+ if (prefs.size === 0) console.log("syncing no folders");
118
+ void runCycle();
119
+ }
120
+
121
+ // ── Hub connection ──────────────────────────────────────────────────────────────────────────────────
122
+
123
+ let socket: WebSocket | undefined;
124
+ let lastPong = 0;
125
+ let reconnectDelay = RECONNECT_MIN_MS;
126
+ /** What the hub was last told about each folder (state and detail), so only changes are sent. */
127
+ const reported = new Map<string, string>();
128
+
129
+ function connect(): void {
130
+ if (session === undefined) return;
131
+ const config = session;
132
+ const url = `${config.endpoint.replace(/^http/, "ws")}/daemon`;
133
+ // Bun's WebSocket takes headers; the browser's does not, which is why the token can travel this way.
134
+ const ws = new WebSocket(url, { headers: authHeaders(config, {}) } as unknown as string[]);
135
+ ws.onopen = () => {
136
+ socket = ws;
137
+ lastPong = Date.now();
138
+ reconnectDelay = RECONNECT_MIN_MS;
139
+ console.log("connected to the hub");
140
+ // Whatever the hub last heard from a previous connection is stale until re-sent.
141
+ reported.clear();
142
+ for (const folder of prefs.keys()) report(folder, "idle");
143
+ };
144
+ ws.onmessage = (event) => {
145
+ const data = String(event.data);
146
+ if (data === "pong") {
147
+ lastPong = Date.now();
148
+ return;
149
+ }
150
+ const message = JSON.parse(data) as HubToDaemon;
151
+ if (message.type === "prefs") applyPrefs(message.folders);
152
+ if (message.type === "changed") void runCycle();
153
+ };
154
+ ws.onclose = () => {
155
+ if (socket === ws) socket = undefined;
156
+ // Only the session that opened it reconnects: after a sign-out, or a sign-in with a new token, this
157
+ // socket belongs to nobody.
158
+ if (session !== config) return;
159
+ setTimeout(connect, reconnectDelay);
160
+ reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
161
+ };
162
+ ws.onerror = () => {
163
+ // `onclose` follows and schedules the reconnect.
164
+ };
165
+ }
166
+
167
+ setInterval(() => {
168
+ if (socket === undefined) return;
169
+ if (Date.now() - lastPong > PONG_TIMEOUT_MS) {
170
+ console.error("hub connection went quiet; reconnecting");
171
+ socket.close();
172
+ return;
173
+ }
174
+ socket.send("ping");
175
+ }, PING_MS);
176
+
177
+ function report(folder: string, state: FolderState, detail?: string, activity?: string): void {
178
+ const key = `${state}|${detail ?? ""}`;
179
+ if (reported.get(folder) === key && activity === undefined) return;
180
+ if (socket === undefined) return;
181
+ const message: DaemonMessage = { type: "status", folder, state, detail, activity };
182
+ socket.send(JSON.stringify(message));
183
+ reported.set(folder, key);
184
+ }
185
+
186
+ // ── Sync cycles ─────────────────────────────────────────────────────────────────────────────────────
187
+
188
+ let running = false;
189
+ let cycleQueued = false;
190
+
191
+ function summarise(result: Report): string {
192
+ const parts = [
193
+ result.pulled.length > 0 ? `pulled ${result.pulled.join(", ")}` : "",
194
+ result.pushed.length > 0 ? `pushed ${result.pushed.join(", ")}` : "",
195
+ result.deletedLocally.length > 0 ? `deleted ${result.deletedLocally.join(", ")}` : "",
196
+ ];
197
+ return parts.filter(Boolean).join("; ");
198
+ }
199
+
200
+ async function runCycle(): Promise<void> {
201
+ if (session === undefined) return;
202
+ if (running) {
203
+ cycleQueued = true;
204
+ return;
205
+ }
206
+ running = true;
207
+ try {
208
+ // Folders sync one after another against the same server, so a change pushed from one folder is
209
+ // pulled into the others on the follow-up pass this triggers.
210
+ for (const [folder, skills] of [...prefs]) {
211
+ try {
212
+ const result = await syncOnce(current(), folder, stateFor(states, folder), skills);
213
+ saveStates(states);
214
+ log(folder, result);
215
+ if (result.rejected.length > 0) report(folder, "attention", result.rejected.join("; "), summarise(result) || undefined);
216
+ else report(folder, "idle", undefined, isQuiet(result) ? undefined : summarise(result));
217
+ // What this folder pushed is pulled into the machine's other folders on the follow-up pass.
218
+ if (result.pushed.length > 0) cycleQueued = true;
219
+ } catch (cause) {
220
+ if (cause instanceof TokenRejected) {
221
+ dropRejectedToken(cause);
222
+ return;
223
+ }
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()) {
232
+ await registerFolders().catch((cause: unknown) => {
233
+ if (cause instanceof TokenRejected) dropRejectedToken(cause);
234
+ });
235
+ }
236
+ } finally {
237
+ running = false;
238
+ if (cycleQueued) {
239
+ cycleQueued = false;
240
+ setTimeout(runCycle, SETTLE_MS);
241
+ }
242
+ }
243
+ }
244
+
245
+ function log(folder: string, result: Report): void {
246
+ for (const path of result.pulled) console.log(`${folder}: pulled ${path}`);
247
+ for (const path of result.pushed) console.log(`${folder}: pushed ${path}`);
248
+ for (const path of result.deletedLocally) console.log(`${folder}: deleted ${path}`);
249
+ for (const path of result.rejected) console.error(`${folder}: refused a path the server sent: ${path}`);
250
+ }
251
+
252
+ let pollTimer: ReturnType<typeof setTimeout> | undefined;
253
+
254
+ /** Re-detects folders each poll: an agent home created since the last one should join without a restart. */
255
+ async function poll(): Promise<void> {
256
+ if (session === undefined) return;
257
+ try {
258
+ if (registered === "" || registrationStale()) await registerFolders();
259
+ } catch (cause) {
260
+ if (cause instanceof TokenRejected) {
261
+ dropRejectedToken(cause);
262
+ return;
263
+ }
264
+ console.error(`could not register folders: ${cause instanceof Error ? cause.message : String(cause)}`);
265
+ }
266
+ await runCycle();
267
+ if (session !== undefined) pollTimer = setTimeout(poll, socket === undefined ? POLL_DISCONNECTED_MS : POLL_CONNECTED_MS);
268
+ }
269
+
270
+ // ── Signing in and out ──────────────────────────────────────────────────────────────────────────────
271
+
272
+ /**
273
+ * Starts a session with a token from the browser. Registering this machine's folders is the first call
274
+ * that needs the token, so it doubles as the check that the token works: a failure leaves the daemon
275
+ * signed out, not half-running, and the token unsaved.
276
+ */
277
+ async function signIn(token: string): Promise<void> {
278
+ if (session !== undefined) await signOut();
279
+ session = { ...settings!, token };
280
+ try {
281
+ await registerFolders();
282
+ } catch (cause) {
283
+ session = undefined;
284
+ throw cause;
285
+ }
286
+ saveToken(token);
287
+ console.log(`signed in as ${session.machine}; syncing with ${session.endpoint}`);
288
+ connect();
289
+ void poll();
290
+ }
291
+
292
+ /**
293
+ * Starts a session with the token saved by an earlier sign-in. Not checked first, unlike `signIn`: at boot
294
+ * the network may not be up yet, and a failure for that reason must not sign the machine out. The first
295
+ * poll registers; a rejected token signs out there.
296
+ */
297
+ function resume(token: string): void {
298
+ session = { ...settings!, token };
299
+ console.log(`signed in as ${session.machine} with the token in ${TOKEN_PATH}; syncing with ${session.endpoint}`);
300
+ connect();
301
+ void poll();
302
+ }
303
+
304
+ /** Stops syncing and forgets the token, here and in `TOKEN_PATH`. Returns the session that ended. */
305
+ function endSession(): Config | undefined {
306
+ const config = session;
307
+ if (config === undefined) return undefined;
308
+ session = undefined;
309
+ deleteToken();
310
+ if (pollTimer !== undefined) clearTimeout(pollTimer);
311
+ socket?.close();
312
+ socket = undefined;
313
+ for (const watcher of watchers.values()) watcher.close();
314
+ watchers.clear();
315
+ prefs = new Map();
316
+ registered = "";
317
+ return config;
318
+ }
319
+
320
+ /**
321
+ * The server no longer accepts the token, so no request can succeed until someone signs in again. Only
322
+ * when it is this session's token: a request still in flight from before a new sign-in may be rejected too.
323
+ */
324
+ function dropRejectedToken(cause: TokenRejected): void {
325
+ if (session?.token !== cause.token) return;
326
+ endSession();
327
+ console.error(`${cause.message}; signed out and deleted ${TOKEN_PATH}. Run \`skill-sync login\` to sign in again.`);
328
+ }
329
+
330
+ /** Revokes the token on the server, forgets it, and stops syncing. Returns whether the revoke succeeded. */
331
+ async function signOut(): Promise<boolean> {
332
+ const config = endSession();
333
+ if (config === undefined) return false;
334
+ // Revoked, not just forgotten: a token copied while it was live would otherwise keep working.
335
+ // A token the server already rejects is as revoked as it can be.
336
+ const revoked = await fetchServer(config, "/cli/token", { method: "DELETE" })
337
+ .then((response) => response.ok, (cause: unknown) => cause instanceof TokenRejected);
338
+ console.log(`signed out${revoked ? "" : " (the server could not be reached to revoke the token)"}`);
339
+ return revoked;
340
+ }
341
+
342
+ let loginInProgress = false;
343
+
344
+ /**
345
+ * One sign-in: listen on 127.0.0.1 for the browser to hand over the token, tell the CLI which URL to
346
+ * open, and finish when the token arrives. The browser's login page posts to this listener only, never to
347
+ * an address the request chose, so a page that tricks you into signing in cannot collect the token.
348
+ */
349
+ function login(reply: Reply): void {
350
+ if (loginInProgress) {
351
+ reply.send({ type: "error", message: "a sign-in is already in progress" });
352
+ return;
353
+ }
354
+ loginInProgress = true;
355
+ const done = (): void => {
356
+ loginInProgress = false;
357
+ listener.close();
358
+ clearTimeout(timer);
359
+ };
360
+ const listener = createServer((request, response) => {
361
+ const token = new URL(request.url ?? "/", "http://127.0.0.1").searchParams.get("token");
362
+ response.writeHead(200, { "content-type": "text/html" });
363
+ response.end(token ? "<p>Signed in. You can close this tab.</p>" : "<p>No token in the redirect.</p>");
364
+ if (token === null) return;
365
+ done();
366
+ signIn(token).then(
367
+ () => reply.send({ type: "signedIn", machine: settings!.machine }),
368
+ (cause) => reply.send({ type: "error", message: `the server refused the sign-in: ${cause instanceof Error ? cause.message : String(cause)}` }),
369
+ );
370
+ });
371
+ const timer = setTimeout(() => {
372
+ done();
373
+ reply.send({ type: "error", message: "timed out waiting for the browser" });
374
+ }, LOGIN_TIMEOUT_MS);
375
+ listener.listen(0, "127.0.0.1", () => {
376
+ const port = (listener.address() as { port: number }).port;
377
+ reply.send({ type: "open", url: `${settings!.endpoint}/cli/login?port=${port}&machine=${encodeURIComponent(settings!.machine)}` });
378
+ });
379
+ }
380
+
381
+ /** The synced list, from the server: the CLI has no token to ask with, so it asks this daemon. */
382
+ function list(reply: Reply): void {
383
+ const config = session;
384
+ if (config === undefined) {
385
+ reply.send({ type: "error", message: "this machine is signed out; run `skill-sync login` first" });
386
+ return;
387
+ }
388
+ fetchServer(config, "/skills")
389
+ .then(async (response) => {
390
+ if (!response.ok) throw new Error(`GET /skills: ${response.status} ${await response.text()}`);
391
+ reply.send({ type: "list", skills: (await response.json() as ListSkillsResponse).skills });
392
+ })
393
+ .catch((cause: unknown) => {
394
+ if (cause instanceof TokenRejected) {
395
+ dropRejectedToken(cause);
396
+ reply.send({ type: "error", message: "the server rejected this machine's token, so it is signed out; run `skill-sync login`" });
397
+ return;
398
+ }
399
+ reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` });
400
+ });
401
+ }
402
+
403
+ function handleControl(message: ControlRequest, reply: Reply): void {
404
+ if (message.type === "login") login(reply);
405
+ else if (message.type === "logout") void signOut().then((revoked) => reply.send({ type: "signedOut", revoked }));
406
+ else if (message.type === "list") list(reply);
407
+ else reply.send({ type: "error", message: `unknown request ${JSON.stringify(message)}` });
408
+ }
409
+
410
+ if (await serve(handleControl) === false) {
411
+ console.log("another skill-sync daemon is already running for this user; standing down");
412
+ // Zero: a second install's daemon is not a failure, and the service manager must not keep retrying it.
413
+ process.exit(0);
414
+ }
415
+ // Only after taking the control socket: a daemon that stands down must not sync too.
416
+ const savedToken = loadToken();
417
+ if (savedToken !== undefined) resume(savedToken);
418
+ else console.log(`skill-sync daemon for ${settings.machine}; waiting for \`skill-sync login\``);
@@ -0,0 +1,136 @@
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 in `~/.jive/skill-sync-token.json`. `login`, `logout` and
13
+ * `list` are requests to it over the control socket; the token goes from the browser straight to the daemon
14
+ * and never through here.
15
+ */
16
+
17
+ const program = new Command("skill-sync")
18
+ .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/");
19
+
20
+ program
21
+ .command("login")
22
+ .description("sign this machine in with your passkey in the browser; it stays signed in until you log out")
23
+ .action(async () => {
24
+ const result = await withDaemon({ type: "login" }, (event) => {
25
+ if (event.type !== "open") return;
26
+ console.log(`Opening ${event.url}`);
27
+ openBrowser(event.url);
28
+ });
29
+ if (result.type === "signedIn") {
30
+ console.log(`Signed in. ${result.machine} is syncing; choose what syncs at https://skill-sync.jive.sh/`);
31
+ } else {
32
+ fail(result);
33
+ }
34
+ });
35
+
36
+ program
37
+ .command("logout")
38
+ .description("revoke this machine's token and stop syncing until the next login")
39
+ .action(async () => {
40
+ const result = await withDaemon({ type: "logout" }, () => undefined);
41
+ if (result.type === "signedOut") {
42
+ console.log(result.revoked ? "Signed out; the token is revoked." : "Signed out locally; the server could not be reached to revoke the token.");
43
+ } else {
44
+ fail(result);
45
+ }
46
+ });
47
+
48
+ program
49
+ .command("list")
50
+ .description("list the skills that sync, as the server holds them; needs this machine signed in")
51
+ .action(async () => {
52
+ const result = await withDaemon({ type: "list" }, () => undefined);
53
+ if (result.type !== "list") fail(result);
54
+ if (result.skills.length === 0) {
55
+ console.log("No skills sync yet; tick them at https://skill-sync.jive.sh/");
56
+ return;
57
+ }
58
+ const width = Math.max(...result.skills.map((skill) => skill.name.length));
59
+ for (const skill of result.skills) {
60
+ const detail = skill.editedAt === null
61
+ ? "no files yet"
62
+ : `${skill.files} ${skill.files === 1 ? "file" : "files"}, last edited ${new Date(skill.editedAt).toLocaleString()} on ${skill.editedBy}`;
63
+ console.log(`${skill.name.padEnd(width)} ${detail}`);
64
+ }
65
+ });
66
+
67
+ program
68
+ .command("upgrade")
69
+ .description("upgrade skill-sync to the latest version with the package manager that installed it")
70
+ .action(async () => {
71
+ await Effect.runPromise(upgrade({ packageName: name })).catch((cause: unknown) => {
72
+ console.error(`Upgrade failed: ${cause instanceof Error ? cause.message : String(cause)}`);
73
+ process.exit(1);
74
+ });
75
+ });
76
+
77
+ program.parse();
78
+ if (process.argv.length <= 2) program.help();
79
+
80
+ /**
81
+ * Sends a request to the running daemon. If none is listening — stopped, or never started since the
82
+ * install — this package's registered daemon is started through its service manager and the request is
83
+ * retried for a few seconds.
84
+ */
85
+ async function withDaemon(message: ControlRequest, onEvent: (event: ControlEvent) => void): Promise<ControlEvent> {
86
+ try {
87
+ return await request(message, onEvent);
88
+ } catch (cause) {
89
+ if (!(cause instanceof DaemonUnreachable)) throw cause;
90
+ }
91
+ await startDaemons();
92
+ for (let attempt = 0; ; attempt++) {
93
+ await new Promise((resolve) => setTimeout(resolve, 500));
94
+ try {
95
+ return await request(message, onEvent);
96
+ } catch (cause) {
97
+ if (!(cause instanceof DaemonUnreachable) || attempt >= 20) {
98
+ console.error(`${cause instanceof Error ? cause.message : String(cause)}. Reinstall skill-sync to register its daemon.`);
99
+ process.exit(1);
100
+ }
101
+ }
102
+ }
103
+ }
104
+
105
+ function fail(event: ControlEvent): never {
106
+ console.error(event.type === "error" ? event.message : `unexpected answer from the daemon: ${JSON.stringify(event)}`);
107
+ process.exit(1);
108
+ }
109
+
110
+ /** Starts this package's registered daemons through their service manager. */
111
+ async function startDaemons(): Promise<void> {
112
+ const statuses = await Effect.runPromise(daemonStatuses).catch(() => []);
113
+ const ours = statuses.filter((status) => status.registration.packageName === name && status.executableExists);
114
+ if (ours.length === 0) {
115
+ return;
116
+ }
117
+ for (const { registration } of ours) {
118
+ const command: string[] = registration.kind === "launchd"
119
+ ? ["launchctl", "kickstart", "-k", `gui/${process.getuid?.() ?? 0}/${registration.unit}`]
120
+ : registration.kind === "systemd"
121
+ ? ["systemctl", "--user", "restart", registration.unit]
122
+ : ["schtasks", "/Run", "/TN", registration.unit];
123
+ const result = spawnSync(command[0]!, command.slice(1), { stdio: ["ignore", "ignore", "pipe"] });
124
+ if (result.status !== 0) {
125
+ console.error(`Could not start ${registration.unit}: ${String(result.stderr ?? "").trim() || `exit ${result.status}`}`);
126
+ }
127
+ }
128
+ }
129
+
130
+ function openBrowser(url: string): void {
131
+ const command = process.platform === "darwin" ? "open"
132
+ : process.platform === "win32" ? "cmd"
133
+ : "xdg-open";
134
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
135
+ spawn(command, args, { stdio: "ignore", detached: true }).unref();
136
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
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";