@jive-sh/skill-sync 0.6.2 → 0.7.0-latest-darwin-arm64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/multi-call-binary +4 -0
  2. package/package.json +11 -36
  3. package/README.md +0 -146
  4. package/bin/package.json +0 -1
  5. package/bin/skill-sync +0 -614
  6. package/bin/skill-sync-daemon +0 -614
  7. package/dist/daemons/skill-sync-daemon.js +0 -499
  8. package/dist/daemons/skill-sync-daemon.js.map +0 -1
  9. package/dist/entrypoints/skill-sync.js +0 -7
  10. package/dist/entrypoints/skill-sync.js.map +0 -1
  11. package/dist/index.js +0 -10
  12. package/dist/index.js.map +0 -1
  13. package/dist/internal/agents/agent-tool.js +0 -92
  14. package/dist/internal/agents/agent-tool.js.map +0 -1
  15. package/dist/internal/agents/claude.js +0 -422
  16. package/dist/internal/agents/claude.js.map +0 -1
  17. package/dist/internal/agents/codex.js +0 -266
  18. package/dist/internal/agents/codex.js.map +0 -1
  19. package/dist/internal/agents/command.js +0 -219
  20. package/dist/internal/agents/command.js.map +0 -1
  21. package/dist/internal/agents/grok.js +0 -172
  22. package/dist/internal/agents/grok.js.map +0 -1
  23. package/dist/internal/agents/index.js +0 -70
  24. package/dist/internal/agents/index.js.map +0 -1
  25. package/dist/internal/cli.js +0 -161
  26. package/dist/internal/cli.js.map +0 -1
  27. package/dist/internal/config.js +0 -131
  28. package/dist/internal/config.js.map +0 -1
  29. package/dist/internal/control.js +0 -113
  30. package/dist/internal/control.js.map +0 -1
  31. package/dist/internal/daemon-control/impl.js +0 -62
  32. package/dist/internal/daemon-control/impl.js.map +0 -1
  33. package/dist/internal/daemon-control/interface.js +0 -4
  34. package/dist/internal/daemon-control/interface.js.map +0 -1
  35. package/dist/internal/folders.js +0 -47
  36. package/dist/internal/folders.js.map +0 -1
  37. package/dist/internal/local-skills.js +0 -43
  38. package/dist/internal/local-skills.js.map +0 -1
  39. package/dist/internal/path.js +0 -36
  40. package/dist/internal/path.js.map +0 -1
  41. package/dist/internal/server.js +0 -32
  42. package/dist/internal/server.js.map +0 -1
  43. package/dist/internal/skill-check.js +0 -83
  44. package/dist/internal/skill-check.js.map +0 -1
  45. package/dist/internal/sync.js +0 -183
  46. package/dist/internal/sync.js.map +0 -1
  47. package/dist/internal/wire.js +0 -24
  48. package/dist/internal/wire.js.map +0 -1
  49. package/install.cjs +0 -614
  50. package/src/daemons/skill-sync-daemon.ts +0 -491
  51. package/src/entrypoints/skill-sync.ts +0 -12
  52. package/src/index.ts +0 -15
  53. package/src/internal/agents/agent-tool.ts +0 -136
  54. package/src/internal/agents/claude.ts +0 -440
  55. package/src/internal/agents/codex.ts +0 -283
  56. package/src/internal/agents/command.ts +0 -257
  57. package/src/internal/agents/grok.ts +0 -176
  58. package/src/internal/agents/index.ts +0 -74
  59. package/src/internal/cli.ts +0 -194
  60. package/src/internal/config.ts +0 -172
  61. package/src/internal/control.ts +0 -153
  62. package/src/internal/daemon-control/impl.ts +0 -74
  63. package/src/internal/daemon-control/interface.ts +0 -38
  64. package/src/internal/folders.ts +0 -50
  65. package/src/internal/local-skills.ts +0 -58
  66. package/src/internal/path.ts +0 -32
  67. package/src/internal/server.ts +0 -34
  68. package/src/internal/skill-check.ts +0 -97
  69. package/src/internal/sync.ts +0 -217
  70. package/src/internal/wire.ts +0 -315
@@ -1,153 +0,0 @@
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
- }
@@ -1,74 +0,0 @@
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());
@@ -1,38 +0,0 @@
1
- import { Context, type Effect } from "effect";
2
- import type { DaemonFailed, DaemonNotRunning } from "../control";
3
- import type { ListedSkill } from "../wire";
4
-
5
- export type DaemonError = DaemonNotRunning | DaemonFailed;
6
-
7
- /** What `addSkill` did; see the `added` event in `control.ts`. */
8
- export interface AddedSkill {
9
- /** False when the skill was already on the synced list. */
10
- readonly added: boolean;
11
- /** This machine's folders that hold the skill. */
12
- readonly folders: ReadonlyArray<string>;
13
- /** Those of them ticked on the dashboard, which upload it. */
14
- readonly syncingFolders: ReadonlyArray<string>;
15
- }
16
-
17
- /**
18
- * What the CLI asks of the running daemon, which owns the sync token, so every request that needs the token goes
19
- * through it. Every method fails with `DaemonNotRunning` when no daemon listens; none starts one by itself, so Tab
20
- * completion can ask without waiting for a daemon to start.
21
- */
22
- export interface IDaemonControl {
23
- /**
24
- * Signs this machine in. `openSignInPage` is given the page where the passkey is verified, and the method
25
- * returns the machine's name once the browser has handed the daemon its token.
26
- */
27
- login(openSignInPage: (url: string) => Effect.Effect<void>): Effect.fn.Return<string, DaemonError>;
28
- /** Signs this machine out; returns whether the server revoked the token. */
29
- logout(): Effect.fn.Return<boolean, DaemonError>;
30
- /** The synced list, as the server holds it. */
31
- listSyncedSkills(): Effect.fn.Return<ReadonlyArray<ListedSkill>, DaemonError>;
32
- /** Puts a skill on this machine on the synced list, once the daemon has checked its files. */
33
- addSkill(skill: string): Effect.fn.Return<AddedSkill, DaemonError>;
34
- /** Starts this package's registered daemon through its service manager (launchd, systemd or Task Scheduler). */
35
- startDaemon(): Effect.fn.Return<void>;
36
- }
37
-
38
- export class DaemonControl extends Context.Service<DaemonControl, IDaemonControl>()("DaemonControl") {}
@@ -1,50 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { detectFolders } from "./agents";
4
- import { hashBytes, listLocalFiles, type Config } from "./config";
5
- import { fetchServer } from "./server";
6
- import {
7
- skillOf, type FileHash, type FolderPrefs, type FoldersRequest, type FoldersResponse, type LocalSkill,
8
- } from "./wire";
9
-
10
- /**
11
- * What this machine tells the service about its folders, and what it hears back.
12
- *
13
- * The daemon and the CLI both register, so this lives in one place: they must describe a folder the same
14
- * way, or the dashboard would show whichever of them spoke last.
15
- */
16
-
17
- /**
18
- * The skills on disk in one folder, with each file's hash. Hashing every file on each check is cheap at
19
- * skills' size, and it is what lets the dashboard show whether this folder's copy is the synced one.
20
- */
21
- export function localSkills(folder: string, config: Config): LocalSkill[] {
22
- const byName = new Map<string, FileHash[]>();
23
- for (const path of listLocalFiles(folder, config.exclude)) {
24
- const name = skillOf(path);
25
- let hash: string;
26
- try {
27
- hash = hashBytes(readFileSync(join(folder, path)));
28
- } catch {
29
- continue; // Deleted between listing and reading; the next check reports the folder as it is.
30
- }
31
- byName.set(name, [...(byName.get(name) ?? []), { path, hash }]);
32
- }
33
- return [...byName].map(([name, files]) => ({ name, files }));
34
- }
35
-
36
- /** Everything registration sends, so a caller can tell when it has changed and is worth re-sending. */
37
- export function describe(config: Config): FoldersRequest {
38
- return { folders: detectFolders().map((path) => ({ path, skills: localSkills(path, config) })) };
39
- }
40
-
41
- /** Registers this machine's folders and skills; returns the folders to sync and the skills in each. */
42
- export async function register(config: Config, request: FoldersRequest): Promise<ReadonlyArray<FolderPrefs>> {
43
- const response = await fetchServer(config, "/folders", {
44
- method: "POST",
45
- headers: { "content-type": "application/json" },
46
- body: JSON.stringify(request),
47
- });
48
- if (!response.ok) throw new Error(`POST /folders: ${response.status} ${await response.text()}`);
49
- return (await response.json() as FoldersResponse).folders;
50
- }
@@ -1,58 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { Option } from "effect";
4
- import { isLock } from "./config";
5
- import { checkSkillToAdd, readFrontmatter } from "./skill-check";
6
-
7
- /** Skills as this machine's detected skills folders hold them, for the CLI's `show` and `add`. */
8
-
9
- /** One folder's copy of a skill, with the description its `SKILL.md` frontmatter gives. */
10
- export interface SkillCopy {
11
- readonly path: string;
12
- readonly description: Option.Option<string>;
13
- }
14
-
15
- /** Every copy of `skill` in `folders`, in the order of `folders`. */
16
- export function skillCopies(input: { readonly skill: string; readonly folders: ReadonlyArray<string> }): ReadonlyArray<SkillCopy> {
17
- return input.folders
18
- .map((folder) => join(folder, input.skill))
19
- .filter((path) => existsSync(path))
20
- .map((path) => ({ path, description: readDescription(join(path, "SKILL.md")) }));
21
- }
22
-
23
- /**
24
- * What `skill-sync show` prints: each description above the paths of the copies that have it. Copies agree once
25
- * synced, so this is usually one description; copies that differ are shown apart rather than one hiding another.
26
- */
27
- export function formatSkillCopies(copies: ReadonlyArray<SkillCopy>): string {
28
- const byDescription = Map.groupBy(copies, (copy) => Option.getOrElse(copy.description, () => "(its SKILL.md has no description)"));
29
- return [...byDescription]
30
- .map(([description, group]) => [description, ...group.map((copy) => ` ${copy.path}`)].join("\n"))
31
- .join("\n\n");
32
- }
33
-
34
- /**
35
- * The skills in `folders` that are not on the synced list and that `skill-sync add` would accept: the same check
36
- * the daemon runs before adding (`checkSkillToAdd`), so Tab offers nothing the daemon would refuse.
37
- */
38
- export function addableSkills(input: {
39
- readonly folders: ReadonlyArray<string>;
40
- readonly exclude: ReadonlyArray<string>;
41
- readonly synced: ReadonlyArray<string>;
42
- }): ReadonlyArray<string> {
43
- const { folders, exclude, synced } = input;
44
- const names = new Set(folders.flatMap((folder) => entries(folder).filter((entry) => !entry.startsWith(".") && !isLock(entry))));
45
- return [...names]
46
- .filter((skill) => !synced.includes(skill) && checkSkillToAdd({ skill, folders, exclude }).ok)
47
- .sort();
48
- }
49
-
50
- function readDescription(skillFile: string): Option.Option<string> {
51
- if (!existsSync(skillFile)) return Option.none();
52
- const description = readFrontmatter(readFileSync(skillFile, "utf8"))?.get("description");
53
- return description === undefined || description === "" ? Option.none() : Option.some(description);
54
- }
55
-
56
- function entries(folder: string): ReadonlyArray<string> {
57
- return existsSync(folder) ? readdirSync(folder) : [];
58
- }
@@ -1,32 +0,0 @@
1
- /**
2
- * Validation for the one piece of untrusted input that becomes a filesystem path.
3
- *
4
- * Shared by the Worker and the daemon on purpose, and deliberately free of any Node import so the Worker
5
- * can bundle it. Both ends check: the server so one compromised client cannot poison what every machine
6
- * pulls, and the daemon because a server it does not control is not a thing to take paths from either.
7
- *
8
- * Without this, a pushed path of `../../.ssh/authorized_keys` is joined to the skills directory and
9
- * written wherever the daemon's user can write.
10
- */
11
-
12
- /** Long enough for any real nesting, short enough that nothing can be used to exhaust anything. */
13
- const MAX_LENGTH = 512;
14
-
15
- export function invalidPathReason(path: string): string | undefined {
16
- if (path.length === 0 || path.length > MAX_LENGTH) return "path is empty or too long";
17
- if (path.includes("\0")) return "path contains a null byte";
18
- if (path.includes("\\")) return "path must use forward slashes";
19
- if (path.startsWith("/")) return "path must be relative";
20
- // A Windows drive letter is absolute on the machine that matters even though it has no leading slash.
21
- if (/^[A-Za-z]:/.test(path)) return "path must be relative";
22
-
23
- for (const segment of path.split("/")) {
24
- if (segment === "") return "path has an empty segment";
25
- if (segment === "." || segment === "..") return "path must not contain . or .. segments";
26
- }
27
- return undefined;
28
- }
29
-
30
- export function isValidPath(path: string): boolean {
31
- return invalidPathReason(path) === undefined;
32
- }
@@ -1,34 +0,0 @@
1
- import type { Config } from "./config";
2
-
3
- /**
4
- * Requests to the skill-sync service, signed with this machine's token.
5
- *
6
- * Every request goes through `fetchServer`, so a token the server no longer accepts is noticed the same
7
- * way whichever request hits it first.
8
- */
9
-
10
- /** The server answered 401: the token was revoked or is unknown, so no retry with it can succeed. */
11
- export class TokenRejected extends Error {
12
- constructor(message: string, readonly token: string) {
13
- super(message);
14
- }
15
- }
16
-
17
- export function authHeaders(config: Config, extra: Record<string, string>): Record<string, string> {
18
- return { authorization: `Bearer ${config.token}`, "x-skill-sync-machine": config.machine, ...extra };
19
- }
20
-
21
- /**
22
- * Sends one request to the server with the token. Throws `TokenRejected` on 401; every other status is
23
- * returned for the caller to judge, since some (a 409 from `PUT /files`) are answers rather than failures.
24
- */
25
- export async function fetchServer(config: Config, path: string, init: RequestInit = {}): Promise<Response> {
26
- const response = await fetch(`${config.endpoint}${path}`, {
27
- ...init,
28
- headers: authHeaders(config, (init.headers ?? {}) as Record<string, string>),
29
- });
30
- if (response.status === 401) {
31
- throw new TokenRejected(`${init.method ?? "GET"} ${path}: the server rejected this machine's token`, config.token);
32
- }
33
- return response;
34
- }
@@ -1,97 +0,0 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { isSkillName } from "./wire";
4
-
5
- /**
6
- * Whether a skill on this machine may go on the synced list, checked before `skill-sync add` asks the
7
- * server to add it.
8
- *
9
- * The synced list is for skills meant for every project. A skill made for one project lives in that
10
- * project (its `.claude/skills`, `.agents/skills` or `.grok/skills`), which is never one of the folders
11
- * skill-sync detects, so a skill is accepted only from a detected folder. That is the one sign of a
12
- * project-specific skill that can be read from disk; a skill written into a home folder but about one
13
- * project is not caught here.
14
- */
15
- export type SkillCheck =
16
- | { readonly ok: true; readonly folders: ReadonlyArray<string> }
17
- | { readonly ok: false; readonly reason: string };
18
-
19
- export function checkSkillToAdd(input: {
20
- readonly skill: string;
21
- /** The skills folders skill-sync detects on this machine (`detectFolders`). */
22
- readonly folders: ReadonlyArray<string>;
23
- /** Top-level names skill-sync never syncs (`Settings.exclude`). */
24
- readonly exclude: ReadonlyArray<string>;
25
- }): SkillCheck {
26
- const { skill, folders, exclude } = input;
27
- if (!isSkillName(skill)) {
28
- return { ok: false, reason: `"${skill}" is not a skill name: lowercase letters and digits in hyphen-joined words, at most 64 characters` };
29
- }
30
- if (exclude.includes(skill)) {
31
- return { ok: false, reason: `"${skill}" is excluded from syncing in ~/.jive/skill-sync.json` };
32
- }
33
- const holding = folders.filter((folder) => isDirectory(join(folder, skill)));
34
- if (holding.length === 0) {
35
- return {
36
- ok: false,
37
- reason: `no skills folder skill-sync syncs has a "${skill}" folder; it looked in ${folders.join(", ") || "no folders"}. `
38
- + "Only skills meant for every project sync: write the skill into one of those folders. A skill inside a "
39
- + "project's own skills folder is specific to that project and stays there.",
40
- };
41
- }
42
- for (const folder of holding) {
43
- const problem = frontmatterProblem(skill, join(folder, skill, "SKILL.md"));
44
- if (problem !== undefined) return { ok: false, reason: problem };
45
- }
46
- return { ok: true, folders: holding };
47
- }
48
-
49
- /** Why a skill's `SKILL.md` would not load as that skill, or undefined when it would. */
50
- function frontmatterProblem(skill: string, path: string): string | undefined {
51
- if (!existsSync(path)) return `${path} does not exist; every skill needs a SKILL.md`;
52
- const fields = readFrontmatter(readFileSync(path, "utf8"));
53
- if (fields === undefined) return `${path} does not start with a frontmatter block between --- lines`;
54
- const name = fields.get("name");
55
- if (name === undefined || name === "") return `${path}'s frontmatter has no name`;
56
- if (name !== skill) return `${path}'s frontmatter name is "${name}", but its folder is "${skill}"; they must match`;
57
- if ((fields.get("description") ?? "") === "") return `${path}'s frontmatter has no description, which is how agents decide to load it`;
58
- return undefined;
59
- }
60
-
61
- /**
62
- * The top-level keys of a `SKILL.md`'s frontmatter, with their values as text. Covers what skills use: a
63
- * plain or quoted value on the key's line, or a block (`>` or `|`) on the indented lines after it.
64
- */
65
- export function readFrontmatter(text: string): Map<string, string> | undefined {
66
- const lines = text.replace(/^/, "").split(/\r?\n/);
67
- if (lines[0]?.trim() !== "---") return undefined;
68
- const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
69
- if (end === -1) return undefined;
70
- const fields = new Map<string, string>();
71
- let blockKey: string | undefined;
72
- for (const line of lines.slice(1, end)) {
73
- const field = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
74
- if (field !== null) {
75
- const key = field[1]!;
76
- const raw = field[2]!;
77
- blockKey = /^[>|][+-]?$/.test(raw.trim()) ? key : undefined;
78
- fields.set(key, blockKey === undefined ? unquote(raw.trim()) : "");
79
- } else if (blockKey !== undefined && /^\s+\S/.test(line)) {
80
- fields.set(blockKey, `${fields.get(blockKey)} ${line.trim()}`.trim());
81
- }
82
- }
83
- return fields;
84
- }
85
-
86
- function unquote(value: string): string {
87
- const quoted = /^(["'])(.*)\1$/.exec(value);
88
- return quoted === null ? value : quoted[2]!;
89
- }
90
-
91
- function isDirectory(path: string): boolean {
92
- try {
93
- return statSync(path).isDirectory();
94
- } catch {
95
- return false;
96
- }
97
- }