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

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 (152) hide show
  1. package/README.md +214 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +34 -0
  4. package/bin/skill-sync-daemon +34 -0
  5. package/dist/daemons/skill-sync-daemon.js +642 -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 +102 -0
  12. package/dist/internal/agents/agent-tool.js.map +1 -0
  13. package/dist/internal/agents/claude.js +424 -0
  14. package/dist/internal/agents/claude.js.map +1 -0
  15. package/dist/internal/agents/codex.js +270 -0
  16. package/dist/internal/agents/codex.js.map +1 -0
  17. package/dist/internal/agents/command.js +219 -0
  18. package/dist/internal/agents/command.js.map +1 -0
  19. package/dist/internal/agents/grok.js +170 -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 +185 -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 +68 -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 +80 -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/skill-refinement/evals/cases.js +143 -0
  44. package/dist/internal/skill-refinement/evals/cases.js.map +1 -0
  45. package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  46. package/dist/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  47. package/dist/internal/skill-refinement/feedback/import-legacy.js +13 -0
  48. package/dist/internal/skill-refinement/feedback/import-legacy.js.map +1 -0
  49. package/dist/internal/skill-refinement/feedback/intake.js +52 -0
  50. package/dist/internal/skill-refinement/feedback/intake.js.map +1 -0
  51. package/dist/internal/skill-refinement/feedback/managed-intake.js +19 -0
  52. package/dist/internal/skill-refinement/feedback/managed-intake.js.map +1 -0
  53. package/dist/internal/skill-refinement/feedback/outbox.js +44 -0
  54. package/dist/internal/skill-refinement/feedback/outbox.js.map +1 -0
  55. package/dist/internal/skill-refinement/jev/impl.js +63 -0
  56. package/dist/internal/skill-refinement/jev/impl.js.map +1 -0
  57. package/dist/internal/skill-refinement/jev/interface.js +6 -0
  58. package/dist/internal/skill-refinement/jev/interface.js.map +1 -0
  59. package/dist/internal/skill-refinement/managed-daemon.js +30 -0
  60. package/dist/internal/skill-refinement/managed-daemon.js.map +1 -0
  61. package/dist/internal/skill-refinement/managed-worker-credentials.js +60 -0
  62. package/dist/internal/skill-refinement/managed-worker-credentials.js.map +1 -0
  63. package/dist/internal/skill-refinement/managed-worker-files.js +25 -0
  64. package/dist/internal/skill-refinement/managed-worker-files.js.map +1 -0
  65. package/dist/internal/skill-refinement/managed-worker-loop.js +36 -0
  66. package/dist/internal/skill-refinement/managed-worker-loop.js.map +1 -0
  67. package/dist/internal/skill-refinement/organization-site.js +13 -0
  68. package/dist/internal/skill-refinement/organization-site.js.map +1 -0
  69. package/dist/internal/skill-refinement/paths.js +62 -0
  70. package/dist/internal/skill-refinement/paths.js.map +1 -0
  71. package/dist/internal/skill-refinement/platform.js +67 -0
  72. package/dist/internal/skill-refinement/platform.js.map +1 -0
  73. package/dist/internal/skill-refinement/service.js +365 -0
  74. package/dist/internal/skill-refinement/service.js.map +1 -0
  75. package/dist/internal/skill-refinement/skills/skill-text.js +219 -0
  76. package/dist/internal/skill-refinement/skills/skill-text.js.map +1 -0
  77. package/dist/internal/skill-refinement/workflow/retry.js +44 -0
  78. package/dist/internal/skill-refinement/workflow/retry.js.map +1 -0
  79. package/dist/internal/skill-refinement/workflow/skill-refinement.js +690 -0
  80. package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +1 -0
  81. package/dist/internal/skill-refinement/writer/impl.js +2 -0
  82. package/dist/internal/skill-refinement/writer/impl.js.map +1 -0
  83. package/dist/internal/skill-refinement/writer/interface.js +2 -0
  84. package/dist/internal/skill-refinement/writer/interface.js.map +1 -0
  85. package/dist/internal/sync.js +182 -0
  86. package/dist/internal/sync.js.map +1 -0
  87. package/dist/internal/wire.js +31 -0
  88. package/dist/internal/wire.js.map +1 -0
  89. package/dist/internal/writer/claude.js +84 -0
  90. package/dist/internal/writer/claude.js.map +1 -0
  91. package/dist/internal/writer/codex.js +102 -0
  92. package/dist/internal/writer/codex.js.map +1 -0
  93. package/dist/internal/writer/interface.js +6 -0
  94. package/dist/internal/writer/interface.js.map +1 -0
  95. package/dist/internal/writer/live.js +13 -0
  96. package/dist/internal/writer/live.js.map +1 -0
  97. package/dist/internal/writer/reset.js +38 -0
  98. package/dist/internal/writer/reset.js.map +1 -0
  99. package/dist/internal/writer/selection.js +79 -0
  100. package/dist/internal/writer/selection.js.map +1 -0
  101. package/package.json +45 -11
  102. package/postinstall.cjs +663 -0
  103. package/src/daemons/skill-sync-daemon.ts +647 -0
  104. package/src/entrypoints/skill-sync.ts +12 -0
  105. package/src/index.ts +15 -0
  106. package/src/internal/agents/agent-tool.ts +149 -0
  107. package/src/internal/agents/claude.ts +442 -0
  108. package/src/internal/agents/codex.ts +288 -0
  109. package/src/internal/agents/command.ts +257 -0
  110. package/src/internal/agents/grok.ts +174 -0
  111. package/src/internal/agents/index.ts +74 -0
  112. package/src/internal/cli.ts +217 -0
  113. package/src/internal/config.ts +172 -0
  114. package/src/internal/control.ts +157 -0
  115. package/src/internal/daemon-control/impl.ts +80 -0
  116. package/src/internal/daemon-control/interface.ts +40 -0
  117. package/src/internal/folders.ts +50 -0
  118. package/src/internal/local-skills.ts +58 -0
  119. package/src/internal/path.ts +32 -0
  120. package/src/internal/server.ts +76 -0
  121. package/src/internal/skill-check.ts +97 -0
  122. package/src/internal/skill-refinement/evals/cases.ts +167 -0
  123. package/src/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  124. package/src/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  125. package/src/internal/skill-refinement/feedback/import-legacy.ts +16 -0
  126. package/src/internal/skill-refinement/feedback/intake.ts +66 -0
  127. package/src/internal/skill-refinement/feedback/managed-intake.ts +19 -0
  128. package/src/internal/skill-refinement/feedback/outbox.ts +50 -0
  129. package/src/internal/skill-refinement/jev/impl.ts +76 -0
  130. package/src/internal/skill-refinement/jev/interface.ts +56 -0
  131. package/src/internal/skill-refinement/managed-daemon.ts +38 -0
  132. package/src/internal/skill-refinement/managed-worker-credentials.ts +59 -0
  133. package/src/internal/skill-refinement/managed-worker-files.ts +24 -0
  134. package/src/internal/skill-refinement/managed-worker-loop.ts +46 -0
  135. package/src/internal/skill-refinement/organization-site.ts +15 -0
  136. package/src/internal/skill-refinement/paths.ts +87 -0
  137. package/src/internal/skill-refinement/platform.ts +71 -0
  138. package/src/internal/skill-refinement/service.ts +418 -0
  139. package/src/internal/skill-refinement/skills/skill-text.ts +292 -0
  140. package/src/internal/skill-refinement/workflow/retry.ts +61 -0
  141. package/src/internal/skill-refinement/workflow/skill-refinement.ts +777 -0
  142. package/src/internal/skill-refinement/writer/impl.ts +1 -0
  143. package/src/internal/skill-refinement/writer/interface.ts +1 -0
  144. package/src/internal/sync.ts +216 -0
  145. package/src/internal/wire.ts +439 -0
  146. package/src/internal/writer/claude.ts +98 -0
  147. package/src/internal/writer/codex.ts +93 -0
  148. package/src/internal/writer/interface.ts +48 -0
  149. package/src/internal/writer/live.ts +19 -0
  150. package/src/internal/writer/reset.ts +34 -0
  151. package/src/internal/writer/selection.ts +84 -0
  152. package/multi-call-binary +0 -4
@@ -0,0 +1,174 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { join } from "node:path";
4
+ import { Result, Schema } from "effect";
5
+ import type { AccountLimits, LocalUse } from "../wire";
6
+ import { CLI_TIMEOUT_MS, DAY_MS, PERIOD_DAYS, USD_MICROS, homesNamed, inSessionOrder, isDirectory, parseJson, unknownShape, windowName, type AgentTool } from "./agent-tool";
7
+ import { askJsonRpc, type RpcResponse } from "./command";
8
+
9
+ /**
10
+ * Grok. Each account is a `GROK_HOME` (`~/.grok`, `~/.grok-<name>`), and Grok's docs name its `skills`
11
+ * folder as where it reads a user's skills. Grok also reads `~/.agents/skills`, undocumented; a skill in
12
+ * both loads once, from the Grok home (checked with `grok inspect`, Grok 1.0.70).
13
+ *
14
+ * - Account: the plan allowance comes from `grok agent stdio`, the same way Grok's `/usage` screen gets it
15
+ * (`readGrokLimits`). `grok` has no command that says who is signed in, so no account is shown.
16
+ * - This machine: what `grok usage <session-id>` prints, the command Grok's docs say to use instead of
17
+ * reading session files: each session's token and cost totals (`costUsdTicks`, 10^10 per US dollar),
18
+ * summed over sessions active in the last `PERIOD_DAYS` days. A session's totals include history it
19
+ * inherited by resume or fork, so a fork counts that part twice.
20
+ */
21
+ export const grok: AgentTool = {
22
+ tool: "grok",
23
+ skillsFolders: (home) => homesNamed(home, "grok").map((account) => join(account, "skills")),
24
+ accounts: (home) => homesNamed(home, "grok"),
25
+ readAccount: async (account, { home, now }) => ({ identity: null, limits: await readGrokLimits({ account, home, now }) }),
26
+ readLocalUse: (account, _home, now) => readGrok(account, now),
27
+ };
28
+
29
+ // ── The account ─────────────────────────────────────────────────────────────────────────────────────
30
+
31
+ const REQUEST_BILLING = 2;
32
+
33
+ /**
34
+ * `_x.ai/billing`'s answer, as Grok 1.0.70 gives it (its `extensions/billing.rs`): the share of the plan's
35
+ * allowance used in the current period, which is a week on SuperGrok plans.
36
+ */
37
+ const BillingAnswer = Schema.Struct({
38
+ config: Schema.Struct({
39
+ creditUsagePercent: Schema.Finite,
40
+ currentPeriod: Schema.Struct({ start: Schema.String, end: Schema.String }),
41
+ }),
42
+ });
43
+
44
+ /**
45
+ * The plan allowance, as Grok's `/usage` screen shows it: that screen asks the agent `_x.ai/billing` over the
46
+ * Agent Client Protocol, so this asks the same of `grok agent stdio`, which fetches it from grok.com with the
47
+ * account's own sign-in. Undocumented, so a changed answer reads as unknown rather than as a guess.
48
+ */
49
+ async function readGrokLimits(input: { readonly account: string; readonly home: string; readonly now: number }): Promise<AccountLimits> {
50
+ const command = join(input.account, "bin", "grok");
51
+ if (!existsSync(command)) return { state: "unknown", reason: `Grok's command is not at ${command}` };
52
+ const asked = await askJsonRpc({
53
+ name: "grok agent stdio",
54
+ command,
55
+ args: ["agent", "--no-leader", "stdio"],
56
+ env: { ...process.env, GROK_HOME: input.account },
57
+ cwd: input.home,
58
+ timeoutMs: CLI_TIMEOUT_MS,
59
+ messages: [
60
+ { id: 1, method: "initialize", params: { protocolVersion: 1, clientCapabilities: {} } },
61
+ { id: REQUEST_BILLING, method: "_x.ai/billing", params: {} },
62
+ ],
63
+ });
64
+ if (asked.kind === "failed") return { state: "unknown", reason: asked.reason };
65
+ return parseBillingAnswer(asked.answers.get(REQUEST_BILLING)!, input.now);
66
+ }
67
+
68
+ export function parseBillingAnswer(answer: RpcResponse, now: number): AccountLimits {
69
+ if (answer.error !== undefined) return { state: "unknown", reason: `\`_x.ai/billing\` failed: ${answer.error.message.slice(0, 160)}` };
70
+ const decoded = Schema.decodeUnknownResult(BillingAnswer)(answer.result);
71
+ if (Result.isFailure(decoded)) return unknownShape("Grok's `_x.ai/billing` answer", decoded.failure.issue);
72
+ const { creditUsagePercent, currentPeriod } = decoded.success.config;
73
+ const start = Date.parse(currentPeriod.start);
74
+ const end = Date.parse(currentPeriod.end);
75
+ if (!Number.isFinite(start) || !Number.isFinite(end)) {
76
+ return { state: "unknown", reason: "Grok's `_x.ai/billing` answer changed shape: its period's start or end is not a time" };
77
+ }
78
+ const minutes = Math.round((end - start) / 60_000);
79
+ return {
80
+ state: "reading",
81
+ asOf: now,
82
+ source: "account",
83
+ windows: [{ name: windowName(minutes), minutes, usedPercent: creditUsagePercent, resetsAt: end }],
84
+ };
85
+ }
86
+
87
+ // ── This machine ────────────────────────────────────────────────────────────────────────────────────
88
+
89
+ const GrokUsage = Schema.Struct({
90
+ sessionId: Schema.String,
91
+ updatedAt: Schema.String,
92
+ session: Schema.Struct({ costUsdTicks: Schema.Finite, totalTokens: Schema.Finite }),
93
+ });
94
+ const TICKS_PER_USD = 1e10;
95
+ /** `grok usage` reads one session's file and exits; this bounds a hung one. */
96
+ const COMMAND_TIMEOUT_MS = 10_000;
97
+
98
+ export type SessionTotals =
99
+ | { readonly kind: "totals"; readonly usd: number; readonly updatedAt: number }
100
+ /** A session with no turn yet: `grok usage` exits 1 saying "No usage recorded". */
101
+ | { readonly kind: "empty" }
102
+ | { readonly kind: "failed"; readonly reason: string };
103
+
104
+ /** A session's totals are fetched again only when its directory changed: each `grok usage` run takes most of a second. */
105
+ const sessionCache = new Map<string, { readonly modifiedAt: number; readonly totals: SessionTotals }>();
106
+
107
+ function readGrok(account: string, now: number): LocalUse {
108
+ const command = join(account, "bin", "grok");
109
+ const sessions = sessionDirs(join(account, "sessions"), now - PERIOD_DAYS * DAY_MS);
110
+ if (sessions.length === 0) return { state: "none" };
111
+ if (!existsSync(command)) return { state: "unknown", reason: `Grok's command is not at ${command}` };
112
+
113
+ const totals: (Extract<SessionTotals, { kind: "totals" }> & { readonly id: string })[] = [];
114
+ for (const session of sessions) {
115
+ const cached = sessionCache.get(session.path);
116
+ const result = cached !== undefined && cached.modifiedAt === session.modifiedAt
117
+ ? cached.totals
118
+ : runGrokUsage(command, account, session.id);
119
+ // A failure is asked again next time rather than kept until the session changes.
120
+ if (result.kind !== "failed") sessionCache.set(session.path, { modifiedAt: session.modifiedAt, totals: result });
121
+ if (result.kind === "failed") return { state: "unknown", reason: result.reason };
122
+ if (result.kind === "totals") totals.push({ ...result, id: session.id });
123
+ }
124
+ if (totals.length === 0) return { state: "none" };
125
+ return {
126
+ state: "spend",
127
+ periodDays: PERIOD_DAYS,
128
+ ...USD_MICROS,
129
+ sessions: inSessionOrder(totals.map((session) => ({ id: session.id, amount: Math.round(session.usd * 10 ** USD_MICROS.exponent), lastActiveAt: session.updatedAt }))),
130
+ partial: false,
131
+ provider: null,
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Sessions active since `since`: `sessions/<encoded working directory>/<session id>/`, whose modification
137
+ * time moves whenever Grok writes the session's files.
138
+ */
139
+ function sessionDirs(dir: string, since: number): { readonly id: string; readonly path: string; readonly modifiedAt: number }[] {
140
+ if (!isDirectory(dir)) return [];
141
+ return readdirSync(dir).flatMap((project) => {
142
+ const projectDir = join(dir, project);
143
+ if (!isDirectory(projectDir)) return [];
144
+ return readdirSync(projectDir).flatMap((id) => {
145
+ const path = join(projectDir, id);
146
+ if (!/^[0-9a-f-]{36}$/i.test(id) || !isDirectory(path)) return [];
147
+ const modifiedAt = statSync(path).mtimeMs;
148
+ return modifiedAt >= since ? [{ id, path, modifiedAt }] : [];
149
+ });
150
+ });
151
+ }
152
+
153
+ export function runGrokUsage(command: string, account: string, sessionId: string): SessionTotals {
154
+ const run = spawnSync(command, ["usage", sessionId], {
155
+ env: { ...process.env, GROK_HOME: account },
156
+ encoding: "utf-8",
157
+ timeout: COMMAND_TIMEOUT_MS,
158
+ });
159
+ if (run.status === 0) return parseGrokUsage(run.stdout);
160
+ const stderr = (run.stderr ?? "").trim();
161
+ if (stderr.includes("No usage recorded")) return { kind: "empty" };
162
+ return { kind: "failed", reason: `\`grok usage\` failed: ${run.error?.message ?? (stderr.slice(0, 160) || `exit ${run.status}`)}` };
163
+ }
164
+
165
+ export function parseGrokUsage(stdout: string): SessionTotals {
166
+ const decoded = Schema.decodeUnknownResult(GrokUsage)(parseJson(stdout));
167
+ if (Result.isFailure(decoded)) {
168
+ const reading = unknownShape("`grok usage` output", decoded.failure.issue);
169
+ return { kind: "failed", reason: reading.state === "unknown" ? reading.reason : "" };
170
+ }
171
+ const updatedAt = Date.parse(decoded.success.updatedAt);
172
+ if (!Number.isFinite(updatedAt)) return { kind: "failed", reason: "`grok usage` output changed shape: updatedAt is not a time" };
173
+ return { kind: "totals", usd: decoded.success.session.costUsdTicks / TICKS_PER_USD, updatedAt };
174
+ }
@@ -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,217 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { Data, Effect, Schedule, Stdio, Stream, pipe } from "effect";
4
+ import { Cli, upgrade } from "jive-abstract-library";
5
+ import { name, version } from "../../package.json";
6
+ import { detectFolders } from "./agents";
7
+ import { loadSettings } from "./config";
8
+ import { DaemonFailed } from "./control";
9
+ import { DaemonControl, type DaemonError, type IDaemonControl } from "./daemon-control/interface";
10
+ import { addableSkills, formatSkillCopies, skillCopies } from "./local-skills";
11
+
12
+ /**
13
+ * The CLI that accompanies the daemon: `login`, `logout`, `list`, `add`, `show`, `feedback`, `upgrade` and `version`. Which
14
+ * folders sync is chosen on the dashboard; skills are ticked there too, or added with `add` by the agent that
15
+ * wrote one.
16
+ *
17
+ * The daemon owns the sync token and keeps it in `~/.jive/skill-sync-token.json`. `login`, `logout`, `list`,
18
+ * `add` and `feedback` are requests to it over the control socket; the daemon claims the token from the server itself, so it
19
+ * never passes through here. Tab after `show` lists the synced skills and Tab after `add` the skills that could be
20
+ * added, both asked of the daemon when Tab is pressed.
21
+ */
22
+
23
+ const DASHBOARD = "https://skill-sync.jive.sh/";
24
+
25
+ /** How long Tab waits for the daemon before showing that it did not answer; it never starts one. */
26
+ const TAB_TIME_LIMIT_SECONDS = 3;
27
+
28
+ /** How often a command asks again after starting the daemon, and how many times. */
29
+ const RETRY_INTERVAL = "500 millis";
30
+ const RETRIES = 20;
31
+
32
+ class SkillNotOnThisMachine extends Data.TaggedError("SkillNotOnThisMachine")<{ readonly message: string }> {}
33
+ class FeedbackNotRead extends Data.TaggedError("FeedbackNotRead")<{ readonly message: string }> {}
34
+ class UpgradeFailed extends Data.TaggedError("UpgradeFailed")<{ readonly message: string }> {}
35
+
36
+ export const skillSync = Cli.make("skill-sync", {
37
+ login: Cli.command({
38
+ description: "sign this machine in with your passkey, approved in a browser on this computer or any other; it stays signed in until you log out",
39
+ *run() {
40
+ const machine = yield* withDaemon((daemon) => daemon.login((url) => pipe(
41
+ Effect.log(`Approve this sign-in with your passkey at ${url} (in a browser on this computer or any other, such as your phone). Waiting…`),
42
+ Effect.andThen(Effect.sync(() => openBrowser(url))),
43
+ )));
44
+ yield* Effect.log(`Signed in. ${machine} is syncing; choose what syncs at ${DASHBOARD}`);
45
+ },
46
+ }),
47
+
48
+ logout: Cli.command({
49
+ description: "revoke this machine's token and stop syncing until the next login",
50
+ *run() {
51
+ const revoked = yield* withDaemon((daemon) => daemon.logout());
52
+ yield* Effect.log(revoked ? "Signed out; the token is revoked." : "Signed out locally; the server could not be reached to revoke the token.");
53
+ },
54
+ }),
55
+
56
+ list: Cli.command({
57
+ description: "list the skills that sync, as the server holds them; needs this machine signed in",
58
+ *run() {
59
+ const skills = yield* withDaemon((daemon) => daemon.listSyncedSkills());
60
+ if (skills.length === 0) {
61
+ yield* Effect.log(`No skills sync yet; tick them at ${DASHBOARD}`);
62
+ return;
63
+ }
64
+ const width = Math.max(...skills.map((skill) => skill.name.length));
65
+ for (const skill of skills) {
66
+ const detail = skill.editedAt === null
67
+ ? "no files yet"
68
+ : `${skill.files} ${skill.files === 1 ? "file" : "files"}, last edited ${new Date(skill.editedAt).toLocaleString()} on ${skill.editedBy}`;
69
+ yield* Effect.log(`${skill.name.padEnd(width)} ${detail}`);
70
+ }
71
+ },
72
+ }),
73
+
74
+ add: Cli.choose({
75
+ 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",
76
+ *choices() {
77
+ const synced = (yield* listForTab).map((skill) => skill.name);
78
+ return addableSkills({ folders: detectFolders(), exclude: loadSettings()?.exclude ?? [], synced });
79
+ },
80
+ next: (skill) => Cli.command({
81
+ description: `put ${skill} on the synced list`,
82
+ *run() {
83
+ const result = yield* withDaemon((daemon) => daemon.addSkill(skill));
84
+ yield* Effect.log(result.added ? `Added ${skill} to the synced list.` : `${skill} was already on the synced list.`);
85
+ if (result.syncingFolders.length === 0) {
86
+ 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.`);
87
+ }
88
+ },
89
+ }),
90
+ }),
91
+
92
+ show: Cli.choose({
93
+ description: "print a synced skill's description and where its copies are on this machine",
94
+ *choices() {
95
+ return (yield* listForTab).map((skill) => skill.name);
96
+ },
97
+ next: (skill) => Cli.command({
98
+ description: `print ${skill}'s description and where its copies are on this machine`,
99
+ *run() {
100
+ const folders = detectFolders();
101
+ const copies = skillCopies({ skill, folders });
102
+ if (copies.length === 0) {
103
+ return yield* new SkillNotOnThisMachine({
104
+ message: `no skills folder skill-sync syncs has a "${skill}" folder; it looked in ${folders.join(", ") || "no folders"}`,
105
+ });
106
+ }
107
+ yield* Effect.log(formatSkillCopies(copies));
108
+ },
109
+ }),
110
+ }),
111
+
112
+ feedback: Cli.command({
113
+ description: "hand one feedback item to this machine's skill refinement workflow: `skill-sync feedback <slug> <file>`, a few words naming it and a file holding his exact words and what drew them",
114
+ *run({ args }) {
115
+ const [slug, file] = args;
116
+ if (slug === undefined || file === undefined || args.length > 2) {
117
+ return yield* new FeedbackNotRead({ message: "usage: skill-sync feedback <slug> <file>, a few words naming the item and the file holding it" });
118
+ }
119
+ const text = yield* Effect.try({
120
+ try: () => readFileSync(file, "utf-8"),
121
+ catch: (cause) => new FeedbackNotRead({ message: `could not read ${file}: ${cause instanceof Error ? cause.message : String(cause)}` }),
122
+ });
123
+ if (text.trim() === "") return yield* new FeedbackNotRead({ message: `${file} is empty` });
124
+ const id = yield* withDaemon((daemon) => daemon.addFeedback({ slug, text }));
125
+ yield* Effect.log(`Added ${id} to the skill refinement queue; see it at ${DASHBOARD}#refinement`);
126
+ },
127
+ }),
128
+
129
+ upgrade: Cli.command({
130
+ description: "upgrade skill-sync to the latest version with the package manager that installed it",
131
+ *run() {
132
+ yield* pipe(upgrade({ packageName: name }), Effect.mapError((message) => new UpgradeFailed({ message: `Upgrade failed: ${message}` })));
133
+ },
134
+ }),
135
+
136
+ version: Cli.command({
137
+ description: "print the version of skill-sync installed here",
138
+ *run() {
139
+ yield* Effect.log(version);
140
+ },
141
+ }),
142
+ });
143
+
144
+ /**
145
+ * Runs the CLI on the process's arguments. A command that fails prints why on stderr, alone, and exits 1; usage
146
+ * errors are the library's (`Cli.CliError`, exit 2).
147
+ */
148
+ export function runSkillSync() {
149
+ return pipe(
150
+ Cli.run(skillSync, { version }),
151
+ Effect.catchTags({
152
+ DaemonFailed: report,
153
+ SkillNotOnThisMachine: report,
154
+ FeedbackNotRead: report,
155
+ UpgradeFailed: report,
156
+ }),
157
+ );
158
+ }
159
+
160
+
161
+ function report(error: { readonly message: string }): Effect.Effect<never, Cli.CliError, Stdio.Stdio> {
162
+ return Effect.gen(function* () {
163
+ const stdio = yield* Stdio.Stdio;
164
+ yield* Effect.orDie(Stream.run(Stream.make(`${error.message}\n`), stdio.stderr()));
165
+ return yield* new Cli.CliError({ message: error.message, exitCode: 1 });
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Runs `use` against the daemon. If none is listening (stopped, or never started since the install) this
171
+ * package's registered daemon is started and `use` is tried again for about ten seconds. Tab never comes here.
172
+ */
173
+ function withDaemon<A>(use: (daemon: IDaemonControl) => Effect.fn.Return<A, DaemonError>): Effect.Effect<A, DaemonFailed, DaemonControl> {
174
+ return Effect.gen(function* () {
175
+ const daemon = yield* DaemonControl;
176
+ const attempt = Effect.gen(() => use(daemon));
177
+ return yield* pipe(
178
+ attempt,
179
+ Effect.catchTag("DaemonNotRunning", () => pipe(
180
+ Effect.gen(() => daemon.startDaemon()),
181
+ Effect.andThen(Effect.sleep(RETRY_INTERVAL)),
182
+ Effect.andThen(Effect.retry(attempt, {
183
+ schedule: Schedule.spaced(RETRY_INTERVAL),
184
+ times: RETRIES,
185
+ while: (error) => error._tag === "DaemonNotRunning",
186
+ })),
187
+ Effect.catchTag("DaemonNotRunning", (error) =>
188
+ Effect.fail(new DaemonFailed({ message: `${error.message}. Reinstall skill-sync to register its daemon.` }))),
189
+ )),
190
+ );
191
+ });
192
+ }
193
+
194
+ /**
195
+ * The synced list for Tab: asked of the daemon, which must already be running, within a time limit, so Tab shows
196
+ * why it has nothing to offer rather than hanging.
197
+ */
198
+ const listForTab = pipe(
199
+ Effect.gen(function* () {
200
+ return yield* (yield* DaemonControl).listSyncedSkills();
201
+ }),
202
+ Effect.timeoutOrElse({
203
+ duration: `${TAB_TIME_LIMIT_SECONDS} seconds`,
204
+ orElse: () => Effect.fail(new DaemonFailed({ message: `the skill-sync daemon did not answer within ${TAB_TIME_LIMIT_SECONDS} seconds` })),
205
+ }),
206
+ );
207
+
208
+ function openBrowser(url: string): void {
209
+ const command = process.platform === "darwin" ? "open"
210
+ : process.platform === "win32" ? "cmd"
211
+ : "xdg-open";
212
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
213
+ // A machine with no desktop has no opener: the address printed above is how it signs in.
214
+ const opener = spawn(command, args, { stdio: "ignore", detached: true });
215
+ opener.on("error", () => undefined);
216
+ opener.unref();
217
+ }
@@ -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
+ }