@jive-sh/skill-sync 0.6.0-latest-darwin-x64 → 0.6.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.
Files changed (70) hide show
  1. package/README.md +146 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +614 -0
  4. package/bin/skill-sync-daemon +614 -0
  5. package/dist/daemons/skill-sync-daemon.js +499 -0
  6. package/dist/daemons/skill-sync-daemon.js.map +1 -0
  7. package/dist/entrypoints/skill-sync.js +7 -0
  8. package/dist/entrypoints/skill-sync.js.map +1 -0
  9. package/dist/index.js +10 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/internal/agents/agent-tool.js +92 -0
  12. package/dist/internal/agents/agent-tool.js.map +1 -0
  13. package/dist/internal/agents/claude.js +422 -0
  14. package/dist/internal/agents/claude.js.map +1 -0
  15. package/dist/internal/agents/codex.js +266 -0
  16. package/dist/internal/agents/codex.js.map +1 -0
  17. package/dist/internal/agents/command.js +137 -0
  18. package/dist/internal/agents/command.js.map +1 -0
  19. package/dist/internal/agents/grok.js +172 -0
  20. package/dist/internal/agents/grok.js.map +1 -0
  21. package/dist/internal/agents/index.js +70 -0
  22. package/dist/internal/agents/index.js.map +1 -0
  23. package/dist/internal/cli.js +161 -0
  24. package/dist/internal/cli.js.map +1 -0
  25. package/dist/internal/config.js +131 -0
  26. package/dist/internal/config.js.map +1 -0
  27. package/dist/internal/control.js +113 -0
  28. package/dist/internal/control.js.map +1 -0
  29. package/dist/internal/daemon-control/impl.js +62 -0
  30. package/dist/internal/daemon-control/impl.js.map +1 -0
  31. package/dist/internal/daemon-control/interface.js +4 -0
  32. package/dist/internal/daemon-control/interface.js.map +1 -0
  33. package/dist/internal/folders.js +47 -0
  34. package/dist/internal/folders.js.map +1 -0
  35. package/dist/internal/local-skills.js +43 -0
  36. package/dist/internal/local-skills.js.map +1 -0
  37. package/dist/internal/path.js +36 -0
  38. package/dist/internal/path.js.map +1 -0
  39. package/dist/internal/server.js +32 -0
  40. package/dist/internal/server.js.map +1 -0
  41. package/dist/internal/skill-check.js +83 -0
  42. package/dist/internal/skill-check.js.map +1 -0
  43. package/dist/internal/sync.js +183 -0
  44. package/dist/internal/sync.js.map +1 -0
  45. package/dist/internal/wire.js +24 -0
  46. package/dist/internal/wire.js.map +1 -0
  47. package/install.cjs +614 -0
  48. package/package.json +36 -11
  49. package/src/daemons/skill-sync-daemon.ts +491 -0
  50. package/src/entrypoints/skill-sync.ts +12 -0
  51. package/src/index.ts +15 -0
  52. package/src/internal/agents/agent-tool.ts +136 -0
  53. package/src/internal/agents/claude.ts +440 -0
  54. package/src/internal/agents/codex.ts +283 -0
  55. package/src/internal/agents/command.ts +173 -0
  56. package/src/internal/agents/grok.ts +176 -0
  57. package/src/internal/agents/index.ts +74 -0
  58. package/src/internal/cli.ts +194 -0
  59. package/src/internal/config.ts +172 -0
  60. package/src/internal/control.ts +153 -0
  61. package/src/internal/daemon-control/impl.ts +74 -0
  62. package/src/internal/daemon-control/interface.ts +38 -0
  63. package/src/internal/folders.ts +50 -0
  64. package/src/internal/local-skills.ts +58 -0
  65. package/src/internal/path.ts +32 -0
  66. package/src/internal/server.ts +34 -0
  67. package/src/internal/skill-check.ts +97 -0
  68. package/src/internal/sync.ts +217 -0
  69. package/src/internal/wire.ts +315 -0
  70. package/multi-call-binary +0 -4
@@ -0,0 +1,491 @@
1
+ import { mkdirSync, watch, type FSWatcher } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { autoUpgrade, exitWhenUninstalled } from "jive-abstract-library";
4
+ import { name, version } from "../../package.json";
5
+ import {
6
+ TOKEN_PATH, deleteToken, loadSettings, loadStates, loadToken, saveStates, saveToken, stateFor,
7
+ type Config,
8
+ } from "../internal/config";
9
+ import { serve, type ControlRequest, type Reply } from "../internal/control";
10
+ import { describe, register } from "../internal/folders";
11
+ import { authHeaders, fetchServer, TokenRejected } from "../internal/server";
12
+ import { describeActivity, isQuiet, syncOnce, type Report } from "../internal/sync";
13
+ import { checkSkillToAdd } from "../internal/skill-check";
14
+ import { detectFolders, readUsage } from "../internal/agents";
15
+ import {
16
+ DAEMON_VERSION_HEADER, type AddSkillResponse, type DaemonMessage, type FolderPrefs, type FolderState, type HubToDaemon, type ListSkillsResponse,
17
+ } from "../internal/wire";
18
+
19
+ /**
20
+ * Keeps every enabled skills folder on this machine identical to every other machine's.
21
+ *
22
+ * Folders are detected: the skills folders each agent tool reads (`AGENT_TOOLS`, `detectFolders`). Which of them sync, and the one list of skills that syncs in all of them, are
23
+ * held by the server and changed from the dashboard, so they survive a reinstall and apply the moment
24
+ * they change. A skill not on the list is never pushed or pulled.
25
+ *
26
+ * The daemon holds a WebSocket to the service's hub. That connection is how the dashboard knows this
27
+ * machine is running, how a preference change arrives, and how a write from another machine triggers a
28
+ * cycle here at once. Polling stays as the fallback: every 5 minutes while connected, every 30 seconds
29
+ * while not, so a dropped connection costs latency and never correctness.
30
+ *
31
+ * `skill-sync login` asks the daemon, over the control socket, to sign in; the token arrives from the
32
+ * browser straight to this process, which keeps it in `~/.jive/skill-sync-token.json` (`TOKEN_PATH`). A
33
+ * daemon that starts and finds that file is signed in, so a restart, a reboot or an upgrade needs no
34
+ * sign-in. Signing out, or the server rejecting the token, deletes the file.
35
+ *
36
+ * Every minute it also reads each Claude, Codex and Grok account on the machine (`readUsage`): who it is
37
+ * and its plan limits, asked of the tool's own CLI at most every five minutes, and this machine's use of
38
+ * it, from the files the tool writes. It sends them over the same connection when they change, for the
39
+ * dashboard. No credential is read or sent: the CLIs make the authenticated calls.
40
+ *
41
+ * It keeps itself on the latest published version (`autoUpgrade`): every 5 minutes it asks the package
42
+ * manager that installed it whether a newer one is out, installs it the same way, and is restarted on it.
43
+ */
44
+
45
+ const POLL_CONNECTED_MS = 5 * 60_000;
46
+ const POLL_DISCONNECTED_MS = 30_000;
47
+ /** Long enough that an editor's write-rename-write lands as one cycle, short enough to feel immediate. */
48
+ const SETTLE_MS = 1_000;
49
+ const PING_MS = 30_000;
50
+ /** No pong for this long means the connection is dead even if the socket has not noticed. */
51
+ const PONG_TIMEOUT_MS = 75_000;
52
+ const RECONNECT_MIN_MS = 5_000;
53
+ const RECONNECT_MAX_MS = 5 * 60_000;
54
+ /** How often this machine's use is read from local files; account limits are asked of the CLIs less often (`ACCOUNT_READ_MS`). */
55
+ const USAGE_READ_MS = 60_000;
56
+ /** How long a sign-in waits for the browser before giving up. */
57
+ const LOGIN_TIMEOUT_MS = 5 * 60_000;
58
+
59
+ exitWhenUninstalled();
60
+
61
+ const settings = loadSettings();
62
+ if (settings === undefined) {
63
+ console.error("~/.jive/skill-sync.json needs an endpoint and a machine name");
64
+ // Zero, not one: the service manager restarts a daemon that fails, and a file nobody has fixed would
65
+ // only fill the log.
66
+ process.exit(0);
67
+ }
68
+ const states = loadStates();
69
+
70
+ /** Set while signed in. Everything that talks to the server reads it; signing out clears it. */
71
+ let session: Config | undefined;
72
+ /** The signed-in config, for code that only runs during a session. */
73
+ function current(): Config {
74
+ if (session === undefined) throw new Error("not signed in");
75
+ return session;
76
+ }
77
+
78
+ /** What was last registered, so registration is repeated only when a folder or skill appears or goes. */
79
+ let registered = "";
80
+ /** The enabled folders, each with the synced list. */
81
+ let prefs = new Map<string, ReadonlySet<string>>();
82
+ const watchers = new Map<string, FSWatcher>();
83
+
84
+ // ── Folders ─────────────────────────────────────────────────────────────────────────────────────────
85
+
86
+ /** Reports this machine's folders and skills, and adopts the server's answer for what syncs. */
87
+ async function registerFolders(): Promise<void> {
88
+ const request = describe(current());
89
+ applyPrefs(await register(current(), request));
90
+ registered = JSON.stringify(request);
91
+ }
92
+
93
+ /** True when a folder or a skill has appeared or gone since the last registration. */
94
+ const registrationStale = (): boolean => JSON.stringify(describe(current())) !== registered;
95
+
96
+ function applyPrefs(folders: ReadonlyArray<FolderPrefs>): void {
97
+ // Only folders this machine still has. The hub can hold a stale list — it answers a reconnect before
98
+ // the next registration — and creating a listed folder whose agent home is gone would bring it back.
99
+ const present = new Set(detectFolders());
100
+ const next = new Map(folders.filter((folder) => present.has(folder.path))
101
+ .map((folder) => [folder.path, new Set(folder.skills)] as const));
102
+ for (const [folder, watcher] of watchers) {
103
+ if (!next.has(folder)) {
104
+ watcher.close();
105
+ watchers.delete(folder);
106
+ }
107
+ }
108
+ // An unticked folder leaves no trace of syncing: its state goes, so the state file lists only folders
109
+ // that sync, and ticking it again starts it fresh.
110
+ // Covers folders with state from an earlier run too, not only ones this run was syncing.
111
+ const stopped = [...new Set([...prefs.keys(), ...Object.keys(states)])].filter((folder) => !next.has(folder));
112
+ for (const folder of stopped) {
113
+ delete states[folder];
114
+ console.log(`stopped syncing ${folder}`);
115
+ }
116
+ if (stopped.length > 0) saveStates(states);
117
+ for (const folder of next.keys()) {
118
+ if (watchers.has(folder)) continue;
119
+ mkdirSync(folder, { recursive: true });
120
+ let settle: ReturnType<typeof setTimeout> | undefined;
121
+ watchers.set(folder, watch(folder, { recursive: true }, () => {
122
+ if (settle !== undefined) clearTimeout(settle);
123
+ settle = setTimeout(runCycle, SETTLE_MS);
124
+ }));
125
+ }
126
+ const changed = JSON.stringify([...next].map(([path, skills]) => [path, [...skills].sort()]))
127
+ !== JSON.stringify([...prefs].map(([path, skills]) => [path, [...skills].sort()]));
128
+ prefs = next;
129
+ if (!changed) return;
130
+ for (const [folder, skills] of prefs) console.log(`syncing ${folder}: ${[...skills].sort().join(", ") || "no skills"}`);
131
+ if (prefs.size === 0) console.log("syncing no folders");
132
+ void runCycle();
133
+ }
134
+
135
+ // ── Hub connection ──────────────────────────────────────────────────────────────────────────────────
136
+
137
+ let socket: WebSocket | undefined;
138
+ let lastPong = 0;
139
+ let reconnectDelay = RECONNECT_MIN_MS;
140
+ /** What the hub was last told about each folder (state and detail), so only changes are sent. */
141
+ const reported = new Map<string, string>();
142
+
143
+ function connect(): void {
144
+ if (session === undefined) return;
145
+ const config = session;
146
+ const url = `${config.endpoint.replace(/^http/, "ws")}/daemon`;
147
+ // Bun's WebSocket takes headers; the browser's does not, which is why the token can travel this way.
148
+ // The version goes with it: an upgrade restarts the daemon, so each connection runs exactly one version.
149
+ const ws = new WebSocket(url, { headers: authHeaders(config, { [DAEMON_VERSION_HEADER]: version }) } as unknown as string[]);
150
+ ws.onopen = () => {
151
+ socket = ws;
152
+ lastPong = Date.now();
153
+ reconnectDelay = RECONNECT_MIN_MS;
154
+ console.log("connected to the hub");
155
+ // Whatever the hub last heard from a previous connection is stale until re-sent.
156
+ reported.clear();
157
+ for (const folder of prefs.keys()) report(folder, "idle");
158
+ reportedUsage = "";
159
+ reportUsage();
160
+ };
161
+ ws.onmessage = (event) => {
162
+ const data = String(event.data);
163
+ if (data === "pong") {
164
+ lastPong = Date.now();
165
+ return;
166
+ }
167
+ const message = JSON.parse(data) as HubToDaemon;
168
+ if (message.type === "prefs") applyPrefs(message.folders);
169
+ if (message.type === "changed") void runCycle();
170
+ };
171
+ ws.onclose = () => {
172
+ if (socket === ws) socket = undefined;
173
+ // Only the session that opened it reconnects: after a sign-out, or a sign-in with a new token, this
174
+ // socket belongs to nobody.
175
+ if (session !== config) return;
176
+ setTimeout(connect, reconnectDelay);
177
+ reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
178
+ };
179
+ ws.onerror = () => {
180
+ // `onclose` follows and schedules the reconnect.
181
+ };
182
+ }
183
+
184
+ setInterval(() => {
185
+ if (socket === undefined) return;
186
+ if (Date.now() - lastPong > PONG_TIMEOUT_MS) {
187
+ console.error("hub connection went quiet; reconnecting");
188
+ socket.close();
189
+ return;
190
+ }
191
+ socket.send("ping");
192
+ }, PING_MS);
193
+
194
+ function report(folder: string, state: FolderState, detail?: string, activity?: string): void {
195
+ const key = `${state}|${detail ?? ""}`;
196
+ if (reported.get(folder) === key && activity === undefined) return;
197
+ if (socket === undefined) return;
198
+ const message: DaemonMessage = { type: "status", folder, state, detail, activity };
199
+ socket.send(JSON.stringify(message));
200
+ reported.set(folder, key);
201
+ }
202
+
203
+ /** The usage the hub last heard, so it is sent again only when a number changes. */
204
+ let reportedUsage = "";
205
+
206
+ /** True while a reading runs: a CLI can take seconds to answer, and two readings at once would ask it twice. */
207
+ let readingUsage = false;
208
+
209
+ /** Sends every account's usage to the hub when it differs from what was last sent. */
210
+ async function reportUsage(): Promise<void> {
211
+ if (socket === undefined || readingUsage) return;
212
+ readingUsage = true;
213
+ let message: DaemonMessage;
214
+ try {
215
+ message = { type: "usage", accounts: await readUsage() };
216
+ } catch (cause) {
217
+ // Only an unreadable home directory gets here; each account's own failure is reported as `unknown`.
218
+ console.error(`could not read account usage: ${cause instanceof Error ? cause.message : String(cause)}`);
219
+ return;
220
+ } finally {
221
+ readingUsage = false;
222
+ }
223
+ const text = JSON.stringify(message);
224
+ // The socket can have closed, or been replaced, while the CLIs ran.
225
+ if (text === reportedUsage || socket === undefined) return;
226
+ socket.send(text);
227
+ reportedUsage = text;
228
+ }
229
+
230
+ setInterval(reportUsage, USAGE_READ_MS);
231
+
232
+ // ── Sync cycles ─────────────────────────────────────────────────────────────────────────────────────
233
+
234
+ let running = false;
235
+ let cycleQueued = false;
236
+
237
+ async function runCycle(): Promise<void> {
238
+ if (session === undefined) return;
239
+ if (running) {
240
+ cycleQueued = true;
241
+ return;
242
+ }
243
+ running = true;
244
+ try {
245
+ // Folders sync one after another against the same server, so a change pushed from one folder is
246
+ // pulled into the others on the follow-up pass this triggers.
247
+ for (const [folder, skills] of [...prefs]) {
248
+ try {
249
+ const result = await syncOnce(current(), folder, stateFor(states, folder), skills);
250
+ saveStates(states);
251
+ log(folder, result);
252
+ if (result.rejected.length > 0) report(folder, "attention", result.rejected.join("; "), describeActivity(result) || undefined);
253
+ else report(folder, "idle", undefined, isQuiet(result) ? undefined : describeActivity(result));
254
+ // What this folder pushed is pulled into the machine's other folders on the follow-up pass.
255
+ if (result.pushed.length > 0) cycleQueued = true;
256
+ } catch (cause) {
257
+ if (cause instanceof TokenRejected) {
258
+ dropRejectedToken(cause);
259
+ return;
260
+ }
261
+ // One failed folder must not end the daemon or the other folders: the usual cause is the network.
262
+ const reason = cause instanceof Error ? cause.message : String(cause);
263
+ console.error(`${folder}: sync failed: ${reason}`);
264
+ report(folder, "attention", `sync failed: ${reason}`);
265
+ }
266
+ }
267
+ // A skill created or removed locally changes what the dashboard should list.
268
+ if (registrationStale()) {
269
+ await registerFolders().catch((cause: unknown) => {
270
+ if (cause instanceof TokenRejected) dropRejectedToken(cause);
271
+ });
272
+ }
273
+ } finally {
274
+ running = false;
275
+ if (cycleQueued) {
276
+ cycleQueued = false;
277
+ setTimeout(runCycle, SETTLE_MS);
278
+ }
279
+ }
280
+ }
281
+
282
+ function log(folder: string, result: Report): void {
283
+ for (const path of result.pulled) console.log(`${folder}: pulled ${path}`);
284
+ for (const path of result.pushed) console.log(`${folder}: pushed ${path}`);
285
+ for (const path of result.deletedLocally) console.log(`${folder}: deleted ${path}`);
286
+ for (const path of result.rejected) console.error(`${folder}: refused a path the server sent: ${path}`);
287
+ }
288
+
289
+ let pollTimer: ReturnType<typeof setTimeout> | undefined;
290
+
291
+ /** Re-detects folders each poll: an agent home created since the last one should join without a restart. */
292
+ async function poll(): Promise<void> {
293
+ if (session === undefined) return;
294
+ try {
295
+ if (registered === "" || registrationStale()) await registerFolders();
296
+ } catch (cause) {
297
+ if (cause instanceof TokenRejected) {
298
+ dropRejectedToken(cause);
299
+ return;
300
+ }
301
+ console.error(`could not register folders: ${cause instanceof Error ? cause.message : String(cause)}`);
302
+ }
303
+ await runCycle();
304
+ if (session !== undefined) pollTimer = setTimeout(poll, socket === undefined ? POLL_DISCONNECTED_MS : POLL_CONNECTED_MS);
305
+ }
306
+
307
+ // ── Signing in and out ──────────────────────────────────────────────────────────────────────────────
308
+
309
+ /**
310
+ * Starts a session with a token from the browser. Registering this machine's folders is the first call
311
+ * that needs the token, so it doubles as the check that the token works: a failure leaves the daemon
312
+ * signed out, not half-running, and the token unsaved.
313
+ */
314
+ async function signIn(token: string): Promise<void> {
315
+ if (session !== undefined) await signOut();
316
+ session = { ...settings!, token };
317
+ try {
318
+ await registerFolders();
319
+ } catch (cause) {
320
+ session = undefined;
321
+ throw cause;
322
+ }
323
+ saveToken(token);
324
+ console.log(`signed in as ${session.machine}; syncing with ${session.endpoint}`);
325
+ connect();
326
+ void poll();
327
+ }
328
+
329
+ /**
330
+ * Starts a session with the token saved by an earlier sign-in. Not checked first, unlike `signIn`: at boot
331
+ * the network may not be up yet, and a failure for that reason must not sign the machine out. The first
332
+ * poll registers; a rejected token signs out there.
333
+ */
334
+ function resume(token: string): void {
335
+ session = { ...settings!, token };
336
+ console.log(`signed in as ${session.machine} with the token in ${TOKEN_PATH}; syncing with ${session.endpoint}`);
337
+ connect();
338
+ void poll();
339
+ }
340
+
341
+ /** Stops syncing and forgets the token, here and in `TOKEN_PATH`. Returns the session that ended. */
342
+ function endSession(): Config | undefined {
343
+ const config = session;
344
+ if (config === undefined) return undefined;
345
+ session = undefined;
346
+ deleteToken();
347
+ if (pollTimer !== undefined) clearTimeout(pollTimer);
348
+ socket?.close();
349
+ socket = undefined;
350
+ for (const watcher of watchers.values()) watcher.close();
351
+ watchers.clear();
352
+ prefs = new Map();
353
+ registered = "";
354
+ return config;
355
+ }
356
+
357
+ /**
358
+ * The server no longer accepts the token, so no request can succeed until someone signs in again. Only
359
+ * when it is this session's token: a request still in flight from before a new sign-in may be rejected too.
360
+ */
361
+ function dropRejectedToken(cause: TokenRejected): void {
362
+ if (session?.token !== cause.token) return;
363
+ endSession();
364
+ console.error(`${cause.message}; signed out and deleted ${TOKEN_PATH}. Run \`skill-sync login\` to sign in again.`);
365
+ }
366
+
367
+ /** Revokes the token on the server, forgets it, and stops syncing. Returns whether the revoke succeeded. */
368
+ async function signOut(): Promise<boolean> {
369
+ const config = endSession();
370
+ if (config === undefined) return false;
371
+ // Revoked, not just forgotten: a token copied while it was live would otherwise keep working.
372
+ // A token the server already rejects is as revoked as it can be.
373
+ const revoked = await fetchServer(config, "/cli/token", { method: "DELETE" })
374
+ .then((response) => response.ok, (cause: unknown) => cause instanceof TokenRejected);
375
+ console.log(`signed out${revoked ? "" : " (the server could not be reached to revoke the token)"}`);
376
+ return revoked;
377
+ }
378
+
379
+ let loginInProgress = false;
380
+
381
+ /**
382
+ * One sign-in: listen on 127.0.0.1 for the browser to hand over the token, tell the CLI which URL to
383
+ * open, and finish when the token arrives. The browser's login page posts to this listener only, never to
384
+ * an address the request chose, so a page that tricks you into signing in cannot collect the token.
385
+ */
386
+ function login(reply: Reply): void {
387
+ if (loginInProgress) {
388
+ reply.send({ type: "error", message: "a sign-in is already in progress" });
389
+ return;
390
+ }
391
+ loginInProgress = true;
392
+ const done = (): void => {
393
+ loginInProgress = false;
394
+ listener.close();
395
+ clearTimeout(timer);
396
+ };
397
+ const listener = createServer((request, response) => {
398
+ const token = new URL(request.url ?? "/", "http://127.0.0.1").searchParams.get("token");
399
+ response.writeHead(200, { "content-type": "text/html" });
400
+ response.end(token ? "<p>Signed in. You can close this tab.</p>" : "<p>No token in the redirect.</p>");
401
+ if (token === null) return;
402
+ done();
403
+ signIn(token).then(
404
+ () => reply.send({ type: "signedIn", machine: settings!.machine }),
405
+ (cause) => reply.send({ type: "error", message: `the server refused the sign-in: ${cause instanceof Error ? cause.message : String(cause)}` }),
406
+ );
407
+ });
408
+ const timer = setTimeout(() => {
409
+ done();
410
+ reply.send({ type: "error", message: "timed out waiting for the browser" });
411
+ }, LOGIN_TIMEOUT_MS);
412
+ listener.listen(0, "127.0.0.1", () => {
413
+ const port = (listener.address() as { port: number }).port;
414
+ reply.send({ type: "open", url: `${settings!.endpoint}/cli/login?port=${port}&machine=${encodeURIComponent(settings!.machine)}` });
415
+ });
416
+ }
417
+
418
+ /** The synced list, from the server: the CLI has no token to ask with, so it asks this daemon. */
419
+ function list(reply: Reply): void {
420
+ const config = session;
421
+ if (config === undefined) {
422
+ reply.send({ type: "error", message: "this machine is signed out; run `skill-sync login` first" });
423
+ return;
424
+ }
425
+ fetchServer(config, "/skills")
426
+ .then(async (response) => {
427
+ if (!response.ok) throw new Error(`GET /skills: ${response.status} ${await response.text()}`);
428
+ reply.send({ type: "list", skills: (await response.json() as ListSkillsResponse).skills });
429
+ })
430
+ .catch((cause: unknown) => {
431
+ if (cause instanceof TokenRejected) {
432
+ dropRejectedToken(cause);
433
+ reply.send({ type: "error", message: "the server rejected this machine's token, so it is signed out; run `skill-sync login`" });
434
+ return;
435
+ }
436
+ reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` });
437
+ });
438
+ }
439
+
440
+ /**
441
+ * Puts a skill from this machine on the synced list, for an agent that has just written it. The files are
442
+ * checked here, where they are; the server only adds the name, and every daemon then syncs the skill.
443
+ */
444
+ function add(skill: string, reply: Reply): void {
445
+ const config = session;
446
+ if (config === undefined) {
447
+ reply.send({ type: "error", message: "this machine is signed out; run `skill-sync login` first" });
448
+ return;
449
+ }
450
+ const check = checkSkillToAdd({ skill, folders: detectFolders(), exclude: config.exclude });
451
+ if (!check.ok) {
452
+ reply.send({ type: "error", message: check.reason });
453
+ return;
454
+ }
455
+ fetchServer(config, `/skills/${encodeURIComponent(skill)}`, { method: "PUT" })
456
+ .then(async (response) => {
457
+ if (!response.ok) throw new Error(`PUT /skills/${skill}: ${response.status} ${await response.text()}`);
458
+ const { added } = await response.json() as AddSkillResponse;
459
+ reply.send({
460
+ type: "added", skill, added, folders: check.folders,
461
+ syncingFolders: check.folders.filter((folder) => prefs.has(folder)),
462
+ });
463
+ })
464
+ .catch((cause: unknown) => {
465
+ if (cause instanceof TokenRejected) {
466
+ dropRejectedToken(cause);
467
+ reply.send({ type: "error", message: "the server rejected this machine's token, so it is signed out; run `skill-sync login`" });
468
+ return;
469
+ }
470
+ reply.send({ type: "error", message: `could not reach the server: ${cause instanceof Error ? cause.message : String(cause)}` });
471
+ });
472
+ }
473
+
474
+ function handleControl(message: ControlRequest, reply: Reply): void {
475
+ if (message.type === "login") login(reply);
476
+ else if (message.type === "logout") void signOut().then((revoked) => reply.send({ type: "signedOut", revoked }));
477
+ else if (message.type === "list") list(reply);
478
+ else if (message.type === "add") add(message.skill, reply);
479
+ else reply.send({ type: "error", message: `unknown request ${JSON.stringify(message)}` });
480
+ }
481
+
482
+ if (await serve(handleControl) === false) {
483
+ console.log("another skill-sync daemon is already running for this user; standing down");
484
+ // Zero: a second install's daemon is not a failure, and the service manager must not keep retrying it.
485
+ process.exit(0);
486
+ }
487
+ // Only after taking the control socket: a daemon that stands down must not sync, or upgrade, too.
488
+ autoUpgrade({ packageName: name });
489
+ const savedToken = loadToken();
490
+ if (savedToken !== undefined) resume(savedToken);
491
+ else console.log(`skill-sync daemon for ${settings.machine}; waiting for \`skill-sync login\``);
@@ -0,0 +1,12 @@
1
+ import { BunRuntime, BunServices } from "@effect/platform-bun";
2
+ import { Effect, pipe } from "effect";
3
+ import { Cli } from "jive-abstract-library";
4
+ import { runSkillSync } from "../internal/cli";
5
+ import { DaemonControlLive } from "../internal/daemon-control/impl";
6
+
7
+ BunRuntime.runMain(pipe(
8
+ runSkillSync(),
9
+ Effect.provide(DaemonControlLive),
10
+ Effect.provide(Cli.terminalLogger),
11
+ Effect.provide(BunServices.layer),
12
+ ));
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 { DAEMON_VERSION_HEADER, isSkillName, skillOf } from "./internal/wire";
11
+ export type {
12
+ AccountIdentity, AccountKey, AccountLimits, AccountUsage, AccountView, MachineAccountReading, AddSkillResponse, DaemonMessage, LocalUse, Money, UsageWindow, DashboardMessage, FileHash, FolderPrefs, FolderState, FolderView, FoldersRequest, FoldersResponse,
13
+ HubToDaemon, ListedSkill, ListFilesResponse, ListSkillsResponse, LocalSkill, MachineView, PutFileRequest, RemoteFile,
14
+ SkillView, Snapshot, SyncedSkill,
15
+ } from "./internal/wire";
@@ -0,0 +1,136 @@
1
+ import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { SchemaIssue } from "effect";
4
+ import { isLock } from "../config";
5
+ import type { AccountIdentity, AccountLimits, AccountUsage, LocalUse } from "../wire";
6
+
7
+ /**
8
+ * One coding agent skill-sync works with (Claude Code, Codex, Grok): where it reads a user's skills, which
9
+ * of its accounts are on this machine, and how much each has used.
10
+ *
11
+ * Everything skill-sync knows about one tool lives in that tool's implementation, so adding a tool is one
12
+ * new file and one line in `AGENT_TOOLS`, and no other code tests a folder name to tell tools apart.
13
+ */
14
+ export interface AgentTool {
15
+ readonly tool: AccountUsage["tool"];
16
+ /**
17
+ * The skills folders this tool reads a user's skills from on this machine, whether or not they exist
18
+ * yet: a folder that is ticked on the dashboard and missing is created.
19
+ */
20
+ skillsFolders(home: string): string[];
21
+ /** This tool's account folders in `home`, as absolute paths. */
22
+ accounts(home: string): string[];
23
+ /**
24
+ * Who the account is and its plan limits, asked of the tool's own CLI, which makes the authenticated
25
+ * call to its service; from the tool's saved record of its last fetch when the CLI cannot be run. Each
26
+ * call runs the CLI, so callers cache the result (`readUsage`).
27
+ */
28
+ readAccount(account: string, context: AccountContext): Promise<AccountReading>;
29
+ /** What this machine's sessions of the account used, from the files the tool writes for itself. */
30
+ readLocalUse(account: string, home: string, now: number): LocalUse;
31
+ }
32
+
33
+ /** What reading an account needs: the home it is in, the time, and where a CLI is (`findCommand` outside tests). */
34
+ export interface AccountContext {
35
+ readonly home: string;
36
+ readonly now: number;
37
+ /** The path of a command, or undefined when it is not installed; `also` lists paths to try after the usual ones. */
38
+ readonly findCommand: (input: { readonly name: string; readonly also?: ReadonlyArray<string> }) => string | undefined;
39
+ }
40
+
41
+ /** What a tool's CLI says about one account. */
42
+ export interface AccountReading {
43
+ readonly identity: AccountIdentity | null;
44
+ readonly limits: AccountLimits;
45
+ }
46
+
47
+ /** Sessions are counted over this many days: Claude Code deletes session files older than 30 days by default. */
48
+ export const PERIOD_DAYS = 30;
49
+ export const DAY_MS = 24 * 60 * 60 * 1000;
50
+ /** A CLI asked for an account's limits gets this long to answer. */
51
+ export const CLI_TIMEOUT_MS = 30_000;
52
+
53
+ const formatIssue = SchemaIssue.makeFormatterDefault();
54
+
55
+ /** A record that failed to decode: what failed, on one line, so the dashboard can say why it shows nothing. */
56
+ export const unknownShape = (what: string, issue: SchemaIssue.Issue): { readonly state: "unknown"; readonly reason: string } =>
57
+ ({ state: "unknown", reason: `${what} changed shape: ${formatIssue(issue).replace(/\s+/g, " ").slice(0, 160)}` });
58
+
59
+ /** A limit's name from its length, the same for every tool: `5-hour`, `weekly`. */
60
+ export const windowName = (minutes: number | null): string =>
61
+ minutes === null ? "limit"
62
+ : minutes === 7 * 24 * 60 ? "weekly"
63
+ : minutes === 24 * 60 ? "daily"
64
+ : minutes % (24 * 60) === 0 ? `${minutes / (24 * 60)}-day`
65
+ : minutes % 60 === 0 ? `${minutes / 60}-hour`
66
+ : `${minutes}-minute`;
67
+
68
+ export function isDirectory(path: string): boolean {
69
+ try {
70
+ return statSync(path).isDirectory();
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ export const parseJson = (line: string): unknown => {
77
+ try {
78
+ return JSON.parse(line);
79
+ } catch {
80
+ return undefined;
81
+ }
82
+ };
83
+
84
+ /**
85
+ * A file's whole lines, last first, reading at most `limit` bytes back from its end. Lines longer than
86
+ * `maxLine` bytes are skipped: holding a multi-megabyte line while reading backwards would copy it once
87
+ * per chunk read, and the lines wanted here are a few hundred bytes.
88
+ */
89
+ export function* linesFromEnd(path: string, limit: number, maxLine = 1024 * 1024): Generator<string> {
90
+ const CHUNK = 64 * 1024;
91
+ const fd = openSync(path, "r");
92
+ try {
93
+ const size = statSync(path).size;
94
+ const stop = Math.max(0, size - limit);
95
+ let position = size;
96
+ // The start of a line whose line break has not been read yet, since reading goes backwards.
97
+ let carry = Buffer.alloc(0);
98
+ // The line being read is longer than `maxLine`; its bytes are dropped until its start is found.
99
+ let oversized = false;
100
+ while (position > stop) {
101
+ const length = Math.min(CHUNK, position - stop);
102
+ position -= length;
103
+ const chunk = Buffer.alloc(length);
104
+ readSync(fd, chunk, 0, length, position);
105
+ const buffer = Buffer.concat([chunk, carry]);
106
+ // Splitting on the newline byte is safe in UTF-8: it never occurs inside a multi-byte character.
107
+ let end = buffer.length;
108
+ for (let index = buffer.length - 1; index >= 0; index--) {
109
+ if (buffer[index] !== 0x0a) continue;
110
+ const line = buffer.subarray(index + 1, end).toString("utf-8").trim();
111
+ if (!oversized && line !== "") yield line;
112
+ oversized = false;
113
+ end = index;
114
+ }
115
+ carry = buffer.subarray(0, end);
116
+ if (carry.length > maxLine) {
117
+ carry = Buffer.alloc(0);
118
+ oversized = true;
119
+ }
120
+ }
121
+ // The file's first line. When the search stopped short of the start, what is left is part of a line.
122
+ const first = carry.toString("utf-8").trim();
123
+ if (stop === 0 && !oversized && first !== "") yield first;
124
+ } finally {
125
+ closeSync(fd);
126
+ }
127
+ }
128
+
129
+ /** The directories in `home` named `.<name>` or `.<name>-<suffix>`, never a lock: one tool's account folders. */
130
+ export function homesNamed(home: string, name: string): string[] {
131
+ return readdirSync(home)
132
+ .filter((entry) => (entry === `.${name}` || entry.startsWith(`.${name}-`)) && !isLock(entry))
133
+ .map((entry) => join(home, entry))
134
+ .filter(isDirectory)
135
+ .sort();
136
+ }