@jive-sh/skill-sync 0.6.1-latest-darwin-x64 → 0.6.1

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 +158 -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 +196 -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,74 @@
1
+ import { homedir } from "node:os";
2
+ import type { AccountUsage, LocalUse } from "../wire";
3
+ import type { AccountContext, AccountReading, AgentTool } from "./agent-tool";
4
+ import { findCommand } from "./command";
5
+ import { claude } from "./claude";
6
+ import { codex } from "./codex";
7
+ import { grok } from "./grok";
8
+
9
+ /** Every coding agent skill-sync syncs skills for and reads usage of. */
10
+ export const AGENT_TOOLS: ReadonlyArray<AgentTool> = [claude, codex, grok];
11
+
12
+ /**
13
+ * Every skills folder any agent tool reads on this machine. Every one is a candidate, whether or not it
14
+ * exists yet, so an account added later joins without anyone listing it. Which of them actually sync is
15
+ * the user's choice on the dashboard; a folder that is synced and missing is created.
16
+ */
17
+ export function detectFolders(home: string = homedir()): string[] {
18
+ return [...new Set(AGENT_TOOLS.flatMap((tool) => tool.skillsFolders(home)))].sort();
19
+ }
20
+
21
+ /**
22
+ * How long an account reading is kept before its CLI is asked again. Each ask starts the tool's CLI
23
+ * (about two seconds of CPU for `claude`) and calls its service, so it happens at most this often per
24
+ * account, while this machine's use, read from local files, is read on every call.
25
+ */
26
+ export const ACCOUNT_READ_MS = 5 * 60_000;
27
+
28
+ const accountCache = new Map<string, { readonly readAt: number; readonly reading: AccountReading }>();
29
+
30
+ /**
31
+ * Every account of every agent tool on this machine: who it is and its plan limits (from the tool's CLI,
32
+ * at most every `ACCOUNT_READ_MS`), and this machine's use of it. One account's failure never hides another's.
33
+ */
34
+ export async function readUsage(input: Partial<AccountContext> = {}): Promise<AccountUsage[]> {
35
+ const home = input.home ?? homedir();
36
+ const context: AccountContext = {
37
+ home,
38
+ now: input.now ?? Date.now(),
39
+ findCommand: input.findCommand ?? ((command) => findCommand({ ...command, home })),
40
+ };
41
+ const now = context.now;
42
+ const accounts = AGENT_TOOLS
43
+ .flatMap((tool) => tool.accounts(home).map((account) => ({ tool, account })))
44
+ .sort((a, b) => a.account.localeCompare(b.account));
45
+ for (const account of accountCache.keys()) {
46
+ if (!accounts.some((entry) => entry.account === account)) accountCache.delete(account);
47
+ }
48
+ return Promise.all(accounts.map(async ({ tool, account }): Promise<AccountUsage> => {
49
+ const reading = await cachedAccount(tool, account, context);
50
+ let local: LocalUse;
51
+ try {
52
+ local = tool.readLocalUse(account, home, now);
53
+ } catch (cause) {
54
+ local = { state: "unknown", reason: `could not read: ${describe(cause)}` };
55
+ }
56
+ return { tool: tool.tool, home: account.slice(home.length).replace(/^[\\/]/, ""), ...reading, local };
57
+ }));
58
+ }
59
+
60
+ async function cachedAccount(tool: AgentTool, account: string, context: AccountContext): Promise<AccountReading> {
61
+ const now = context.now;
62
+ const cached = accountCache.get(account);
63
+ if (cached !== undefined && now - cached.readAt < ACCOUNT_READ_MS) return cached.reading;
64
+ let reading: AccountReading;
65
+ try {
66
+ reading = await tool.readAccount(account, context);
67
+ } catch (cause) {
68
+ reading = { identity: null, limits: { state: "unknown", reason: `could not read: ${describe(cause)}` } };
69
+ }
70
+ accountCache.set(account, { readAt: now, reading });
71
+ return reading;
72
+ }
73
+
74
+ const describe = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause);
@@ -0,0 +1,194 @@
1
+ import { spawn } from "node:child_process";
2
+ import { Data, Effect, Schedule, Stdio, Stream, pipe } from "effect";
3
+ import { Cli, upgrade } from "jive-abstract-library";
4
+ import { name, version } from "../../package.json";
5
+ import { detectFolders } from "./agents";
6
+ import { loadSettings } from "./config";
7
+ import { DaemonFailed } from "./control";
8
+ import { DaemonControl, type DaemonError, type IDaemonControl } from "./daemon-control/interface";
9
+ import { addableSkills, formatSkillCopies, skillCopies } from "./local-skills";
10
+
11
+ /**
12
+ * The CLI that accompanies the daemon: `login`, `logout`, `list`, `add`, `show`, `upgrade` and `version`. Which
13
+ * folders sync is chosen on the dashboard; skills are ticked there too, or added with `add` by the agent that
14
+ * wrote one.
15
+ *
16
+ * The daemon owns the sync token and keeps it in `~/.jive/skill-sync-token.json`. `login`, `logout`, `list` and
17
+ * `add` are requests to it over the control socket; the token goes from the browser straight to the daemon and
18
+ * never through here. Tab after `show` lists the synced skills and Tab after `add` the skills that could be
19
+ * added, both asked of the daemon when Tab is pressed.
20
+ */
21
+
22
+ const DASHBOARD = "https://skill-sync.jive.sh/";
23
+
24
+ /** How long Tab waits for the daemon before showing that it did not answer; it never starts one. */
25
+ const TAB_TIME_LIMIT_SECONDS = 3;
26
+
27
+ /** How often a command asks again after starting the daemon, and how many times. */
28
+ const RETRY_INTERVAL = "500 millis";
29
+ const RETRIES = 20;
30
+
31
+ class SkillNotOnThisMachine extends Data.TaggedError("SkillNotOnThisMachine")<{ readonly message: string }> {}
32
+ class UpgradeFailed extends Data.TaggedError("UpgradeFailed")<{ readonly message: string }> {}
33
+
34
+ export const skillSync = Cli.make("skill-sync", {
35
+ login: Cli.command({
36
+ description: "sign this machine in with your passkey in the browser; it stays signed in until you log out",
37
+ *run() {
38
+ const machine = yield* withDaemon((daemon) => daemon.login((url) => pipe(
39
+ Effect.log(`Opening ${url}`),
40
+ Effect.andThen(Effect.sync(() => openBrowser(url))),
41
+ )));
42
+ yield* Effect.log(`Signed in. ${machine} is syncing; choose what syncs at ${DASHBOARD}`);
43
+ },
44
+ }),
45
+
46
+ logout: Cli.command({
47
+ description: "revoke this machine's token and stop syncing until the next login",
48
+ *run() {
49
+ const revoked = yield* withDaemon((daemon) => daemon.logout());
50
+ yield* Effect.log(revoked ? "Signed out; the token is revoked." : "Signed out locally; the server could not be reached to revoke the token.");
51
+ },
52
+ }),
53
+
54
+ list: Cli.command({
55
+ description: "list the skills that sync, as the server holds them; needs this machine signed in",
56
+ *run() {
57
+ const skills = yield* withDaemon((daemon) => daemon.listSyncedSkills());
58
+ if (skills.length === 0) {
59
+ yield* Effect.log(`No skills sync yet; tick them at ${DASHBOARD}`);
60
+ return;
61
+ }
62
+ const width = Math.max(...skills.map((skill) => skill.name.length));
63
+ for (const skill of skills) {
64
+ const detail = skill.editedAt === null
65
+ ? "no files yet"
66
+ : `${skill.files} ${skill.files === 1 ? "file" : "files"}, last edited ${new Date(skill.editedAt).toLocaleString()} on ${skill.editedBy}`;
67
+ yield* Effect.log(`${skill.name.padEnd(width)} ${detail}`);
68
+ }
69
+ },
70
+ }),
71
+
72
+ add: Cli.choose({
73
+ description: "put a skill meant for every project on the synced list; give its folder name, which must match the name in its SKILL.md. It must be in a folder skill-sync syncs, with a valid SKILL.md. Repeating it changes nothing",
74
+ *choices() {
75
+ const synced = (yield* listForTab).map((skill) => skill.name);
76
+ return addableSkills({ folders: detectFolders(), exclude: loadSettings()?.exclude ?? [], synced });
77
+ },
78
+ next: (skill) => Cli.command({
79
+ description: `put ${skill} on the synced list`,
80
+ *run() {
81
+ const result = yield* withDaemon((daemon) => daemon.addSkill(skill));
82
+ yield* Effect.log(result.added ? `Added ${skill} to the synced list.` : `${skill} was already on the synced list.`);
83
+ if (result.syncingFolders.length === 0) {
84
+ yield* Effect.log(`None of the folders holding it on this machine (${result.folders.join(", ")}) is ticked at ${DASHBOARD}, so its files upload once one is.`);
85
+ }
86
+ },
87
+ }),
88
+ }),
89
+
90
+ show: Cli.choose({
91
+ description: "print a synced skill's description and where its copies are on this machine",
92
+ *choices() {
93
+ return (yield* listForTab).map((skill) => skill.name);
94
+ },
95
+ next: (skill) => Cli.command({
96
+ description: `print ${skill}'s description and where its copies are on this machine`,
97
+ *run() {
98
+ const folders = detectFolders();
99
+ const copies = skillCopies({ skill, folders });
100
+ if (copies.length === 0) {
101
+ return yield* new SkillNotOnThisMachine({
102
+ message: `no skills folder skill-sync syncs has a "${skill}" folder; it looked in ${folders.join(", ") || "no folders"}`,
103
+ });
104
+ }
105
+ yield* Effect.log(formatSkillCopies(copies));
106
+ },
107
+ }),
108
+ }),
109
+
110
+ upgrade: Cli.command({
111
+ description: "upgrade skill-sync to the latest version with the package manager that installed it",
112
+ *run() {
113
+ yield* pipe(upgrade({ packageName: name }), Effect.mapError((message) => new UpgradeFailed({ message: `Upgrade failed: ${message}` })));
114
+ },
115
+ }),
116
+
117
+ version: Cli.command({
118
+ description: "print the version of skill-sync installed here",
119
+ *run() {
120
+ yield* Effect.log(version);
121
+ },
122
+ }),
123
+ });
124
+
125
+ /**
126
+ * Runs the CLI on the process's arguments. A command that fails prints why on stderr, alone, and exits 1; usage
127
+ * errors are the library's (`Cli.CliError`, exit 2).
128
+ */
129
+ export function runSkillSync() {
130
+ return pipe(
131
+ Cli.run(skillSync, { version }),
132
+ Effect.catchTags({
133
+ DaemonFailed: report,
134
+ SkillNotOnThisMachine: report,
135
+ UpgradeFailed: report,
136
+ }),
137
+ );
138
+ }
139
+
140
+
141
+ function report(error: { readonly message: string }): Effect.Effect<never, Cli.CliError, Stdio.Stdio> {
142
+ return Effect.gen(function* () {
143
+ const stdio = yield* Stdio.Stdio;
144
+ yield* Effect.orDie(Stream.run(Stream.make(`${error.message}\n`), stdio.stderr()));
145
+ return yield* new Cli.CliError({ message: error.message, exitCode: 1 });
146
+ });
147
+ }
148
+
149
+ /**
150
+ * Runs `use` against the daemon. If none is listening (stopped, or never started since the install) this
151
+ * package's registered daemon is started and `use` is tried again for about ten seconds. Tab never comes here.
152
+ */
153
+ function withDaemon<A>(use: (daemon: IDaemonControl) => Effect.fn.Return<A, DaemonError>): Effect.Effect<A, DaemonFailed, DaemonControl> {
154
+ return Effect.gen(function* () {
155
+ const daemon = yield* DaemonControl;
156
+ const attempt = Effect.gen(() => use(daemon));
157
+ return yield* pipe(
158
+ attempt,
159
+ Effect.catchTag("DaemonNotRunning", () => pipe(
160
+ Effect.gen(() => daemon.startDaemon()),
161
+ Effect.andThen(Effect.sleep(RETRY_INTERVAL)),
162
+ Effect.andThen(Effect.retry(attempt, {
163
+ schedule: Schedule.spaced(RETRY_INTERVAL),
164
+ times: RETRIES,
165
+ while: (error) => error._tag === "DaemonNotRunning",
166
+ })),
167
+ Effect.catchTag("DaemonNotRunning", (error) =>
168
+ Effect.fail(new DaemonFailed({ message: `${error.message}. Reinstall skill-sync to register its daemon.` }))),
169
+ )),
170
+ );
171
+ });
172
+ }
173
+
174
+ /**
175
+ * The synced list for Tab: asked of the daemon, which must already be running, within a time limit, so Tab shows
176
+ * why it has nothing to offer rather than hanging.
177
+ */
178
+ const listForTab = pipe(
179
+ Effect.gen(function* () {
180
+ return yield* (yield* DaemonControl).listSyncedSkills();
181
+ }),
182
+ Effect.timeoutOrElse({
183
+ duration: `${TAB_TIME_LIMIT_SECONDS} seconds`,
184
+ orElse: () => Effect.fail(new DaemonFailed({ message: `the skill-sync daemon did not answer within ${TAB_TIME_LIMIT_SECONDS} seconds` })),
185
+ }),
186
+ );
187
+
188
+ function openBrowser(url: string): void {
189
+ const command = process.platform === "darwin" ? "open"
190
+ : process.platform === "win32" ? "cmd"
191
+ : "xdg-open";
192
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
193
+ spawn(command, args, { stdio: "ignore", detached: true }).unref();
194
+ }
@@ -0,0 +1,172 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, rmSync, 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, sync state and the sync token, all under `~/.jive/`.
8
+ *
9
+ * A file rather than environment variables: the endpoint and which machine this is differ per computer
10
+ * and have to survive a login, which is exactly what a config file is for and exactly what an environment
11
+ * variable is not. Which folders to sync is not in here: they are detected, and the choice to leave one
12
+ * out is kept on the server so the dashboard can change it and a reinstalled daemon still remembers it.
13
+ */
14
+
15
+ const JIVE_HOME = join(homedir(), ".jive");
16
+ export const CONFIG_PATH = join(JIVE_HOME, "skill-sync.json");
17
+ const STATE_PATH = join(JIVE_HOME, "skill-sync-state.json");
18
+ /**
19
+ * The sync token, written at sign-in so the daemon is still signed in after a restart, a reboot or an
20
+ * upgrade. An ordinary file: anything that can read the home directory can copy the token, and the
21
+ * dashboard can revoke it.
22
+ */
23
+ export const TOKEN_PATH = join(JIVE_HOME, "skill-sync-token.json");
24
+ /**
25
+ * How the CLI reaches the running daemon: a Unix socket in `~/.jive/`, or a named pipe on Windows. Only
26
+ * this user can open either, which is what lets the CLI hand the daemon work that involves the token.
27
+ */
28
+ export const CONTROL_SOCKET = process.platform === "win32"
29
+ ? `\\\\.\\pipe\\jive-skill-sync-${userInfo().username}`
30
+ : join(JIVE_HOME, "skill-sync.sock");
31
+
32
+ /** Managed by Claude's own cloud sync; see `Settings.exclude`. */
33
+ const DEFAULT_EXCLUDE = ["synced"] as const;
34
+
35
+ /** What `~/.jive/skill-sync.json` holds: nothing secret, so it can live in a file. */
36
+ export interface Settings {
37
+ readonly endpoint: string;
38
+ /**
39
+ * Top-level directory names under each synced folder to leave alone.
40
+ *
41
+ * `synced` holds the skills Claude already pulls from the cloud itself. Syncing them here would mean
42
+ * two systems writing the same files, each undoing the other, and none of them are yours to edit.
43
+ * The list applies to every detected folder, so in Codex's and Grok's skills folders it keeps a skill
44
+ * named `synced` from syncing.
45
+ */
46
+ readonly exclude: ReadonlyArray<string>;
47
+ /** Names this machine on the server: on the dashboard, and as the machine each edit came from. */
48
+ readonly machine: string;
49
+ }
50
+
51
+ /** Settings plus the token, which the daemon has once signed in. */
52
+ export interface Config extends Settings {
53
+ readonly token: string;
54
+ }
55
+
56
+ /** Sync progress for one folder. Each folder syncs with the server on its own, so each has its own. */
57
+ export interface State {
58
+ /** Highest server sequence number already applied. */
59
+ cursor: number;
60
+ /** Last hash this machine agreed with the server on, per relative path. Absent means never synced. */
61
+ known: Record<string, string>;
62
+ /** The synced list as of last cycle, to notice a skill being added to it. */
63
+ skills?: string[];
64
+ }
65
+
66
+ /** Every folder's `State`, keyed by the folder's absolute path. */
67
+ export type States = Record<string, State>;
68
+
69
+ /**
70
+ * The settings, writing a template on first run. Undefined when the file lacks an endpoint or a machine
71
+ * name, which only happens if someone edited it.
72
+ */
73
+ export function loadSettings(): Settings | undefined {
74
+ if (!existsSync(CONFIG_PATH)) {
75
+ mkdirSync(JIVE_HOME, { recursive: true });
76
+ writeFileSync(CONFIG_PATH, `${JSON.stringify({
77
+ endpoint: "https://skill-sync.jive.sh",
78
+ machine: machineName(),
79
+ exclude: DEFAULT_EXCLUDE,
80
+ }, null, 2)}\n`);
81
+ }
82
+ const settings = readJson<Partial<Settings>>(CONFIG_PATH);
83
+ if (!settings.endpoint || !settings.machine) return undefined;
84
+ return { endpoint: settings.endpoint, machine: settings.machine, exclude: settings.exclude ?? DEFAULT_EXCLUDE };
85
+ }
86
+
87
+ function readJson<T>(path: string): T {
88
+ try {
89
+ return JSON.parse(readFileSync(path, "utf-8")) as T;
90
+ } catch {
91
+ return {} as T;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Every folder's sync state.
97
+ *
98
+ * Before folders were detected the file held one folder's `{ cursor, known }`, for the folder then named
99
+ * by `skillsDir` in the settings. That state is carried over to that folder: dropping it would make the
100
+ * folder look never-synced, and every file in it that differs from the server would become a conflict.
101
+ */
102
+ export function loadStates(): States {
103
+ const stored = readJson<Partial<State> & { folders?: States }>(STATE_PATH);
104
+ if (stored.folders !== undefined) return stored.folders;
105
+ const legacyFolder = readJson<{ skillsDir?: string }>(CONFIG_PATH).skillsDir;
106
+ if (legacyFolder !== undefined && stored.cursor !== undefined && stored.known !== undefined) {
107
+ return { [legacyFolder]: { cursor: stored.cursor, known: stored.known } };
108
+ }
109
+ return {};
110
+ }
111
+
112
+ /** The saved token, or undefined when this machine is signed out. */
113
+ export function loadToken(): string | undefined {
114
+ return readJson<{ token?: string }>(TOKEN_PATH).token;
115
+ }
116
+
117
+ export function saveToken(token: string): void {
118
+ mkdirSync(JIVE_HOME, { recursive: true });
119
+ writeFileSync(TOKEN_PATH, `${JSON.stringify({ token }, null, 2)}\n`);
120
+ }
121
+
122
+ export function deleteToken(): void {
123
+ rmSync(TOKEN_PATH, { force: true });
124
+ }
125
+
126
+ export function stateFor(states: States, folder: string): State {
127
+ states[folder] ??= { cursor: 0, known: {} };
128
+ return states[folder];
129
+ }
130
+
131
+ export function saveStates(states: States): void {
132
+ mkdirSync(JIVE_HOME, { recursive: true });
133
+ writeFileSync(STATE_PATH, `${JSON.stringify({ folders: states }, null, 2)}\n`);
134
+ }
135
+
136
+ /**
137
+ * A name ending in `.lock` is another program's lock, never an agent home, a skill or a skill's file.
138
+ * Claude Code locks a path by creating an empty `<path>.lock` folder beside it and removing it when done;
139
+ * counted as an agent home, `~/.claude-<name>.lock` was filled with skills and the lock could not be released.
140
+ */
141
+ export const isLock = (name: string): boolean => name.endsWith(".lock");
142
+
143
+ /** `HOSTNAME` is not set on macOS, so the template was writing "unknown" on exactly this machine. */
144
+ function machineName(): string {
145
+ return hostname().replace(/\.local$/, "").replace(/[^A-Za-z0-9-]+/g, "-") || "unknown";
146
+ }
147
+
148
+ export function hashBytes(bytes: Uint8Array): string {
149
+ return createHash("sha256").update(bytes).digest("hex");
150
+ }
151
+
152
+ /**
153
+ * Every file under a synced folder, as paths relative to it with forward slashes.
154
+ *
155
+ * Normalised because the same skill synced from Windows and macOS must be one row, not two.
156
+ */
157
+ export function listLocalFiles(folder: string, exclude: ReadonlyArray<string> = DEFAULT_EXCLUDE): string[] {
158
+ if (!existsSync(folder)) return [];
159
+
160
+ const found: string[] = [];
161
+ const walk = (dir: string, top: boolean): void => {
162
+ for (const entry of readdirSync(dir)) {
163
+ if (entry.startsWith(".") || isLock(entry)) continue;
164
+ if (top && exclude.includes(entry)) continue;
165
+ const full = join(dir, entry);
166
+ if (statSync(full).isDirectory()) walk(full, false);
167
+ else found.push(relative(folder, full).split(sep).join("/"));
168
+ }
169
+ };
170
+ walk(folder, true);
171
+ return found.sort();
172
+ }
@@ -0,0 +1,153 @@
1
+ import { createConnection, createServer, type Server, type Socket } from "node:net";
2
+ import { chmodSync, rmSync } from "node:fs";
3
+ import { Cause, Data, Effect, Queue, Stream } from "effect";
4
+ import { CONTROL_SOCKET } from "./config";
5
+ import type { ListedSkill } from "./wire";
6
+
7
+ /**
8
+ * The channel between the CLI and the running daemon.
9
+ *
10
+ * The daemon owns the sync token: it receives it from the browser and keeps it in `~/.jive/`, so it never
11
+ * passes through the CLI. The CLI's `login`, `logout`, `list` and `add` are requests to the daemon over this
12
+ * channel. Messages are newline-delimited JSON; each request gets events until one that
13
+ * ends it.
14
+ */
15
+
16
+ export type ControlRequest =
17
+ | { readonly type: "login" }
18
+ | { readonly type: "logout" }
19
+ /** The synced list, which the daemon fetches from the server with its token. */
20
+ | { readonly type: "list" }
21
+ /** Puts a skill on this machine on the synced list, after checking its files (`checkSkillToAdd`). */
22
+ | { readonly type: "add"; readonly skill: string };
23
+
24
+ export type ControlEvent =
25
+ /** Sign-in has started: the CLI opens this URL in the browser, where the passkey is verified. */
26
+ | { readonly type: "open"; readonly url: string }
27
+ | { readonly type: "signedIn"; readonly machine: string }
28
+ | { readonly type: "signedOut"; readonly revoked: boolean }
29
+ | { readonly type: "list"; readonly skills: ReadonlyArray<ListedSkill> }
30
+ /**
31
+ * The skill is on the synced list. `added` is false when it already was. `folders` are this machine's
32
+ * folders that hold it; `syncingFolders` are those ticked on the dashboard, which upload it.
33
+ */
34
+ | {
35
+ readonly type: "added";
36
+ readonly skill: string;
37
+ readonly added: boolean;
38
+ readonly folders: ReadonlyArray<string>;
39
+ readonly syncingFolders: ReadonlyArray<string>;
40
+ }
41
+ | { readonly type: "error"; readonly message: string };
42
+
43
+ const isFinal = (event: ControlEvent): boolean => event.type !== "open";
44
+
45
+ /** No daemon is listening on the control socket: it is stopped, or has not started since the install. */
46
+ export class DaemonNotRunning extends Data.TaggedError("DaemonNotRunning")<{ readonly message: string }> {}
47
+
48
+ /** The daemon is running but the request failed: it refused it, answered nonsense, or hung up. */
49
+ export class DaemonFailed extends Data.TaggedError("DaemonFailed")<{ readonly message: string }> {}
50
+
51
+ /**
52
+ * Sends one request and streams the daemon's events, ending after the final one. The socket is closed when the
53
+ * stream ends or is interrupted, so a caller that stops waiting (a time limit on Tab) leaves nothing open.
54
+ */
55
+ export function requestEvents(message: ControlRequest): Stream.Stream<ControlEvent, DaemonNotRunning | DaemonFailed> {
56
+ return Stream.callback<ControlEvent, DaemonNotRunning | DaemonFailed>((queue) => Effect.acquireRelease(
57
+ Effect.sync(() => {
58
+ let settled = false;
59
+ const fail = (error: DaemonNotRunning | DaemonFailed) => {
60
+ if (settled) return;
61
+ settled = true;
62
+ Queue.failCauseUnsafe(queue, Cause.fail(error));
63
+ };
64
+ const socket = createConnection(CONTROL_SOCKET);
65
+ socket.on("connect", () => socket.write(`${JSON.stringify(message)}\n`));
66
+ socket.on("error", (cause: NodeJS.ErrnoException) => fail(cause.code === "ENOENT" || cause.code === "ECONNREFUSED"
67
+ ? new DaemonNotRunning({ message: `the skill-sync daemon is not running (${cause.code} on ${CONTROL_SOCKET})` })
68
+ : new DaemonFailed({ message: cause.message })));
69
+ readLines(socket, (line) => {
70
+ if (settled) return;
71
+ let event: ControlEvent;
72
+ try {
73
+ event = JSON.parse(line) as ControlEvent;
74
+ } catch {
75
+ return fail(new DaemonFailed({ message: `unexpected answer from the daemon: ${line}` }));
76
+ }
77
+ Queue.offerUnsafe(queue, event);
78
+ if (isFinal(event)) {
79
+ settled = true;
80
+ socket.end();
81
+ Queue.endUnsafe(queue);
82
+ }
83
+ });
84
+ socket.on("close", () => fail(new DaemonFailed({ message: "the daemon closed the connection without answering" })));
85
+ return socket;
86
+ }),
87
+ (socket) => Effect.sync(() => socket.destroy()),
88
+ ));
89
+ }
90
+
91
+ /** One request being answered: send events, and end the conversation with a final one. */
92
+ export interface Reply {
93
+ readonly send: (event: ControlEvent) => void;
94
+ }
95
+
96
+ /**
97
+ * Listens on the control socket. Resolves false, without listening, when another live daemon already
98
+ * holds it: two installs of skill-sync mean two daemons, and the second stands down rather than fight.
99
+ */
100
+ export async function serve(handle: (message: ControlRequest, reply: Reply) => void): Promise<Server | false> {
101
+ if (await answers()) return false;
102
+ // Nothing answered, so a socket file left here is from a daemon that died; it would block the listen.
103
+ if (process.platform !== "win32") rmSync(CONTROL_SOCKET, { force: true });
104
+
105
+ const server = createServer((socket) => {
106
+ const reply: Reply = {
107
+ send: (event) => {
108
+ if (socket.writable) socket.write(`${JSON.stringify(event)}\n`);
109
+ if (isFinal(event)) socket.end();
110
+ },
111
+ };
112
+ readLines(socket, (line) => {
113
+ try {
114
+ handle(JSON.parse(line) as ControlRequest, reply);
115
+ } catch (cause) {
116
+ reply.send({ type: "error", message: cause instanceof Error ? cause.message : String(cause) });
117
+ }
118
+ });
119
+ socket.on("error", () => undefined); // A CLI that went away mid-request; nothing to tell it.
120
+ });
121
+ await new Promise<void>((resolve, reject) => {
122
+ server.once("error", reject);
123
+ server.listen(CONTROL_SOCKET, () => resolve());
124
+ });
125
+ // Only this user may talk to the daemon that holds their token.
126
+ if (process.platform !== "win32") chmodSync(CONTROL_SOCKET, 0o600);
127
+ return server;
128
+ }
129
+
130
+ /** Whether a live daemon is listening on the control socket. */
131
+ function answers(): Promise<boolean> {
132
+ return new Promise((resolve) => {
133
+ const socket = createConnection(CONTROL_SOCKET);
134
+ socket.on("connect", () => {
135
+ socket.end();
136
+ resolve(true);
137
+ });
138
+ socket.on("error", () => resolve(false));
139
+ });
140
+ }
141
+
142
+ function readLines(socket: Socket, onLine: (line: string) => void): void {
143
+ let buffer = "";
144
+ socket.on("data", (chunk) => {
145
+ buffer += chunk.toString();
146
+ let newline: number;
147
+ while ((newline = buffer.indexOf("\n")) >= 0) {
148
+ const line = buffer.slice(0, newline).trim();
149
+ buffer = buffer.slice(newline + 1);
150
+ if (line !== "") onLine(line);
151
+ }
152
+ });
153
+ }
@@ -0,0 +1,74 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { Effect, Layer, Option, Stream, pipe } from "effect";
3
+ import { daemonStatuses } from "jive-abstract-library";
4
+ import { name } from "../../../package.json";
5
+ import { DaemonFailed, requestEvents, type ControlEvent, type ControlRequest } from "../control";
6
+ import type { ListedSkill } from "../wire";
7
+ import { DaemonControl, type AddedSkill, type DaemonError, type IDaemonControl } from "./interface";
8
+
9
+ class DaemonControlImpl implements IDaemonControl {
10
+ *login(openSignInPage: (url: string) => Effect.Effect<void>): Effect.fn.Return<string, DaemonError> {
11
+ const event = yield* finalEvent({ type: "login" }, (event) => event.type === "open" ? openSignInPage(event.url) : Effect.void);
12
+ if (event.type !== "signedIn") return yield* unexpected(event);
13
+ return event.machine;
14
+ }
15
+
16
+ *logout(): Effect.fn.Return<boolean, DaemonError> {
17
+ const event = yield* finalEvent({ type: "logout" });
18
+ if (event.type !== "signedOut") return yield* unexpected(event);
19
+ return event.revoked;
20
+ }
21
+
22
+ *listSyncedSkills(): Effect.fn.Return<ReadonlyArray<ListedSkill>, DaemonError> {
23
+ const event = yield* finalEvent({ type: "list" });
24
+ if (event.type !== "list") return yield* unexpected(event);
25
+ return event.skills;
26
+ }
27
+
28
+ *addSkill(skill: string): Effect.fn.Return<AddedSkill, DaemonError> {
29
+ const event = yield* finalEvent({ type: "add", skill });
30
+ if (event.type !== "added") return yield* unexpected(event);
31
+ return { added: event.added, folders: event.folders, syncingFolders: event.syncingFolders };
32
+ }
33
+
34
+ *startDaemon(): Effect.fn.Return<void> {
35
+ const statuses = yield* pipe(daemonStatuses, Effect.catch(() => Effect.succeed([])));
36
+ const ours = statuses.filter((status) => status.registration.packageName === name && status.executableExists);
37
+ for (const { registration } of ours) {
38
+ const command: string[] = registration.kind === "launchd"
39
+ ? ["launchctl", "kickstart", "-k", `gui/${process.getuid?.() ?? 0}/${registration.unit}`]
40
+ : registration.kind === "systemd"
41
+ ? ["systemctl", "--user", "restart", registration.unit]
42
+ : ["schtasks", "/Run", "/TN", registration.unit];
43
+ const result = yield* Effect.sync(() => spawnSync(command[0]!, command.slice(1), { stdio: ["ignore", "ignore", "pipe"] }));
44
+ if (result.status !== 0) {
45
+ yield* Effect.logError(`Could not start ${registration.unit}: ${String(result.stderr ?? "").trim() || `exit ${result.status}`}`);
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ /** The event that ends the conversation, after handing each earlier one (only `open`, during login) to `onEvent`. */
52
+ function finalEvent(
53
+ message: ControlRequest,
54
+ onEvent: (event: ControlEvent) => Effect.Effect<void> = () => Effect.void,
55
+ ): Effect.Effect<ControlEvent, DaemonError> {
56
+ return pipe(
57
+ requestEvents(message),
58
+ Stream.tap(onEvent),
59
+ Stream.runLast,
60
+ Effect.flatMap(Option.match({
61
+ onNone: () => Effect.fail(new DaemonFailed({ message: "the daemon closed the connection without answering" })),
62
+ onSome: (event) => Effect.succeed(event),
63
+ })),
64
+ );
65
+ }
66
+
67
+ /** An `error` event is the daemon refusing the request; anything else is an answer to a different request. */
68
+ function unexpected(event: ControlEvent): Effect.Effect<never, DaemonFailed> {
69
+ return Effect.fail(new DaemonFailed({
70
+ message: event.type === "error" ? event.message : `unexpected answer from the daemon: ${JSON.stringify(event)}`,
71
+ }));
72
+ }
73
+
74
+ export const DaemonControlLive = Layer.succeed(DaemonControl, new DaemonControlImpl());