Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): built-in skill updates, skills.sh install counting, MCP bundle-path parity (#3089)

tim-inkeep69df90298d36
diff --git a/.changeset/olive-pianos-shake.md b/.changeset/olive-pianos-shake.md
new file mode 100644
index 000000000..c86a9d5a3
--- /dev/null
+++ b/.changeset/olive-pianos-shake.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Show an Update button on OK's built-in skills, and make `ok init --no-skills` state that it opts out machine-wide.
+
+The built-in skills (`open-knowledge-discovery`, `open-knowledge-write-skill`) had no way to surface an available update. The server already synthesizes their provenance and supports re-pulling them, but the built-in preview tab hardcoded its header actions to nothing, so the hook that checks for updates never mounted. The tab now shows a source link and an Update button when the upstream copy differs. Updates stay manual — built-ins never auto-apply.
+
+`ok init --no-skills` reported `skipped (opted out via --no-skills)`. Nothing was skipped: the decline is recorded against your home directory and both bundles are removed from every user-global skill directory, so running it once in a throwaway project turned the built-ins off for every project on the machine. The summary now says that, and names how to undo it.
+
+`installUserSkill` also enforces the opt-out itself rather than trusting each caller to check first, so a declined bundle can't be reinstalled by a caller that forgets the gate.
diff --git a/.changeset/plenty-hounds-report.md b/.changeset/plenty-hounds-report.md
new file mode 100644
index 000000000..fe46a5a22
--- /dev/null
+++ b/.changeset/plenty-hounds-report.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Count skill installs on skills.sh, and let the MCP verbs reach every file a skill ships.
+
+Installing a skill you found on skills.sh never registered with the marketplace you chose it from, so its install count — the signal its listing ranks on — stayed flat no matter how many people installed through OK. Explore installs now report to skills.sh. So do built-in and starter-pack skills, once per skill per machine, never on the launch reclaim. A hand-typed `owner/repo` is not reported: you never visited the marketplace, so it is not told what you installed. Turn it off in Settings → Preferences, or with `DO_NOT_TRACK` / `DISABLE_TELEMETRY`. Private and local sources are never reported.
+
+Separately, the MCP `write` / `edit` / `delete` verbs and the `skills({ name, file })` read only accepted paths under `references/` or `scripts/`, while an import writes a skill's whole directory verbatim. OK could install a skill and then refuse to open its own files — `mattpocock/skills/grill-me` ships `agents/openai.yaml`. Any path that stays inside the skill dir is now accepted; the traversal, absolute-path and NUL guards are unchanged.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index cbf27ee30..0e028b6fe 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -10,7 +10,7 @@ OpenKnowledge keeps your knowledge base as plain markdown in your own project di
This page lists every one of them: **when** each write happens, **what** it is, and **where** it is written.
<Callout type="info" title="The short version">
- **Nothing leaves your machine by default — except the desktop app's automatic checks.** Diagnostic logs and telemetry stay on your machine. The things that *can* send data off it — semantic search, a diagnostic or bug-report bundle, and GitHub sync — are opt-in or on-demand. The desktop app is the exception: it checks for updates automatically (sending its app version and channel), and on its first launch opens your browser once to check for a pending share link. All of them are listed under [What leaves your machine](#what-leaves-your-machine).
+ **Nothing about your content leaves your machine by default.** Diagnostic logs and telemetry stay on your machine. The things that *can* send data off it — semantic search, a diagnostic or bug-report bundle, and GitHub sync — are opt-in or on-demand. Three automatic exceptions, none of which touch your documents: the desktop app checks for updates (sending its app version and channel), on its first launch it opens your browser once to check for a pending share link, and installing a **published skill** reports that install to skills.sh so the skill's public install count is accurate — the skill's name and source repository, once per skill per machine, and never for a private or local source. All of them are listed under [What leaves your machine](#what-leaves-your-machine), and the skill report can be turned off.
</Callout>
## How to read this page
@@ -275,7 +275,7 @@ In the desktop app you don't need the CLI for finer control. **Settings → AI t
## What leaves your machine
-By default, **nothing.** Everything above is written to your own disk. The only ways data leaves your machine are these — all opt-in or on-demand, except two automatic desktop-app actions (the update check, and a one-time share-link check on first launch):
+None of your content, by default. Everything above is written to your own disk. The only ways data leaves your machine are these — all opt-in or on-demand, except three automatic actions that carry no document content (the desktop update check, a one-time share-link check on first launch, and the skill-install report):
| What | When | Where it goes |
| --- | --- | --- |
@@ -286,6 +286,7 @@ By default, **nothing.** Everything above is written to your own disk. The only
| GitHub sync / share | When you sync, clone, publish, or share | GitHub |
| Update check | Automatically — on launch and periodically while the desktop app runs | OpenKnowledge update service (`openknowledge.ai/updates`), which redirects to GitHub; sends the app version and channel |
| First-launch share check | Once, automatically, on the desktop app's first launch | `openknowledge.ai/continue` — redeems a share link if you installed from one |
+| Skill-install report | Automatically, the first time a published skill is installed on this machine — OpenKnowledge's own built-in and starter-pack skills, and skills you install from a skills.sh listing. Once per skill per machine; never re-sent on a re-run, a reinstall, or an app launch. A skill you install by typing a repository yourself is **not** reported, and neither is a private, local, or internal-hostname source | `add-skill.vercel.sh` — the skill's name, its source repository, and which agent tools it was installed for. No file contents. This is what gives a published skill an accurate install count. Turn it off in **Settings → Preferences**, by setting `telemetry.skillInstallReports.enabled: false`, or with `DO_NOT_TRACK=1` / `DISABLE_TELEMETRY=1` |
| npm/`npx` fetch | During install (CLI) | The npm registry |
Local diagnostic logs and telemetry are scrubbed of credential-bearing attributes and never sent anywhere on their own.
diff --git a/packages/app/src/components/SkillPreviewTab.builtin-actions.dom.test.tsx b/packages/app/src/components/SkillPreviewTab.builtin-actions.dom.test.tsx
new file mode 100644
index 000000000..914ed48ac
--- /dev/null
+++ b/packages/app/src/components/SkillPreviewTab.builtin-actions.dom.test.tsx
@@ -0,0 +1,93 @@
+/**
+ * Tier-3 RTL mount tests for the built-in skill's header actions.
+ *
+ * This surface existed as `headerActions = builtin ? null : (…)` — the update
+ * machinery was complete on the server and simply had nothing rendering it, so
+ * no built-in could ever show an Update button. These tests pin the two states
+ * that gap produced: an Update button only when upstream actually differs, and
+ * a source link whenever provenance resolves.
+ */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+const useSkillOriginMock = vi.fn();
+vi.mock('@/hooks/use-skill-origin', () => ({
+ useSkillOrigin: (args: unknown) => useSkillOriginMock(args),
+}));
+
+import { BuiltinHeaderActions } from './SkillPreviewTab';
+
+interface OriginState {
+ origin: unknown;
+ github: string | null;
+ updateAvailable: boolean;
+ reimport: () => Promise<void>;
+ reimporting: boolean;
+}
+
+function mockOrigin(overrides: Partial<OriginState> = {}): OriginState {
+ const state: OriginState = {
+ origin: { source: 'inkeep/open-knowledge-skills', importedAt: '2026-07-30T00:00:00.000Z' },
+ github: 'https://github.com/inkeep/open-knowledge-skills',
+ updateAvailable: false,
+ reimport: vi.fn().mockResolvedValue(undefined),
+ reimporting: false,
+ ...overrides,
+ };
+ useSkillOriginMock.mockReturnValue(state);
+ return state;
+}
+
+afterEach(() => {
+ cleanup();
+ useSkillOriginMock.mockReset();
+});
+
+describe('BuiltinHeaderActions', () => {
+ test('renders nothing when provenance has not resolved', () => {
+ mockOrigin({ origin: null, github: null });
+ const { container } = render(<BuiltinHeaderActions scope="global" name="x" />);
+ expect(container.innerHTML).toBe('');
+ });
+
+ test('shows the source link but NO Update button when up to date', () => {
+ mockOrigin({ updateAvailable: false });
+ render(<BuiltinHeaderActions scope="global" name="open-knowledge-discovery" />);
+ expect(screen.getByRole('link').getAttribute('href')).toBe(
+ 'https://github.com/inkeep/open-knowledge-skills',
+ );
+ // The whole point of the gate: Update is not a permanent control.
+ expect(screen.queryByRole('button', { name: /update/i })).toBeNull();
+ });
+
+ test('shows Update when upstream differs, and clicking it re-pulls', async () => {
+ const state = mockOrigin({ updateAvailable: true });
+ render(<BuiltinHeaderActions scope="global" name="open-knowledge-discovery" />);
+ const button = screen.getByRole('button', { name: /^update$/i });
+ await userEvent.click(button);
+ expect(state.reimport).toHaveBeenCalledTimes(1);
+ });
+
+ test('disables the button while a re-pull is in flight', () => {
+ mockOrigin({ updateAvailable: true, reimporting: true });
+ render(<BuiltinHeaderActions scope="global" name="open-knowledge-discovery" />);
+ expect((screen.getByRole('button', { name: /updating/i }) as HTMLButtonElement).disabled).toBe(
+ true,
+ );
+ });
+
+ test('omits the link when no source URL resolves', () => {
+ mockOrigin({ github: null, updateAvailable: true });
+ render(<BuiltinHeaderActions scope="global" name="open-knowledge-discovery" />);
+ expect(screen.queryByRole('link')).toBeNull();
+ expect(screen.getByRole('button', { name: /^update$/i })).toBeTruthy();
+ });
+
+ test('addresses the hook by the skill it was given', () => {
+ mockOrigin();
+ render(<BuiltinHeaderActions scope="project" name="open-knowledge" />);
+ expect(useSkillOriginMock).toHaveBeenCalledWith({ scope: 'project', name: 'open-knowledge' });
+ });
+});
diff --git a/packages/app/src/components/SkillPreviewTab.tsx b/packages/app/src/components/SkillPreviewTab.tsx
index e2b3d7832..35606694f 100644
--- a/packages/app/src/components/SkillPreviewTab.tsx
+++ b/packages/app/src/components/SkillPreviewTab.tsx
@@ -24,6 +24,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { useExplorePreviewInstall } from '@/hooks/use-explore-preview-install';
import { useOpenSkill } from '@/hooks/use-open-skill';
+import { useSkillOrigin } from '@/hooks/use-skill-origin';
import { hashFromSkillFile, hashFromSkillPreview, type SkillPreviewFlavor } from '@/lib/doc-hash';
import { useSkillScopeLabels } from '@/lib/skill-scope';
import { discoverSkillsInSource, fetchSkillDetail } from '@/lib/skills-api';
@@ -56,6 +57,44 @@ interface Props {
*/
const SKILL_MD = 'SKILL.md';
+/**
+ * Provenance link + Update action for one of OK's built-in skills.
+ *
+ * Its own component so `useSkillOrigin` — whose update check dry-run-fetches
+ * upstream — mounts ONLY for built-ins. Hoisting the hook into
+ * {@link SkillPreviewTab} would fire that fetch for every explore/detected
+ * preview too, which have no origin to re-pull.
+ *
+ * Built-ins carry no stored lockfile entry; the server synthesizes one from the
+ * installed content (source `inkeep/open-knowledge-skills`, `autoUpdate: false`),
+ * so the Update button is always a deliberate click and never an auto-apply.
+ * Content stays read-only in-app — a re-pull is the sanctioned way it changes.
+ */
+export function BuiltinHeaderActions({ scope, name }: { scope: SkillScope; name: string }) {
+ const { origin, github, updateAvailable, reimport, reimporting } = useSkillOrigin({
+ scope,
+ name,
+ });
+ if (!origin) return null;
+ return (
+ <div className="flex gap-1">
+ {github ? (
+ <Button variant="ghost" size="sm" className="px-2" asChild>
+ <a href={github} target="_blank" rel="noreferrer">
+ <Trans>Source</Trans>
+ <ArrowUpRightIcon className="h-3.5 w-3.5" />
+ </a>
+ </Button>
+ ) : null}
+ {updateAvailable ? (
+ <Button size="sm" onClick={() => void reimport()} disabled={reimporting}>
+ {reimporting ? <Trans>Updating</Trans> : <Trans>Update</Trans>}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
export function SkillPreviewTab({
flavor,
source,
@@ -136,7 +175,15 @@ export function SkillPreviewTab({
// Explore and plugin-copy previews install through the shared per-agent menu.
// Import is implied on the first destination choice, so opening/cancelling the
// menu never creates a draft or silently privileges one skills root.
- const previewInstall = useExplorePreviewInstall({ source, name, initialScope: targetScope });
+ const previewInstall = useExplorePreviewInstall({
+ source,
+ name,
+ initialScope: targetScope,
+ // Explore rows come from a skills.sh listing the user picked, so the
+ // install counts toward it; the plugin-copy flow's source is a local
+ // harness cache dir and must not be announced to the marketplace.
+ marketplace: flavor === 'explore',
+ });
// The moment the IMPORT completes (bundle on disk), replace this preview with
// the real editable skill tab — the editor-install fan-out keeps running in
// the background and the INSTALLED badge catches up via the list refetch.
@@ -194,7 +241,9 @@ export function SkillPreviewTab({
<Trans>This is a preview of {boldName}. Install it into your agents.</Trans>
);
- const headerActions = builtin ? null : (
+ const headerActions = builtin ? (
+ <BuiltinHeaderActions scope={targetScope} name={name} />
+ ) : (
<>
<div className="flex gap-1">
{detail?.skillsUrl ? (
diff --git a/packages/app/src/components/settings/settings-fields.ts b/packages/app/src/components/settings/settings-fields.ts
index 7a060d874..09efbcd7f 100644
--- a/packages/app/src/components/settings/settings-fields.ts
+++ b/packages/app/src/components/settings/settings-fields.ts
@@ -41,6 +41,14 @@ export const FIELDS_USER_PREFERENCES: FieldDef[] = [
label: msg`Open preview when agent edits`,
description: msg`When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.).`,
},
+ {
+ path: ['telemetry', 'skillInstallReports', 'enabled'],
+ // Behavior first: most people have never visited skills.sh, so leading with
+ // the destination names something they can't evaluate. What it DOES — count
+ // an install so a published skill shows a real number — is the decision.
+ label: msg`Count skill installs publicly`,
+ description: msg`When you install a published skill, tell the skill directory (skills.sh) so its install count is accurate. Sends the skill name, its source repository, and which agent tools it went to — never file contents, and never for a skill from a private, local, or hand-typed source. Once per skill per machine.`,
+ },
];
// The color-theme picker is a theme "plugin": it lives in the Plugins menu
diff --git a/packages/app/src/hooks/use-explore-preview-install.ts b/packages/app/src/hooks/use-explore-preview-install.ts
index 34b7c86e4..3aceaab1f 100644
--- a/packages/app/src/hooks/use-explore-preview-install.ts
+++ b/packages/app/src/hooks/use-explore-preview-install.ts
@@ -20,10 +20,15 @@ export function useExplorePreviewInstall({
source,
name,
initialScope,
+ marketplace,
}: {
source: string;
name: string;
initialScope: SkillScope;
+ /** The source is a skills.sh listing (Explore), so the install is reported to
+ * skills.sh and counts toward that listing. False for the plugin-copy flow,
+ * whose source is a local harness cache dir. */
+ marketplace?: boolean;
}): {
scope: SkillScope;
setScope: (s: SkillScope) => void;
@@ -55,18 +60,22 @@ export function useExplorePreviewInstall({
// set-exact; custom-path places): the default-editor auto-projection would
// silently install into editors the user never picked.
const importScope = scope;
- const pending = importSkill({ source, skill: name, scope: importScope, install: false }).then(
- (res) => {
- if (!res.ok) {
- toast.error(t`Install failed: ${res.error}`);
- return null;
- }
- importedNameRef.current = res.name;
- importedScopeRef.current = importScope;
- setImportedName(res.name);
- return res.name;
- },
- );
+ const pending = importSkill({
+ source,
+ skill: name,
+ scope: importScope,
+ install: false,
+ ...(marketplace ? { marketplace: true } : {}),
+ }).then((res) => {
+ if (!res.ok) {
+ toast.error(t`Install failed: ${res.error}`);
+ return null;
+ }
+ importedNameRef.current = res.name;
+ importedScopeRef.current = importScope;
+ setImportedName(res.name);
+ return res.name;
+ });
importPromiseRef.current = pending;
const result = await pending;
importPromiseRef.current = null;
diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.ts
index 92268a593..980f6fcf7 100644
--- a/packages/app/src/lib/skills-api.ts
+++ b/packages/app/src/lib/skills-api.ts
@@ -285,6 +285,10 @@ export async function importSkill(input: {
/** false = import only, no default-editor auto-projection (the caller
* installs explicitly afterwards). */
install?: boolean;
+ /** The source is a skills.sh listing the user chose (Explore), so the install
+ * is reported to skills.sh and counts toward that listing. Never set for a
+ * hand-entered source. */
+ marketplace?: boolean;
}): Promise<
| {
ok: true;
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 0dab4a1f6..f98e4a937 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -185,6 +185,7 @@
"2hYmUH": ["[email protected]"],
"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Enter a valid URL (for example https://api.openai.com/v1)."],
+ "2jUGEP": ["Count skill installs publicly"],
"2m_bmh": [["label"], " (", ["0"], ")"],
"2myNzt": ["We've filed it with the team and attached your logs."],
"2n3oDU": [
@@ -1435,6 +1436,9 @@
"NnQapF": ["Open with AI ", ["targetDisplayName"]],
"NpC29w": ["Create a new list item from the current list item."],
"NrFwux": ["Failed to save content rules — ", ["0"]],
+ "Ns0z5o": [
+ "When you install a published skill, tell the skill directory (skills.sh) so its install count is accurate. Sends the skill name, its source repository, and which agent tools it went to — never file contents, and never for a skill from a private, local, or hand-typed source. Once per skill per machine."
+ ],
"Nu4DdT": ["Sync"],
"Nu4oKW": ["Description"],
"NuH1jp": ["Public repository"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 94a3d00e5..66334f71e 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -3234,6 +3234,10 @@ msgstr "Couldn't update skills sharing — {detail}."
msgid "Couldn't work out where to send the comments — they stay queued."
msgstr "Couldn't work out where to send the comments — they stay queued."
+#: src/components/settings/settings-fields.ts
+msgid "Count skill installs publicly"
+msgstr "Count skill installs publicly"
+
#: src/components/ConsentDialogBody.tsx
msgid "Counting markdown files"
msgstr "Counting markdown files"
@@ -11337,6 +11341,7 @@ msgid "Up to date"
msgstr "Up to date"
#: src/components/SkillOriginInline.tsx
+#: src/components/SkillPreviewTab.tsx
msgid "Update"
msgstr "Update"
@@ -11390,6 +11395,7 @@ msgid "Updates from the source apply automatically (unless edited locally)"
msgstr "Updates from the source apply automatically (unless edited locally)"
#: src/components/SkillOriginInline.tsx
+#: src/components/SkillPreviewTab.tsx
#: src/components/SkillUpdateConflictDialog.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Updating"
@@ -11745,6 +11751,10 @@ msgstr "When the agent runs its scheduled work."
msgid "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
msgstr "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
+#: src/components/settings/settings-fields.ts
+msgid "When you install a published skill, tell the skill directory (skills.sh) so its install count is accurate. Sends the skill name, its source repository, and which agent tools it went to — never file contents, and never for a skill from a private, local, or hand-typed source. Once per skill per machine."
+msgstr "When you install a published skill, tell the skill directory (skills.sh) so its install count is accurate. Sends the skill name, its source repository, and which agent tools it went to — never file contents, and never for a skill from a private, local, or hand-typed source. Once per skill per machine."
+
#: src/components/settings/AttachmentsSection.tsx
msgid "Where newly added attachments are placed."
msgstr "Where newly added attachments are placed."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 4c40c9515..694990fae 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -185,6 +185,7 @@
"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],
"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Ēńţēŕ à vàĺĩď ŨŔĹ (ƒōŕ ēxàḿƥĺē ĥţţƥś://àƥĩ.ōƥēńàĩ.ćōḿ/v1)."],
+ "2jUGEP": ["Ćōũńţ śķĩĺĺ ĩńśţàĺĺś ƥũƀĺĩćĺŷ"],
"2m_bmh": [["label"], " (", ["0"], ")"],
"2myNzt": ["Ŵē'vē ƒĩĺēď ĩţ ŵĩţĥ ţĥē ţēàḿ àńď àţţàćĥēď ŷōũŕ ĺōĝś."],
"2n3oDU": [
@@ -1435,6 +1436,9 @@
"NnQapF": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"]],
"NpC29w": ["Ćŕēàţē à ńēŵ ĺĩśţ ĩţēḿ ƒŕōḿ ţĥē ćũŕŕēńţ ĺĩśţ ĩţēḿ."],
"NrFwux": ["Ƒàĩĺēď ţō śàvē ćōńţēńţ ŕũĺēś — ", ["0"]],
+ "Ns0z5o": [
+ "Ŵĥēń ŷōũ ĩńśţàĺĺ à ƥũƀĺĩśĥēď śķĩĺĺ, ţēĺĺ ţĥē śķĩĺĺ ďĩŕēćţōŕŷ (śķĩĺĺś.śĥ) śō ĩţś ĩńśţàĺĺ ćōũńţ ĩś àććũŕàţē. Śēńďś ţĥē śķĩĺĺ ńàḿē, ĩţś śōũŕćē ŕēƥōśĩţōŕŷ, àńď ŵĥĩćĥ àĝēńţ ţōōĺś ĩţ ŵēńţ ţō — ńēvēŕ ƒĩĺē ćōńţēńţś, àńď ńēvēŕ ƒōŕ à śķĩĺĺ ƒŕōḿ à ƥŕĩvàţē, ĺōćàĺ, ōŕ ĥàńď-ţŷƥēď śōũŕćē. Ōńćē ƥēŕ śķĩĺĺ ƥēŕ ḿàćĥĩńē."
+ ],
"Nu4DdT": ["Śŷńć"],
"Nu4oKW": ["Ďēśćŕĩƥţĩōń"],
"NuH1jp": ["Ƥũƀĺĩć ŕēƥōśĩţōŕŷ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index f1b23be7e..36be551b1 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -3230,6 +3230,10 @@ msgstr ""
msgid "Couldn't work out where to send the comments — they stay queued."
msgstr ""
+#: src/components/settings/settings-fields.ts
+msgid "Count skill installs publicly"
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "Counting markdown files"
msgstr ""
@@ -11333,6 +11337,7 @@ msgid "Up to date"
msgstr ""
#: src/components/SkillOriginInline.tsx
+#: src/components/SkillPreviewTab.tsx
msgid "Update"
msgstr ""
@@ -11386,6 +11391,7 @@ msgid "Updates from the source apply automatically (unless edited locally)"
msgstr ""
#: src/components/SkillOriginInline.tsx
+#: src/components/SkillPreviewTab.tsx
#: src/components/SkillUpdateConflictDialog.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Updating"
@@ -11741,6 +11747,10 @@ msgstr ""
msgid "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
msgstr ""
+#: src/components/settings/settings-fields.ts
+msgid "When you install a published skill, tell the skill directory (skills.sh) so its install count is accurate. Sends the skill name, its source repository, and which agent tools it went to — never file contents, and never for a skill from a private, local, or hand-typed source. Once per skill per machine."
+msgstr ""
+
#: src/components/settings/AttachmentsSection.tsx
msgid "Where newly added attachments are placed."
msgstr ""
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index aba0f7421..98e13f39c 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -2215,13 +2215,33 @@ export function formatInitResult(result: InitCommandResult, cwd: string): string
);
const target = hostLabels.length > 0 ? hostLabels.join(', ') : 'the shared ~/.agents store';
lines.push(` open-knowledge ${success(`installed for ${target}`)}`);
+ // Disclosed at the point it happens, not only in the docs: this is the
+ // one automatic outbound call `ok init` makes, and a user who cares
+ // should not have to go looking for it.
+ lines.push(
+ ` ${dim('Counted on skills.sh (skill name + source repo, once per machine).')}`,
+ );
+ lines.push(` ${dim('Opt out: DO_NOT_TRACK=1, or Settings → Preferences.')}`);
break;
}
case 'skip-current':
lines.push(` open-knowledge ${success('already installed at current version')}`);
break;
case 'declined':
- lines.push(` open-knowledge ${dim('skipped (opted out via --no-skills)')}`);
+ // NOT "skipped": the decline is recorded against $HOME and the bundles
+ // are REMOVED from every user-global skill dir, so one `--no-skills` in
+ // a throwaway project turns them off for every project on the machine.
+ // Saying so is the whole mitigation — no confirmation prompt, because
+ // the flag is meant to be scriptable.
+ lines.push(` open-knowledge ${dim('opted out via --no-skills')}`);
+ lines.push(
+ ` ${dim('This is a machine-wide choice: the built-in skills are removed from your')}`,
+ );
+ lines.push(
+ ` ${dim('user-global skill directories and stay off for every project until you')}`,
+ );
+ lines.push(` ${dim('re-enable them by running init again without the flag:')}`);
+ lines.push(` ${dim(' ok init')}`);
break;
case 'no-hosts':
lines.push(
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index fa365a0ce..d524554b6 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -163,6 +163,10 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'appearance.preview.autoOpen',
'appearance.theme',
'editor.wordWrap',
+ // The one `telemetry` leaf that leaves the machine. USER scope so a
+ // repository cannot decide that its collaborators report to a third
+ // party — its `localSink.*` siblings are project-scope and local-only.
+ 'telemetry.skillInstallReports.enabled',
]);
});
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index 432d8781c..263affa5d 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -600,6 +600,25 @@ export const ConfigSchema = z.looseObject({
logs: { maxBytes: DEFAULT_LOGS_MAX_BYTES },
attributeDenylist: [...DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST],
}),
+ // The ONLY key under `telemetry` that leaves the machine — every sibling
+ // above is a local sink. Named as its own leaf rather than folded into
+ // `localSink` precisely so the outbound posture can't be mistaken for the
+ // local-only one. USER scope: a project must not be able to decide that
+ // its collaborators' machines phone a third party.
+ skillInstallReports: z
+ .looseObject({
+ enabled: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'user',
+ agentSettable: false,
+ defaultScope: 'user',
+ description:
+ 'Report skill installs to skills.sh so a published skill shows an accurate install count. Sends the skill name, its source repo, and which agent tools it was installed for — never file contents, and never for a private or local source. One report per skill per machine. Default on; the DO_NOT_TRACK and DISABLE_TELEMETRY environment variables also turn it off.',
+ })
+ .default(true),
+ })
+ .default({ enabled: true }),
})
.default({
localSink: {
@@ -608,6 +627,7 @@ export const ConfigSchema = z.looseObject({
logs: { maxBytes: DEFAULT_LOGS_MAX_BYTES },
attributeDenylist: [...DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST],
},
+ skillInstallReports: { enabled: true },
}),
// PROJECT-scope: the loss-capture ring records bridge loss-class events
// (deferred re-derives, tripped detectors/backstops, written recovery
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index ec4199dba..1fb0e0f7e 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -1530,6 +1530,10 @@ export const SkillImportRequestSchema = z
description:
'Pass false to import WITHOUT the default-editor auto-projection (the caller installs explicitly afterwards). Default true.',
}),
+ marketplace: z.boolean().optional().meta({
+ description:
+ 'The source came from a skills.sh listing the user chose (the Explore tab), so the install is reported to skills.sh and counts toward that listing. Off by default: a hand-typed repo must not be announced to skills.sh. Honors the `telemetry.skillInstallReports.enabled` setting and DO_NOT_TRACK.',
+ }),
...agentIdentityFields,
summary: summaryField,
})
diff --git a/packages/core/src/skill-state/schema.ts b/packages/core/src/skill-state/schema.ts
index 7530d4714..d2b41469e 100644
--- a/packages/core/src/skill-state/schema.ts
+++ b/packages/core/src/skill-state/schema.ts
@@ -146,6 +146,18 @@ export const SkillStateSchema = z.looseObject({
'Per-bundle opt-in decisions keyed by install name. Absent key = no recorded decision.',
})
.optional(),
+ // Dedupe ledger for the skills.sh install report. Entries are
+ // `<owner/repo>#<skill>`; presence means "already reported from this
+ // machine". This is what makes the reported number mean installs rather than
+ // launches — the desktop reclaim sweep runs every launch and `ok init` is
+ // re-runnable, so without it both would re-report.
+ installsReported: z
+ .array(z.string())
+ .register(skillStateFieldRegistry, {
+ description:
+ 'Skill installs already reported to skills.sh from this machine, as `<owner/repo>#<skill>`. Append-only; presence suppresses a re-report.',
+ })
+ .optional(),
});
export type SkillState = z.infer<typeof SkillStateSchema>;
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index d82a8979a..8754a904c 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -17,7 +17,8 @@
* 3. armMcpWiring (first-launch MCP consent flow)
* 4. If lastOpenedProject set AND not Option-held → open editor for that project
* Else → open Navigator window
- * 5. installUserSkill (idempotent global skill install)
+ * 5. reclaimUserSkillsOnLaunch (seed-if-absent global skill install — never
+ * overwrites an existing copy; updates flow through the manual re-pull)
* 6. bootAutoUpdater (wired last so update toasts find a real window)
* 7. macOS Dock icon click → re-open Navigator
*
diff --git a/packages/server/assets/skills/write-skill/SKILL.md b/packages/server/assets/skills/write-skill/SKILL.md
index 237508ee3..ca470a1f5 100644
--- a/packages/server/assets/skills/write-skill/SKILL.md
+++ b/packages/server/assets/skills/write-skill/SKILL.md
@@ -141,8 +141,11 @@ skills({ name: "<name>", file: "references/tiers.md" }) # → { path, kind, te
delete({ skill: { name: "<name>", files: ["references/tiers.md"] } })
```
-Paths are skill-relative and must live under `references/` or `scripts/` (one
-level deep). A project `.md` reference becomes a live content doc that
+Paths are skill-relative and must stay inside the skill dir (no `../`, no
+absolute paths). `references/` and `scripts/` are the conventional homes and the
+ones to reach for; other roots (`assets/`, a per-harness dir) are accepted
+because published skills ship them and an import preserves them verbatim. Keep
+references one level deep. A project `.md` reference becomes a live content doc that
auto-connects to its SKILL in the graph regardless of how the body mentions it —
a backticked `` `references/<name>.md` `` path joins the graph just like a
`[[references/<name>]]` wiki-link. Reach for a wiki-link (or
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index bc8220e5f..15825edf4 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -764,6 +764,7 @@ import {
scanSkillFolderStates,
unlinkEditorSkillFolder,
} from './skill-folder-links.ts';
+import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';
import {
readFolderExpectations,
readSkillInstallModeRaw,
@@ -778,6 +779,7 @@ import {
import { restoreSkillVersion } from './skill-restore.ts';
import { getPopularSkills } from './skills-leaderboard.ts';
import { mutateSkillsLock, readSkillsLockFile } from './skills-lock-store.ts';
+import { reportSkillInstall } from './skills-sh-install-report.ts';
import { SuggestLinksTargetNotFoundError, suggestLinks } from './suggest-links.ts';
import type { SyncEngine } from './sync-engine.ts';
import { getMeter, getTracer, withSpan, withSpanSync } from './telemetry.ts';
@@ -18824,7 +18826,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'skill' },
);
- // ─── `/api/skill-file` — ONE bundle file (references/** + scripts/**) ──────
+ // ─── `/api/skill-file` — ONE bundle file (any path inside the skill) ──────
//
// The whole-bundle read/write/delete surface beneath SKILL.md. Routing splits
// by scope × type: a PROJECT `.md` reference is a real CRDT content doc
@@ -19138,7 +19140,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:invalid-request',
- 'Invalid skill file path (must be a file under references/ or scripts/, no `..`).',
+ 'Invalid skill file path (must name a file inside the skill dir, no `..`).',
{ handler: 'skill-file-put' },
);
return;
@@ -19301,7 +19303,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:invalid-request',
- 'Invalid skill file path (must be a file under references/ or scripts/).',
+ 'Invalid skill file path (must name a file inside the skill dir).',
{ handler: 'skill-file-delete' },
);
return;
@@ -19416,7 +19418,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:invalid-request',
- 'Both paths must live under references/ or scripts/ inside the skill.',
+ 'Both paths must stay inside the skill dir.',
{ handler: 'skill-file-rename', detail: fromKind === null ? from : to },
);
return;
@@ -19983,12 +19985,17 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// The picked upstream skill dir basename — recorded in the lockfile so a
// later reimport re-selects the same skill in a multi-skill source.
let upstreamSkill: string | undefined;
+ // The marketplace-facing coordinates (`owner/repo`, or a website
+ // catalog's hostname) — what an install report names. Distinct from
+ // `sourceLabel`, which keeps the raw string the user typed.
+ let resolvedSourceForReport = body.source;
{
const rawSource = body.source;
try {
const skillsSh = await resolveSkillsShImportSource(rawSource, body.skill);
const resolvedSource = skillsSh?.source ?? rawSource;
+ resolvedSourceForReport = resolvedSource;
const selectedSkill = body.skill ?? skillsSh?.skill;
const spec = skillsSh?.spec ?? parseSource(resolvedSource);
if (!spec) {
@@ -20070,19 +20077,32 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
// Steps 2-6 (dedupe → collision → write → attribute → lockfile → project)
// are the shared import spine, also used by the upload endpoint.
- respondSkillImport(
- res,
- await runSkillImport({
- acquiredDir,
- scope,
- sourceLabel,
- ref,
- publisher,
- upstreamSkill,
- actor,
- skipProjection: body.install === false,
- }),
- );
+ const outcome = await runSkillImport({
+ acquiredDir,
+ scope,
+ sourceLabel,
+ ref,
+ publisher,
+ upstreamSkill,
+ actor,
+ skipProjection: body.install === false,
+ });
+ // Count it on skills.sh, but ONLY when the user came from a skills.sh
+ // listing (`marketplace`, set by the Explore tab). A hand-typed
+ // `owner/repo` is not announced to a third party — the user never went
+ // to the marketplace, and telling it which repos they install would be
+ // a disclosure they did not ask for.
+ //
+ // This is the mechanism that actually moves the counter. Fetching the
+ // bundle through skills.sh's download API does NOT: verified against a
+ // skill sitting at 8 installs, which stayed at 8 after a download.
+ if (body.marketplace === true && outcome.ok) {
+ void reportSkillInstall(
+ { source: resolvedSourceForReport, skills: [outcome.body.name] },
+ resolveSkillInstallReportSettings(),
+ );
+ }
+ respondSkillImport(res, outcome);
} catch (e) {
errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skill.', {
handler: 'skill-import',
diff --git a/packages/server/src/mcp/tools/edit.ts b/packages/server/src/mcp/tools/edit.ts
index 55baa1e57..3c86d1118 100644
--- a/packages/server/src/mcp/tools/edit.ts
+++ b/packages/server/src/mcp/tools/edit.ts
@@ -712,7 +712,7 @@ export function register(server: ServerInstance, deps: EditDeps): void {
})
.optional()
.describe(
- 'Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE `references/**`+`scripts/**` bundle file.',
+ 'Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE bundle file.',
),
summary: summaryArgSchema,
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
diff --git a/packages/server/src/mcp/tools/skills.test.ts b/packages/server/src/mcp/tools/skills.test.ts
index cb71ffbe2..c7057cc6c 100644
--- a/packages/server/src/mcp/tools/skills.test.ts
+++ b/packages/server/src/mcp/tools/skills.test.ts
@@ -69,11 +69,20 @@ describe('skills read tool — bundle-file gating short-circuits before the netw
expect(text(r)).toContain('..');
});
- test('`file` outside references/ or scripts/ is rejected', async () => {
+ test('an absolute `file` is rejected before any request', async () => {
const handler = captureSkills(UNREACHABLE);
- const r = await handler({ name: 'trip-log', file: 'notes/x.md' });
+ const r = await handler({ name: 'trip-log', file: '/etc/passwd' });
expect(r.isError).toBe(true);
- expect(text(r)).toContain('references/');
+ expect(text(r)).toContain('skill-relative');
+ });
+
+ // A bundle root outside references//scripts/ is ORDINARY — acquisition writes
+ // whatever the published skill ships, so the reader must be able to reach it.
+ // Reaching the network (unreachable here) proves it passed validation.
+ test('`file` under another bundle root passes validation and attempts the read', async () => {
+ const handler = captureSkills(UNREACHABLE);
+ const r = await handler({ name: 'trip-log', file: 'agents/openai.yaml' });
+ expect(text(r)).toContain('Server unreachable');
});
});
diff --git a/packages/server/src/mcp/tools/skills.ts b/packages/server/src/mcp/tools/skills.ts
index 0f7808b5b..1cf9be20d 100644
--- a/packages/server/src/mcp/tools/skills.ts
+++ b/packages/server/src/mcp/tools/skills.ts
@@ -201,7 +201,7 @@ const SkillBundleFileEntrySchema = z.object({
path: z.string().describe('Skill-relative path (e.g. "references/tiers.md").'),
kind: z
.enum(['reference', 'script'])
- .describe('`reference` (under references/) or `script` (under scripts/).'),
+ .describe('`script` for anything under scripts/; `reference` for every other bundle file.'),
});
const SkillReadOutputSchema = z.object({
@@ -251,7 +251,7 @@ const DESCRIPTION = [
'**Four modes:**',
'- **Marketplace search** (pass `query`): search skills.sh and return import-ready rows (`name`, `source`, `description`, `publisher`, installs). Use when a user asks to find/browse/add an external skill. Then call `import({ source, skill: name })` on the chosen row.',
'- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts.',
- "- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its `references/**`+`scripts/**` bundle files. `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).",
+ "- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its bundle files (`references/**`, `scripts/**`, and any other file the skill ships). `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).",
"- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`).",
].join('\n');
@@ -283,7 +283,7 @@ export function register(server: ServerInstance, deps: SkillsToolDeps): void {
.string()
.optional()
.describe(
- 'With `name`: read ONE bundle file by its skill-relative path (`references/...`/`scripts/...`).',
+ 'With `name`: read ONE bundle file by its skill-relative path (e.g. `references/x.md`, `agents/openai.yaml`).',
),
scope: SkillScopeArg.optional(),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
diff --git a/packages/server/src/mcp/tools/verb-schemas.test.ts b/packages/server/src/mcp/tools/verb-schemas.test.ts
index cefab4593..6e4a086b1 100644
--- a/packages/server/src/mcp/tools/verb-schemas.test.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.test.ts
@@ -120,21 +120,34 @@ describe('resolveSkillFilePath — bundle-file path allowlist', () => {
if (nested.ok) expect(nested.kind).toBe('reference');
});
- test('rejects `..` traversal, absolute paths, and other top-level dirs', () => {
+ test('rejects `..` traversal and absolute paths', () => {
for (const bad of [
'references/../../etc/passwd',
'../escape.md',
'references/../scripts/../../x',
'/abs/path.md',
'C:\\windows\\system32',
+ // Authored via `body`; a second write path would validate differently.
'SKILL.md',
- 'notes/x.md',
- 'assets/img.png',
]) {
expect(resolveSkillFilePath(bad).ok).toBe(false);
}
});
+ // Acquisition captures a skill's whole directory byte-for-byte, so a
+ // two-root allowlist here meant OK could write a file on import that it then
+ // refused to let an agent read or edit. Real published skills ship exactly
+ // these shapes (`mattpocock/skills/grill-me` carries `agents/openai.yaml`).
+ test('accepts bundle roots beyond references/ and scripts/', () => {
+ for (const good of ['assets/img.png', 'agents/openai.yaml', '.claude-plugin/plugin.json']) {
+ const r = resolveSkillFilePath(good);
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.kind).toBe('reference');
+ }
+ const rootFile = resolveSkillFilePath('LICENSE');
+ expect(rootFile.ok).toBe(true);
+ });
+
test('rejects a bare allowed root with no leaf, empty, and NUL', () => {
expect(resolveSkillFilePath('references').ok).toBe(false);
expect(resolveSkillFilePath('scripts/').ok).toBe(false);
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index d3616f7a5..6e4712490 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -206,33 +206,44 @@ export function resolveSkillName(
}
// ─────────────────────────── skill bundle files ───────────────────────────
-// A skill is a DIRECTORY: `SKILL.md` (authored via `body`) plus optional
-// one-level `references/**` + `scripts/**`. Bundle files are addressed by a
-// SKILL-RELATIVE path (`references/x.md`, `scripts/run.sh`) — agents never see
-// or pass `.ok/...` paths; the verb maps the relative path onto the on-disk
-// skill dir. The allowlist below is the single safety gate every bundle-file
-// verb (write / edit / delete / read) funnels through.
+// A skill is a DIRECTORY: `SKILL.md` (authored via `body`) plus any other file
+// beside it — conventionally `references/**` + `scripts/**`, but published
+// skills also ship `assets/`, `.claude-plugin/`, per-harness dirs, and root
+// files, and acquisition preserves all of it byte-for-byte. Bundle files are
+// addressed by a SKILL-RELATIVE path — agents never see or pass `.ok/...`
+// paths; the verb maps the relative path onto the on-disk skill dir. The gate
+// below is the single containment check every bundle-file verb
+// (write / edit / delete / read) funnels through.
export const SKILL_FILES_DESCRIBE =
'Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). ' +
- '`path` is SKILL-RELATIVE and MUST live under `references/` or `scripts/` (e.g. "references/tiers.md", "scripts/run.sh") — ' +
- 'no `../`, no absolute paths, no other top-level dir. `content` is the full text. Text only (no binary). ' +
+ '`path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — ' +
+ 'no `../`, no absolute paths. `content` is the full text. Text only (no binary). ' +
'Independent of `body`: write one reference without resending SKILL.md.';
export const SKILL_FILE_DESCRIBE =
- 'A single SKILL-RELATIVE bundle file path under `references/` or `scripts/` (e.g. "references/tiers.md"). ' +
+ 'A single SKILL-RELATIVE bundle file path (e.g. "references/tiers.md"). ' +
'For `edit`, names the one bundle file to find/replace in; for `skills`, the one file to read.';
-/** A bundle file is a `reference` (under `references/`) or a `script` (under `scripts/`). */
+/** `script` for anything under `scripts/`; `reference` for every other bundle
+ * file. Two values, because the only distinction that changes handling is
+ * "is this executable-shaped" — not which folder it sits in. */
export type SkillFileKind = 'reference' | 'script';
/**
- * Validate + normalize a SKILL-RELATIVE bundle-file path against the allowlist:
- * it must sit under `references/` or `scripts/`, carry a non-empty leaf, and
- * never escape (no `..` segments, no absolute path, no NUL). Returns the
- * normalized POSIX-relative path + its `kind`, or a teaching error (not a
- * throw) so write / edit / delete / read share one rule (mirrors
- * `resolveTemplatePath`). `SKILL.md` is rejected here — it is authored via
- * `body`, never as a bundle file.
+ * Validate + normalize a SKILL-RELATIVE bundle-file path: it must stay inside
+ * the skill dir (no `..` segments, no absolute path, no NUL) and name a file
+ * rather than a bare directory. Returns the normalized POSIX-relative path +
+ * its `kind`, or a teaching error (not a throw) so write / edit / delete / read
+ * share one rule (mirrors `resolveTemplatePath`). `SKILL.md` is rejected — it
+ * is authored via `body`, never as a bundle file.
+ *
+ * ANY root is accepted, not just `references/` + `scripts/`. Acquisition
+ * captures a skill's whole directory byte-for-byte (`acquire/parse.ts`:
+ * root files, `assets/`, `.claude-plugin/`, any subdir), so a two-root
+ * allowlist here meant OK could WRITE a file on import that it then refused to
+ * let an agent read or edit — real published skills ship exactly that
+ * (`mattpocock/skills/grill-me` carries `agents/openai.yaml`). Containment is
+ * the invariant worth enforcing; a directory-name allowlist was never it.
*/
export function resolveSkillFilePath(
path: string,
@@ -257,26 +268,33 @@ export function resolveSkillFilePath(
if (segments.some((s) => s === '..')) {
return {
ok: false,
- error: `a skill file \`path\` may not contain ".." — "${path}" could escape the skill dir. Allowed roots: references/, scripts/.`,
+ error: `a skill file \`path\` may not contain ".." — "${path}" could escape the skill dir.`,
};
}
- const top = segments[0];
- if (top !== 'references' && top !== 'scripts') {
+ if (segments.length === 0) {
+ return { ok: false, error: 'a skill file `path` is required (e.g. "references/tiers.md").' };
+ }
+ // A bare `references` / `scripts` is a directory, not a file — the one
+ // ambiguity worth naming, since any other single segment (`LICENSE`,
+ // `AGENTS.md`) is a legitimate root file and can't be told apart lexically.
+ if (segments.length === 1 && (segments[0] === 'references' || segments[0] === 'scripts')) {
return {
ok: false,
- error: `a skill file \`path\` must start with \`references/\` or \`scripts/\` — "${path}" is not allowed. SKILL.md is authored via \`body\`.`,
+ error: `a skill file \`path\` needs a file under \`${segments[0]}/\` (e.g. "${segments[0]}/notes.md") — "${path}" names only the directory.`,
};
}
- if (segments.length < 2) {
+ // SKILL.md has exactly one authoring surface (`body`). Admitting it here too
+ // would give the same bytes two write paths with different validation.
+ if (segments.length === 1 && segments[0]?.toLowerCase() === 'skill.md') {
return {
ok: false,
- error: `a skill file \`path\` needs a file under \`${top}/\` (e.g. "${top}/notes.md") — "${path}" names only the directory.`,
+ error: 'SKILL.md is authored via `body`, not as a bundle file.',
};
}
return {
ok: true,
path: segments.join('/'),
- kind: top === 'scripts' ? 'script' : 'reference',
+ kind: segments[0] === 'scripts' ? 'script' : 'reference',
};
}
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 4e2f8eb05..2e0f15b46 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -591,11 +591,11 @@ async function handleAsset(
/**
* Write a skill bundle: SKILL.md (when `description` present) and/or any
- * `references/**`+`scripts/**` files. `body` is optional → an agent can write
- * one reference into an existing skill without resending SKILL.md. Each
- * `files` path is validated against the allowlist (`references/`/`scripts/`
- * only, no escape) before any network call. SKILL.md is written first so a
- * file write into a brand-new skill finds its dir.
+ * bundle file beside it. `body` is optional → an agent can write one reference
+ * into an existing skill without resending SKILL.md. Each `files` path is
+ * validated for containment (inside the skill dir, no escape) before any
+ * network call. SKILL.md is written first so a file write into a brand-new
+ * skill finds its dir.
*/
async function handleSkillWrite(
skill: {
@@ -936,7 +936,9 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
z.object({
path: z
.string()
- .describe('Skill-relative path under `references/` or `scripts/`.'),
+ .describe(
+ 'Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.',
+ ),
content: z.string().describe('Full text of the bundle file.'),
}),
)
@@ -946,7 +948,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
})
.optional()
.describe(
- 'Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files (under `references/**` or `scripts/**` — no other root is accepted) via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }',
+ 'Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }',
),
asset: z
.object({
diff --git a/packages/server/src/seed/install-pack-skill.ts b/packages/server/src/seed/install-pack-skill.ts
index 108fb02e4..47862a17c 100644
--- a/packages/server/src/seed/install-pack-skill.ts
+++ b/packages/server/src/seed/install-pack-skill.ts
@@ -37,8 +37,10 @@ import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from
import { resolveDefaultSkillHomeRel, scanInPlaceSkills } from '../in-place-skills.ts';
import { getLogger } from '../logger.ts';
import { BUNDLE_SKILL_NAME } from '../skill-bundles.ts';
+import { resolveSkillInstallReportSettings } from '../skill-install-report-config.ts';
import { listPackSkillSources, type PackSkillSource } from '../skill-pack-sources.ts';
import { hostSkillsRootEscapes, projectInPlaceSkill } from '../skill-projection.ts';
+import { reportSkillInstall } from '../skills-sh-install-report.ts';
/**
* Display labels for the editors that keep project-local skills (returned in the
@@ -122,6 +124,8 @@ export async function installPackSkill(projectDir: string, packId: string): Prom
return existsSync(join(projectDir, rel, PLATFORM_SKILL_NAME, 'SKILL.md'));
});
+ // Resolved once per seed, not per skill — a pack can ship a dozen.
+ const reportSettings = resolveSkillInstallReportSettings();
const installed = new Set<string>();
// The scan (not any marker) is truth under the in-place model — one scan
// covers the absent-check for every pack skill.
@@ -179,6 +183,14 @@ export async function installPackSkill(projectDir: string, packId: string): Prom
// Provenance for the reimport-based update path (no bespoke pack-update handler).
recordPackSkillProvenance(projectDir, name, skillDir);
+ // Count it on skills.sh. Pack skills ship inside the app bundle, so there
+ // is nothing to fetch from the marketplace and the event is the only way
+ // the listing reflects them. Inside the `!alreadyPresent` branch AND
+ // deduped per machine by the reporter, so re-running seed reports nothing.
+ void reportSkillInstall(
+ { source: OPENKNOWLEDGE_SKILLS_REPO, skills: [name] },
+ { home: reportSettings.home, enabled: reportSettings.enabled },
+ );
}
// (2) Fan the source into each set-up editor via the guarded in-place
diff --git a/packages/server/src/skill-install-report-config.test.ts b/packages/server/src/skill-install-report-config.test.ts
new file mode 100644
index 000000000..bc26bd046
--- /dev/null
+++ b/packages/server/src/skill-install-report-config.test.ts
@@ -0,0 +1,69 @@
+/**
+ * This resolver IS the user's opt-out. Its three branches — absent file,
+ * explicit `false`, unreadable file — decide whether anything leaves the
+ * machine, so each one is pinned here rather than left to inspection.
+ */
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import { describe, expect, test } from 'vitest';
+import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';
+
+function freshHome(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-report-config-'));
+}
+
+/** Write a user config with the given YAML body. */
+function writeUserConfig(home: string, yaml: string): string {
+ const path = resolveConfigPath('user', home, home);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, yaml, 'utf-8');
+ return path;
+}
+
+describe('resolveSkillInstallReportSettings', () => {
+ test('no user config at all → the schema default (on)', () => {
+ expect(resolveSkillInstallReportSettings(freshHome()).enabled).toBe(true);
+ });
+
+ test('config present but silent on the key → the schema default (on)', () => {
+ const home = freshHome();
+ writeUserConfig(home, 'appearance:\n theme: dark\n');
+ expect(resolveSkillInstallReportSettings(home).enabled).toBe(true);
+ });
+
+ test('explicit false is honored', () => {
+ const home = freshHome();
+ writeUserConfig(home, 'telemetry:\n skillInstallReports:\n enabled: false\n');
+ expect(resolveSkillInstallReportSettings(home).enabled).toBe(false);
+ });
+
+ test('explicit true is honored', () => {
+ const home = freshHome();
+ writeUserConfig(home, 'telemetry:\n skillInstallReports:\n enabled: true\n');
+ expect(resolveSkillInstallReportSettings(home).enabled).toBe(true);
+ });
+
+ // The safe-fail direction for a setting that governs what leaves the machine.
+ // A file that EXISTS but cannot be read may hold an explicit decline, and
+ // assuming consent because we couldn't check is the wrong way to be wrong.
+ test('a config that exists but cannot be read → OFF, not the default', () => {
+ const home = freshHome();
+ const path = resolveConfigPath('user', home, home);
+ // A directory where the file belongs: every read fails with EISDIR.
+ mkdirSync(path, { recursive: true });
+ expect(resolveSkillInstallReportSettings(home).enabled).toBe(false);
+ });
+
+ test('malformed YAML → OFF', () => {
+ const home = freshHome();
+ writeUserConfig(home, 'telemetry:\n skillInstallReports:\n enabled: [unclosed\n');
+ expect(resolveSkillInstallReportSettings(home).enabled).toBe(false);
+ });
+
+ test('reports the home it resolved against', () => {
+ const home = freshHome();
+ expect(resolveSkillInstallReportSettings(home).home).toBe(home);
+ });
+});
diff --git a/packages/server/src/skill-install-report-config.ts b/packages/server/src/skill-install-report-config.ts
new file mode 100644
index 000000000..4d54313e5
--- /dev/null
+++ b/packages/server/src/skill-install-report-config.ts
@@ -0,0 +1,63 @@
+/**
+ * Resolve `telemetry.skillInstallReports.enabled` from the USER config.
+ *
+ * Read as raw YAML rather than through the schema reader for the same reason
+ * `local-sink-resolver.ts` does: a schema-defaulted read cannot tell "absent"
+ * from "explicitly true", and this is a setting where an explicit `false` must
+ * win over anything. Absent → the schema default (on).
+ *
+ * User scope, not project: a repository must not be able to decide that its
+ * collaborators' machines report to a third party.
+ */
+
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import { parse as parseYaml } from 'yaml';
+import { getLogger } from './logger.ts';
+
+export interface SkillInstallReportSettings {
+ enabled: boolean;
+ home: string;
+}
+
+/**
+ * Never throws: telemetry bookkeeping must not be able to break an install.
+ *
+ * A config that EXISTS but cannot be read or parsed resolves to DISABLED, not
+ * to the default. The default is only correct when we know the user expressed
+ * no preference — an absent file. If the file is there and unreadable, an
+ * explicit `enabled: false` may be sitting inside it, and the failure direction
+ * that matters for a setting governing what leaves the machine is "say nothing"
+ * rather than "assume consent". The mirror of the opt-out gate in
+ * `installUserSkill`: unknowable means decline.
+ */
+export function resolveSkillInstallReportSettings(
+ homedirOverride?: string,
+): SkillInstallReportSettings {
+ const home = homedirOverride ?? homedir();
+ let path: string;
+ try {
+ path = resolveConfigPath('user', home, home);
+ } catch (err) {
+ getLogger('skills').warn({ err }, 'could not resolve the user config path; not reporting');
+ return { enabled: false, home };
+ }
+ // No file at all: the user has expressed no preference, so the schema default
+ // (on) applies — same reading the Settings pane shows them.
+ if (!existsSync(path)) return { enabled: true, home };
+ try {
+ const raw = parseYaml(readFileSync(path, 'utf-8')) as
+ | { telemetry?: { skillInstallReports?: { enabled?: unknown } } }
+ | null
+ | undefined;
+ const value = raw?.telemetry?.skillInstallReports?.enabled;
+ return { enabled: typeof value === 'boolean' ? value : true, home };
+ } catch (err) {
+ getLogger('skills').warn(
+ { err, path },
+ 'user config exists but could not be read; not reporting skill installs',
+ );
+ return { enabled: false, home };
+ }
+}
diff --git a/packages/server/src/skill-install.test.ts b/packages/server/src/skill-install.test.ts
index 9ec111c25..990b19bc4 100644
--- a/packages/server/src/skill-install.test.ts
+++ b/packages/server/src/skill-install.test.ts
@@ -21,7 +21,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { HOSTS_WITH_USER_SKILL_DIR } from '@inkeep/open-knowledge-core';
import { beforeEach, describe, expect, test } from 'vitest';
-
+import { BUNDLE_SKILL_NAME } from './skill-bundles.ts';
import {
buildAndOpenSkill,
detectUserSkillHosts,
@@ -29,6 +29,7 @@ import {
type SkillInstallLogger,
type SpawnLike,
} from './skill-install.ts';
+import { writeBundleDecision } from './skill-state.ts';
async function readServerVersion(): Promise<string> {
const raw = await readFile(new URL('../package.json', import.meta.url), 'utf-8');
@@ -233,6 +234,67 @@ describe('installUserSkill — scope discipline', () => {
expect(events.at(-1)?.reason).toBe('no-hosts');
});
+ // The decline gate used to live only in the callers, so a caller that forgot
+ // it would reinstall a bundle the user had turned off — and a decline also
+ // removes the bundle from disk, so the reinstall reverses an explicit choice.
+ test('an explicitly declined bundle is never installed, even with a host present', async () => {
+ const home = freshHome();
+ installHost(home, '.claude');
+ await writeBundleDecision(home, BUNDLE_SKILL_NAME.discovery, false);
+
+ const result = await installUserSkill({ home });
+
+ expect(result).toBe('skip-current');
+ expect(existsSync(centralSkillDirFor(home))).toBe(false);
+ expect(existsSync(hostSkillDirFor(home, '.claude'))).toBe(false);
+ expect(readInstallEvents(home).at(-1)?.reason).toBe('declined');
+ });
+
+ // `force` bypasses the VERSION fast-path, not consent — `ok init` passes it on
+ // every bundle, so letting it through the decline gate would make a re-init
+ // silently undo an opt-out.
+ test('force does not override an explicit decline', async () => {
+ const home = freshHome();
+ installHost(home, '.claude');
+ await writeBundleDecision(home, BUNDLE_SKILL_NAME.discovery, false);
+
+ expect(await installUserSkill({ home, force: true })).toBe('skip-current');
+ expect(existsSync(centralSkillDirFor(home))).toBe(false);
+ });
+
+ // An UNREADABLE decision is not "no decision". Collapsing the two would
+ // install a bundle whose recorded state may be an explicit decline — and a
+ // decline also deletes the files, so reversing it is visible to the user.
+ test('an unreadable decision file declines rather than installing', async () => {
+ const home = freshHome();
+ installHost(home, '.claude');
+ // A directory where the state file belongs: reads fail with EISDIR, which
+ // is neither ENOENT (absent) nor a parse error (both of which read as
+ // "fresh install" by design).
+ mkdirSync(join(home, '.ok', 'skill-state.yml'), { recursive: true });
+ const { logger, records } = makeRecordingLogger();
+
+ const result = await installUserSkill({ home, logger });
+
+ expect(result).toBe('skip-current');
+ expect(existsSync(centralSkillDirFor(home))).toBe(false);
+ expect(
+ records.some(
+ (r) => (r.data as { event?: string }).event === 'skill-install.gate.decision-read-failed',
+ ),
+ ).toBe(true);
+ });
+
+ // Absent decision means "first install", not "declined" — the reclaim sweeps
+ // own the `?? installedOnDisk` grandfathering, this path must not import it.
+ test('no recorded decision still installs', async () => {
+ const home = freshHome();
+ installHost(home, '.claude');
+
+ expect(await installUserSkill({ home })).toBe('installed');
+ expect(existsSync(join(centralSkillDirFor(home), 'SKILL.md'))).toBe(true);
+ });
+
test('detectUserSkillHosts reports only the hosts present on disk', () => {
const home = freshHome();
expect(detectUserSkillHosts(home)).toEqual([]);
diff --git a/packages/server/src/skill-install.ts b/packages/server/src/skill-install.ts
index c70cb1c3d..c9d61b1ea 100644
--- a/packages/server/src/skill-install.ts
+++ b/packages/server/src/skill-install.ts
@@ -3,7 +3,11 @@ import { existsSync } from 'node:fs';
import { stat } from 'node:fs/promises';
import { homedir, platform as osPlatform } from 'node:os';
import { dirname, isAbsolute, join, resolve as resolvePath } from 'node:path';
-import { type EditorId, HOSTS_WITH_USER_SKILL_DIR } from '@inkeep/open-knowledge-core';
+import {
+ type EditorId,
+ HOSTS_WITH_USER_SKILL_DIR,
+ OPENKNOWLEDGE_SKILLS_REPO,
+} from '@inkeep/open-knowledge-core';
import {
type BuildSkillZipResult,
buildSkillZip,
@@ -14,7 +18,9 @@ import { tracedCpSync, tracedMkdir, tracedMkdirSync, tracedRmSync } from './fs-t
import { getLogger } from './logger.ts';
import { BUNDLE_SKILL_NAME, type BundleId } from './skill-bundles.ts';
import { recordSkillInstallEvent, type SkillInstallEventOutcome } from './skill-install-events.ts';
+import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';
import {
+ readBundleDecision,
readServerPackageVersion,
readTargetRecordedAt,
readTargetVersion,
@@ -22,6 +28,7 @@ import {
type SkillStateSurface,
writeTargetVersion,
} from './skill-state.ts';
+import { reportSkillInstall } from './skills-sh-install-report.ts';
/**
* Minimal logger duck-type accepted by `installUserSkill`. Compatible with
@@ -55,10 +62,10 @@ export interface InstallUserSkillOptions {
logger?: SkillInstallLogger;
/**
* Install-source attribution recorded on the per-target YAML entry.
- * Defaults to `'cli-npx-skills-add'` for the CLI / `ok init` path. The
- * Electron desktop main-process direct-invoke site (`packages/desktop/
- * src/main/index.ts` first-launch flow) passes `'desktop-direct'` to
- * distinguish it from a user-typed `ok init`.
+ * Defaults to `'cli-npx-skills-add'` for the CLI / `ok init` path — today's
+ * only production caller. `'desktop-direct'` is the sibling value the
+ * desktop's own writer (`skill-reclaim.ts`) records; it no longer reaches
+ * this function.
*/
surface?: SkillStateSurface;
/**
@@ -307,6 +314,44 @@ export async function installUserSkill(
);
};
+ // Opt-out backstop, enforced HERE rather than trusted to every caller. The
+ // decline gate lived only in the callers, so a new one that forgot it would
+ // reinstall a bundle the user had explicitly turned off — and because a
+ // decline also REMOVES the bundle from disk, that reinstall reverses a
+ // deliberate choice rather than merely being redundant.
+ //
+ // Keys on an explicit `false`, NOT on `resolveBundleEnabled`. That helper's
+ // `decision ?? installedOnDisk` fallback belongs to the reclaim sweeps, which
+ // run unprompted on every launch and must not resurrect a bundle on a machine
+ // that never consented. This function is only ever reached deliberately, and
+ // `ok init` records the decision BEFORE calling — so an absent decision here
+ // means "first install", not "declined", and must still install.
+ let declined: boolean | null;
+ try {
+ declined = await readBundleDecision(home, bundleName, logger);
+ } catch (err) {
+ // Read FAILURE is not "no decision". Collapsing the two (EACCES after a
+ // `sudo ok init`, a truncated write, a corrupted YAML) would install a
+ // bundle whose recorded state might be an explicit decline — and a decline
+ // also removes the files, so reversing it is visible and unwanted. When the
+ // answer is unknowable, decline: an over-cautious skip is recoverable and
+ // reported in the init summary, whereas silently undoing an opt-out is not.
+ logger.warn(
+ { event: 'skill-install.gate.decision-read-failed', bundle: bundleId, err },
+ 'Could not read the opt-out decision; skipping the install rather than risk reversing it.',
+ );
+ await report('skip-current', undefined, 'decision-read-failed');
+ return 'skip-current';
+ }
+ if (declined === false) {
+ logger.info?.(
+ { event: 'skill-install.declined', bundle: bundleId },
+ 'Bundle is opted out; skipping user-global skill install.',
+ );
+ await report('skip-current', undefined, 'declined');
+ return 'skip-current';
+ }
+
let currentVersion: string;
try {
currentVersion = await readServerPackageVersion();
@@ -424,6 +469,26 @@ export async function installUserSkill(
.join(', ')}`,
);
await report('installed', currentVersion);
+ // Count this install on skills.sh. Built-ins ship inside the app bundle, so
+ // there is nothing to fetch from the marketplace and the event is the only
+ // way the listing can reflect them. Deduped per machine inside the reporter,
+ // so the launch reclaim and a re-run of `ok init` contribute nothing.
+ //
+ // NOT awaited. `ok init` loops this once per user-global bundle, so awaiting
+ // a third-party HTTP call with a 3s timeout would add seconds of dead wait to
+ // every init on a firewalled or offline machine. The reporter claims its
+ // ledger entry before sending, so dropping the request costs one uncounted
+ // install rather than a duplicate.
+ void reportSkillInstall(
+ {
+ source: OPENKNOWLEDGE_SKILLS_REPO,
+ skills: [bundleName],
+ agents: hosts.map((h) => h.editorId),
+ global: true,
+ version: currentVersion,
+ },
+ { home, enabled: resolveSkillInstallReportSettings(home).enabled },
+ );
return 'installed';
}
diff --git a/packages/server/src/skill-state.ts b/packages/server/src/skill-state.ts
index 1928a4877..de3c0a8d9 100644
--- a/packages/server/src/skill-state.ts
+++ b/packages/server/src/skill-state.ts
@@ -314,7 +314,14 @@ export async function readBundleDecision(
bundleName: string,
logger?: SkillStateLogger,
): Promise<boolean | null> {
- const state = await readSkillStateFile(home, logger).catch(() => null);
+ // Deliberately NOT `.catch(() => null)`. `readSkillStateFile` already returns
+ // null for a MISSING file (ENOENT) and for an unparseable one, so the only
+ // errors that reach here are the ones a caller must be able to tell apart
+ // from "no decision recorded" — EACCES after a `sudo ok init`, EIO, a
+ // truncated read. Collapsing those into null let an install proceed against
+ // what might be an explicit decline. Callers that genuinely want the
+ // permissive reading (the launch reclaim sweeps) opt in with their own catch.
+ const state = await readSkillStateFile(home, logger);
const entry = state?.bundles?.[bundleName];
return typeof entry?.enabled === 'boolean' ? entry.enabled : null;
}
@@ -342,6 +349,38 @@ export async function writeBundleDecision(
});
}
+/**
+ * Installs already reported to skills.sh from this machine, as
+ * `<owner/repo>#<skill>`. A missing / unreadable state file reads as empty:
+ * the cost of that is at most one duplicate report, whereas throwing would
+ * fail an install over telemetry bookkeeping.
+ */
+export async function readInstallReported(
+ home: string,
+ logger?: SkillStateLogger,
+): Promise<Set<string>> {
+ const state = await readSkillStateFile(home, logger).catch(() => null);
+ return new Set(state?.installsReported ?? []);
+}
+
+/**
+ * Append reported install keys. Atomic RMW under the same lock as every other
+ * skill-state write, and set-unioned so two concurrent installs can't clobber
+ * each other's entries.
+ */
+export async function writeInstallReported(
+ home: string,
+ keys: readonly string[],
+ logger?: SkillStateLogger,
+): Promise<void> {
+ if (keys.length === 0) return;
+ await withSkillStateWriteLock(home, async () => {
+ const existing = (await readSkillStateFile(home, logger)) ?? emptySkillState();
+ const merged = new Set([...(existing.installsReported ?? []), ...keys]);
+ await writeSkillStateFile(home, { ...existing, installsReported: [...merged].sort() });
+ });
+}
+
/**
* Canonical skill version: the `version` field of
* `@inkeep/open-knowledge-server`'s `package.json`. Exposed to the renderer
diff --git a/packages/server/src/skills-sh-install-report.test.ts b/packages/server/src/skills-sh-install-report.test.ts
new file mode 100644
index 000000000..50016894b
--- /dev/null
+++ b/packages/server/src/skills-sh-install-report.test.ts
@@ -0,0 +1,197 @@
+/**
+ * The reporter's job is to send ONE event per genuine install. Most of these
+ * tests are about when it must stay silent — the launch reclaim runs on every
+ * desktop start, so a reporter that fires per call would turn an install count
+ * into a launch count.
+ */
+import { mkdirSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { reportSkillInstall } from './skills-sh-install-report.ts';
+
+function freshHome(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-install-report-'));
+}
+
+/** Records every URL it is called with; always succeeds. */
+function recordingFetch(): { calls: string[]; impl: typeof fetch } {
+ const calls: string[] = [];
+ const impl = (async (url: string) => {
+ calls.push(String(url));
+ return { ok: true, status: 200 };
+ }) as unknown as typeof fetch;
+ return { calls, impl };
+}
+
+const ENABLED = { enabled: true, env: {} as NodeJS.ProcessEnv };
+
+describe('reportSkillInstall', () => {
+ test('sends one install event carrying source, skills and agents', async () => {
+ const { calls, impl } = recordingFetch();
+ const reported = await reportSkillInstall(
+ {
+ source: 'inkeep/open-knowledge-skills',
+ skills: ['open-knowledge-discovery'],
+ agents: ['claude', 'codex'],
+ global: true,
+ version: '9.9.9',
+ },
+ { home: freshHome(), ...ENABLED, fetchImpl: impl },
+ );
+ expect(reported).toEqual(['open-knowledge-discovery']);
+ expect(calls).toHaveLength(1);
+ const url = new URL(calls[0] as string);
+ expect(url.origin + url.pathname).toBe('https://add-skill.vercel.sh/t');
+ expect(url.searchParams.get('event')).toBe('install');
+ expect(url.searchParams.get('source')).toBe('inkeep/open-knowledge-skills');
+ expect(url.searchParams.get('skills')).toBe('open-knowledge-discovery');
+ expect(url.searchParams.get('agents')).toBe('claude,codex');
+ expect(url.searchParams.get('global')).toBe('1');
+ expect(url.searchParams.get('v')).toBe('9.9.9');
+ });
+
+ // The rule that makes the number mean "installs" rather than "launches".
+ test('reports a given skill only once per machine', async () => {
+ const home = freshHome();
+ const { calls, impl } = recordingFetch();
+ const report = { source: 'inkeep/open-knowledge-skills', skills: ['open-knowledge-discovery'] };
+ await reportSkillInstall(report, { home, ...ENABLED, fetchImpl: impl });
+ await reportSkillInstall(report, { home, ...ENABLED, fetchImpl: impl });
+ await reportSkillInstall(report, { home, ...ENABLED, fetchImpl: impl });
+ expect(calls).toHaveLength(1);
+ });
+
+ test('reports only the skills not already reported', async () => {
+ const home = freshHome();
+ const { calls, impl } = recordingFetch();
+ const source = 'inkeep/open-knowledge-skills';
+ await reportSkillInstall({ source, skills: ['a'] }, { home, ...ENABLED, fetchImpl: impl });
+ await reportSkillInstall({ source, skills: ['a', 'b'] }, { home, ...ENABLED, fetchImpl: impl });
+ expect(calls).toHaveLength(2);
+ expect(new URL(calls[1] as string).searchParams.get('skills')).toBe('b');
+ });
+
+ // The ledger entry is claimed BEFORE the send and never un-claimed. Nothing
+ // awaits this call, so a process exiting mid-flight would otherwise leave the
+ // entry unwritten and re-report the same install next run — inflating a
+ // public count. A dropped send costs one uncounted install instead.
+ test('a failed send is not retried on the next run', async () => {
+ const home = freshHome();
+ const failing = (async () => {
+ throw new Error('network down');
+ }) as unknown as typeof fetch;
+ await reportSkillInstall(
+ { source: 'o/r', skills: ['x'] },
+ { home, ...ENABLED, fetchImpl: failing },
+ );
+ const { calls, impl } = recordingFetch();
+ await reportSkillInstall(
+ { source: 'o/r', skills: ['x'] },
+ { home, ...ENABLED, fetchImpl: impl },
+ );
+ expect(calls).toEqual([]);
+ });
+
+ // If the claim cannot be written there is nothing on disk to suppress the
+ // next run, so sending anyway would produce the duplicate the claim-first
+ // ordering exists to prevent.
+ test('does not send when the ledger claim cannot be written', async () => {
+ const home = freshHome();
+ // A directory where the state file belongs: every write to it fails.
+ mkdirSync(join(home, '.ok', 'skill-state.yml'), { recursive: true });
+ const { calls, impl } = recordingFetch();
+ const reported = await reportSkillInstall(
+ { source: 'o/r', skills: ['x'] },
+ { home, ...ENABLED, fetchImpl: impl },
+ );
+ expect(reported).toEqual([]);
+ expect(calls).toEqual([]);
+ });
+
+ test('resolves rather than rejecting when the network throws', async () => {
+ const failing = (async () => {
+ throw new Error('network down');
+ }) as unknown as typeof fetch;
+ await expect(
+ reportSkillInstall(
+ { source: 'o/r', skills: ['x'] },
+ { home: freshHome(), ...ENABLED, fetchImpl: failing },
+ ),
+ ).resolves.toEqual(['x']);
+ });
+});
+
+describe('reportSkillInstall — stays silent', () => {
+ test('when the setting is off', async () => {
+ const { calls, impl } = recordingFetch();
+ await reportSkillInstall(
+ { source: 'o/r', skills: ['x'] },
+ { home: freshHome(), enabled: false, env: {}, fetchImpl: impl },
+ );
+ expect(calls).toEqual([]);
+ });
+
+ test.each([['DO_NOT_TRACK'], ['DISABLE_TELEMETRY']])('when %s is set', async (name) => {
+ const { calls, impl } = recordingFetch();
+ await reportSkillInstall(
+ { source: 'o/r', skills: ['x'] },
+ { home: freshHome(), enabled: true, env: { [name]: '1' }, fetchImpl: impl },
+ );
+ expect(calls).toEqual([]);
+ });
+
+ // A private repo's name, and a local path, are the user's information. The
+ // upstream CLI gates its own event on a repo-privacy probe for the same
+ // reason; refusing anything that isn't a plain `owner/repo` is the blunt
+ // version of that and errs toward saying nothing.
+ test.each([
+ ['a local absolute path', '/Users/someone/private-skills'],
+ ['a relative path', './local'],
+ ['a git URL', '[email protected]:acme/secret.git'],
+ ['an https URL', 'https://github.com/acme/secret'],
+ ['a bare name', 'not-a-repo'],
+ ['a bare local dir that looks host-ish', 'my-skills'],
+ ])('for %s', async (_label, source) => {
+ const { calls, impl } = recordingFetch();
+ await reportSkillInstall(
+ { source, skills: ['x'] },
+ { home: freshHome(), ...ENABLED, fetchImpl: impl },
+ );
+ expect(calls).toEqual([]);
+ });
+
+ // An internal hostname is not a marketplace publisher, and the NAME itself is
+ // the sensitive part — it describes a network the collector has no business
+ // knowing about.
+ // Reserved TLD position only. A private label in the MIDDLE
+ // (`foo.corp.example.com`) is an ordinary public name and stays reportable —
+ // widening to "contains" would refuse legitimate publishers.
+ test.each([
+ ['skills.corp'],
+ ['wiki.internal'],
+ ['host.local'],
+ ['box.lan'],
+ ['thing.home.arpa'],
+ ['dev.localhost'],
+ ])('for the internal hostname %s', async (source) => {
+ const { calls, impl } = recordingFetch();
+ await reportSkillInstall(
+ { source, skills: ['x'] },
+ { home: freshHome(), ...ENABLED, fetchImpl: impl },
+ );
+ expect(calls).toEqual([]);
+ });
+
+ // A website catalog is the other shape skills.sh indexes (`open.feishu.cn`),
+ // so it reports — the dot is what separates it from a bare local dir name.
+ test('but a website-catalog hostname IS reported', async () => {
+ const { calls, impl } = recordingFetch();
+ await reportSkillInstall(
+ { source: 'open.feishu.cn', skills: ['lark-attendance'] },
+ { home: freshHome(), ...ENABLED, fetchImpl: impl },
+ );
+ expect(calls).toHaveLength(1);
+ expect(new URL(calls[0] as string).searchParams.get('source')).toBe('open.feishu.cn');
+ });
+});
diff --git a/packages/server/src/skills-sh-install-report.ts b/packages/server/src/skills-sh-install-report.ts
new file mode 100644
index 000000000..6d73f38df
--- /dev/null
+++ b/packages/server/src/skills-sh-install-report.ts
@@ -0,0 +1,199 @@
+/**
+ * Report a skill install to skills.sh so a published skill's install count
+ * reflects real adoption.
+ *
+ * This is the ONLY outbound third-party call OK makes on the skill paths — the
+ * `telemetry.localSink.*` config keys are all local-only sinks. It exists
+ * because skills.sh counts installs from an explicit event, NOT from serving
+ * files: `npx skills add` fetches bundle content from `skills.sh/api/download/…`
+ * and separately fires this event. OK acquires skills by cloning the source
+ * repo directly, so without this it is invisible to the counter no matter how
+ * many people install through OK.
+ *
+ * Wire format is the `skills` CLI's, matched field for field so both clients
+ * land in one bucket rather than two shapes the receiver has to reconcile.
+ *
+ * Three rules keep this honest:
+ * 1. ONE report per (skill, source) per machine. The desktop reclaim sweep
+ * runs on every launch and `ok init` is re-runnable; reporting per call
+ * would climb the counter without anyone installing anything. The
+ * dedupe ledger is what makes the number mean "installs", not "launches".
+ * 2. PUBLIC sources only. A private repo's name is the user's information,
+ * not ours to send — the same reason the upstream CLI gates its own event
+ * on a repo-privacy probe. Local paths are skipped for the same reason.
+ * 3. Never blocks and never fails an install. Fire-and-forget with a short
+ * timeout; a dead network is not an install error.
+ */
+
+import { getLogger } from './logger.ts';
+import { readInstallReported, writeInstallReported } from './skill-state.ts';
+
+/** The `skills` CLI's telemetry collector. Same endpoint, same query shape. */
+const TELEMETRY_URL = 'https://add-skill.vercel.sh/t';
+
+const REPORT_TIMEOUT_MS = 3000;
+
+/**
+ * `owner/repo` — the only source shape we report. Deliberately NOT a general
+ * URL matcher: a git URL can carry credentials, and a local path is nobody's
+ * business but the user's. Anything else is skipped silently.
+ *
+ * The dot segments are excluded explicitly: `[\w.-]+` happily matches `.` and
+ * `..`, so a plain character-class check reads `./local` and `../vendor` as
+ * `owner/repo` and would have shipped a local directory name to a third party.
+ * A leading dot elsewhere is fine (`acme/.github` is a real repository).
+ */
+/**
+ * Reserved / private-network suffixes (RFC 6762 `.local`, RFC 8375 `.home.arpa`,
+ * RFC 6761 `.test`/`.invalid`/`.localhost`, plus the conventional intranet
+ * names). A source under one of these is an internal host, never a public
+ * marketplace listing.
+ */
+const PRIVATE_HOST_SUFFIXES = [
+ '.local',
+ '.internal',
+ '.intranet',
+ '.corp',
+ '.home',
+ '.home.arpa',
+ '.lan',
+ '.private',
+ '.test',
+ '.invalid',
+ '.localhost',
+ '.localdomain',
+] as const;
+
+function isPublicRepoSource(source: string): boolean {
+ const parts = source.split('/');
+ // A website catalog publishes under a bare hostname (`open.feishu.cn`) — the
+ // other shape skills.sh indexes. A dot is what separates it from a bare local
+ // directory name.
+ if (parts.length === 1) {
+ if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(source)) {
+ return false;
+ }
+ // An internal hostname is not a marketplace publisher, and its NAME is the
+ // sensitive part — `skills.corp.acme` tells a third party about a network
+ // it has no business knowing. A source that only resolves inside someone's
+ // VPN cannot be a skills.sh listing anyway.
+ return !PRIVATE_HOST_SUFFIXES.some((suffix) => source.toLowerCase().endsWith(suffix));
+ }
+ if (parts.length !== 2) return false;
+ return parts.every((part) => /^[\w.-]+$/.test(part) && part !== '.' && part !== '..');
+}
+
+export interface SkillInstallReport {
+ /** `owner/repo` the skill came from. Non-matching sources are skipped. */
+ source: string;
+ /** Skill names installed from that source in this operation. */
+ skills: readonly string[];
+ /** Editor/host ids the skill was placed into (`claude`, `codex`, …). */
+ agents?: readonly string[];
+ /** True when the install landed at user-global scope. */
+ global?: boolean;
+ /** OK version, sent as the client version so the receiver can tell us apart. */
+ version?: string;
+}
+
+export interface ReportSkillInstallDeps {
+ /** `$HOME` — the dedupe ledger lives beside the other skill state. */
+ home: string;
+ /** Resolved `telemetry.skillInstallReports.enabled`. */
+ enabled: boolean;
+ /** Test seam. */
+ fetchImpl?: typeof globalThis.fetch;
+ /** Test seam — defaults to `process.env`. */
+ env?: NodeJS.ProcessEnv;
+}
+
+/**
+ * The two environment variables the `skills` CLI itself honors, plus the
+ * broader `DO_NOT_TRACK` convention. Checked in addition to the config toggle
+ * so a machine-wide opt-out works without editing OK's config.
+ */
+function envOptOut(env: NodeJS.ProcessEnv): boolean {
+ return Boolean(env.DISABLE_TELEMETRY || env.DO_NOT_TRACK);
+}
+
+/**
+ * Report an install, once. Resolves when the attempt is done (or immediately
+ * when skipped) so callers may `void` it without an unhandled rejection.
+ *
+ * Returns the skills actually reported — empty when the report was skipped,
+ * which is the normal case on every run after the first.
+ */
+export async function reportSkillInstall(
+ report: SkillInstallReport,
+ deps: ReportSkillInstallDeps,
+): Promise<readonly string[]> {
+ const env = deps.env ?? process.env;
+ if (!deps.enabled || envOptOut(env)) return [];
+ if (!isPublicRepoSource(report.source.trim())) return [];
+
+ // Drop the ones already reported from this machine, so a re-init or a
+ // launch-time reclaim contributes nothing.
+ // A read failure reads as "nothing reported yet", which risks a duplicate —
+ // logged so an over-count investigation has a trail rather than a mystery.
+ const alreadyReported = await readInstallReported(deps.home).catch((err: unknown) => {
+ getLogger('skills').warn(
+ { err, source: report.source },
+ 'could not read the install-report ledger; a duplicate report is possible',
+ );
+ return new Set<string>();
+ });
+ const fresh = report.skills.filter((s) => !alreadyReported.has(`${report.source}#${s}`));
+ if (fresh.length === 0) return [];
+
+ const params = new URLSearchParams({
+ event: 'install',
+ source: report.source,
+ skills: fresh.join(','),
+ });
+ if (report.agents && report.agents.length > 0) params.set('agents', report.agents.join(','));
+ if (report.global) params.set('global', '1');
+ if (report.version) params.set('v', report.version);
+
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
+ if (!fetchImpl) return [];
+
+ // Claim the ledger entries BEFORE sending, and never un-claim them.
+ //
+ // The alternative — record only on a confirmed 2xx — reads as more careful
+ // but errs the wrong way. Nothing awaits this call (it must not sit on the
+ // `ok init` or seed critical path), so a process that exits mid-flight would
+ // leave the entry unwritten and re-report the same install on the next run.
+ // That inflates someone's public count. Claiming first inverts the failure to
+ // "a dropped send is never retried", which under-counts instead — the safe
+ // direction for a number we are asserting about other people's skills.
+ try {
+ await writeInstallReported(
+ deps.home,
+ fresh.map((s) => `${report.source}#${s}`),
+ );
+ } catch (err) {
+ // No claim, no send. Reporting anyway would leave nothing on disk to
+ // suppress the next run — the duplicate this ordering exists to prevent.
+ getLogger('skills').warn(
+ { err, source: report.source, skills: fresh },
+ 'skill install report ledger write failed; not reporting this install',
+ );
+ return [];
+ }
+
+ try {
+ await fetchImpl(`${TELEMETRY_URL}?${params.toString()}`, {
+ signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),
+ });
+ } catch (err) {
+ // A dead network is not an install error, and by the contract above this
+ // one is simply not counted. Logged rather than swallowed: on a machine
+ // that blocks the collector this fires on every install, and a silent
+ // catch makes "why is our count flat" undiagnosable.
+ getLogger('skills').warn(
+ { err, source: report.source, skills: fresh },
+ 'skill install report could not be delivered; this install is not counted',
+ );
+ }
+ return fresh;
+}
diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.ts
index 76b34afb7..8d07daaa3 100644
--- a/test-support/vitest.base.ts
+++ b/test-support/vitest.base.ts
@@ -85,6 +85,12 @@ export const okVitestBase = {
environment: 'node',
testTimeout: 30_000,
hookTimeout: 30_000,
+ // The skills.sh install report honors the standard opt-out vars. Setting one
+ // here means no test run — local or CI — can report an install it did not
+ // make, and no suite depends on reaching a third-party host to pass. A test
+ // that wants to exercise the reporter injects its own `fetchImpl` and
+ // `env`, so this never hides the behavior under test.
+ env: { DO_NOT_TRACK: '1' },
setupFiles: [bunGlobalShimPath],
include: ['**/*.test.ts?(x)'],
exclude: [...configDefaults.exclude, '**/*.spec.*', '**/*.e2e.*', '**/*.dom.test.ts?(x)'],