@jive-sh/skill-sync 0.6.1 → 0.6.2-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.
- package/multi-call-binary +4 -0
- package/package.json +11 -36
- package/README.md +0 -146
- package/bin/package.json +0 -1
- package/bin/skill-sync +0 -614
- package/bin/skill-sync-daemon +0 -614
- package/dist/daemons/skill-sync-daemon.js +0 -499
- package/dist/daemons/skill-sync-daemon.js.map +0 -1
- package/dist/entrypoints/skill-sync.js +0 -7
- package/dist/entrypoints/skill-sync.js.map +0 -1
- package/dist/index.js +0 -10
- package/dist/index.js.map +0 -1
- package/dist/internal/agents/agent-tool.js +0 -92
- package/dist/internal/agents/agent-tool.js.map +0 -1
- package/dist/internal/agents/claude.js +0 -422
- package/dist/internal/agents/claude.js.map +0 -1
- package/dist/internal/agents/codex.js +0 -266
- package/dist/internal/agents/codex.js.map +0 -1
- package/dist/internal/agents/command.js +0 -158
- package/dist/internal/agents/command.js.map +0 -1
- package/dist/internal/agents/grok.js +0 -172
- package/dist/internal/agents/grok.js.map +0 -1
- package/dist/internal/agents/index.js +0 -70
- package/dist/internal/agents/index.js.map +0 -1
- package/dist/internal/cli.js +0 -161
- package/dist/internal/cli.js.map +0 -1
- package/dist/internal/config.js +0 -131
- package/dist/internal/config.js.map +0 -1
- package/dist/internal/control.js +0 -113
- package/dist/internal/control.js.map +0 -1
- package/dist/internal/daemon-control/impl.js +0 -62
- package/dist/internal/daemon-control/impl.js.map +0 -1
- package/dist/internal/daemon-control/interface.js +0 -4
- package/dist/internal/daemon-control/interface.js.map +0 -1
- package/dist/internal/folders.js +0 -47
- package/dist/internal/folders.js.map +0 -1
- package/dist/internal/local-skills.js +0 -43
- package/dist/internal/local-skills.js.map +0 -1
- package/dist/internal/path.js +0 -36
- package/dist/internal/path.js.map +0 -1
- package/dist/internal/server.js +0 -32
- package/dist/internal/server.js.map +0 -1
- package/dist/internal/skill-check.js +0 -83
- package/dist/internal/skill-check.js.map +0 -1
- package/dist/internal/sync.js +0 -183
- package/dist/internal/sync.js.map +0 -1
- package/dist/internal/wire.js +0 -24
- package/dist/internal/wire.js.map +0 -1
- package/install.cjs +0 -614
- package/src/daemons/skill-sync-daemon.ts +0 -491
- package/src/entrypoints/skill-sync.ts +0 -12
- package/src/index.ts +0 -15
- package/src/internal/agents/agent-tool.ts +0 -136
- package/src/internal/agents/claude.ts +0 -440
- package/src/internal/agents/codex.ts +0 -283
- package/src/internal/agents/command.ts +0 -196
- package/src/internal/agents/grok.ts +0 -176
- package/src/internal/agents/index.ts +0 -74
- package/src/internal/cli.ts +0 -194
- package/src/internal/config.ts +0 -172
- package/src/internal/control.ts +0 -153
- package/src/internal/daemon-control/impl.ts +0 -74
- package/src/internal/daemon-control/interface.ts +0 -38
- package/src/internal/folders.ts +0 -50
- package/src/internal/local-skills.ts +0 -58
- package/src/internal/path.ts +0 -32
- package/src/internal/server.ts +0 -34
- package/src/internal/skill-check.ts +0 -97
- package/src/internal/sync.ts +0 -217
- package/src/internal/wire.ts +0 -315
|
@@ -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") {}
|
package/src/internal/folders.ts
DELETED
|
@@ -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
|
-
}
|
package/src/internal/path.ts
DELETED
|
@@ -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
|
-
}
|
package/src/internal/server.ts
DELETED
|
@@ -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
|
-
}
|
package/src/internal/sync.ts
DELETED
|
@@ -1,217 +0,0 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import { hashBytes, isLock, listLocalFiles, type Config, type State } from "./config";
|
|
4
|
-
import { invalidPathReason } from "./path";
|
|
5
|
-
import { fetchServer } from "./server";
|
|
6
|
-
import { skillOf, type ListFilesResponse, type PutFileRequest } from "./wire";
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* One sync cycle: take every newer edit the server has, then send every newer edit this folder has.
|
|
10
|
-
*
|
|
11
|
-
* The latest edit wins, always. Every file carries the time it was last edited: here, the file's
|
|
12
|
-
* modification time; on the server, the edit time of the version it holds. When this folder and the
|
|
13
|
-
* server disagree about a file, whichever was edited later is kept, on both sides. Nothing is merged and
|
|
14
|
-
* nothing is set aside, so every folder converges on the same bytes.
|
|
15
|
-
*
|
|
16
|
-
* A pulled file is given the server's edit time as its modification time, so the next cycle does not
|
|
17
|
-
* mistake the pull for a local edit.
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
export interface Report {
|
|
21
|
-
readonly pulled: string[];
|
|
22
|
-
readonly pushed: string[];
|
|
23
|
-
readonly deletedLocally: string[];
|
|
24
|
-
/** Paths the server offered that this machine refused to write. */
|
|
25
|
-
readonly rejected: string[];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** True when a report has nothing in it worth telling anyone. */
|
|
29
|
-
export function isQuiet(report: Report): boolean {
|
|
30
|
-
return [report.pulled, report.pushed, report.deletedLocally, report.rejected].every((list) => list.length === 0);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* What a cycle changed, as the dashboard shows it under the folder: per direction, how many files in
|
|
35
|
-
* which skills ("pulled 64 files: agentic-collaboration 52, senior-swe 12"), never the file paths, which
|
|
36
|
-
* after a large pull fill the page. Empty when nothing changed.
|
|
37
|
-
*/
|
|
38
|
-
export function describeActivity(report: Report): string {
|
|
39
|
-
const direction = (verb: string, paths: ReadonlyArray<string>): string => {
|
|
40
|
-
if (paths.length === 0) return "";
|
|
41
|
-
const perSkill = new Map<string, number>();
|
|
42
|
-
for (const path of paths) perSkill.set(skillOf(path), (perSkill.get(skillOf(path)) ?? 0) + 1);
|
|
43
|
-
const skills = [...perSkill].sort(([a], [b]) => a.localeCompare(b)).map(([skill, files]) => `${skill} ${files}`);
|
|
44
|
-
return `${verb} ${paths.length} ${paths.length === 1 ? "file" : "files"}: ${skills.join(", ")}`;
|
|
45
|
-
};
|
|
46
|
-
return [
|
|
47
|
-
direction("pulled", report.pulled),
|
|
48
|
-
direction("pushed", report.pushed),
|
|
49
|
-
direction("deleted", report.deletedLocally),
|
|
50
|
-
].filter(Boolean).join("; ");
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* `skills` is the synced list. Every other skill in the folder is local to it: never pushed, never
|
|
55
|
-
* overwritten, never deleted by a sync.
|
|
56
|
-
*/
|
|
57
|
-
export async function syncOnce(config: Config, folder: string, state: State, skills: ReadonlySet<string>): Promise<Report> {
|
|
58
|
-
const report: Report = { pulled: [], pushed: [], deletedLocally: [], rejected: [] };
|
|
59
|
-
mkdirSync(folder, { recursive: true });
|
|
60
|
-
|
|
61
|
-
// A skill added to the list since last cycle may have server files older than the cursor; re-read from the start.
|
|
62
|
-
if ([...skills].some((skill) => !(state.skills ?? []).includes(skill))) state.cursor = 0;
|
|
63
|
-
state.skills = [...skills].sort();
|
|
64
|
-
// A skill removed from the list stops being tracked here. Left in `known`, its files would look deleted
|
|
65
|
-
// from this folder and the push would delete them on every machine.
|
|
66
|
-
for (const path of Object.keys(state.known)) {
|
|
67
|
-
if (!skills.has(skillOf(path)) || path.split("/").some(isLock)) delete state.known[path];
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const present = new Set(listLocalFiles(folder, config.exclude).filter((path) => skills.has(skillOf(path))));
|
|
71
|
-
// Files deleted here since the last cycle. When they were deleted is not recorded anywhere, so the
|
|
72
|
-
// deletion counts as an edit made now: the pull leaves these paths alone and the push deletes them.
|
|
73
|
-
const deletedHere = new Set(Object.keys(state.known).filter((path) => !present.has(path)));
|
|
74
|
-
|
|
75
|
-
const ctx: Cycle = { config, folder, state, report, skills };
|
|
76
|
-
await pull(ctx, deletedHere, present);
|
|
77
|
-
await push(ctx, present);
|
|
78
|
-
return report;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
interface Cycle {
|
|
82
|
-
readonly config: Config;
|
|
83
|
-
readonly folder: string;
|
|
84
|
-
readonly state: State;
|
|
85
|
-
readonly report: Report;
|
|
86
|
-
readonly skills: ReadonlySet<string>;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** When this file was last edited here, to the millisecond the server stores. */
|
|
90
|
-
const editedAt = (file: string): number => Math.floor(statSync(file).mtimeMs);
|
|
91
|
-
|
|
92
|
-
async function pull(ctx: Cycle, deletedHere: ReadonlySet<string>, present: Set<string>): Promise<void> {
|
|
93
|
-
const { config, folder, state, report } = ctx;
|
|
94
|
-
const body = await (await call(config, `/files?since=${state.cursor}`)).json() as ListFilesResponse;
|
|
95
|
-
|
|
96
|
-
for (const file of body.files) {
|
|
97
|
-
// The server is not trusted to supply a path either: one bad row would otherwise write outside the
|
|
98
|
-
// skills directory on every machine that syncs.
|
|
99
|
-
const badPath = invalidPathReason(file.path);
|
|
100
|
-
if (badPath) {
|
|
101
|
-
report.rejected.push(`${file.path} (${badPath})`);
|
|
102
|
-
continue;
|
|
103
|
-
}
|
|
104
|
-
if (!ctx.skills.has(skillOf(file.path))) continue;
|
|
105
|
-
// Never written here: the file listing skips lock names, so a pulled one would read as deleted next cycle.
|
|
106
|
-
if (file.path.split("/").some(isLock)) continue;
|
|
107
|
-
// Deleted here, which is newer than anything the server has; the push sends the deletion.
|
|
108
|
-
if (deletedHere.has(file.path)) continue;
|
|
109
|
-
|
|
110
|
-
const local = join(folder, file.path);
|
|
111
|
-
const exists = existsSync(local);
|
|
112
|
-
const localHash = exists ? hashBytes(readFileSync(local)) : undefined;
|
|
113
|
-
if (localHash === (file.hash ?? undefined)) {
|
|
114
|
-
if (file.hash === null) delete state.known[file.path];
|
|
115
|
-
else state.known[file.path] = file.hash;
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
// Edited here since this folder last agreed with the server, and later than the server's version:
|
|
119
|
-
// this folder's edit wins, and the push sends it.
|
|
120
|
-
if (exists && localHash !== state.known[file.path] && editedAt(local) > file.editedAt) continue;
|
|
121
|
-
|
|
122
|
-
await apply(ctx, file, present);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
state.cursor = body.cursor;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
async function push(ctx: Cycle, present: Set<string>): Promise<void> {
|
|
129
|
-
const { config, folder, state, report } = ctx;
|
|
130
|
-
for (const path of [...present]) {
|
|
131
|
-
const file = join(folder, path);
|
|
132
|
-
const bytes = readFileSync(file);
|
|
133
|
-
const hash = hashBytes(bytes);
|
|
134
|
-
if (state.known[path] === hash) continue;
|
|
135
|
-
const later = await put(config, { path, hash, content: Buffer.from(bytes).toString("base64"), editedAt: editedAt(file) });
|
|
136
|
-
if (later === undefined) {
|
|
137
|
-
state.known[path] = hash;
|
|
138
|
-
report.pushed.push(path);
|
|
139
|
-
} else {
|
|
140
|
-
await apply(ctx, { path, ...later }, present);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// A path this folder agreed on that is no longer on disk was deleted here. The server keeps the
|
|
145
|
-
// deletion, or the next machine to sync would upload the file again.
|
|
146
|
-
for (const path of Object.keys(state.known)) {
|
|
147
|
-
if (present.has(path)) continue;
|
|
148
|
-
const later = await put(config, { path, hash: null, content: null, editedAt: Date.now() });
|
|
149
|
-
if (later === undefined) {
|
|
150
|
-
delete state.known[path];
|
|
151
|
-
report.pushed.push(`${path} (deleted)`);
|
|
152
|
-
} else {
|
|
153
|
-
await apply(ctx, { path, ...later }, present);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** The server's version of a file, as it answers a refused write. */
|
|
159
|
-
interface ServerVersion {
|
|
160
|
-
readonly hash: string | null;
|
|
161
|
-
readonly editedAt: number;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Writes the server's version of a file here: its bytes with its edit time, or a deletion. Used by the
|
|
166
|
-
* pull, and by the push when the server refuses a write because it holds a later edit, so a refused write
|
|
167
|
-
* settles at once rather than waiting for a pull that may never list the file again.
|
|
168
|
-
*/
|
|
169
|
-
async function apply(ctx: Cycle, file: ServerVersion & { readonly path: string }, present: Set<string>): Promise<void> {
|
|
170
|
-
const { config, folder, state, report } = ctx;
|
|
171
|
-
const local = join(folder, file.path);
|
|
172
|
-
if (file.hash === null) {
|
|
173
|
-
rmSync(local, { force: true });
|
|
174
|
-
removeEmptyParents(folder, local);
|
|
175
|
-
present.delete(file.path);
|
|
176
|
-
delete state.known[file.path];
|
|
177
|
-
report.deletedLocally.push(file.path);
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
const content = new Uint8Array(await (await call(config, `/content/${file.hash}`)).arrayBuffer());
|
|
181
|
-
mkdirSync(dirname(local), { recursive: true });
|
|
182
|
-
writeFileSync(local, content);
|
|
183
|
-
utimesSync(local, new Date(), new Date(file.editedAt));
|
|
184
|
-
state.known[file.path] = file.hash;
|
|
185
|
-
present.add(file.path);
|
|
186
|
-
report.pulled.push(file.path);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** A deleted skill leaves no empty directory behind, which would still show up as a skill. */
|
|
190
|
-
function removeEmptyParents(folder: string, file: string): void {
|
|
191
|
-
for (let dir = dirname(file); dir !== folder && dir.startsWith(folder); dir = dirname(dir)) {
|
|
192
|
-
if (readdirSync(dir).length > 0) return;
|
|
193
|
-
rmdirSync(dir);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** Undefined when the server took the write; otherwise the later version it holds instead. */
|
|
198
|
-
async function put(config: Config, body: Omit<PutFileRequest, "machine">): Promise<ServerVersion | undefined> {
|
|
199
|
-
const request: PutFileRequest = { ...body, machine: config.machine };
|
|
200
|
-
const response = await fetchServer(config, "/files", {
|
|
201
|
-
method: "PUT",
|
|
202
|
-
headers: { "content-type": "application/json" },
|
|
203
|
-
body: JSON.stringify(request),
|
|
204
|
-
});
|
|
205
|
-
if (response.status === 409) {
|
|
206
|
-
const current = await response.json() as { currentHash: string | null; currentEditedAt: number };
|
|
207
|
-
return { hash: current.currentHash, editedAt: current.currentEditedAt };
|
|
208
|
-
}
|
|
209
|
-
if (!response.ok) throw new Error(`PUT /files ${body.path}: ${response.status} ${await response.text()}`);
|
|
210
|
-
return undefined;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
async function call(config: Config, path: string): Promise<Response> {
|
|
214
|
-
const response = await fetchServer(config, path);
|
|
215
|
-
if (!response.ok) throw new Error(`GET ${path}: ${response.status} ${await response.text()}`);
|
|
216
|
-
return response;
|
|
217
|
-
}
|